@engineeros/connector 1.59.60 → 1.59.61
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 Qt=await gt.text().catch(()=>"");if(xt(),z.blockedRequest)throw new qe("blocked",z.blockedRequest);let Mn=null;try{Mn=JSON.parse(Qt)}catch{Mn=null}return z.response={status:gt.status(),text:Qt,json:Mn,ms:c()-tt},{method:be,url:Z}}let Wd=async G=>{let ae=[...new Set([...String(G??"").matchAll(W7)].map(te=>te[1]))],ye=String(G??"");for(let te of ae){let be=f[te];if(be===void 0||be==="")throw new qe("blocked",`Set ${te} on the hunt host (\`engineeros-connector secret set ${te} --project ${C??"<project id>"}\`).`);let Z;try{Z=await Ah({value:String(be),now:c,sleep:Eo})}catch{throw new qe("blocked",`${te} is not a valid authenticator secret.`)}ye=ye.replaceAll(`{totp:${te}}`,Z)}return ye};async function Ur(G,ae=Be,{signingIn:ye=!1}={}){if(xt(),z.blockedRequest)throw new qe("blocked",z.blockedRequest);let te={action:G.action,target:is(await Wd(G.target),ae),data:is(await Wd(G.data),ae),check:is(G.check,ae)};if(xt(),te.action==="fill"&&!ye&&mI(te.data).blocked)throw new qe("blocked",Rv);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 Eo(1e3)}if(!ye){let Z=jr(te,de);if(Z)throw new qe("blocked",`Refused by the rule of engagement "${Z}".`)}let be=te.check?ss(te.check):[];switch(te.action){case"open app":{if(y.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||[Q,t.api_url].some(Z=>/^https?:/i.test(Z??"")))throw new qe("blocked","Electron cannot enforce this web target's approved socket destinations. Use the managed local browser for protected web testing.");if(Ee)throw new qe("needs_repair","Open the app once per case.");S("Local Electron actions are available; Electron network transport is not qualified for protected web testing."),Ee=await v({executablePath:y.app_path,args:y.app_arguments||[],cwd:l}),me?.aborted&&(await pr(),xt()),await Ut();break}case"use account":Sr(await Gn(te.target.trim()));break;case"open":{await Ut();let Z=se(te.target.trim(),Q),Ne=tt=>new qe("blocked",`${z.account.role}'s recorded sign-in has expired or was signed out: opening ${Z} led to ${tt}. Record it again in Bug Hunter Setup.`),Ce;try{Ce=await z.page.goto(Z,{waitUntil:"domcontentloaded",timeout:V.navigation})}catch(tt){let gt=String(tt.message).split(`
|
|
2638
2638
|
`)[0];throw z.account?.storage_state&&/ERR_BLOCKED_BY_CLIENT/.test(gt)?Ne("another site"):new qe("blocked",`Opening ${Z} failed: ${Dt(gt)}`)}if(await Ft(),z.account?.storage_state&&Kh(Z,z.page.url(),le))throw Ne(Dt(z.page.url(),200));await io({requested:Z,reopen:async()=>{Ce=await z.page.goto(Z,{waitUntil:"domcontentloaded",timeout:V.navigation}),await Ft()}}),await Et();let Ge=Ce?.status?.()??200;if(Ge>=500)throw new qe("failed",`The server answered ${Ge} for ${Z}.`,`server error ${Ge}`);break}case"click":case"hover":case"check":case"uncheck":case"fill":case"select":{await Ut();let Z=await rr(to(te.target));await Qs(async()=>{te.action==="click"?await Z.click({timeout:V.action}):te.action==="hover"?await Z.hover({timeout:V.action}):te.action==="check"?await Z.check({timeout:V.action}):te.action==="uncheck"?await Z.uncheck({timeout:V.action}):te.action==="fill"?await Z.fill(te.data,{timeout:V.action}):await Z.selectOption({label:te.data},{timeout:V.action})}),te.action==="click"&&await Ft();break}case"press":{if(await Ut(),te.target.trim()){let Z=await rr(to(te.target));await Qs(()=>Z.press(te.data.trim(),{timeout:V.action}))}else await Qs(()=>z.page.keyboard.press(te.data.trim()));await Ft();break}case"go back":await Ut(),await Qs(()=>z.page.goBack({timeout:V.navigation})),await Ft();break;case"reload":await Ut(),await Qs(()=>z.page.reload({timeout:V.navigation})),await Ft(),await Et();break;case"set viewport":{await Ut();let[Z,Ne]=(te.data||te.target).trim().toLowerCase().split("x").map(Number);await z.page.setViewportSize({width:Z,height:Ne});break}case"wait for":await Ut();break;case"request":{await Ut();let{method:Z,url:Ne}=await Gd(te.target,te.data);if(z.response.status>=500&&!be.some(Ce=>["status","status_below","status_in"].includes(Ce.kind)))throw new qe("failed",`The server answered ${z.response.status} for ${Z} ${Ne}.`,`status was ${z.response.status}: ${Dt(z.response.text,200)}`);break}case"poll":{await Ut();let Z=c()+(Number(te.data.trim())||C7)*1e3;for(;;){await Gd(te.target,"");let Ne=[];for(let Ce of be){let Ge=await ys(Ce);Ge!==null&&Ne.push(Ge)}if(!Ne.length)break;if(c()>=Z)throw new qe("failed",`It never answered as expected: ${Ne.join("; ")}.`,Ne.join("; "));await Eo(I7)}return Pn()}case"set device":{if(z.page)throw new qe("needs_repair","Set the device before opening a page or using an account.");if(y.device_cloud_url){lt=te.data.trim(),dt.hasTouch=!0;break}let Z=te.data.trim().toLowerCase(),Ne=Object.entries(_).find(([tt])=>tt.toLowerCase()===Z);if(!Ne)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:Ce,...Ge}=Ne[1];Object.assign(dt,Ge);break}case"tap":{if(await Ut(),!dt.hasTouch)throw new qe("needs_repair","tap needs a touch device; set one with set device first.");let Z=await rr(to(te.target));await Qs(()=>Z.tap({timeout:V.action})),await Ft();break}case"set locale":if(z.page)throw new qe("needs_repair","Set the locale before opening a page or using an account.");dt.locale=te.data.trim();break;case"set time zone":if(z.page)throw new qe("needs_repair","Set the time zone before opening a page or using an account.");dt.timezoneId=te.data.trim();break;case"set network":{await Ut();let Z=te.data.trim().toLowerCase();$n=Z,Hn.setNetwork(Z),await z.context.setOffline(Z==="offline"),Z!=="offline"&&await(await z.context.newCDPSession(z.page)).send("Network.emulateNetworkConditions",Z==="slow"?R7:O7);break}case"run":{let Z;try{Z=jn(te.target.trim())}catch(Ge){throw new qe("needs_repair",`\`${te.target}\` cannot run without a shell: ${Ge.message}`)}let Ne=m7.basename(Z[0]).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase();if(!J.has(Ne))throw new qe("blocked",`${Z[0]} is not a program this hunter may run (${[...J].join(", ")||"none are allowed"}).`);let Ce=await d(Z,{onChild:Wa,cwd:l,timeoutMs:V.command,...u?{env:u}:{},...te.data?{input:te.data}:{}});if(Ce.notFound)throw new qe("blocked",`${Z[0]} is not installed on the hunt host.`);z.command={exitCode:Ce.exitCode,output:Fe(String(Ce.output??""))};break}case"use":{let Z=ee.get(te.target.trim().toLowerCase());if(Z?.builtin==="inbox"){if(!R)throw new qe("blocked","The test inbox is not set up on this hunt host.");z.command=await Oh(R,te.data,ut);break}if(!Z)throw new qe("blocked",`${te.target.trim()} is not an instrument approved for this environment (${[...ee.keys()].join(", ")||"none are"}).`);let Ne=Z.env??[],Ce=Ne.filter(Jt=>f[Jt]===void 0);if(Ce.length)throw new qe("blocked",`Set ${Ce.join(", ")} on the hunt host to use ${Z.name}.`);let Ge=Object.fromEntries(Ne.map(Jt=>[Jt,String(f[Jt])])),tt={...ae,...Ge,data:te.data,since:new Date(ut).toISOString()},gt=(Z.command??[]).map(Jt=>is(String(Jt),tt)),Qt=await d(gt,{onChild:Wa,cwd:l,timeoutMs:V.command,env:{...u??process.env,...Ge}});if(Qt.notFound)throw new qe("blocked",`${gt[0]} is not installed on the hunt host.`);let Mn=String(Qt.output??"");for(let Jt of Object.values(Ge))Jt&&(Mn=Mn.replaceAll(Jt,"[secret]"));z.command={exitCode:Qt.exitCode,output:Fe(Mn)};break}case"wait until":{let Z=/^step\s+(\d+)$/i.exec(te.target.trim()),Ne=Z?xl[Number(Z[1])-1]:ut;if(Ne===void 0)throw new qe("needs_repair",`wait until counts from step ${Z[1]}, which has not run yet.`);let Ce=Ne+(bh(te.data)??0);if(Ce-c()>N7)throw new qe("needs_repair","wait until may wait at most three hours.");Ce>c()&&await Eo(Ce-c());break}case"crawl":{await Ut();let Z=Math.min(Number(te.data)||ib,P7),Ne=z.account?.role??null,Ce=c(),Ge=()=>c()<Ce+Math.min(V.crawl+z.scanMs,3*V.crawl),tt=at?[]:[{url:se(te.target.trim()||"/",Q),from:null,source:"link"}],gt=[];for(let ce of Uh(Ze,de))try{gt.push({url:se(ce.path,Q),from:null,source:ce.source,seed:!0})}catch{}let Qt=gt.some(ce=>ce.url.includes("/#/")),Mn=new Set(fe),Jt=new Set(fe),Xa=new Map,Wn=!1,ei=new Map,Tt={pages:0,server_errors:[],broken_links:[],routes:[],scripts:[],controls_explored:0,explore_blocked_writes:0,explore_stopped_pages:0,explore_stopped_time:0};z.crawl=Tt;let Ao=[],q=null,K=async()=>{let[ce,ge]=await Promise.all([z.page.title(),z.page.evaluate(Mi)]);return`${ce??""}\0${ge.elements.join("")}`},_e=async()=>{let ce=`__engineeros_probe_${Math.random().toString(36).slice(2,8)}`;try{return await z.page.goto(se(Qt?`/#/${ce}`:`/${ce}`,Q),{waitUntil:"domcontentloaded",timeout:V.navigation}),await Ft(),await K()}catch{return!1}};for(;(tt.length||gt.length)&&Tt.pages<Z&&Ge()&&!ct();){xt();let ce=gt.length&&(Wn||!tt.length)?gt.shift():tt.shift();Wn=!Wn;let ge=cr(new URL(ce.url));if(ge===null)continue;let Me=Zu(ge);if(Mn.has(ge)||(ei.get(Me)??0)>=D7||(Mn.add(ge),ei.set(Me,(ei.get(Me)??0)+1),jr({action:"open",target:ge,data:"",check:""},de)))continue;ce.seed&&q===null&&(q=await _e()),z.path=ce.from,z.pathRole=Ne;let He={path:ge.slice(0,300),source:ce.source,status:null,outcome:"reached",from_path:ce.from?ce.from.slice(0,300):null},ze=(rt,pt=null)=>{ce.from&&(Tt.broken_links.push({from:ce.from,url:ce.url,status:rt}),Hn.note("broken_link",ce.from,{url:ce.url,status:rt,error:pt,message:`A link to ${ge} ${rt?`answers ${rt}`:"cannot be opened"}`}))},yt;try{yt=await z.page.goto(ce.url,{waitUntil:"domcontentloaded",timeout:V.navigation})}catch(rt){let pt=String(rt.message).split(`
|
|
2639
2639
|
`)[0];/ERR_(?!BLOCKED_BY_CLIENT)[A-Z_]+/.test(pt)&&ze(null,pt),Tt.routes.push({...He,outcome:"error"});continue}await Ft(),Ne&&await io({requested:ce.url,crawling:!0,reopen:async()=>{yt=await z.page.goto(ce.url,{waitUntil:"domcontentloaded",timeout:V.navigation}),await Ft()}}).catch(()=>!1),await Et();let we=yt?.status?.()??200;He.status=we;let it=we===404||we===410;if(await(async()=>{if(!Ne||it)return!1;if(we===403)return!0;if(we>=400)return!1;try{let[rt,pt,Er]=await Promise.all([z.page.title(),z.page.evaluate(Mi),z.page.evaluate(()=>document.querySelector("h1")?.innerText??"")]);return H7.test(`${rt??""} ${Er??""}`)&&pt.elements.length<=G7}catch{return!1}})()){Tt.routes.push({...He,outcome:"forbidden"});continue}let At=cr(new URL(z.page.url())),We=we===401||we===403||Kh(ce.url,z.page.url(),le)||At!==ge&&Ci({key:At,elements:(await z.page.evaluate(Mi).catch(()=>({elements:[]}))).elements});if(We){if(Tt.routes.push({...He,outcome:"sign_in"}),ce.seed){let rt=new URL(z.page.url()),pt=`${rt.origin}${we===401||we===403?`:${we}`:cr(rt)}`,Er=(Xa.get(pt)??0)+1;Xa.set(pt,Er),Er>=3&>.length&&(Tt.deferred_seeds=gt.length,gt.length=0)}if(we===401||we===403)continue}else if(ce.seed){if(it||q&&await K()===q){Tt.routes.push({...He,outcome:"not_found"});continue}}else if(it){ze(we),Tt.routes.push({...He,outcome:"not_found"});continue}else we>=400&&we!==401&&we!==403&&ze(we);let kt=new URL(z.page.url()),St=cr(kt);if(We||Tt.routes.push({...He,outcome:we>=500?"error":"reached"}),St===null||!le.has(kt.hostname.toLowerCase())||Jt.has(St))continue;Jt.add(St),Tt.pages+=1,We&&St!==ge&&Tt.routes.push({path:St.slice(0,300),source:"navigation",status:we,outcome:"reached",from_path:null}),we>=500&&Tt.server_errors.push(St),await Pn(),await ve();let bn=await z.page.evaluate(Sj).catch(()=>[]);Ao.push({key:St,url:z.page.url(),links:Array.isArray(bn)?bn.length:0});for(let rt of Array.isArray(bn)?bn:[]){let pt;try{pt=new URL(rt,kt)}catch{continue}!/^https?:$/.test(pt.protocol)||!le.has(pt.hostname.toLowerCase())||Lh(pt.href,de)&&(Dv.test(pt.hash)||(pt.hash=""),Mn.has(cr(pt))||tt.push({url:pt.toString(),from:St,source:"link"}))}}if(await Gt(),Je&&!h&&Ao.length&&!ct()){let ce=c(),ge=()=>ct()||c()-ce>=V.explore,Me=[...Ao].sort((ze,yt)=>ze.links-yt.links),He=async ze=>{await z.page.goto(ze.url,{waitUntil:"domcontentloaded",timeout:V.navigation}).catch(()=>{}),await Ft()};z.exploring=!0;try{for(let ze=0;ze<Me.length&&!Tt.explore_stopped_time;ze+=1){if(xt(),ge()){Tt.explore_stopped_time=1;break}let yt=Me[ze];try{await z.page.goto(yt.url,{waitUntil:"domcontentloaded",timeout:V.navigation})}catch{continue}await Ft();let we=await z.page.evaluate(tj).catch(()=>[]),{chosen:it,cut:Le}=nj(Array.isArray(we)?we:[],{forbidden:de,limit:Vv});Le&&(Tt.explore_stopped_pages+=1);let At=0;for(let We of it){if(xt(),ge()){Tt.explore_stopped_time=1;break}let kt=We.role?z.page.getByRole(We.role,{name:We.name,exact:!0}):z.page.getByText(We.name,{exact:!0});if(await kt.count()!==1)continue;let St=(await z.page.evaluate(Mi)).elements;try{await kt.click({timeout:V.action})}catch{}Tt.controls_explored+=1,await Eo(V.exploreSettle),await Ft();let bn=z.page.url(),rt=null,pt=!1;try{let To=new URL(bn);rt=cr(To),pt=le.has(To.hostname.toLowerCase())}catch{}if(rt!==null&&rt!==yt.key&&pt){!Jt.has(rt)&&Tt.pages<Z&&(Jt.add(rt),Mn.add(rt),z.path=yt.key,z.pathRole=Ne,Tt.pages+=1,Tt.routes.push({path:rt.slice(0,300),source:"navigation",status:200,outcome:"reached",from_path:yt.key.slice(0,300)}),await Pn(),await ve(),At=0,Me.push({key:rt,url:bn,links:0})),await He(yt);continue}let Er=(await z.page.evaluate(Mi)).elements,Fr=Er.filter(To=>!St.includes(To));if(Fr.length>=2){let To={key:yt.key.slice(0,300),origin:new URL(z.page.url()).origin,title:Dt(await z.page.title().catch(()=>""),300),elements:[...new Set([...St,...Er])].slice(0,sb).map(qr=>Dt(qr,200)),role:Ne};i(To),X(To)}if(await ve(),Fr.length)At=0,await He(yt);else if(++At>=3){ge()&&(Tt.explore_stopped_time=1);break}}}}finally{z.exploring=!1}Tt.explore_blocked_writes=z.blockedWrites}Tt.scripts=Hn.scripts(),Tt.remaining_routes=[...tt,...gt].flatMap(ce=>{let ge=cr(new URL(ce.url));return ge&&!Mn.has(ge)?[{path:ge,source:ce.source}]:[]});return}case"remember":{let Z=te.data.trim(),Ne=te.target.trim();if(Ne==="url")await Ut(),ae[Z]=z.page.url();else if(/^output(?:\s+field\s+|$)/i.test(Ne)){if(!z.command)throw new qe("needs_repair","Nothing was run before this step to remember output from.");let Ce=Ne.replace(/^output\s*(?:field\s+)?/i,"");if(!Ce)ae[Z]=z.command.output.trim();else{let Ge=null;try{Ge=JSON.parse(z.command.output)}catch{Ge=null}let tt=Ge===null?{found:!1}:ad(Ge,Ce);if(!tt.found)throw new qe("needs_repair",`The last output has no field ${Ce} to remember.`);ae[Z]=Qc(tt.value)}}else if(/^field\s+/i.test(Ne)){let Ce=Ne.replace(/^field\s+/i,""),Ge=z.response?ad(z.response.json,Ce):{found:!1};if(!Ge.found)throw new qe("needs_repair",`The last response has no field ${Ce} to remember.`);ae[Z]=Qc(Ge.value)}else{await Ut();let Ce=await rr(to(Ne));ae[Z]=String(await Ce.innerText()).trim()}break}default:throw new qe("needs_repair",`\`${te.action}\` is not an action.`)}if(xt(),z.blockedRequest)throw new qe("blocked",z.blockedRequest);await jt(be),await Pn()}let Qi=async()=>(await Hn.settled(),{execution_context:{browser:Ee?"electron":e?.browserType?.().name()??null,browser_version:typeof(Ee||e)?.version=="function"?(Ee||e).version():null,role:z.account?.role??"",context_sha256:bj("sha256").update(JSON.stringify(Vt)).digest("hex")},signals:Hn.signals(),api_calls:h?[]:Hn.apiCalls(),vitals:Zi,scanned:Va,scan_ms:z.scanMs});try{for(let[G,ae]of B.slice(0,Ve===null?B.length:Ve-1).entries())try{if(z.step=G+1,await Ur(ae),z.blockedRequest)throw new qe("blocked",z.blockedRequest);xl[G]=c(),await ve()}catch(ye){let te=z.blockedRequest||z.transportBlocker?new qe("blocked",z.blockedRequest??`${z.transportBlocker} The functional check could not complete with that dependency unavailable: ${Dt(ye.message)}`):ye instanceof qe?ye:me?.aborted?new qe("blocked",Dt(me.reason?.message??"The hunt was stopped; remaining actions were not run.")):new qe("failed",Dt(ye.message));z.crawl||await Pn({final:!0}).catch(()=>{});let be=await Lr(),Z=be?[{label:"after",step:G+1,media_type:"image/jpeg",data_base64:be}]:[];return nt={outcome:te.outcome,failed_step:G+1,message:`${oe} step ${G+1}: ${Dt(te.message,1e3)}`,observed:te.observed?Dt(te.observed,1e3):null,duration_ms:c()-ut,evidence:[...Z,...Yi],...await Qi(),...z.crawl?{crawl:z.crawl}:{}}}return z.crawl||await Pn({final:!0}).catch(()=>{}),nt={outcome:"passed",failed_step:null,message:null,observed:null,duration_ms:c()-ut,evidence:Yi,...await Qi(),...z.crawl?{crawl:z.crawl}:{}}}finally{if(nt&&Re){if(nt.cleanup={state:"not_required",from_step:null,reason:null},Ve!==null){let ye=Dt(is(Re.test_data,{unique:Be.unique}),1e3),te=Ve;nt.cleanup={state:"completed",from_step:Ve,reason:null,test_data_scope:ye};try{xt(),z.blockedRequest=null;for(let[be,Z]of B.slice(Ve-1).entries()){if(te=Ve+be,/\{[A-Za-z_][A-Za-z0-9_]*\}/.test(is(Z.target+" "+Z.data,Be)))throw new Error("Cleanup needs an identifier that this case did not observe. Resolve the owned test data before retrying.");if(await Ur(Z),z.blockedRequest)throw new Error("Cleanup was refused by this run's scope.")}}catch(be){nt.cleanup={state:"pending",from_step:Ve,reason:`The approved cleanup could not complete: ${Dt(be.message,500)} Resolve this case's owned test data before another attempt.`,primary_outcome:nt.outcome,primary_failed_step:nt.failed_step,primary_message:nt.message,test_data_scope:ye},nt.outcome="blocked",nt.failed_step=te,nt.message=nt.cleanup.reason}}Object.assign(nt,await Qi()),nt.duration_ms=c()-ut}if(!me?.aborted){for(let ye of wt.values())if(ye.account?.storage_state)try{let te=new Set(ye.account.sign_in_binding.origins),be=Ni(ye.page.url(),te)?await ye.page.evaluate(rb):null,Z=ye.account.storage_state.sessionStorage??[],Ne=Pi(await ye.context.storageState({indexedDB:!0}),te,be?[...Z.filter(Ce=>Ce.origin!==be.origin),be]:Z);await bt(ye.account,Ne)}catch{S("The case evidence was retained, but its renewed sign-in could not be kept. Check the protected store before the next run.")}}me?.removeEventListener("abort",zt);let ae=(await Promise.allSettled([Ga,pr()])).find(ye=>ye.status==="rejected");if(ae)throw ae.reason}}return{run:async(B,oe)=>{let X=async Re=>{if(I)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 Ze=await F(B,{...oe,profileReservation:Re});return Ze.cleanup?.state==="pending"&&(I=!0),Ze};if(oe?.caseMetadata?.effects==="read_only"||B.some(Re=>Re.action==="crawl"))return X();let ne=B.filter(Re=>Re.action==="use account"&&n.some(Ze=>Ze.storage_state&&Ze.role.toLowerCase()===String(Re.target).trim().toLowerCase())),ue=j&&oe?.signal?AbortSignal.any([j,oe.signal]):j??oe?.signal;try{return await P.run(Oe(ne),{signal:ue},X)}catch(Re){if(Re.code!=="HUNT_RESOURCES_BLOCKED")throw Re;return{outcome:"blocked",failed_step:1,message:Re.message,duration_ms:0,evidence:[]}}}}}$r();import _n from"node:path";import{mkdirSync as bie}from"node:fs";import{format as kie}from"node:util";In();N();dn();In();import{createHash as V7}from"node:crypto";import{readFile as J7,readdir as X7,rm as K7}from"node:fs/promises";import cd from"node:path";import{isDeepStrictEqual as Y7}from"node:util";var Z7=new Set(["prompt.completed","prompt.failed"]),ab=e=>V7("sha256").update(e).digest("hex"),Qh=new Map,tl=new Map,Aj=e=>ab(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 em(e,t){let r=(Qh.get(e)??Promise.resolve()).catch(()=>{}).then(t).finally(()=>{Qh.get(e)===r&&Qh.delete(e)});return Qh.set(e,r),r}function Tj(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,cd.resolve(e.workspace)]);return cd.join(cd.dirname(Un(e.workspace)),"prompt-results",ab(t))}function tm(e,t){if(!Z7.has(t.type)||!t.prompt_id)throw new Error("Only final prompt results belong in the prompt outbox.");return cd.join(Tj(e),`${ab(JSON.stringify([t.prompt_id,t.execution_revision??1]))}.json`)}async function nm(e){try{return JSON.parse(await J7(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw t}}function Rj({getConfig:e,send:t,onRetained:n=()=>{}}){let r;function o(a,c){let l=Date.now();for(let[u,d]of tl)d.expires<=l&&tl.delete(u);if(c&&tl.has(a)&&tl.get(a).digest!==Aj(c))throw new Error(`A different final result was already acknowledged for this prompt revision. Original evidence retained in EngineerOS; receipt: ${a}.`);return tl.has(a)?{status:"delivered",file:a}:null}async function s(a,c){let l=JSON.parse(JSON.stringify(c)),u=await nm(a);if(!u){u={update:l,saved_at:new Date().toISOString()};try{await De(a,JSON.stringify(u),{replace:!1})}catch(d){if(d.code!=="EEXIST")throw d;if(u=await nm(a),!u)throw new Error(`Another connector delivered or changed this prompt result. Reconcile its existing receipt before retrying: ${a}`)}}if(!Y7(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),tl.set(a,{expires:Date.now()+36e5,digest:Aj(c.update)}),await K7(a,{force:!0}),{status:"delivered",file:a}}catch(l){if(l.retryable===!1){let d=l.message||"EngineerOS rejected this prompt result.";return await De(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=tm(e(),a);return em(c,()=>o(c,a)?{file:c,record:null}:s(c,a))},deliver(a){let c=tm(e(),a);return em(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=tm(e(),{...a,type:"prompt.completed"});return em(c,async()=>{let l=o(c);if(l)return l;let u=await nm(c);return u?i(c,u):null})},flush(){if(r)return r;let a=Tj(e());return r=(async()=>{let c;try{c=await X7(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=cd.join(a,l);if((await em(u,async()=>{let p=await nm(u);if(!p||p.rejection)return null;if(u!==tm(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 Oj({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();Ka();N();var ld=new Map;function ud(e,t=Date.now()){let n=ld.get(e);return!n||t>=n.retryAt}function Cj(e,t,n,{remedy:r=null,now:o=Date.now()}={}){let s=ld.get(e),i=(s?.failures??0)+1,a=Math.min(3e4*2**(i-1),6e5),c={id:e,title:t,remedy:r,message:Q7(n),failures:i,firstFailedAt:s?.firstFailedAt??o,retryAt:o+a,retryInMs:a};return ld.set(e,c),c}function Ij(e){return ld.delete(e)}function jj(e=Date.now()){return[...ld.values()].map(t=>({...t,status:t.failures>=5?"failed":"warning",retryInMs:Math.max(t.retryAt-e,0)}))}function Q7(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}In();var cb=22,eZ=500,tZ=300,nZ=20,Nj={ok:0,warning:1,failed:2},Mj={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."}},rZ=360*6e4,Pj=new WeakMap,oZ="connector.diagnostics";function sZ(e){return e.reduce((t,n)=>Nj[n.status]>Nj[t]?n.status:t,"ok")}async function Dj({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=[iZ(a),aZ(e),await dd("backend","EngineerOS backend",()=>cZ(e,i)),await dd("coding_agent","Coding agent",()=>lZ(e,t,r.inspectAgent,i)),...s?[dZ(s)]:[],...r.connectorJobs?[await dd("local_execution","Local testing work",()=>pZ(r.connectorJobs))]:[],await dd("tool_registry","Tool registry",()=>fZ(t,r.inspectTools)),...e?.hunt_host?[]:[await dd("goal_runner","Goal runner",()=>hZ(t,r.runnerStatus,{serviceStatus:r.macRunnerStatus}))],...jj().map(mZ),...o.map(l=>en(l.id,l.title,l.status,l.detail,l.remedy))].slice(0,nZ);return{checked_at:new Date().toISOString(),connector_version:String(n).slice(0,50),status:sZ(c),checks:c}}function lb(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 Lj(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:oZ,...t})??{}}function iZ(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=cb?en("node_runtime","Node runtime","ok",`Node ${e}.`):en("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${cb} this connector requires.`,`Install Node ${cb} or later, then start the connector again.`)}function aZ(e){return e?.connector_id&&e.token?en("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):en("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function cZ(e,t){if(!e?.server_url)return en("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=Qk(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return en("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${wn(s,{network:!0})}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return en("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"?en("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):en("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&&Oo(a,i)>0?en("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,Mj[o.protocol].remedy):en("coding_agent","Coding agent","ok",s)}catch(o){return en("coding_agent","Coding agent","failed",Uj(o),null)}}async function uZ(e,t){let n=Mj[e];if(!n)return null;let r=Pj.get(t)??new Map;Pj.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<rZ)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;kn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function dZ({state:e,detail:t,remedy:n=null}){return en("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function pZ(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return en("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?en("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."):en("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function fZ(e,t){let n=await t(e);if(n?.error)return en("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 en("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function hZ(e,t,{platform:n=process.platform,serviceStatus:r=qC}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return en("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 en("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 en("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 en("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 en("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function mZ(e){return en(e.id,e.title,e.status,`Failing since ${ao(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function dd(e,t,n){try{return await n()}catch(r){return en(e,t,"failed",Uj(r),null)}}function en(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,eZ),remedy:o?String(o).slice(0,tZ):null}}function Uj(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import AZ from"node:path";N();import gZ from"node:path";var qj=2,wZ=300*1e3,yZ={pytest:40,"node:test":40,vitest:60,jest:60},_Z=3,vZ=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),bZ=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),Fj=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 rm(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function zj(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function kZ(e){let t=String(e?.name??"");return bZ.has(t)?{support:"helper"}:vZ.has(t)?{support:"run"}:Fj.has(t)?{support:"skipped",reason:Fj.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var ub=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),SZ=(e,t)=>!t||e.startsWith(`${t}/`);function xZ(e,t){let n=null;for(let r of t)r.name!==e.framework||!SZ(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function EZ(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 Bj({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(ub)):null,i=[];for(let l of e){let u=kZ(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:ub(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:ub(u.file)})))s&&!s.has(l.file)||xZ(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=$Z(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(_Z,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function $Z(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:[]}]:EZ(e.files,{perShard:yZ[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var TZ=3;function om(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=_$(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&&rm(e),quality_baseline_contract:qj,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_scenarios:dI,bug_hunt_performance:1,bug_hunt_specialists:1,bug_hunt_actions:[...vh],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Ca(n),bug_hunt_sign_in:Oa,bug_hunt_inputs:1,bug_hunt_checks:[...Av],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_recovery:e.hunt_host?0:1,goal_run_contract:TZ,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.60",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:ch,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:AZ.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...Lu(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...DR(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();dn();sa();import{createHash as Gj}from"node:crypto";import{readFile as RZ}from"node:fs/promises";import OZ from"node:os";import pb from"node:path";var CZ=/^[A-Z_][A-Z0-9_]*$/,IZ=80,jZ=64,Hj="hunt-secret-";function fd(e){return typeof e=="string"&&e.length>0&&e.length<=IZ&&CZ.test(e)}function sm(e){let t=`${Hj}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=jZ?t:`${Hj}h${Gj("sha256").update(String(e)).digest("hex").slice(0,40)}`}function NZ(e){let t=Gj("sha256").update(pb.resolve(e??process.cwd())).digest("hex").slice(0,16);return pb.join(OZ.homedir(),".engineeros","hunt-secrets",t)}function db(e){if(!fd(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function hd({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??NZ(e),o=t??or({directory:r}),s=pb.join(r,"names.json");async function i(){let u;try{u=await RZ(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(fd)}catch{return[]}}let a=Promise.resolve(),c=u=>{let d=a.then(async()=>{let p=new Set(await i());u(p),await De(s,`${JSON.stringify({names:[...p].sort()},null,2)}
|
|
2640
|
+
`)}async function Lj(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:oZ,...t})??{}}function iZ(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=cb?en("node_runtime","Node runtime","ok",`Node ${e}.`):en("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${cb} this connector requires.`,`Install Node ${cb} or later, then start the connector again.`)}function aZ(e){return e?.connector_id&&e.token?en("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):en("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function cZ(e,t){if(!e?.server_url)return en("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=Qk(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return en("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${wn(s,{network:!0})}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return en("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"?en("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):en("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&&Oo(a,i)>0?en("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,Mj[o.protocol].remedy):en("coding_agent","Coding agent","ok",s)}catch(o){return en("coding_agent","Coding agent","failed",Uj(o),null)}}async function uZ(e,t){let n=Mj[e];if(!n)return null;let r=Pj.get(t)??new Map;Pj.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<rZ)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;kn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function dZ({state:e,detail:t,remedy:n=null}){return en("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function pZ(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return en("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?en("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."):en("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function fZ(e,t){let n=await t(e);if(n?.error)return en("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 en("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function hZ(e,t,{platform:n=process.platform,serviceStatus:r=qC}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return en("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 en("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 en("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 en("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 en("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function mZ(e){return en(e.id,e.title,e.status,`Failing since ${ao(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function dd(e,t,n){try{return await n()}catch(r){return en(e,t,"failed",Uj(r),null)}}function en(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,eZ),remedy:o?String(o).slice(0,tZ):null}}function Uj(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import AZ from"node:path";N();import gZ from"node:path";var qj=2,wZ=300*1e3,yZ={pytest:40,"node:test":40,vitest:60,jest:60},_Z=3,vZ=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),bZ=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),Fj=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 rm(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function zj(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function kZ(e){let t=String(e?.name??"");return bZ.has(t)?{support:"helper"}:vZ.has(t)?{support:"run"}:Fj.has(t)?{support:"skipped",reason:Fj.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var ub=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),SZ=(e,t)=>!t||e.startsWith(`${t}/`);function xZ(e,t){let n=null;for(let r of t)r.name!==e.framework||!SZ(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function EZ(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 Bj({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(ub)):null,i=[];for(let l of e){let u=kZ(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:ub(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:ub(u.file)})))s&&!s.has(l.file)||xZ(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=$Z(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(_Z,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function $Z(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:[]}]:EZ(e.files,{perShard:yZ[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var TZ=3;function om(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=_$(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&&rm(e),quality_baseline_contract:qj,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_scenarios:dI,bug_hunt_performance:1,bug_hunt_specialists:1,bug_hunt_actions:[...vh],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Ca(n),bug_hunt_sign_in:Oa,bug_hunt_inputs:1,bug_hunt_checks:[...Av],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_recovery:e.hunt_host?0:1,goal_run_contract:TZ,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.61",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:ch,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:AZ.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...Lu(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...DR(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();dn();sa();import{createHash as Gj}from"node:crypto";import{readFile as RZ}from"node:fs/promises";import OZ from"node:os";import pb from"node:path";var CZ=/^[A-Z_][A-Z0-9_]*$/,IZ=80,jZ=64,Hj="hunt-secret-";function fd(e){return typeof e=="string"&&e.length>0&&e.length<=IZ&&CZ.test(e)}function sm(e){let t=`${Hj}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=jZ?t:`${Hj}h${Gj("sha256").update(String(e)).digest("hex").slice(0,40)}`}function NZ(e){let t=Gj("sha256").update(pb.resolve(e??process.cwd())).digest("hex").slice(0,16);return pb.join(OZ.homedir(),".engineeros","hunt-secrets",t)}function db(e){if(!fd(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function hd({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??NZ(e),o=t??or({directory:r}),s=pb.join(r,"names.json");async function i(){let u;try{u=await RZ(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(fd)}catch{return[]}}let a=Promise.resolve(),c=u=>{let d=a.then(async()=>{let p=new Set(await i());u(p),await De(s,`${JSON.stringify({names:[...p].sort()},null,2)}
|
|
2641
2641
|
`)});return a=d.catch(()=>{}),d},l={directory:r,async get(u){db(u);let d=await o.get(e,sm(u));return typeof d=="string"&&d!==""?d:null},async set(u,d){if(db(u),typeof d!="string"||d==="")throw new Error("A secret needs a value.");await o.put(e,sm(u),d),await c(p=>p.add(u))},async remove(u){db(u),await o.delete(e,sm(u)),await c(d=>d.delete(u))},async names(){return(await i()).sort()},async has(u){return fd(u)?!!await o.has(e,sm(u)):!1},async values(u){let d={};for(let p of[...new Set(u??[])]){if(!fd(p))continue;let f=await l.get(p);f!==null&&(d[p]=f)}return d}};return l}async function Wj({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 pd=(e,t)=>(t?.(e),{ok:!1,message:e});async function Vj({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 pd("Use `secret set NAME`, `secret list` or `secret remove NAME`.",i);let c=hd({workspace:n,vault:o,directory:s});try{if(e==="list"){let d=await c.names();return a(!0,d.length?d.join(`
|
|
@@ -2855,7 +2855,7 @@ It is checked with the provider and stored in this machine's protected vault
|
|
|
2855
2855
|
(Windows Data Protection, the macOS Keychain or the Linux Secret Service).
|
|
2856
2856
|
EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function gie(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(`
|
|
2857
2857
|
`),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
|
|
2858
|
-
`)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 hD=Symbol("missing");function wie(e,t){return new Promise(n=>{let r=hie(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?hD:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function fD(e,t){for(let n of jd){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 mD(e,t,n,{vault:r=b0(),run:o=Fm,fetchImpl:s=fetch,secret:i=gie,interactive:a=wie,install:c=Mm,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(mie),n.help?0:2;if(e==="integrations")return fD(l,(await Bm({run:o,vault:r})).providers),0;let d=t[0];if(!jd.includes(d))return u(`Unknown provider ${d}. Choose one of: ${jd.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=La[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===hD){let _=await Hi(f);if(!_){l(`Installing the ${$d[f].label} ${$d[f].version} for the connector...`);try{_=(await c(f)).path}catch(y){return u(y.message),1}}g=await a(_,["auth","login"])}return g?(u(`${g} ${zm[d]} is how this machine signs in to ${d}.`),1):(fD(l,{[d]:(await Bm({run:o,vault:r})).providers[d]}),0)}let p=er[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await k0(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),g=await S0(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 yie}from"node:child_process";async function gD({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=yie,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ai(await wr(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await _ie(o,c.entry,i,t);if(l===Cl){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 wr(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await xg(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 _ie(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Ya]:"1",[_g]:r.entry,[vg]: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 Ki="1.59.
|
|
2858
|
+
`)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 hD=Symbol("missing");function wie(e,t){return new Promise(n=>{let r=hie(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?hD:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function fD(e,t){for(let n of jd){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 mD(e,t,n,{vault:r=b0(),run:o=Fm,fetchImpl:s=fetch,secret:i=gie,interactive:a=wie,install:c=Mm,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(mie),n.help?0:2;if(e==="integrations")return fD(l,(await Bm({run:o,vault:r})).providers),0;let d=t[0];if(!jd.includes(d))return u(`Unknown provider ${d}. Choose one of: ${jd.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=La[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===hD){let _=await Hi(f);if(!_){l(`Installing the ${$d[f].label} ${$d[f].version} for the connector...`);try{_=(await c(f)).path}catch(y){return u(y.message),1}}g=await a(_,["auth","login"])}return g?(u(`${g} ${zm[d]} is how this machine signs in to ${d}.`),1):(fD(l,{[d]:(await Bm({run:o,vault:r})).providers[d]}),0)}let p=er[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await k0(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),g=await S0(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 yie}from"node:child_process";async function gD({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=yie,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ai(await wr(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await _ie(o,c.entry,i,t);if(l===Cl){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 wr(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await xg(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 _ie(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Ya]:"1",[_g]:r.entry,[vg]: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 Ki="1.59.61",Km="1.59.61",Sie=3e5,Ym=["queued","running","reporting"],xie=5e3,x0={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."},E0={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."},Eie=6e4,$ie=3e4,Aie=60*6e4,$0={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},A0={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:cn,positional:ln,flags:et}=Jj(process.argv.slice(2));cn==="version"&&(console.log(Ki),process.exit(0));var Ks=null,an=!1,tr=null,Ud=null,CD=!1,ID=null,H0=null,vn=null,Hd=null,U0,wD,Fd,T0,yD,hl,bl,jD=xm({getWorkspace:()=>L.workspace,onRecorded:e=>nM(L,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}`))}),Tie=dD({getWorkspace:()=>L.workspace,getConfig:()=>L,huntSignIns:jD}),qd=Zj();cn==="results"&&(ln[0]!=="upload"&&(console.log(fm),process.exit(et.help||!ln[0]?0:2)),process.exit(await iP(et)));(cn==="connect"||cn==="disconnect"||cn==="integrations")&&process.exit(await mD(cn,ln,et,{fetchImpl:cD}));if(cn==="delivery"){let e=_n.resolve(et.workspace||process.cwd());try{if(ln[0]==="execute")await QC(et.input);else if(ln[0]==="worker"){let t=await Fn(e);if(!t)throw new Error("Restore the paired connector configuration before reporting or executing delivery work.");await RC(t,et["attempt-id"])}else if(ln[0]==="probe"){let t=await lh().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(wn(t)),process.exit(1)}}if(cn==="runner"){let e=_n.resolve(et.workspace||process.cwd()),t=ln[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?_n.join(_n.dirname(hn(e,et["run-id"])),"worker.log"):_n.join(e,".engineeros","runner","service.log");bie(_n.dirname(n),{recursive:!0});let r=(...s)=>Uu(n,`${kie(...s)}
|
|
2859
2859
|
`),o=(s,i,a)=>(Uu(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 Fn(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await Gr({...n,runner_keep_awake:et["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await UC(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 zC(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await Sa(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await Ai(e),null,2)):t==="serve"?await WC(e):t==="worker"?await VC(e,et["run-id"]):tn("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){tn(vv(n,e).message)}}et["assessment-workers"]!==void 0&&tn("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(cn==="secret")try{let e=xv(et),t=ln[0]||"list",n=await Vj({action:t,name:ln[1],workspace:e,readValue:()=>Wj({label:`Value for ${ln[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){tn(e.message)}if(cn==="tools"){try{let e=xv(et),t=ln[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=ln[1];r||tn(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await Hy(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 Fy(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:ln[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await Uy(e,t,ln[1]);let n=await eo(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){tn(e.message)}process.exit(process.exitCode||0)}if(cn==="agents"){let e;try{e=await c_()}catch(n){tn(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await Eu(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(cn==="agent"){let e=ln[0],t=ln[1]||"check";(!e||!["check","install"].includes(t))&&tn("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await $u(e):await Eu(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){tn(n instanceof Error?n.message:String(n))}process.exit(0)}if(cn==="mcp"){let e=et.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=et["run-id"]||ln[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await Fn(e);await gN({config:n,runId:t,version:Ki,input:process.stdin,output:process.stdout}),process.exit(0)}if(cn==="context-mcp"){let e=et["config-workspace"]||et.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await Fn(e);t||tn("This workspace is not paired with EngineerOS."),await KN({config:t,workspace:et.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:Ki,input:process.stdin,output:process.stdout}),process.exit(0)}if(cn==="status"){let e=await Fn(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(cn==="doctor"){let e=_n.resolve(et.workspace||process.cwd()),t=await Fn(e),n=await lN(e),r=await Ha(t||{workspace:e},e,fb(n));console.log(lb(r)),process.exit(r.status==="failed"?1:0)}if(cn==="update"){let e=ln[0]||"status";try{let t=kg(process.argv[1],Km),n=await Eg(Hr(),t,{action:e,policy:ln[1]??null});console.log(jl($g(n,t,{supervised:!0})))}catch(t){tn(`${t.message}
|
|
2860
2860
|
Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var gl=cn==="hunt-host";if(gl){try{et.workspace=nI(ln,et)}catch(e){tn(e.message)}!ln[0]&&_n.resolve(et.workspace)!==_n.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((cn==="start"||cn==="pair"||gl)&&process.env[Ya]!=="1"&&kn(Km))try{process.exit(await gD({root:Hr(),bundled:{version:Km,entry:_n.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:_n.resolve(et.workspace||process.cwd())}))}catch(e){tn(`The connector process could not be started: ${e.message}`)}if(gl){try{await rI(et.workspace,ln[0]?et.agent:null)}catch(e){tn(e.message)}cn=ln[0]?"pair":"start"}var L,Ba,zd;if(cn==="pair"){let e=ln[0];e||tn("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||tn("Pairing requires --url with the EngineerOS backend address."),et.agent&&et["agent-command"]&&tn("Use either --agent or --agent-command, not both.");let n=et["agent-protocol"]||(et["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||tn(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(et.agent||et["agent-command"])&&tn("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{et.agent&&(await Eu(et.agent),r=await l_(et.agent))}catch(o){tn(o instanceof Error?o.message:String(o))}L={server_url:Rg(t),workspace:_n.resolve(et.workspace||process.cwd()),onboard:et.onboard===!0,onboarding_pending:et.onboard===!0,hunt_host:gl,...et["knowledge-dir"]?{knowledge_dir:_n.resolve(et["knowledge-dir"])}:{},agent_protocol:n,agent_command:et["agent-command"]||null,agent_args:Qie(et["agent-args"]),agent_name:et["agent-name"]||null,...r,skip_git_repo_check:gl||et["skip-git-repo-check"]===!0,name:et.name||`${vie.hostname()} - ${_n.basename(_n.resolve(et.workspace||process.cwd()))}`},zd=await Fn(L.workspace),Ba={type:"pair",pairing_code:e,name:L.name,capabilities:{},...Gk(zd,L.server_url)}}else cn==="start"?(L=await Fn(et.workspace||process.cwd()),L||tn("This connector is not paired. Create a pairing command in EngineerOS first."),gl&&!L.hunt_host&&tn("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),et["knowledge-dir"]&&(L={...L,knowledge_dir:_n.resolve(et["knowledge-dir"])},await Gr(L)),L.token||tn("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),Ba={type:"authenticate",connector_id:L.connector_id,token:L.token}):tn("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var ND=JC(L,{reportError:e=>console.error(e)}),Ji=0,Zm=!1,qa=null,dr=new Map,R0=0,O0=new Set,wl=[],nr=new Map,fn,F0,Wm,ws=null,Vm=!1,PD=0,C0=null,I0=[],Jm,MD,Pd=1e3,yl,_D=0,j0=!1,gs=!1,xo,_l=!1,Xm=!1,Qm=!1,q0=0;function Gi(e){return q0+=1,e.finally(()=>{q0-=1})}var ml,Fa=0;function kl({exitCode:e=0}={}){if(Fa=Math.max(Fa,e),ml)return ml;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),ml=Rie().finally(()=>clearTimeout(t)),ml}async function Rie(){if(an=!0,Hd?.stop(),Ks?.stop(),H0?.stop(),ID?.stop(),clearInterval(U0),vn?.stop(),MD?.(),clearTimeout(Jm),clearInterval(F0),clearInterval(Wm),await Promise.all([...[...dr.values()].map(e=>vr(e.child))]),await Promise.all([...nr.values()].map(V0)),await hl?.cancelAll(),await Fd?.stop(),await bl?.abortAll(),await xu(),await yE().catch(e=>{Fa=Math.max(Fa,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),fn?.close(),Fa&&Fa!==Cl){let e;await Promise.race([(async()=>{await Ks?.drain(),await Ha(L,L.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Fa)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{kl()});var vD=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{vD||(vD=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await kl({exitCode:1}))});vn=R$();process.on("exit",()=>{Hd?.stop(),vn.stop()});vn.banner(`EngineerOS connector ${Ki}`,[L.workspace,L.server_url]);Ks=Yj({actions:{refresh_tool_inventory:async()=>{mt.tool_inventory=await eo(L.workspace),Mr()},restart_goal_runner:()=>Sa(L.workspace)},onNotify:()=>Ha(L,L.workspace),explain:async e=>{if(!await Js())return null;let{reading:t}=await BO(L,e);return t},onUpdate:e=>cN(L.workspace,e)});ID=dN({render:(e,t)=>vn.write(e,t),onRecord:e=>Ks.observe(e)});H0=pN({workspace:L.workspace,onRecord:e=>{Ks.observe(e),vn.line(e.channel,e.level,e.message)}});Ks.start();L.hunt_host||H0.start();vn.live&&!L.hunt_host&&(U0=setInterval(()=>{Oie().catch(()=>{})},xie),U0.unref?.());var N0=new Set;async function Oie(){if(L.hunt_host)return;wD??=wv(L.workspace);let{jobs:e}=await wD(),t=new Set,n=e.filter(r=>r.status!=="queued"&&Ym.includes(r.status)).length;for(let r of e){if(!Ym.includes(r.status))continue;t.add(r.runId),N0.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;vn.status(`goal:${r.runId}`,r.activity?.message||o,Cie(r),{agent:r.status!=="queued",link:qa&&`${qa}/goals`,phase:o}),vn.step(`goal:${r.runId}`,r.activity?.message)}for(let r of N0)t.has(r)||(N0.delete(r),vn.clearStatus(`goal:${r}`))}function Cie(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function Js({ignoreBugHunt:e=!1}={}){if(an||dr.size>0||nr.size>0||Ji>0||(hl?.active??0)>0||(Fd?.active??0)>0||!e&&(bl?.active??0)>0)return!1;try{let{jobs:t}=await Ai(L.workspace);return!an&&!t.some(n=>Ym.includes(n.status))}catch{return!1}}try{let e=L.hunt_host?{}:await ri(L.workspace);e.committed&&(L.onboarding_pending=!0,L.connector_id&&await Gr(L),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await BD(e)}var DD=await wr(Hr()).then(e=>e.policy!=="manual",()=>!1),Bt;try{Bt=await Mu(L,L.workspace)}catch(e){await BD(e)}console.log(`Using ${Bt.name} through ${Bt.protocol} (${Bt.version}).`);console.log(`System time: ${ao()} (${Intl.DateTimeFormat().resolvedOptions().timeZone}).`);var LD=async()=>hd({workspace:L.workspace}).names().catch(()=>[]),mt=om(L,Bt,await eo(L.workspace),{secretNames:await LD()}),Xs=Ck({workspace:L.workspace,running:kg(process.argv[1],Km),supervised:process.env[Ya]==="1",isIdle:async()=>!an&&dr.size===0&&wl.length===0&&nr.size===0&&Ji===0&&q0===0&&!_l&&!Qm&&(bl?.active??0)===0&&(Fd?.active??0)===0&&!Vm,restart:()=>kl({exitCode:Cl}),onChange:e=>{mt.runtime_update=e,fn?.readyState===WebSocket.OPEN&&Mr()}});try{await Xs.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}L={...L,execution_profiles:Bt.executionProfiles??null};cn==="pair"&&zd?.connector_id||await Gr(L);mt.agent_session={...mt.agent_session,status:"checking",message:`Checking that ${Bt.name} can answer.`};mt.bug_hunt_browser=!1;Ba.capabilities=mt;console.log(js(L.worker_limit)===null?`Workers: automatic, ${Ic()} ${Bt.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${js(L.worker_limit)} ${Bt.name} workers side by side, set with /workers.`);var Bd=_d({getConfig:()=>L}),Sl=async e=>{let t;try{t=await Ps(L,e)}catch(n){throw[401,403].includes(n.status)&&(gs=!0,console.error("EngineerOS withdrew this connector's authorization. Local work is stopping; saved reports are retained."),kl()),n}return t?.execution_sync&&await Iie(t.execution_sync),t},bD=nh(Sl,{signature:nC}),vl=Rj({getConfig:()=>L,send:Sl,onRetained:({status:e,file:t,reason:n})=>console.error(`Prompt result ${e==="pending"?"saved for automatic delivery":"rejected; original evidence retained"}: ${t}${n?` (${n})`:""}`)}),z0=Oj({capacity:()=>Lu(L.worker_limit).worker_limit-dr.size}),P0,M0=!1,Nd,Dd=new Map,B0=new Set,D0;function Vi(){return Fd??=hP({getConfig:()=>L,jobStore:Bd,canRun:()=>Js()}),bl??=MM({getConfig:()=>({...L,tool_inventory:mt.tool_inventory}),jobStore:Bd,recordedSignIns:jD,isIdle:()=>Js({ignoreBugHunt:!0}),canRun:async e=>{if(!await Js({ignoreBugHunt:!0}))return!1;let t=e.assignment;return t.kind!=="production_check"&&tr?.state!=="ready"?!1:t.surface?.app_surface==="webdriver"||mt.bug_hunt_browser===!0},activity:{status:vn.status,step:W0,agents:vn.agents,finish:vn.finish}}),{scheduledTests:Fd,bugHunts:bl}}async function Iie(e){let t=Vi(),n=[];for(let r of e.jobs??[])await Bd.get(r.kind,r.id)&&n.push(r);await Promise.all([t.bugHunts.sync(n),t.scheduledTests.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}`;B0.has(o)||Dd.set(o,r)}UD()}function UD(){D0||an||(D0=(async()=>{let e=Vi();for(;Dd.size&&!an;){let[t,n]=Dd.entries().next().value;Dd.delete(t),B0.add(t);try{if(n.type==="bug_hunt.grant")await e.bugHunts.configure(n);else if(n.type===ym)await e.scheduledTests.configure(n);else if(n.type===Kb)await e.bugHunts.handle(n);else if(n.type===wm)await e.scheduledTests.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{B0.delete(t)}}})().finally(()=>{D0=null}))}async function FD(){if(!(!L.connector_id||!L.token||an))return Nd||(Nd=(async()=>{let e=Vi();await Promise.all([e.bugHunts.start(),e.scheduledTests.start()]);let t=await Bd.list();for(let n of t)if(n.kind==="bug_hunt_grant"&&n.status==="provisioning"){let r=n.checkpoint?.pending_context??n.assignment;Dd.set(`bug_hunt.grant:${n.id}`,r)}UD(),t.some(n=>["authorized","queued","running"].includes(n.status)&&Date.parse(n.execution_lease.expires_at)>Date.now())&&(GD(),tg()),Wie()})().catch(e=>{throw Nd=null,e}),Nd)}async function jie(){let e=await Ai(L.workspace).catch(()=>({service:null,jobs:[]}));return{version:Ki,now:Date.now(),workspace:L.workspace,config_path:Un(L.workspace),config:L,agent:Bt,automatic_worker_limit:Ic(),worker_limit:js(L.worker_limit),connection:{state:Nie(),server_url:L.server_url,last_error:xo||null},work:{assessments:[...dr.values()].map(t=>({stage:t.stage,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:Bt.name})),prompts:[...nr.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:Bt.name})),integrations:Ji},runner:e,runtime_update:Xs.report(),health:Ks?.health()??null,activity:qd.snapshot()}}function Nie(){return an||gs?"stopped":fn?.readyState===WebSocket.OPEN?"connected":"connecting"}var Pie={async cancelPrompt(e){let t=[...nr.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=>zD(e),setVerbose(e){return e===Zm?`Detailed agent activity is already ${e?"on":"off"}.`:(G0(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"?(Xs.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 Xs.command(e),jl(await Xs.refresh()))}};Hd=nN({ui:vn,snapshot:jie,actions:Pie});Hd&&console.log(tN());await qD();var kD=new Set;async function qD(){if(an||gs)return;console.log(`Connecting ${L.name} to ${L.server_url}`),gs=!1,xo=void 0;let e=new WebSocket(L.server_url);fn=e;let t=S$(e,L.server_url,{onTimeout:r=>{fn===e&&(xo=r,console.error(r),L0())}});MD=t,e.addEventListener("open",()=>{if(fn!==e){e.close();return}try{if(w$(fn,e,Ba))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){xo=wn(r),console.error(`Could not authenticate the WebSocket connection: ${xo}`);try{e.close()}catch{}L0()}}),e.addEventListener("message",r=>{if(fn!==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: ${wn(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){an=!0,gs=!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=zd?.connector_id===r.connector.id;if(L=Wk(L,zd,r.connector.id,r.token),await Gr(L),r.connector?.capabilities?.http_updates!==!0){an=!0,gs=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}Ba={type:"authenticate",connector_id:L.connector_id,token:L.token,capabilities:mt},console.log(s?`Reconnected existing workspace connector ${L.connector_id}; assessment history is preserved.`:`Paired. Connector ${L.connector_id} is online.`),$D(r);return}if(r.type==="authenticated"){t();let s=L.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(yl?`Reconnected after ${Ct(Date.now()-yl)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),yl=void 0,$D(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){Qm||Die(r);return}if(r.type==="workspace.refresh"){za();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await zD(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){G0(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(Vs=!1,mt.bug_hunt_browser=!1,Mr());try{mt.tool_inventory=await Fy(L.workspace,r,void 0,{confirmLocal:i=>Hd?.confirm(i)??!1,log:Ld}),s&&(Vs=!0),mt.bug_hunt_browser=Ca(mt.tool_inventory)&&Vs,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:mt.tool_inventory})),Mr(),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 Hy(L.workspace,r,{onStatus:async()=>{mt.tool_inventory=await eo(L.workspace),Mr()}});mt.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:mt.tool_inventory})),Mr(),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"){fi(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===uD){Gi(Tie(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),pD(L,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}`;G_(wl,dr.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Xi();return}if(r.type==="prompt.execute"){let s=nr.get(r.prompt_id);s?JD(r)>s.executionRevision&&await Xie(s,r):!await vl.replay(r)&&!nr.has(r.prompt_id)&&VD(r);return}if(r.type==="prompt.cancel"){let s=nr.get(r.prompt_id);s&&await V0(s);return}if(r.type==="agent.warm"){zie(r);return}if(r.type==="run.available"){if(L.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await ND.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${_n.join(L.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${wn(s)}`)}return}if(r.type==="delivery.task.start"||r.type==="delivery.task.cancel"){if(L.hunt_host)throw new Error("Pair a repository connector before dispatching delivery tasks.");await AC(L.workspace,L.connector_id,r),await Sa(L.workspace);return}if(r.type==="goal.cleanup"){try{await GC(L.workspace),await Sa(L.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){Zie(r);return}if(r.type==="run.cancelled"){await gv(L.workspace,r.run_id);return}if(r.type===AA){hl??=yy({getConfig:()=>L,onTestsCommitted:()=>za()}),Gi(hl.handle(r));return}if(r.type===TA){hl??=yy({getConfig:()=>L,onTestsCommitted:()=>za()}),await hl.cancel(r);return}if(r.type===Kb){Gi(Vi().bugHunts.handle(r)).catch(s=>console.error(`Bug Hunter assignment: ${s.message}`));return}if(r.type==="bug_hunt.grant"){Gi(Vi().bugHunts.configure(r)).catch(s=>console.error(`Bug Hunter settings: ${s.message}`));return}if(r.type===TM){bl?.stop(r);return}if(r.type===wm){Gi(Vi().scheduledTests.handle(r)).catch(s=>console.error(`Scheduled test assignment: ${s.message}`));return}if(r.type===ym){Gi(Vi().scheduledTests.configure(r)).catch(s=>console.error(`Scheduled test settings: ${s.message}`));return}if(r.type===_P){T0??=TP({getConfig:()=>L}),Gi(T0.handle(r));return}if(r.type===vP){await T0?.cancel(r);return}if(r.type===OP){yD??=CP({getConfig:()=>L,isIdle:()=>Js(),agentTurn:hO}),Gi(yD.handle(r));return}if(r.type==="connector.update"){Mie(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await kl();return}if(r.type==="connector.revoked"){an=!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"){gs=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);kD.has(o)||(kD.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${Ki}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),fn!==e||ml)return;let o=y$(r);if(!o.retry||gs||an){console.error(o.message),o.retry&&gs&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),kl();return}xo=xo?`${o.message} ${xo}`:o.message,L0()}),e.addEventListener("error",r=>{fn===e&&(xo=g$(r),console.error(`WebSocket connection to ${L.server_url} failed: ${xo}`))})}async function Mie(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=Xs.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 Xs.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 Die(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";Qm=!0,console.log(`Starting interactive ${Bt.name} provider ${n}.`);try{await(n==="logout"?k$:b$)(Bt,L.workspace),Bt=await Mu(L,L.workspace),tr=null,mt=om(L,Bt,mt.tool_inventory,{secretNames:await LD()}),Ba.capabilities=mt,fn.readyState===WebSocket.OPEN&&(fn.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:mt.agent_session})),fn.close(1e3,`Provider ${n} completed`)),console.log(`${Bt.name} provider ${n} completed.`)}catch(r){let o=wn(r).slice(0,500);fn.readyState===WebSocket.OPEN&&fn.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{Qm=!1}}function L0(){if(an||gs||Jm)return;let e=xo?` Last error: ${xo}`:"",t=yl?` Offline for ${Ct(Date.now()-yl)}.`:"";yl??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(Pd/1e3)}s.`),Jm=setTimeout(()=>{Jm=void 0,qD()},Pd),Pd=Math.min(3e4,Pd*2)}async function za(){if(!L.hunt_host&&(Xm=!0,!(_l||an||fn.readyState!==WebSocket.OPEN))){Xm=!1,_l=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await JO(L.workspace),t=await VO(L.workspace,L.last_head_reported??L.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(yr(L.server_url,L.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.token}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(await mc(n,"the workspace"));let r=await n.json(),o=r.source_revision;L={...L,onboarding_pending:!1,last_snapshot_head:e.head_revision??L.last_snapshot_head,last_head_reported:e.head_revision??L.last_head_reported,last_head_branch:e.head_revision?e.branch??null:L.last_head_branch},await Gr(L),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 vb({workspace:L.workspace,connectorId:L.connector_id,snapshot:e,refresh:sc,buildMap:(a,c)=>um(L.workspace,a,{head:c.head_revision,branch:c.branch}),log:a=>console.error(a)});if(s&&o){let a=await fetch(Xk(L.server_url,L.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.token}`},body:JSON.stringify({source_revision:o,quality_map_base64:s.base64})});a.ok?await dm(L.workspace,L.connector_id,s.map).catch(()=>{}):console.error(await mc(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: ${wn(e)}`)}finally{_l=!1,Xm&&!an&&fn.readyState===WebSocket.OPEN&&za()}}}var Lie=8e6,SD,xD="";async function Uie({current:e,previous:t}){if(_l||fn?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=_n.resolve(L.workspace),r=async()=>{L={...L,last_head_reported:e.head,last_head_branch:e.branch??null},await Gr(L)},o=await _b(L.workspace,L.connector_id),s=async()=>{if(await za(),L.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let i,a=async()=>(i??=sc(L.workspace,L.connector_id),(await i).index),c=null,l=await UN({previous:{head:t.head,branch:t.branch??null},current:e,compare:(f,g)=>Z_(L.workspace,f,g),inventoryDelta:async f=>{let g=await a();return DS(n,Object.entries(g.files).map(([_,y])=>({path:_,size:y.size})),f)},mapDelta:async()=>{let f=await a();return c=await um(L.workspace,f,{head:e.head,branch:e.branch}),yb(o,c)},contentHead:(await Pp(n).catch(()=>null))?.content_head_revision??null});if(l.status==="snapshot")return s();let u=JSON.stringify(l.report);if(Buffer.byteLength(u)>Lie)return s();let d=await fetch(Kk(L.server_url,L.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.token}`},body:u});if(!d.ok)throw new Error(await mc(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 dm(L.workspace,L.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 Fie(){L.hunt_host||L.onboarding_pending||_l||fn?.readyState!==WebSocket.OPEN||(SD??=LN({readHead:()=>DN(L.workspace),getLastReported:()=>({head:L.last_head_reported??L.last_snapshot_head,branch:L.last_head_branch}),onChange:Uie,onError:e=>{e.message!==xD&&(xD=e.message,console.error(`The new commit could not be reported yet: ${wn(e)}`))}}),SD.poll().catch(()=>{}))}var qie=6e4,ED=0;async function zie(e){if(L.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?L.sessions?.[t]:void 0,r=[];Date.now()-ED>qie&&(ED=Date.now(),r.push(sc(L.workspace,L.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),L.agent_protocol==="acp"&&r.push(wR(L.workspace,L,{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(`${Bt?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Mr(){an||!L.connector_id||!L.token||(M0=!0,!P0&&(P0=(async()=>{do M0=!1,await Bie();while(M0&&!an)})().catch(e=>console.error(`Connector synchronization: ${wn(e,{network:!0})}`)).finally(()=>{P0=null})))}async function Bie(){let e=jO(dr),t=await Bd.snapshot();bD.update({type:"assessment.workers",assessment_workers:e,tool_inventory:mt.tool_inventory,runtime_update:mt.runtime_update,agent_session:mt.agent_session,bug_hunt_browser:mt.bug_hunt_browser,connector_jobs:t.jobs,...Lu(L.worker_limit)}),await bD.flush()}async function zD(e){let t=js(e);return t===js(L.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(L={...L,worker_limit:t},await Gr(L),Xi(),Mr(),t===null?`Workers are automatic again: up to ${Ic()} side by side for this machine's CPU and memory, for ${gd} (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: ${gd}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function G0(e){if(e!==Zm){if(Zm=e,!e)for(let t of dr.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."),Mr()}}function W0(e,t,n=null){vn.step(e,t,n)&&Zm&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function Hie(){clearInterval(Wm);let e=!1,t=()=>{e||dr.size>0||nr.size>0||(e=!0,Ha(L,L.workspace).finally(()=>{e=!1}))};t(),Wm=setInterval(t,Sie),Wm.unref?.()}async function Ha(e,t,n=Ks?.healthChecks()??[]){let r=await Dj({config:e,workspace:t,version:Ki,insights:[...n,...Ud?[Ud]:[]],agentSession:tr,probes:{inspectAgent:(o,s)=>an?Bt:Mu(o,s),inspectTools:o=>an?mt.tool_inventory:eo(o),runnerStatus:Ai,connectorJobs:()=>_d({getConfig:()=>e}).list()}});try{CD=(await Lj(e,r,Ps))?.autonomy_scan===!0}catch(o){console.error(`Connector self-check reporting failed: ${wn(o,{network:!0})}`)}return r}async function BD(e){if(an)return ml;let t=e instanceof Error?e.message:String(e),n=await Ha(L,L.workspace).catch(()=>null);n&&console.error(lb(n)),tn(t)}function $D(e){vl.flush().catch(t=>console.error(`Saved prompt result delivery: ${t.message}`)),G0(e.connector?.activity_log_enabled===!0),qa=e.project_url??null,Pd=1e3,GD(),tg(),Xs.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),FD().catch(t=>console.error(`Saved connector work: ${t.message}`)),(L.onboarding_pending||Xm)&&za()}var Md=null,Vs=!1,HD=0,Gie=Date.now();async function GD(){return Md||(Md=(async()=>{DD&&await QT(L.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Ld("Preparing Bug Hunter's Playwright runtime; missing browser dependencies are installed automatically.");let{diagnostics:t}=await Su(L.workspace,{log:Ld});mt.bug_hunt_browser_diagnostics=t,Vs=!0,Ud=null,mt.tool_inventory=await eo(L.workspace),mt.bug_hunt_browser=Ca(mt.tool_inventory)&&Vs,Ld(`Bug Hunter's browser is ready (${Ct(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${Ct(Date.now()-e)}: ${t.message}`),mt.bug_hunt_browser=!1,Ud={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."},Ha(L,L.workspace).catch(()=>null)}Mr()})(),Md)}function Ld(e){console.log(`[browser] ${e}`)}async function tg(){if(!["checking","ready"].includes(tr?.state)){HD=Date.now(),mt.agent_session={...mt.agent_session,status:"checking",message:`Checking that ${Bt.name} can answer.`},Mr(),tr={state:"checking",detail:`Asking ${Bt.name} one question to confirm its session.`},console.log(`Checking that ${Bt.name} can answer before accepting work.`);try{await LO(L,Bt.name),tr={state:"ready",detail:`${Bt.name} answered; its session is usable.`},mt.agent_session={...mt.agent_session,status:"authenticated",message:tr.detail},console.log(tr.detail)}catch(e){tr={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:L.hunt_host?sI(L.agent_id||L.agent_protocol):Ac(L.agent_id||L.agent_protocol)},mt.agent_session={...mt.agent_session,status:"logged_out",message:tr.remedy},console.error(`${tr.detail}
|
|
2861
2861
|
${tr.remedy}`)}Mr(),tr.state==="ready"&&(Xi(),Vi().bugHunts.wake().catch(e=>console.error(`Bug Hunter local scheduler: ${e.message}`))),await Ha(L,L.workspace).catch(()=>null)}}function Wie(){clearInterval(F0);let e=!1,t=0,n=0,r=!1,o=()=>{fn?.readyState===WebSocket.OPEN&&vl.flush().catch(s=>console.error(`Saved prompt result delivery: ${s.message}`)),Xs.tick(),Vie(),Fie(),Md&&(tr===null||L.hunt_host&&tr?.state==="failed"&&Date.now()-HD>=oI(Gie))&&Js().then(s=>{if(s)return tg()}),!L.hunt_host&&!r&&ud(A0.id)&&(r=!0,ND.flush().then(()=>Gm(A0)).catch(s=>Hm(A0,s)).finally(()=>{r=!1})),Mr(),!L.hunt_host&&!ws&&Date.now()-t>=Eie&&ud(x0.id)&&(t=Date.now(),WD().then(()=>Gm(x0)).catch(s=>Hm(x0,s))),!L.hunt_host&&CD&&!Vm&&ud(E0.id)&&Date.now()-PD>=cT&&(Vm=!0,Jie().then(()=>Gm(E0)).catch(s=>Hm(E0,s)).finally(()=>{Vm=!1})),!e&&Date.now()-n>=$ie&&ud($0.id)&&(e=!0,n=Date.now(),eo(L.workspace).then(async s=>{if(mt.tool_inventory=s,!Vs&&Ca(s))try{let{diagnostics:i}=await Su(L.workspace,{log:Ld});mt.bug_hunt_browser_diagnostics=i,Vs=!0}catch{Vs=!1}mt.bug_hunt_browser=Ca(s)&&Vs,mt.bug_hunt_browser&&(Ud=null),Mr(),Gm($0)}).catch(s=>Hm($0,s)).finally(()=>{e=!1}))};o(),F0=setInterval(o,1e4),Hie()}async function Vie(){if(!(!DD||L.agent_protocol!=="acp"||!L.agent_id||j0||tr?.state==="checking"||Date.now()-_D<Aie)){j0=!0;try{if(!await Js())return;_D=Date.now();let e,t=await ER(L,{verify:async r=>{e=await Mu(r,L.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===L||an)return;L={...t,execution_profiles:e.executionProfiles??null},await Gr(L),Bt=e,tr=null;let n=om(L,Bt,mt.tool_inventory);if(Object.assign(mt,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),Ba.capabilities=mt,!await Js())return;await xu(),tg(),fn?.readyState===WebSocket.OPEN&&fn.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{j0=!1}}}function Hm(e,t){let n=Cj(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 Gm(e){Ij(e.id)&&console.log(`${e.title} recovered.`)}async function Jie(){if(L.hunt_host||!await Js())return;PD=Date.now();let{jobs:e}=await Ai(L.workspace).catch(()=>({jobs:[]})),t=await lT(L.workspace,{jobs:e});if(!uT(t))return;let n=`${t.fingerprint}:${I0.join(",")}`,r=C0?.key===n,o=r?C0.candidates:await HO(L,t,I0);C0={key:n,candidates:o};let s=await Sl(fT(t,o,{version:Ki}));Array.isArray(s?.refused)&&(I0=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 Wi=null,AD=null;async function WD(){if(!L.hunt_host){if(ws)return ws;ws=(async()=>{let e=await eT(L,{knownRevision:Wi?.revision??null});if(e.unchanged||(Wi=e),AD===Wi.revision)return Wi;let{jobs:t}=await Ai(L.workspace);return!t.some(r=>Ym.includes(r.status))&&Ji===0&&dr.size===0&&(await _f(L.workspace,Wi),AD=Wi.revision),Wi})();try{return await ws}finally{ws=null,Xi()}}}function TD(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)),nr.get(e)?.events.push(n)}var RD=null;function Xi(){z0.drain();let e=fn.readyState===WebSocket.OPEN,t=dr.values().next().value,n=js(L.worker_limit)??Math.min(Ic(),W_(t?.workerLimit??wl[0]?.worker_limit)),r=e&&!ws&&Ji===0?xO(wl,dr.size,Math.max(0,n-z0.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:W_(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};dr.set(i,a),Yie(s,a)}r.length>0&&Mr();let o=EO({queued:wl,running:dr.size,workerLimit:n,connected:e,designSync:!!ws,integrations:Ji});o&&o!==RD&&console.log(o),RD=o}function eg(e){let t=V_(e);return t?`${Bt.name} on ${t}`:Bt.name}async function VD(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s=`${r} \xB7 ${eg(e)}`,i=DO(e,Bt.name),a={runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:aC(Sl),executionRevision:JD(e),sessionKey:eh(e),sessionId:null,phase:"preparing",lastMessage:s,replacement:null};nr.set(t,a);let c=!1,l,u=iC(Sl,{type:"prompt.heartbeat",prompt_id:t,execution_revision:a.executionRevision},{onError:w=>{c&&_i(w)||console.error(`[${n}] Prompt heartbeat: ${w.message}`)}}),d,p=w=>{let h=w?JSON.stringify(w):null;c||!h||h===d||nr.get(t)!==a||(d=h,TD(t,w))},f=Number(e.answer_within_seconds),g=f>0?o+f*1e3:void 0;console.log([`[${n}] ${i} for ${r}.`,`${Bt.name} can reason for several minutes without reporting a step.`,...g?[Xw(g,o)]:[]].join(" ")),TD(t,{kind:"status",message:i}),vn.status(n,s,o,{link:qa,answerBy:g,phase:a.phase});let _=w=>{if(c)return;let h=bO(w),m=vO(w),S=wa(w);nr.get(t)===a&&(m&&(a.phase=m),(S??h?.message)&&(a.lastMessage=S??h?.message),vn.status(n,a.lastMessage,o,{link:qa,answerBy:g,phase:a.phase}),W0(n,S??h?.message));let x=w.type==="forge.output"?null:S;p(h??(x?{kind:"status",message:x}:null))},y="failed",v=[r],k;try{k=await z0.acquire({signal:a.cancellation.signal,onWaiting:()=>_({type:"connector.step",message:"Waiting for an available connector worker"})}),th(e)||(_({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await sT(WD,{pinned:!!e.local_design_context,last:Wi,onFallback:(x,b)=>_({type:"connector.step",message:`Design context not refreshed (${x.message}); continuing with ${b?"the copy synced earlier":"none"}`})})});let w=await pO(e,L,{onProcess:x=>{nr.get(t)===a&&(a.child=x)},onController:x=>{nr.get(t)===a&&(a.controller=x)},onSession:x=>{a.sessionId=x},onEvent:_},{signal:a.cancellation.signal});if(k(),Xi(),a.stoppedHere)throw new Error(OD);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 vl.save(h),c=!0,a.events.stop(),l=u.stop(),a.phase="delivering",a.lastMessage="Delivering completed response",vn.status(n,a.lastMessage,o,{link:qa,phase:a.phase,agent:!1});let m=w.singleTurn?Vk(L.sessions,w.sessionKey):Og(L.sessions,w.sessionKey,w.sessionId);if(JSON.stringify(m)!==JSON.stringify(L.sessions||{})&&(L={...L,sessions:m},await Gr(L)),a.cancelled)return;let S=await vl.deliver(h);qd.record("prompt","completed",{durationMs:Date.now()-o,usage:w.usage}),y=S.status==="delivered"?"finished":"undelivered",v=[Kp(w.usage),r]}catch(w){let h=a.stoppedHere?OD:wn(w);if(qd.record("prompt","failed",{durationMs:Date.now()-o}),a.stoppedHere&&(y="cancelled"),!a.cancelled&&!c){try{await vl.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&&(y="undelivered",console.error(`[${n}] ${h} The original completed result remains saved for delivery.`))}finally{k?.(),Xi(),await(l??u.stop()),a.events.stop();let w=a.replacement;w?(y="replaced",v=[`continuing on ${eg(w)}`,r]):a.cancelled&&(y="cancelled"),vn.finish(n,y,v),nr.get(t)===a&&nr.delete(t),w&&Kie(a,w)}}var OD="Cancelled from the connector terminal by the person running it.";async function V0(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function JD(e){return Number(e.execution_revision)||1}async function Xie(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 ${eg(t)}.`),await V0(e))}function Kie(e,t){e.sessionId&&(L={...L,sessions:Og(L.sessions,e.sessionKey,e.sessionId)},Gr(L).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),VD(t)}async function Yie(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 ${eg(e)}.`),!O0.has(n)){O0.add(n);try{let m=await wO(L.workspace);if(!m.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let S=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). ${S}`)}}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,_=()=>!an&&dr.get(t.key)===t,y=async m=>{try{return await oC(Sl,m)||console.warn(`[${s}] ${rC}`),!0}catch(S){return console.error(`Assessment failure delivery: ${S.message}`),!1}},v=(m,{milestone:S=!0}={})=>{if(!_()||S&&f===m)return;S&&(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,vn.status(s,x,o,{link:qa,phase:t.phase,agent:!a})};v(`Starting ${r} assessment stage`);let k=setInterval(()=>{let m=Date.now(),S=m-t.lastActivityAt,x=i&&!a?_O(r,S):null;if(!d&&x){d=x,console.error(`[assessment:${r}] ${d}`),Y_(t.controller,t.child);return}d||Ks.observe({at:m,level:"info",message:vn.status(s,`${t.lastMessage} \xB7 last agent activity ${Ct(S)} ago (${t.eventCount.toLocaleString()} events)`,o,{phase:t.phase,agent:!a})})},15e3),w={onSession:async m=>{_()&&(p=String(m),await Vx(L.workspace,n,r,m,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:m=>{_()&&(t.controller=m)},onProcess:m=>{_()&&(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 S=yO(m);if(S&&v(S),!_())return;let x=wa(m);!x||x===t.lastDetail||(t.lastDetail=x,W0(s,x))}},h=(m,S)=>B_(m,S,L,w,{draftPath:_n.relative(L.workspace,_n.join(Jr(L.workspace,n),m.report_file)).split(_n.sep).join("/")});try{let m=R0-Date.now();m>0&&(v(`Waiting ${Math.ceil(m/1e3)}s for the model provider's rate limit to clear`),await new Promise(O=>setTimeout(O,m+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,v("Calculating changed files and affected behavior"));let S=await Zx(L.workspace,e),x=await bw(L.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(x)h(x,S),v("Recovered completed stage report from connector storage");else{if(p=await Jx(L.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),p&&v("Restoring interrupted agent session"),x=await dO(S,L,w,{previousSessionId:p}),d)throw new Error(d);a=!0,await vw(L.workspace,n,S,x)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let b=O=>fetch(Zk(L.server_url,L.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.token}`},body:JSON.stringify(O),signal:AbortSignal.timeout(W1)}),E,R=await MO(x,{submit:O=>PO(O,b,{isActive:()=>_()&&!an,readAcknowledgement:async T=>{let j=await T.json();if(r==="synthesis"&&j?.status==="completed"&&(typeof j.report_markdown!="string"||!j.report_markdown.trim().startsWith(`# Workspace Assessment
|