@engineeros/connector 1.59.35 → 1.59.36
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.
|
@@ -967,7 +967,7 @@ ${r}`);if(!s&&c&&i.some(f=>$J.test(f)))return"consent";if(a&&i.some(f=>UO.test(f
|
|
|
967
967
|
`)[0])}`)}let Ke=await Te.text().catch(()=>"");_t();let Rt=null;try{Rt=JSON.parse(Ke)}catch{Rt=null}return z.response={status:Te.status(),text:Ke,json:Rt,ms:c()-Me},{method:ot,url:J}}let ea=async F=>{let le=[...new Set([...String(F??"").matchAll(uX)].map(X=>X[1]))],he=String(F??"");for(let X of le){let ot=f[X];if(ot===void 0||ot==="")throw new We("blocked",`Set ${X} on the hunt host (\`engineeros-connector secret set ${X} --project ${I??"<project id>"}\`).`);let J;try{J=await ff({value:String(ot),now:c,sleep:mn})}catch{throw new We("blocked",`${X} is not a valid authenticator secret.`)}he=he.replaceAll(`{totp:${X}}`,J)}return he};async function Tt(F,le=je,{signingIn:he=!1}={}){if(_t(),z.blockedRequest)throw new We("blocked",z.blockedRequest);let X={action:F.action,target:Hs(await ea(F.target),le),data:Hs(await ea(F.data),le),check:Hs(F.check,le)};if(_t(),X.action==="fill"&&!he&&sO(X.data).blocked)throw new We("blocked",Xy);if(re&&(X.action==="request"&&!/^(GET|HEAD)\s+/i.test(X.target)||["use account","run","open app"].includes(X.action)||X.action==="press"&&/enter/i.test(X.data)))throw new We("blocked","Public pages only permits signed-out browsing and GET or HEAD request steps, without submitting.");if(b){if(!["open","request","wait for"].includes(X.action)||X.action==="request"&&!/^GET\s+/.test(X.target)||X.data)throw new We("blocked","This action is not production-safe.");await mn(1e3)}if(!he){let J=Pr(X,ae);if(J)throw new We("blocked",`Refused by the rule of engagement "${J}".`)}let ot=X.check?Fo(X.check):[];switch(X.action){case"open app":{if(g.app_surface!=="electron")throw new We("blocked","open app requires an Electron or WebDriver hunter.");if(process.env.ENGINEEROS_HUNT_HOST!=="dedicated")throw new We("blocked","Electron requires ENGINEEROS_HUNT_HOST=dedicated on a VM or spare machine.");if(Oe)throw new We("needs_repair","Open the app once per case.");Oe=await y({executablePath:g.app_path,args:g.app_arguments||[],cwd:l}),Y?.aborted&&(await He(),_t()),await Ve();break}case"use account":Kt(await Ur(X.target.trim()));break;case"open":{await Ve();let J=Ue(X.target.trim(),ee),be=Te=>new We("blocked",`${z.account.role}'s recorded sign-in has expired or was signed out: opening ${J} led to ${Te}. Record it again in Bug Hunter Setup.`),ye;try{ye=await z.page.goto(J,{waitUntil:"domcontentloaded",timeout:D.navigation})}catch(Te){let Ke=String(Te.message).split(`
|
|
968
968
|
`)[0];throw z.account?.storage_state&&/ERR_BLOCKED_BY_CLIENT/.test(Ke)?be("another site"):new We("blocked",`Opening ${J} failed: ${Yt(Ke)}`)}if(await It(),z.account?.storage_state&&qO(J,z.page.url(),Z))throw be(Yt(z.page.url(),200));await In({requested:J,reopen:async()=>{ye=await z.page.goto(J,{waitUntil:"domcontentloaded",timeout:D.navigation}),await It()}}),await me();let Me=ye?.status?.()??200;if(Me>=500)throw new We("failed",`The server answered ${Me} for ${J}.`,`server error ${Me}`);break}case"click":case"hover":case"check":case"uncheck":case"fill":case"select":{await Ve();let J=await ao(Mr(X.target));await lo(async()=>{X.action==="click"?await J.click({timeout:D.action}):X.action==="hover"?await J.hover({timeout:D.action}):X.action==="check"?await J.check({timeout:D.action}):X.action==="uncheck"?await J.uncheck({timeout:D.action}):X.action==="fill"?await J.fill(X.data,{timeout:D.action}):await J.selectOption({label:X.data},{timeout:D.action})}),X.action==="click"&&await It();break}case"press":{if(await Ve(),X.target.trim()){let J=await ao(Mr(X.target));await lo(()=>J.press(X.data.trim(),{timeout:D.action}))}else await lo(()=>z.page.keyboard.press(X.data.trim()));await It();break}case"go back":await Ve(),await lo(()=>z.page.goBack({timeout:D.navigation})),await It();break;case"reload":await Ve(),await lo(()=>z.page.reload({timeout:D.navigation})),await It(),await me();break;case"set viewport":{await Ve();let[J,be]=(X.data||X.target).trim().toLowerCase().split("x").map(Number);await z.page.setViewportSize({width:J,height:be});break}case"wait for":await Ve();break;case"request":{await Ve();let{method:J,url:be}=await ur(X.target,X.data);if(z.response.status>=500&&!ot.some(ye=>["status","status_below","status_in"].includes(ye.kind)))throw new We("failed",`The server answered ${z.response.status} for ${J} ${be}.`,`status was ${z.response.status}: ${Yt(z.response.text,200)}`);break}case"poll":{await Ve();let J=c()+(Number(X.data.trim())||XJ)*1e3;for(;;){await ur(X.target,"");let be=[];for(let ye of ot){let Me=await Qi(ye);Me!==null&&be.push(Me)}if(!be.length)break;if(c()>=J)throw new We("failed",`It never answered as expected: ${be.join("; ")}.`,be.join("; "));await mn(KJ)}return Lt()}case"set device":{if(z.page)throw new We("needs_repair","Set the device before opening a page or using an account.");if(g.device_cloud_url){at=X.data.trim(),nt.hasTouch=!0;break}let J=X.data.trim().toLowerCase(),be=Object.entries(m).find(([Te])=>Te.toLowerCase()===J);if(!be)throw new We("needs_repair",`${X.data.trim()} is not a device the browser knows; use a name such as iPhone 13 or Pixel 7.`);let{defaultBrowserType:ye,...Me}=be[1];Object.assign(nt,Me);break}case"tap":{if(await Ve(),!nt.hasTouch)throw new We("needs_repair","tap needs a touch device; set one with set device first.");let J=await ao(Mr(X.target));await lo(()=>J.tap({timeout:D.action})),await It();break}case"set locale":nt.locale=X.data.trim();break;case"set time zone":nt.timezoneId=X.data.trim();break;case"set network":{await Ve();let J=X.data.trim().toLowerCase();Qt.setNetwork(J),await z.context.setOffline(J==="offline"),J!=="offline"&&await(await z.context.newCDPSession(z.page)).send("Network.emulateNetworkConditions",J==="slow"?VJ:JJ);break}case"run":{let J;try{J=Sn(X.target.trim())}catch(Me){throw new We("needs_repair",`\`${X.target}\` cannot run without a shell: ${Me.message}`)}let be=h_.basename(J[0]).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase();if(!Q.has(be))throw new We("blocked",`${J[0]} is not a program this hunter may run (${[...Q].join(", ")||"none are allowed"}).`);let ye=await p(J,{onChild:Mt,cwd:l,timeoutMs:D.command,...u?{env:u}:{},...X.data?{input:X.data}:{}});if(ye.notFound)throw new We("blocked",`${J[0]} is not installed on the hunt host.`);z.command={exitCode:ye.exitCode,output:st(String(ye.output??""))};break}case"use":{let J=ue.get(X.target.trim().toLowerCase());if(J?.builtin==="inbox"){if(!C)throw new We("blocked","The test inbox is not set up on this hunt host.");z.command=await gf(C,X.data,$e);break}if(!J)throw new We("blocked",`${X.target.trim()} is not an instrument approved for this environment (${[...ue.keys()].join(", ")||"none are"}).`);let be=J.env??[],ye=be.filter(cn=>f[cn]===void 0);if(ye.length)throw new We("blocked",`Set ${ye.join(", ")} on the hunt host to use ${J.name}.`);let Me=Object.fromEntries(be.map(cn=>[cn,String(f[cn])])),Te={...le,...Me,data:X.data,since:new Date($e).toISOString()},Ke=(J.command??[]).map(cn=>Hs(String(cn),Te)),Rt=await p(Ke,{onChild:Mt,cwd:l,timeoutMs:D.command,env:{...u??process.env,...Me}});if(Rt.notFound)throw new We("blocked",`${Ke[0]} is not installed on the hunt host.`);let Ht=String(Rt.output??"");for(let cn of Object.values(Me))cn&&(Ht=Ht.replaceAll(cn,"[secret]"));z.command={exitCode:Rt.exitCode,output:st(Ht)};break}case"wait until":{let J=/^step\s+(\d+)$/i.exec(X.target.trim()),be=J?Sc[Number(J[1])-1]:$e;if(be===void 0)throw new We("needs_repair",`wait until counts from step ${J[1]}, which has not run yet.`);let ye=be+(lf(X.data)??0);if(ye-c()>ZJ)throw new We("needs_repair","wait until may wait at most three hours.");ye>c()&&await mn(ye-c());break}case"crawl":{await Ve();let J=Math.min(Number(X.data)||m_,QJ),be=z.account?.role??null,ye=c(),Me=()=>c()<ye+Math.min(D.crawl+z.scanMs,3*D.crawl),Te=W?[]:[{url:Ue(X.target.trim()||"/",ee),from:null,source:"link"}],Ke=[];for(let Ce of xf(oe,ae))try{Ke.push({url:Ue(Ce.path,ee),from:null,source:Ce.source,seed:!0})}catch{}let Rt=Ke.some(Ce=>Ce.url.includes("/#/")),Ht=new Set(V),cn=new Set(V),fi=new Map,Ss=!1,q=new Map,K={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=K;let Se=[],Pe=null,qe=async()=>{let[Ce,Re]=await Promise.all([z.page.title(),z.page.evaluate(Vs)]);return`${Ce??""}\0${Re.elements.join("")}`},lt=async()=>{let Ce=`__engineeros_probe_${Math.random().toString(36).slice(2,8)}`;try{return await z.page.goto(Ue(Rt?`/#/${Ce}`:`/${Ce}`,ee),{waitUntil:"domcontentloaded",timeout:D.navigation}),await It(),await qe()}catch{return!1}};for(;(Te.length||Ke.length)&&K.pages<J&&Me()&&!ke();){_t();let Ce=Ke.length&&(Ss||!Te.length)?Ke.shift():Te.shift();Ss=!Ss;let Re=_r(new URL(Ce.url));if(Re===null)continue;let Ie=Wl(Re);if(Ht.has(Re)||(q.get(Ie)??0)>=tX||(Ht.add(Re),q.set(Ie,(q.get(Ie)??0)+1),Pr({action:"open",target:Re,data:"",check:""},ae)))continue;Ce.seed&&Pe===null&&(Pe=await lt()),z.path=Ce.from,z.pathRole=be;let pt={path:Re.slice(0,300),source:Ce.source,status:null,outcome:"reached",from_path:Ce.from?Ce.from.slice(0,300):null},Je=(St,ln=null)=>{Ce.from&&(K.broken_links.push({from:Ce.from,url:Ce.url,status:St}),Qt.note("broken_link",Ce.from,{url:Ce.url,status:St,error:ln,message:`A link to ${Re} ${St?`answers ${St}`:"cannot be opened"}`}))},et;try{et=await z.page.goto(Ce.url,{waitUntil:"domcontentloaded",timeout:D.navigation})}catch(St){let ln=String(St.message).split(`
|
|
969
969
|
`)[0];/ERR_(?!BLOCKED_BY_CLIENT)[A-Z_]+/.test(ln)&&Je(null,ln),K.routes.push({...pt,outcome:"error"});continue}await It(),be&&await In({requested:Ce.url,crawling:!0,reopen:async()=>{et=await z.page.goto(Ce.url,{waitUntil:"domcontentloaded",timeout:D.navigation}),await It()}}).catch(()=>!1),await me();let rt=et?.status?.()??200;pt.status=rt;let Sr=rt===404||rt===410;if(await(async()=>{if(!be||Sr)return!1;if(rt===403)return!0;if(rt>=400)return!1;try{let[St,ln,hi]=await Promise.all([z.page.title(),z.page.evaluate(Vs),z.page.evaluate(()=>document.querySelector("h1")?.innerText??"")]);return cX.test(`${St??""} ${hi??""}`)&&ln.elements.length<=lX}catch{return!1}})()){K.routes.push({...pt,outcome:"forbidden"});continue}let gn=_r(new URL(z.page.url())),$n=rt===401||rt===403||qO(Ce.url,z.page.url(),Z)||gn!==Re&&Ws({key:gn,elements:(await z.page.evaluate(Vs).catch(()=>({elements:[]}))).elements});if($n){if(K.routes.push({...pt,outcome:"sign_in"}),Ce.seed){let St=new URL(z.page.url()),ln=`${St.origin}${rt===401||rt===403?`:${rt}`:_r(St)}`,hi=(fi.get(ln)??0)+1;fi.set(ln,hi),hi>=3&&Ke.length&&(K.deferred_seeds=Ke.length,Ke.length=0)}if(rt===401||rt===403)continue}else if(Ce.seed){if(Sr||Pe&&await qe()===Pe){K.routes.push({...pt,outcome:"not_found"});continue}}else if(Sr){Je(rt),K.routes.push({...pt,outcome:"not_found"});continue}else rt>=400&&rt!==401&&rt!==403&&Je(rt);let gt=new URL(z.page.url()),Ot=_r(gt);if($n||K.routes.push({...pt,outcome:rt>=500?"error":"reached"}),Ot===null||!Z.has(gt.hostname.toLowerCase())||cn.has(Ot))continue;cn.add(Ot),K.pages+=1,$n&&Ot!==Re&&K.routes.push({path:Ot.slice(0,300),source:"navigation",status:rt,outcome:"reached",from_path:null}),rt>=500&&K.server_errors.push(Ot),await Lt(),await lr();let Ae=await z.page.evaluate(GO).catch(()=>[]);Se.push({key:Ot,url:z.page.url(),links:Array.isArray(Ae)?Ae.length:0});for(let St of Array.isArray(Ae)?Ae:[]){let ln;try{ln=new URL(St,gt)}catch{continue}!/^https?:$/.test(ln.protocol)||!Z.has(ln.hostname.toLowerCase())||Sf(_r(ln),ae)&&(g_.test(ln.hash)||(ln.hash=""),Ht.has(_r(ln))||Te.push({url:ln.toString(),from:Ot,source:"link"}))}}if(await we(),ce&&!b&&Se.length&&!ke()){let Ce=c(),Re=()=>ke()||c()-Ce>=D.explore,Ie=[...Se].sort((Je,et)=>Je.links-et.links),pt=async Je=>{await z.page.goto(Je.url,{waitUntil:"domcontentloaded",timeout:D.navigation}).catch(()=>{}),await It()};z.exploring=!0;try{for(let Je=0;Je<Ie.length&&!K.explore_stopped_time;Je+=1){if(_t(),Re()){K.explore_stopped_time=1;break}let et=Ie[Je];try{await z.page.goto(et.url,{waitUntil:"domcontentloaded",timeout:D.navigation})}catch{continue}await It();let rt=await z.page.evaluate(NO).catch(()=>[]),{chosen:Sr,cut:Gr}=MO(Array.isArray(rt)?rt:[],{forbidden:ae,limit:c_});Gr&&(K.explore_stopped_pages+=1);let gn=0;for(let $n of Sr){if(_t(),Re()){K.explore_stopped_time=1;break}let gt=$n.role?z.page.getByRole($n.role,{name:$n.name,exact:!0}):z.page.getByText($n.name,{exact:!0});if(await gt.count()!==1)continue;let Ot=(await z.page.evaluate(Vs)).elements;try{await gt.click({timeout:D.action})}catch{}K.controls_explored+=1,await mn(D.exploreSettle),await It();let Ae=z.page.url(),St=null,ln=!1;try{let mi=new URL(Ae);St=_r(mi),ln=Z.has(mi.hostname.toLowerCase())}catch{}if(St!==null&&St!==et.key&&ln){!cn.has(St)&&K.pages<J&&(cn.add(St),Ht.add(St),z.path=et.key,z.pathRole=be,K.pages+=1,K.routes.push({path:St.slice(0,300),source:"navigation",status:200,outcome:"reached",from_path:et.key.slice(0,300)}),await Lt(),await lr(),gn=0,Ie.push({key:St,url:Ae,links:0})),await pt(et);continue}let hi=(await z.page.evaluate(Vs)).elements,ib=hi.filter(mi=>!Ot.includes(mi));if(ib.length>=2){let mi={key:et.key.slice(0,300),title:String(await z.page.title().catch(()=>"")??"").slice(0,300),elements:[...new Set([...Ot,...hi])].slice(0,p_),role:be};i(mi),B(mi)}if(await lr(),ib.length)gn=0,await pt(et);else if(++gn>=3){Re()&&(K.explore_stopped_time=1);break}}}}finally{z.exploring=!1}K.explore_blocked_writes=z.blockedWrites}K.scripts=Qt.scripts(),K.remaining_routes=[...Te,...Ke].flatMap(Ce=>{let Re=_r(new URL(Ce.url));return Re&&!Ht.has(Re)?[{path:Re,source:Ce.source}]:[]});return}case"remember":{let J=X.data.trim(),be=X.target.trim();if(be==="url")await Ve(),le[J]=z.page.url();else if(/^output(?:\s+field\s+|$)/i.test(be)){if(!z.command)throw new We("needs_repair","Nothing was run before this step to remember output from.");let ye=be.replace(/^output\s*(?:field\s+)?/i,"");if(!ye)le[J]=z.command.output.trim();else{let Me=null;try{Me=JSON.parse(z.command.output)}catch{Me=null}let Te=Me===null?{found:!1}:Kl(Me,ye);if(!Te.found)throw new We("needs_repair",`The last output has no field ${ye} to remember.`);le[J]=ec(Te.value)}}else if(/^field\s+/i.test(be)){let ye=be.replace(/^field\s+/i,""),Me=z.response?Kl(z.response.json,ye):{found:!1};if(!Me.found)throw new We("needs_repair",`The last response has no field ${ye} to remember.`);le[J]=ec(Me.value)}else{await Ve();let ye=await ao(Mr(be));le[J]=String(await ye.innerText()).trim()}break}default:throw new We("needs_repair",`\`${X.action}\` is not an action.`)}_t(),await To(ot),await Lt()}let Qn=async()=>(await Qt.settled(),{signals:Qt.signals(),api_calls:b?[]:Qt.apiCalls(),vitals:Ki,scanned:di,scan_ms:z.scanMs});try{for(let[F,le]of Ze.entries())try{if(z.step=F+1,await Tt(le),z.blockedRequest)throw new We("blocked",z.blockedRequest);Sc[F]=c(),await lr()}catch(he){let X=z.blockedRequest?new We("blocked",z.blockedRequest):he instanceof We?he:Y?.aborted?new We("blocked",Yt(Y.reason?.message??"The hunt was stopped; remaining actions were not run.")):new We("failed",Yt(he.message));z.crawl||await Lt({final:!0}).catch(()=>{});let ot=await Yi(),J=ot?[{label:"after",step:F+1,media_type:"image/jpeg",data_base64:ot}]:[];return{outcome:X.outcome,failed_step:F+1,message:`${At} step ${F+1}: ${Yt(X.message,1e3)}`,observed:X.observed?Yt(X.observed,1e3):null,duration_ms:c()-$e,evidence:[...J,...Xt],...await Qn(),...z.crawl?{crawl:z.crawl}:{}}}return z.crawl||await Lt({final:!0}).catch(()=>{}),{outcome:"passed",failed_step:null,message:null,observed:null,duration_ms:c()-$e,evidence:Xt,...await Qn(),...z.crawl?{crawl:z.crawl}:{}}}finally{Y?.removeEventListener("abort",an);let le=(await Promise.allSettled([xn,He()])).find(he=>he.status==="rejected");if(le)throw le.reason}}return{run:Ft}}pr();import Cn from"node:path";import{mkdirSync as Zne}from"node:fs";import{format as Qne}from"node:util";Pn();N();ta();N();var Yl=new Map;function Zl(e,t=Date.now()){let n=Yl.get(e);return!n||t>=n.retryAt}function JO(e,t,n,{remedy:r=null,now:o=Date.now()}={}){let s=Yl.get(e),i=(s?.failures??0)+1,a=Math.min(3e4*2**(i-1),6e5),c={id:e,title:t,remedy:r,message:dX(n),failures:i,firstFailedAt:s?.firstFailedAt??o,retryAt:o+a,retryInMs:a};return Yl.set(e,c),c}function XO(e){return Yl.delete(e)}function KO(e=Date.now()){return[...Yl.values()].map(t=>({...t,status:t.failures>=5?"failed":"warning",retryInMs:Math.max(t.retryAt-e,0)}))}function dX(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}Pn();var w_=22,pX=500,fX=300,hX=20,YO={ok:0,warning:1,failed:2},QO={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."}},mX=360*6e4,ZO=new WeakMap,gX="connector.diagnostics";function wX(e){return e.reduce((t,n)=>YO[n.status]>YO[t]?n.status:t,"ok")}async function eC({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=[yX(a),_X(e),await Ql("backend","EngineerOS backend",()=>vX(e,i)),await Ql("coding_agent","Coding agent",()=>bX(e,t,r.inspectAgent,i)),...s?[SX(s)]:[],...r.connectorJobs?[await Ql("local_execution","Local testing work",()=>xX(r.connectorJobs))]:[],await Ql("tool_registry","Tool registry",()=>EX(t,r.inspectTools)),...e?.hunt_host?[]:[await Ql("goal_runner","Goal runner",()=>$X(t,r.runnerStatus,{serviceStatus:r.macRunnerStatus}))],...KO().map(AX),...o.map(l=>Gt(l.id,l.title,l.status,l.detail,l.remedy))].slice(0,hX);return{checked_at:new Date().toISOString(),connector_version:String(n).slice(0,50),status:wX(c),checks:c}}function y_(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(`
|
|
970
|
-
`)}async function tC(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:gX,...t})??{}}function yX(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=w_?Gt("node_runtime","Node runtime","ok",`Node ${e}.`):Gt("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${w_} this connector requires.`,`Install Node ${w_} or later, then start the connector again.`)}function _X(e){return e?.connector_id&&e.token?Gt("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):Gt("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function vX(e,t){if(!e?.server_url)return Gt("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=S0(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return Gt("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${__(s)}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return Gt("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"?Gt("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):Gt("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function bX(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 kX(o.protocol,r):null;return a&&fo(a,i)>0?Gt("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,QO[o.protocol].remedy):Gt("coding_agent","Coding agent","ok",s)}catch(o){return Gt("coding_agent","Coding agent","failed",__(o),null)}}async function kX(e,t){let n=QO[e];if(!n)return null;let r=ZO.get(t)??new Map;ZO.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<mX)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;dn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function SX({state:e,detail:t,remedy:n=null}){return Gt("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function xX(e){let n=(await e()).filter(r=>r.status==="blocked");if(n.length){let r=n[0];return Gt("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${r.blocked_report?.error?.message||r.error||r.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.")}return Gt("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function EX(e,t){let n=await t(e);if(n?.error)return Gt("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 Gt("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function $X(e,t,{platform:n=process.platform,serviceStatus:r=IR}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return Gt("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 Gt("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 Gt("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 Gt("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 Gt("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function AX(e){return Gt(e.id,e.title,e.status,`Failing since ${Hr(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Ql(e,t,n){try{return await n()}catch(r){return Gt(e,t,"failed",__(r),null)}}function Gt(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,pX),remedy:o?String(o).slice(0,fX):null}}function __(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import UX from"node:path";N();import TX from"node:path";var rC=2,RX=300*1e3,OX={pytest:40,"node:test":40,vitest:60,jest:60},CX=3,IX=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),jX=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),nC=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 Rf(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function oC(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function NX(e){let t=String(e?.name??"");return jX.has(t)?{support:"helper"}:IX.has(t)?{support:"run"}:nC.has(t)?{support:"skipped",reason:nC.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var v_=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),MX=(e,t)=>!t||e.startsWith(`${t}/`);function PX(e,t){let n=null;for(let r of t)r.name!==e.framework||!MX(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function DX(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>RX&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function sC({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(v_)):null,i=[];for(let l of e){let u=NX(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:v_(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:v_(u.file)})))s&&!s.has(l.file)||PX(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=LX(l,r);l.shards=u.map(({files:p,packages:d},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:p,directory:l.root,packages:d}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(CX,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function LX(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=TX.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:[]}]:DX(e.files,{perShard:OX[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var FX=2;function Of(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=yx(t.protocol);return{agent_protocols:[t.protocol],coding_agent:!0,connector_jobs:!0,bug_hunt_development_v1:!0,...e.hunt_host?{hunt_host:!0}:{},capability_delivery:!e.hunt_host,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&&Rf(e),quality_baseline_contract:rC,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_actions:[...cf],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Fi(n),bug_hunt_sign_in:!0,bug_hunt_inputs:1,bug_hunt_checks:[...Vy],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_run_contract:FX,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.35",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:Yp,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:UX.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...zp(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...EA(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();un();Si();import{createHash as aC}from"node:crypto";import{readFile as zX}from"node:fs/promises";import BX from"node:os";import k_ from"node:path";var GX=/^[A-Z_][A-Z0-9_]*$/,HX=80,qX=64,iC="hunt-secret-";function tu(e){return typeof e=="string"&&e.length>0&&e.length<=HX&&GX.test(e)}function Cf(e){let t=`${iC}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=qX?t:`${iC}h${aC("sha256").update(String(e)).digest("hex").slice(0,40)}`}function WX(e){let t=aC("sha256").update(k_.resolve(e??process.cwd())).digest("hex").slice(0,16);return k_.join(BX.homedir(),".engineeros","hunt-secrets",t)}function b_(e){if(!tu(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function nu({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??WX(e),o=t??Wn({directory:r}),s=k_.join(r,"names.json");async function i(){let u;try{u=await zX(s,"utf8")}catch(p){if(p?.code==="ENOENT")return[];throw p}try{let p=JSON.parse(u);return(Array.isArray(p?.names)?p.names:[]).filter(tu)}catch{return[]}}let a=Promise.resolve(),c=u=>{let p=a.then(async()=>{let d=new Set(await i());u(d),await De(s,`${JSON.stringify({names:[...d].sort()},null,2)}
|
|
970
|
+
`)}async function tC(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:gX,...t})??{}}function yX(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=w_?Gt("node_runtime","Node runtime","ok",`Node ${e}.`):Gt("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${w_} this connector requires.`,`Install Node ${w_} or later, then start the connector again.`)}function _X(e){return e?.connector_id&&e.token?Gt("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):Gt("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function vX(e,t){if(!e?.server_url)return Gt("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=S0(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return Gt("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${__(s)}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return Gt("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"?Gt("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):Gt("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function bX(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 kX(o.protocol,r):null;return a&&fo(a,i)>0?Gt("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,QO[o.protocol].remedy):Gt("coding_agent","Coding agent","ok",s)}catch(o){return Gt("coding_agent","Coding agent","failed",__(o),null)}}async function kX(e,t){let n=QO[e];if(!n)return null;let r=ZO.get(t)??new Map;ZO.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<mX)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;dn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function SX({state:e,detail:t,remedy:n=null}){return Gt("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function xX(e){let n=(await e()).filter(r=>r.status==="blocked");if(n.length){let r=n[0];return Gt("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${r.blocked_report?.error?.message||r.error||r.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.")}return Gt("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function EX(e,t){let n=await t(e);if(n?.error)return Gt("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 Gt("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function $X(e,t,{platform:n=process.platform,serviceStatus:r=IR}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return Gt("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 Gt("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 Gt("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 Gt("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 Gt("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function AX(e){return Gt(e.id,e.title,e.status,`Failing since ${Hr(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Ql(e,t,n){try{return await n()}catch(r){return Gt(e,t,"failed",__(r),null)}}function Gt(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,pX),remedy:o?String(o).slice(0,fX):null}}function __(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import UX from"node:path";N();import TX from"node:path";var rC=2,RX=300*1e3,OX={pytest:40,"node:test":40,vitest:60,jest:60},CX=3,IX=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),jX=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),nC=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 Rf(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function oC(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function NX(e){let t=String(e?.name??"");return jX.has(t)?{support:"helper"}:IX.has(t)?{support:"run"}:nC.has(t)?{support:"skipped",reason:nC.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var v_=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),MX=(e,t)=>!t||e.startsWith(`${t}/`);function PX(e,t){let n=null;for(let r of t)r.name!==e.framework||!MX(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function DX(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>RX&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function sC({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(v_)):null,i=[];for(let l of e){let u=NX(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:v_(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:v_(u.file)})))s&&!s.has(l.file)||PX(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=LX(l,r);l.shards=u.map(({files:p,packages:d},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:p,directory:l.root,packages:d}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(CX,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function LX(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=TX.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:[]}]:DX(e.files,{perShard:OX[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var FX=2;function Of(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=yx(t.protocol);return{agent_protocols:[t.protocol],coding_agent:!0,connector_jobs:!0,bug_hunt_development_v1:!0,...e.hunt_host?{hunt_host:!0}:{},capability_delivery:!e.hunt_host,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&&Rf(e),quality_baseline_contract:rC,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_actions:[...cf],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Fi(n),bug_hunt_sign_in:!0,bug_hunt_inputs:1,bug_hunt_checks:[...Vy],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_run_contract:FX,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.36",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:Yp,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:UX.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...zp(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...EA(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();un();Si();import{createHash as aC}from"node:crypto";import{readFile as zX}from"node:fs/promises";import BX from"node:os";import k_ from"node:path";var GX=/^[A-Z_][A-Z0-9_]*$/,HX=80,qX=64,iC="hunt-secret-";function tu(e){return typeof e=="string"&&e.length>0&&e.length<=HX&&GX.test(e)}function Cf(e){let t=`${iC}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=qX?t:`${iC}h${aC("sha256").update(String(e)).digest("hex").slice(0,40)}`}function WX(e){let t=aC("sha256").update(k_.resolve(e??process.cwd())).digest("hex").slice(0,16);return k_.join(BX.homedir(),".engineeros","hunt-secrets",t)}function b_(e){if(!tu(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function nu({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??WX(e),o=t??Wn({directory:r}),s=k_.join(r,"names.json");async function i(){let u;try{u=await zX(s,"utf8")}catch(p){if(p?.code==="ENOENT")return[];throw p}try{let p=JSON.parse(u);return(Array.isArray(p?.names)?p.names:[]).filter(tu)}catch{return[]}}let a=Promise.resolve(),c=u=>{let p=a.then(async()=>{let d=new Set(await i());u(d),await De(s,`${JSON.stringify({names:[...d].sort()},null,2)}
|
|
971
971
|
`)});return a=p.catch(()=>{}),p},l={directory:r,async get(u){b_(u);let p=await o.get(e,Cf(u));return typeof p=="string"&&p!==""?p:null},async set(u,p){if(b_(u),typeof p!="string"||p==="")throw new Error("A secret needs a value.");await o.put(e,Cf(u),p),await c(d=>d.add(u))},async remove(u){b_(u),await o.delete(e,Cf(u)),await c(p=>p.delete(u))},async names(){return(await i()).sort()},async has(u){return tu(u)?!!await o.has(e,Cf(u)):!1},async values(u){let p={};for(let d of[...new Set(u??[])]){if(!tu(d))continue;let f=await l.get(d);f!==null&&(p[d]=f)}return p}};return l}async function cC({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(`
|
|
972
972
|
`),c?o(c):r(s)},a=c=>{for(let l of c){if(l==="\r"||l===`
|
|
973
973
|
`||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 eu=(e,t)=>(t?.(e),{ok:!1,message:e});async function lC({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 eu("Use `secret set NAME`, `secret list` or `secret remove NAME`.",i);let c=nu({workspace:n,vault:o,directory:s});try{if(e==="list"){let p=await c.names();return a(!0,p.length?p.join(`
|
|
@@ -1204,7 +1204,7 @@ It is checked with the provider and stored in this machine's protected vault
|
|
|
1204
1204
|
(Windows Data Protection, the macOS Keychain or the Linux Secret Service).
|
|
1205
1205
|
EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function Vne(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(`
|
|
1206
1206
|
`),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
|
|
1207
|
-
`)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 WN=Symbol("missing");function Jne(e,t){return new Promise(n=>{let r=qne(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?WN:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function qN(e,t){for(let n of Su){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 VN(e,t,n,{vault:r=Nv(),run:o=bh,fetchImpl:s=fetch,secret:i=Vne,interactive:a=Jne,install:c=wh,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(Wne),n.help?0:2;if(e==="integrations")return qN(l,(await xh({run:o,vault:r})).providers),0;let p=t[0];if(!Su.includes(p))return u(`Unknown provider ${p}. Choose one of: ${Su.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=Hi[p];if(e==="disconnect")return l(`${p} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===WN){let m=await oi(f);if(!m){l(`Installing the ${gu[f].label} ${gu[f].version} for the connector...`);try{m=(await c(f)).path}catch(g){return u(g.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${Sh[p]} is how this machine signs in to ${p}.`),1):(qN(l,{[p]:(await xh({run:o,vault:r})).providers[p]}),0)}let d=Gn[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await Mv(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await Pv(r,p,{token:f,site:n.site,email:n.email},s);return l(`Connected ${d.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}N();import{spawn as Xne}from"node:child_process";async function JN({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=Xne,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=$s(await nr(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await Kne(o,c.entry,i,t);if(l===Nc){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 p=await nr(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await lm(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 ${d.version}.`);continue}catch(d){s(`Automatic rollback failed: ${d.message}`)}}return l??1}}function Kne(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[ra]:"1",[om]:r.entry,[sm]: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,p)=>{l(),o({code:u,signal:p})})})}var ui="1.59.
|
|
1207
|
+
`)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 WN=Symbol("missing");function Jne(e,t){return new Promise(n=>{let r=qne(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?WN:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function qN(e,t){for(let n of Su){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 VN(e,t,n,{vault:r=Nv(),run:o=bh,fetchImpl:s=fetch,secret:i=Vne,interactive:a=Jne,install:c=wh,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(Wne),n.help?0:2;if(e==="integrations")return qN(l,(await xh({run:o,vault:r})).providers),0;let p=t[0];if(!Su.includes(p))return u(`Unknown provider ${p}. Choose one of: ${Su.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=Hi[p];if(e==="disconnect")return l(`${p} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===WN){let m=await oi(f);if(!m){l(`Installing the ${gu[f].label} ${gu[f].version} for the connector...`);try{m=(await c(f)).path}catch(g){return u(g.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${Sh[p]} is how this machine signs in to ${p}.`),1):(qN(l,{[p]:(await xh({run:o,vault:r})).providers[p]}),0)}let d=Gn[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await Mv(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await Pv(r,p,{token:f,site:n.site,email:n.email},s);return l(`Connected ${d.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}N();import{spawn as Xne}from"node:child_process";async function JN({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=Xne,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=$s(await nr(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await Kne(o,c.entry,i,t);if(l===Nc){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 p=await nr(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await lm(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 ${d.version}.`);continue}catch(d){s(`Automatic rollback failed: ${d.message}`)}}return l??1}}function Kne(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[ra]:"1",[om]:r.entry,[sm]: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,p)=>{l(),o({code:u,signal:p})})})}var ui="1.59.36",Ch="1.59.36",ere=3e5,Ih=["queued","running","reporting"],tre=5e3,Dv={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."},Lv={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."},nre=6e4,rre=3e4,ore=60*6e4,Uv={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Fv={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:Jt,positional:Zt,flags:tt}=uC(process.argv.slice(2));Jt==="version"&&(console.log(ui),process.exit(0));var ks=null,sn=!1,Hn=null,Tu=null,lM=!1,uM=null,nb=null,hn=null,ju=null,Zv,XN,Ru,zv,KN,fc,_c,dM=th({getWorkspace:()=>M.workspace,onRecorded:e=>_j(M,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}`))}),sre=GN({getWorkspace:()=>M.workspace,getConfig:()=>M,huntSignIns:dM}),Ou=hC();Jt==="results"&&(Zt[0]!=="upload"&&(console.log(Uf),process.exit(tt.help||!Zt[0]?0:2)),process.exit(await kI(tt)));(Jt==="connect"||Jt==="disconnect"||Jt==="integrations")&&process.exit(await VN(Jt,Zt,tt,{fetchImpl:FN}));if(Jt==="delivery"){let e=Cn.resolve(tt.workspace||process.cwd());try{if(Zt[0]==="execute")await HR(tt.input);else if(Zt[0]==="worker"){let t=await An(e);if(!t)throw new Error("Restore the paired connector configuration before reporting or executing delivery work.");await vR(t,tt["attempt-id"])}else if(Zt[0]==="probe"){let t=await Zp().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(Dn(t)),process.exit(1)}}if(Jt==="runner"){let e=Cn.resolve(tt.workspace||process.cwd()),t=Zt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?Cn.join(Cn.dirname(en(e,tt["run-id"])),"worker.log"):Cn.join(e,".engineeros","runner","service.log");Zne(Cn.dirname(n),{recursive:!0});let r=(...s)=>jl(n,`${Qne(...s)}
|
|
1208
1208
|
`),o=(s,i,a)=>(jl(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(tt["keep-awake"]!==void 0){if(!["on","off"].includes(tt["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await An(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await Vr({...n,runner_keep_awake:tt["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await OR(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 jR(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await Di(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await Bs(e),null,2)):t==="serve"?await DR(e):t==="worker"?await LR(e,tt["run-id"]):Ut("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){Ut(zy(n,e).message)}}tt["assessment-workers"]!==void 0&&Ut("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(Jt==="secret")try{let e=qy(tt),t=Zt[0]||"list",n=await lC({action:t,name:Zt[1],workspace:e,readValue:()=>cC({label:`Value for ${Zt[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){Ut(e.message)}if(Jt==="tools"){try{let e=qy(tt),t=Zt[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=Zt[1];r||Ut(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await mw(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 yl(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:Zt[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await pw(e,t,Zt[1]);let n=await Nr(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){Ut(e.message)}process.exit(process.exitCode||0)}if(Jt==="agents"){let e;try{e=await Cw()}catch(n){Ut(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await vl(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(Jt==="agent"){let e=Zt[0],t=Zt[1]||"check";(!e||!["check","install"].includes(t))&&Ut("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await bl(e):await vl(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){Ut(n instanceof Error?n.message:String(n))}process.exit(0)}if(Jt==="mcp"){let e=tt.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=tt["run-id"]||Zt[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await An(e);await IC({config:n,runId:t,version:ui,input:process.stdin,output:process.stdout}),process.exit(0)}if(Jt==="context-mcp"){let e=tt["config-workspace"]||tt.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await An(e);t||Ut("This workspace is not paired with EngineerOS."),await pI({config:t,workspace:tt.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:ui,input:process.stdin,output:process.stdout}),process.exit(0)}if(Jt==="status"){let e=await An(tt.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(Jt==="doctor"){let e=Cn.resolve(tt.workspace||process.cwd()),t=await An(e),n=await EC(e),r=await Xi(t||{workspace:e},e,S_(n));console.log(y_(r)),process.exit(r.status==="failed"?1:0)}if(Jt==="update"){let e=Zt[0]||"status";try{let t=am(process.argv[1],Ch),n=await um($r(),t,{action:e,policy:Zt[1]??null});console.log(Pc(dm(n,t,{supervised:!0})))}catch(t){Ut(`${t.message}
|
|
1209
1209
|
Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var mc=Jt==="hunt-host";if(mc)try{tt.workspace=VR(Zt,tt)}catch(e){Ut(e.message)}if((Jt==="start"||Jt==="pair"||mc)&&process.env[ra]!=="1"&&dn(Ch))try{process.exit(await JN({root:$r(),bundled:{version:Ch,entry:Cn.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:Cn.resolve(tt.workspace||process.cwd())}))}catch(e){Ut(`The connector process could not be started: ${e.message}`)}if(mc){try{await JR(tt.workspace,Zt[0]?tt.agent:null)}catch(e){Ut(e.message)}Jt=Zt[0]?"pair":"start"}var M,Ji,Cu;if(Jt==="pair"){let e=Zt[0];e||Ut("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=tt.url;t||Ut("Pairing requires --url with the EngineerOS backend address."),tt.agent&&tt["agent-command"]&&Ut("Use either --agent or --agent-command, not both.");let n=tt["agent-protocol"]||(tt["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||Ut(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(tt.agent||tt["agent-command"])&&Ut("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{tt.agent&&(await vl(tt.agent),r=await Iw(tt.agent))}catch(o){Ut(o instanceof Error?o.message:String(o))}M={server_url:hm(t),workspace:Cn.resolve(tt.workspace||process.cwd()),onboard:tt.onboard===!0,onboarding_pending:tt.onboard===!0,hunt_host:mc,agent_protocol:n,agent_command:tt["agent-command"]||null,agent_args:Ore(tt["agent-args"]),agent_name:tt["agent-name"]||null,...r,skip_git_repo_check:mc||tt["skip-git-repo-check"]===!0,name:tt.name||`${Yne.hostname()} - ${Cn.basename(Cn.resolve(tt.workspace||process.cwd()))}`},Cu=await An(M.workspace),Ji={type:"pair",pairing_code:e,name:M.name,capabilities:{},...m0(Cu,M.server_url)}}else Jt==="start"?(M=await An(tt.workspace||process.cwd()),M||Ut("This connector is not paired. Create a pairing command in EngineerOS first."),mc&&!M.hunt_host&&Ut("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),M.token||Ut("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),Ji={type:"authenticate",connector_id:M.connector_id,token:M.token}):Ut("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var pM=UR(M,{reportError:e=>console.error(e)}),li=0,jh=!1,vc=null,cr=new Map,Bv=0,Gv=new Set,gc=[],Zn=new Map,fn,Qv,Ah,Wo=null,Th=!1,fM=0,Hv=null,qv=[],Rh,hM,Eu=1e3,wc,YN=0,Wv=!1,qo=!1,io,ai=!1,Nh=!1,eb=0;function si(e){return eb+=1,e.finally(()=>{eb-=1})}var hc,Wi=0;function bc({exitCode:e=0}={}){if(Wi=Math.max(Wi,e),hc)return hc;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),hc=ire().finally(()=>clearTimeout(t)),hc}async function ire(){if(sn=!0,ju?.stop(),ks?.stop(),nb?.stop(),uM?.stop(),clearInterval(Zv),hn?.stop(),hM?.(),clearTimeout(Rh),clearInterval(Qv),clearInterval(Ah),await Promise.all([...[...cr.values()].map(e=>sr(e.child))]),await Promise.all([...Zn.values()].map(sb)),await fc?.cancelAll(),await Ru?.stop(),await _c?.abortAll(),await _l(),await hb().catch(e=>{Wi=Math.max(Wi,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),fn?.close(),Wi&&Wi!==Nc){let e;await Promise.race([(async()=>{await ks?.drain(),await Xi(M,M.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Wi)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{bc()});var ZN=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{ZN||(ZN=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await bc({exitCode:1}))});hn=vb();process.on("exit",()=>{ju?.stop(),hn.stop()});hn.banner(`EngineerOS connector ${ui}`,[M.workspace,M.server_url]);ks=fC({actions:{refresh_tool_inventory:async()=>{dt.tool_inventory=await Nr(M.workspace),kr()},restart_goal_runner:()=>Di(M.workspace)},onNotify:()=>Xi(M,M.workspace),explain:async e=>{if(!await vs())return null;let{reading:t}=await L1(M,e);return t},onUpdate:e=>xC(M.workspace,e)});uM=AC({render:(e,t)=>hn.write(e,t),onRecord:e=>ks.observe(e)});nb=TC({workspace:M.workspace,onRecord:e=>{ks.observe(e),hn.line(e.channel,e.level,e.message)}});ks.start();M.hunt_host||nb.start();hn.live&&!M.hunt_host&&(Zv=setInterval(()=>{are().catch(()=>{})},tre),Zv.unref?.());var Vv=new Set;async function are(){if(M.hunt_host)return;XN??=Ly(M.workspace);let{jobs:e}=await XN(),t=new Set,n=e.filter(r=>r.status!=="queued"&&Ih.includes(r.status)).length;for(let r of e){if(!Ih.includes(r.status))continue;t.add(r.runId),Vv.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;hn.status(`goal:${r.runId}`,r.activity?.message||o,cre(r),{agent:r.status!=="queued",link:vc&&`${vc}/goals`,phase:o}),hn.step(`goal:${r.runId}`,r.activity?.message)}for(let r of Vv)t.has(r)||(Vv.delete(r),hn.clearStatus(`goal:${r}`))}function cre(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function vs({ignoreBugHunt:e=!1}={}){if(sn||cr.size>0||Zn.size>0||li>0||(fc?.active??0)>0||(Ru?.active??0)>0||!e&&(_c?.active??0)>0)return!1;try{let{jobs:t}=await Bs(M.workspace);return!sn&&!t.some(n=>Ih.includes(n.status))}catch{return!1}}try{let e=M.hunt_host?{}:await na(M.workspace);e.committed&&(M.onboarding_pending=!0,M.connector_id&&await Vr(M),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await bM(e)}var mM=await nr($r()).then(e=>e.policy!=="manual",()=>!1),jt;try{jt=await Cl(M,M.workspace)}catch(e){await bM(e)}console.log(`Using ${jt.name} through ${jt.protocol} (${jt.version}).`);console.log(`System time: ${Hr()} (${Intl.DateTimeFormat().resolvedOptions().timeZone}).`);var gM=async()=>nu({workspace:M.workspace}).names().catch(()=>[]),dt=Of(M,jt,await Nr(M.workspace),{secretNames:await gM()}),bs=t0({workspace:M.workspace,running:am(process.argv[1],Ch),supervised:process.env[ra]==="1",isIdle:async()=>!sn&&cr.size===0&&gc.length===0&&Zn.size===0&&li===0&&eb===0&&!ai&&!Nh&&(_c?.active??0)===0&&(Ru?.active??0)===0&&!Th,restart:()=>bc({exitCode:Nc}),onChange:e=>{dt.runtime_update=e,fn?.readyState===WebSocket.OPEN&&kr()}});try{await bs.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}M={...M,execution_profiles:jt.executionProfiles??null};Jt==="pair"&&Cu?.connector_id||await Vr(M);dt.agent_session={...dt.agent_session,status:"checking",message:`Checking that ${jt.name} can answer.`};dt.bug_hunt_browser=!1;Ji.capabilities=dt;console.log(as(M.worker_limit)===null?`Workers: automatic, ${Ma()} ${jt.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${as(M.worker_limit)} ${jt.name} workers side by side, set with /workers.`);var Iu=au({getConfig:()=>M}),Vi=async e=>{let t;try{t=await ls(M,e)}catch(n){throw[401,403].includes(n.status)&&(qo=!0,console.error("EngineerOS withdrew this connector's authorization. Local work is stopping; saved reports are retained."),bc()),n}return t?.execution_sync&&await lre(t.execution_sync),t},QN=qp(Vi,{signature:J1}),Jv,Xv=!1,xu,Au=new Map,tb=new Set,Kv;function ci(){return Ru??=OI({getConfig:()=>M,jobStore:Iu,canRun:()=>vs()}),_c??=hN({getConfig:()=>({...M,tool_inventory:dt.tool_inventory}),jobStore:Iu,recordedSignIns:dM,isIdle:()=>vs({ignoreBugHunt:!0}),canRun:async e=>{if(!await vs({ignoreBugHunt:!0}))return!1;let t=e.assignment;return t.kind!=="production_check"&&Hn?.state!=="ready"?!1:t.surface?.app_surface==="webdriver"||dt.bug_hunt_browser===!0},activity:{status:hn.status,step:ob,agents:hn.agents,finish:hn.finish}}),{scheduledTests:Ru,bugHunts:_c}}async function lre(e){let t=ci(),n=[];for(let r of e.jobs??[])await Iu.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}`;tb.has(o)||Au.set(o,r)}wM()}function wM(){Kv||sn||(Kv=(async()=>{let e=ci();for(;Au.size&&!sn;){let[t,n]=Au.entries().next().value;Au.delete(t),tb.add(t);try{if(n.type==="bug_hunt.grant")await e.bugHunts.configure(n);else if(n.type===Hf)await e.scheduledTests.configure(n);else if(n.type===cv)await e.bugHunts.handle(n);else if(n.type===Gf)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{tb.delete(t)}}})().finally(()=>{Kv=null}))}async function yM(){if(!(!M.connector_id||!M.token||sn))return xu||(xu=(async()=>{let e=ci();await Promise.all([e.bugHunts.start(),e.scheduledTests.start()]);let t=await Iu.list();for(let n of t)if(n.kind==="bug_hunt_grant"&&n.status==="provisioning"){let r=n.checkpoint?.pending_context??n.assignment;Au.set(`bug_hunt.grant:${n.id}`,r)}wM(),t.some(n=>["authorized","queued","running"].includes(n.status)&&Date.parse(n.execution_lease.expires_at)>Date.now())&&(SM(),Ph()),Sre()})().catch(e=>{throw xu=null,e}),xu)}async function ure(){let e=await Bs(M.workspace).catch(()=>({service:null,jobs:[]}));return{version:ui,now:Date.now(),workspace:M.workspace,config_path:hr(M.workspace),config:M,agent:jt,automatic_worker_limit:Ma(),worker_limit:as(M.worker_limit),connection:{state:dre(),server_url:M.server_url,last_error:io||null},work:{assessments:[...cr.values()].map(t=>({stage:t.stage,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:jt.name})),prompts:[...Zn.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:jt.name})),integrations:li},runner:e,runtime_update:bs.report(),health:ks?.health()??null,activity:Ou.snapshot()}}function dre(){return sn||qo?"stopped":fn?.readyState===WebSocket.OPEN?"connected":"connecting"}var pre={async cancelPrompt(e){let t=[...Zn.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=>vM(e),setVerbose(e){return e===jh?`Detailed agent activity is already ${e?"on":"off"}.`:(rb(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"?(bs.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 bs.command(e),Pc(await bs.refresh()))}};ju=yC({ui:hn,snapshot:ure,actions:pre});ju&&console.log(wC());await _M();var eM=new Set;async function _M(){if(sn||qo)return;console.log(`Connecting ${M.name} to ${M.server_url}`),qo=!1,io=void 0;let e=new WebSocket(M.server_url);fn=e;let t=kx(e,M.server_url,{onTimeout:r=>{fn===e&&(io=r,console.error(r),Yv())}});hM=t,e.addEventListener("open",()=>{if(fn!==e){e.close();return}try{if(gx(fn,e,Ji))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){io=Dn(r),console.error(`Could not authenticate the WebSocket connection: ${io}`);try{e.close()}catch{}Yv()}}),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: ${Dn(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){sn=!0,qo=!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=Cu?.connector_id===r.connector.id;if(M=g0(M,Cu,r.connector.id,r.token),await Vr(M),r.connector?.capabilities?.http_updates!==!0){sn=!0,qo=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}Ji={type:"authenticate",connector_id:M.connector_id,token:M.token,capabilities:dt},console.log(s?`Reconnected existing workspace connector ${M.connector_id}; assessment history is preserved.`:`Paired. Connector ${M.connector_id} is online.`),oM(r);return}if(r.type==="authenticated"){t();let s=M.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(wc?`Reconnected after ${vt(Date.now()-wc)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),wc=void 0,oM(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){Nh||hre(r);return}if(r.type==="workspace.refresh"){yc();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await vM(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){rb(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(_s=!1,dt.bug_hunt_browser=!1,kr());try{dt.tool_inventory=await yl(M.workspace,r,void 0,{confirmLocal:i=>ju?.confirm(i)??!1,log:Oh}),s&&(_s=!0),dt.bug_hunt_browser=Fi(dt.tool_inventory)&&_s,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:dt.tool_inventory})),kr(),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 mw(M.workspace,r,{onStatus:async()=>{dt.tool_inventory=await Nr(M.workspace),kr()}});dt.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:dt.tool_inventory})),kr(),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"){ha(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===BN){si(sre(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),HN(M,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}`;fy(gc,cr.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),kc();return}if(r.type==="prompt.execute"){let s=Zn.get(r.prompt_id);s?$M(r)>s.executionRevision&&await $re(s,r):EM(r);return}if(r.type==="prompt.cancel"){let s=Zn.get(r.prompt_id);s&&await sb(s);return}if(r.type==="agent.warm"){_re(r);return}if(r.type==="run.available"){if(M.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await pM.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${Cn.join(M.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${Dn(s)}`)}return}if(r.type==="delivery.task.start"||r.type==="delivery.task.cancel"){if(M.hunt_host)throw new Error("Pair a repository connector before dispatching delivery tasks.");await yR(M.workspace,M.connector_id,r),await Di(M.workspace);return}if(r.type==="goal.cleanup"){try{await PR(M.workspace),await Di(M.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){Rre(r);return}if(r.type==="run.cancelled"){await Dy(M.workspace,r.run_id);return}if(r.type===vE){fc??=Wg({getConfig:()=>M,onTestsCommitted:()=>yc()}),si(fc.handle(r));return}if(r.type===bE){fc??=Wg({getConfig:()=>M,onTestsCommitted:()=>yc()}),await fc.cancel(r);return}if(r.type===cv){si(ci().bugHunts.handle(r)).catch(s=>console.error(`Bug Hunter assignment: ${s.message}`));return}if(r.type==="bug_hunt.grant"){si(ci().bugHunts.configure(r)).catch(s=>console.error(`Bug Hunter settings: ${s.message}`));return}if(r.type===iN){_c?.stop(r);return}if(r.type===Gf){si(ci().scheduledTests.handle(r)).catch(s=>console.error(`Scheduled test assignment: ${s.message}`));return}if(r.type===Hf){si(ci().scheduledTests.configure(r)).catch(s=>console.error(`Scheduled test settings: ${s.message}`));return}if(r.type===MI){zv??=HI({getConfig:()=>M}),si(zv.handle(r));return}if(r.type===PI){await zv?.cancel(r);return}if(r.type===WI){KN??=VI({getConfig:()=>M,isIdle:()=>vs(),agentTurn:l1}),si(KN.handle(r));return}if(r.type==="connector.update"){fre(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await bc();return}if(r.type==="connector.revoked"){sn=!0,console.error("This connector was revoked in EngineerOS."),e.close();return}if(r.type==="run.error"){console.error(`EngineerOS: ${r.message}`),r.run_id||(ai=!1);return}if(r.type==="connection.error"){qo=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);eM.has(o)||(eM.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${ui}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),fn!==e||hc)return;let o=wx(r);if(!o.retry||qo||sn){console.error(o.message),o.retry&&qo&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),bc();return}io=io?`${o.message} ${io}`:o.message,Yv()}),e.addEventListener("error",r=>{fn===e&&(io=mx(r),console.error(`WebSocket connection to ${M.server_url} failed: ${io}`))})}async function fre(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=bs.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 bs.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 hre(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";Nh=!0,console.log(`Starting interactive ${jt.name} provider ${n}.`);try{await(n==="logout"?bx:vx)(jt,M.workspace),jt=await Cl(M,M.workspace),Hn=null,dt=Of(M,jt,dt.tool_inventory,{secretNames:await gM()}),Ji.capabilities=dt,fn.readyState===WebSocket.OPEN&&(fn.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:dt.agent_session})),fn.close(1e3,`Provider ${n} completed`)),console.log(`${jt.name} provider ${n} completed.`)}catch(r){let o=Dn(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{Nh=!1}}function Yv(){if(sn||qo||Rh)return;let e=io?` Last error: ${io}`:"",t=wc?` Offline for ${vt(Date.now()-wc)}.`:"";wc??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(Eu/1e3)}s.`),Rh=setTimeout(()=>{Rh=void 0,_M()},Eu),Eu=Math.min(3e4,Eu*2)}async function yc(){if(!M.hunt_host&&!(ai||fn.readyState!==WebSocket.OPEN)){ai=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await B1(M.workspace),t=await z1(M.workspace,M.last_head_reported??M.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(rr(M.server_url,M.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(await ya(n,"the workspace"));let r=await n.json(),o=r.source_revision;M={...M,onboarding_pending:!1,last_snapshot_head:e.head_revision??M.last_snapshot_head,last_head_reported:e.head_revision??M.last_head_reported,last_head_branch:e.head_revision?e.branch??null:M.last_head_branch},await Vr(M),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(`Excluded ${e.excluded_file_count.toLocaleString()} sensitive or generated file(s).`),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 O_({workspace:M.workspace,connectorId:M.connector_id,snapshot:e,refresh:la,buildMap:(a,c)=>Pf(M.workspace,a,{head:c.head_revision,branch:c.branch}),log:a=>console.error(a)});if(s&&o){let a=await fetch(_0(M.server_url,M.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:JSON.stringify({source_revision:o,quality_map_base64:s.base64})});a.ok?await Df(M.workspace,M.connector_id,s.map).catch(()=>{}):console.error(await ya(a,"the workspace quality map"))}i&&console.log(`Built the local context index: ${i.total_files.toLocaleString()} file(s) ready for assignment context.`),ai=!1}catch(e){ai=!1,console.error(`Workspace assessment failed: ${Dn(e)}`)}}}var mre=8e6,tM,nM="";async function gre({current:e,previous:t}){if(ai||fn?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=Cn.resolve(M.workspace),r=async()=>{M={...M,last_head_reported:e.head,last_head_branch:e.branch??null},await Vr(M)},o=await R_(M.workspace,M.connector_id),s=async()=>{if(await yc(),M.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let{index:i}=await la(M.workspace,M.connector_id),a=null,c=await tI({previous:{head:t.head,branch:t.branch??null},current:e,compare:(d,f)=>vy(M.workspace,d,f),inventoryDelta:d=>ek(n,Object.entries(i.files).map(([f,h])=>({path:f,size:h.size})),d),mapDelta:async()=>(a=await Pf(M.workspace,i,{head:e.head,branch:e.branch}),T_(o,a)),contentHead:(await $d(n).catch(()=>null))?.content_head_revision??null});if(c.status==="snapshot")return s();if(c.status==="nothing")return r();let l=JSON.stringify(c.report);if(Buffer.byteLength(l)>mre)return s();let u=await fetch(v0(M.server_url,M.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:l});if(!u.ok)throw new Error(await ya(u,"the new commit"));let p=await u.json().catch(()=>({}));if(p.needs_snapshot)return s();await r(),a&&await Df(M.workspace,M.connector_id,a).catch(()=>{}),console.log(`Reported ${c.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 wre(){M.hunt_host||M.onboarding_pending||ai||fn?.readyState!==WebSocket.OPEN||(tM??=eI({readHead:()=>QC(M.workspace),getLastReported:()=>({head:M.last_head_reported??M.last_snapshot_head,branch:M.last_head_branch}),onChange:gre,onError:e=>{e.message!==nM&&(nM=e.message,console.error(`The new commit could not be reported yet: ${Dn(e)}`))}}),tM.poll().catch(()=>{}))}var yre=6e4,rM=0;async function _re(e){if(M.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?M.sessions?.[t]:void 0,r=[];Date.now()-rM>yre&&(rM=Date.now(),r.push(la(M.workspace,M.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),M.agent_protocol==="acp"&&r.push(iA(M.workspace,M,{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(`${jt?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function kr(){sn||!M.connector_id||!M.token||(Xv=!0,!Jv&&(Jv=(async()=>{do Xv=!1,await vre();while(Xv&&!sn)})().catch(e=>console.error(`Connector synchronization: ${e.message}`)).finally(()=>{Jv=null})))}async function vre(){let e=T1(cr),t=await Iu.snapshot();QN.update({type:"assessment.workers",assessment_workers:e,tool_inventory:dt.tool_inventory,runtime_update:dt.runtime_update,agent_session:dt.agent_session,bug_hunt_browser:dt.bug_hunt_browser,connector_jobs:t.jobs,...zp(M.worker_limit)}),await QN.flush()}async function vM(e){let t=as(e);return t===as(M.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(M={...M,worker_limit:t},await Vr(M),kc(),kr(),t===null?`Workers are automatic again: up to ${Ma()} side by side for this machine's CPU and memory, for ${ou} (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: ${ou}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function rb(e){if(e!==jh){if(jh=e,!e)for(let t of cr.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."),kr()}}function ob(e,t,n=null){hn.step(e,t,n)&&jh&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function bre(){clearInterval(Ah);let e=!1,t=()=>{e||cr.size>0||Zn.size>0||(e=!0,Xi(M,M.workspace).finally(()=>{e=!1}))};t(),Ah=setInterval(t,ere),Ah.unref?.()}async function Xi(e,t,n=ks?.healthChecks()??[]){let r=await eC({config:e,workspace:t,version:ui,insights:[...n,...Tu?[Tu]:[]],agentSession:Hn,probes:{inspectAgent:(o,s)=>sn?jt:Cl(o,s),inspectTools:o=>sn?dt.tool_inventory:Nr(o),runnerStatus:Bs,connectorJobs:()=>au({getConfig:()=>e}).list()}});try{lM=(await tC(e,r,ls))?.autonomy_scan===!0}catch(o){console.error(`EngineerOS did not accept the connector self-check: ${o instanceof Error?o.message:String(o)}`)}return r}async function bM(e){if(sn)return hc;let t=e instanceof Error?e.message:String(e),n=await Xi(M,M.workspace).catch(()=>null);n&&console.error(y_(n)),Ut(t)}function oM(e){rb(e.connector?.activity_log_enabled===!0),vc=e.project_url??null,Eu=1e3,SM(),Ph(),bs.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),yM().catch(t=>console.error(`Saved connector work: ${t.message}`)),M.onboarding_pending&&yc()}var $u=null,_s=!1,kM=0,kre=Date.now();async function SM(){return $u||($u=(async()=>{mM&&await z$(M.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Oh("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await XR(M.workspace,{log:Oh}),_s=!0,Tu=null,dt.tool_inventory=await Nr(M.workspace),dt.bug_hunt_browser=Fi(dt.tool_inventory)&&_s,Oh(`Bug Hunter's browser is ready (${vt(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${vt(Date.now()-e)}: ${t.message}`),dt.bug_hunt_browser=!1,Tu={id:"hunt_browser",title:"Bug Hunter browser",status:"failed",detail:t.message,remedy:`Run engineeros-connector tools setup playwright --workspace "${M.workspace}", then restart this connector to retry browser setup.`},Xi(M,M.workspace).catch(()=>null)}kr()})(),$u)}function Oh(e){console.log(`[browser] ${e}`)}async function Ph(){if(!["checking","ready"].includes(Hn?.state)){kM=Date.now(),dt.agent_session={...dt.agent_session,status:"checking",message:`Checking that ${jt.name} can answer.`},kr(),Hn={state:"checking",detail:`Asking ${jt.name} one question to confirm its session.`},console.log(`Checking that ${jt.name} can answer before accepting work.`);try{await j1(M,jt.name),Hn={state:"ready",detail:`${jt.name} answered; its session is usable.`},dt.agent_session={...dt.agent_session,status:"authenticated",message:Hn.detail},console.log(Hn.detail)}catch(e){Hn={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:M.hunt_host?YR(M.agent_id||M.agent_protocol):Oa(M.agent_id||M.agent_protocol)},dt.agent_session={...dt.agent_session,status:"logged_out",message:Hn.remedy},console.error(`${Hn.detail}
|
|
1210
1210
|
${Hn.remedy}`)}kr(),Hn.state==="ready"&&(kc(),ci().bugHunts.wake().catch(e=>console.error(`Bug Hunter local scheduler: ${e.message}`))),await Xi(M,M.workspace).catch(()=>null)}}function Sre(){clearInterval(Qv);let e=!1,t=0,n=0,r=!1,o=()=>{bs.tick(),xre(),wre(),$u&&(Hn===null||M.hunt_host&&Hn?.state==="failed"&&Date.now()-kM>=KR(kre))&&vs().then(s=>{if(s)return Ph()}),!M.hunt_host&&!r&&Zl(Fv.id)&&(r=!0,pM.flush().then(()=>$h(Fv)).catch(s=>Eh(Fv,s)).finally(()=>{r=!1})),kr(),!M.hunt_host&&!Wo&&Date.now()-t>=nre&&Zl(Dv.id)&&(t=Date.now(),xM().then(()=>$h(Dv)).catch(s=>Eh(Dv,s))),!M.hunt_host&&lM&&!Th&&Zl(Lv.id)&&Date.now()-fM>=QE&&(Th=!0,Ere().then(()=>$h(Lv)).catch(s=>Eh(Lv,s)).finally(()=>{Th=!1})),!e&&Date.now()-n>=rre&&Zl(Uv.id)&&(e=!0,n=Date.now(),Nr(M.workspace).then(async s=>{if(dt.tool_inventory=s,!_s&&Fi(s))try{await(await gi(await Js(M.workspace))).close(),_s=!0}catch{_s=!1}dt.bug_hunt_browser=Fi(s)&&_s,dt.bug_hunt_browser&&(Tu=null),kr(),$h(Uv)}).catch(s=>Eh(Uv,s)).finally(()=>{e=!1}))};o(),Qv=setInterval(o,1e4),bre()}async function xre(){if(!(!mM||M.agent_protocol!=="acp"||!M.agent_id||Wv||Hn?.state==="checking"||Date.now()-YN<ore)){Wv=!0;try{if(!await vs())return;YN=Date.now();let e,t=await hA(M,{verify:async r=>{e=await Cl(r,M.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===M||sn)return;M={...t,execution_profiles:e.executionProfiles??null},await Vr(M),jt=e,Hn=null;let n=Of(M,jt,dt.tool_inventory);if(Object.assign(dt,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),Ji.capabilities=dt,!await vs())return;await _l(),Ph(),fn?.readyState===WebSocket.OPEN&&fn.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{Wv=!1}}}function Eh(e,t){let n=JO(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 $h(e){XO(e.id)&&console.log(`${e.title} recovered.`)}async function Ere(){if(M.hunt_host||!await vs())return;fM=Date.now();let{jobs:e}=await Bs(M.workspace).catch(()=>({jobs:[]})),t=await e$(M.workspace,{jobs:e});if(!t$(t))return;let n=`${t.fingerprint}:${qv.join(",")}`,r=Hv?.key===n,o=r?Hv.candidates:await U1(M,t,qv);Hv={key:n,candidates:o};let s=await Vi(o$(t,o,{version:ui}));Array.isArray(s?.refused)&&(qv=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 ii=null,sM=null;async function xM(){if(!M.hunt_host){if(Wo)return Wo;Wo=(async()=>{let e=await qE(M,{knownRevision:ii?.revision??null});if(e.unchanged||(ii=e),sM===ii.revision)return ii;let{jobs:t}=await Bs(M.workspace);return!t.some(r=>Ih.includes(r.status))&&li===0&&cr.size===0&&(await sp(M.workspace,ii),sM=ii.revision),ii})();try{return await Wo}finally{Wo=null,kc()}}}function iM(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)),Zn.get(e)?.events.push(n)}var aM=null;function kc(){let e=fn.readyState===WebSocket.OPEN,t=cr.values().next().value,n=as(M.worker_limit)??Math.min(Ma(),hy(t?.workerLimit??gc[0]?.worker_limit)),r=e&&!Wo&&li===0?_1(gc,cr.size,n):[];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:hy(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};cr.set(i,a),Tre(s,a)}r.length>0&&kr();let o=v1({queued:gc,running:cr.size,workerLimit:n,connected:e,designSync:!!Wo,integrations:li});o&&o!==aM&&console.log(o),aM=o}function Mh(e){let t=my(e);return t?`${jt.name} on ${t}`:jt.name}async function EM(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s=`${r} \xB7 ${Mh(e)}`,i=I1(e,jt.name),a={runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:Z1(Vi),executionRevision:$M(e),sessionKey:Bp(e),sessionId:null,phase:"preparing",lastMessage:s,replacement:null};Zn.set(t,a);let c=Y1(Vi,{type:"prompt.heartbeat",prompt_id:t,execution_revision:a.executionRevision},{onError:g=>console.error(`[${n}] Prompt heartbeat: ${g.message}`)}),l,u=g=>{let y=g?JSON.stringify(g):null;!y||y===l||Zn.get(t)!==a||(l=y,iM(t,g))},p=Number(e.answer_within_seconds),d=p>0?o+p*1e3:void 0;console.log([`[${n}] ${i} for ${r}.`,`${jt.name} can reason for several minutes without reporting a step.`,...d?[Gh(d,o)]:[]].join(" ")),iM(t,{kind:"status",message:i}),hn.status(n,s,o,{link:vc,answerBy:d,phase:a.phase});let f=g=>{let y=g1(g),v=m1(g),_=ji(g);Zn.get(t)===a&&(v&&(a.phase=v),(_??y?.message)&&(a.lastMessage=_??y?.message),hn.status(n,a.lastMessage,o,{link:vc,answerBy:d,phase:a.phase}),ob(n,_??y?.message));let w=g.type==="forge.output"?null:_;u(y??(w?{kind:"status",message:w}:null))},h="failed",m=[r];try{Gp(e)||(f({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await KE(xM,{pinned:!!e.local_design_context,last:ii,onFallback:(_,w)=>f({type:"connector.step",message:`Design context not refreshed (${_.message}); continuing with ${w?"the copy synced earlier":"none"}`})})});let g=await a1(e,M,{onProcess:_=>{Zn.get(t)===a&&(a.child=_)},onController:_=>{Zn.get(t)===a&&(a.controller=_)},onSession:_=>{a.sessionId=_},onEvent:f},{signal:a.cancellation.signal});if(a.stoppedHere)throw new Error(cM);let y=g.singleTurn?w0(M.sessions,g.sessionKey):mm(M.sessions,g.sessionKey,g.sessionId);if(JSON.stringify(y)!==JSON.stringify(M.sessions||{})&&(M={...M,sessions:y},await Vr(M)),a.cancelled)return;await a.events.close().catch(_=>{console.error(`[${n}] Prompt progress delivery: ${_.message} The agent has finished; submitting its complete response separately.`)});let v=await Hp(Vi,{type:"prompt.completed",prompt_id:t,execution_revision:a.executionRevision,content:g.content,model:g.model,session_id:g.sessionId,usage:g.usage});v||console.error(`[${n}] ${Sy}`),Ou.record("prompt","completed",{durationMs:Date.now()-o,usage:g.usage}),h=v?"finished":"undelivered",m=[Lu(g.usage),r]}catch(g){let y=a.stoppedHere?cM:Dn(g);if(Ou.record("prompt","failed",{durationMs:Date.now()-o}),a.stoppedHere&&(h="cancelled"),!a.cancelled){try{await Hp(Vi,{type:"prompt.failed",prompt_id:t,execution_revision:a.executionRevision,message:y})||console.error(`[${n}] ${Sy}`)}catch(v){console.error(`[${n}] Prompt failure delivery: ${v.message}`)}console.error(y)}}finally{await c.stop(),a.events.stop();let g=a.replacement;g?(h="replaced",m=[`continuing on ${Mh(g)}`,r]):a.cancelled&&(h="cancelled"),hn.finish(n,h,m),Zn.get(t)===a&&Zn.delete(t),g&&Are(a,g)}}var cM="Cancelled from the connector terminal by the person running it.";async function sb(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function $M(e){return Number(e.execution_revision)||1}async function $re(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 ${Mh(t)}.`),await sb(e))}function Are(e,t){e.sessionId&&(M={...M,sessions:mm(M.sessions,e.sessionKey,e.sessionId)},Vr(M).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),EM(t)}async function Tre(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 ${Mh(e)}.`),!Gv.has(n)){Gv.add(n);try{let b=await p1(M.workspace);if(!b.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let x=b.accepted_head_revision?b.current_head_revision?b.current_head_revision!==b.accepted_head_revision?`The workspace is now at commit \`${b.current_head_revision}\`; the accepted assessment is from \`${b.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${b.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 ${b.stages.length||"no"} section(s). ${x}`)}}catch(b){console.error(`Assessment freshness check failed: ${b.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,p=null,d=null,f=null,h=new Set,m=()=>!sn&&cr.get(t.key)===t,g=async b=>{try{return await Hp(Vi,b)||console.warn(`[${s}] ${X1}`),!0}catch(x){return console.error(`Assessment failure delivery: ${x.message}`),!1}},y=(b,{milestone:x=!0}={})=>{if(!m()||x&&f===b)return;x&&(f=b,h.has(b)||(h.add(b),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${b}.`));let k=String(b).slice(0,500);t.progressPercent=c,t.lastMessage=k,hn.status(s,k,o,{link:vc,phase:t.phase})};y(`Starting ${r} assessment stage`);let v=setInterval(()=>{let b=Date.now(),x=b-t.lastActivityAt,k=i&&!a?h1(r,x):null;if(!p&&k){p=k,console.error(`[assessment:${r}] ${p}`),_y(t.controller,t.child);return}p||ks.observe({at:b,level:"info",message:hn.status(s,`${t.lastMessage} \xB7 last agent activity ${vt(x)} ago (${t.eventCount.toLocaleString()} events)`,o,{phase:t.phase})})},15e3),_={onSession:async b=>{m()&&(d=String(b),await lS(M.workspace,n,r,b,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:b=>{m()&&(t.controller=b)},onProcess:b=>{m()&&(t.child=b,i=!0,t.phase!=="correcting"&&(t.phase="running",y("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:b=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let x=f1(b);if(x&&y(x),!m())return;let k=ji(b);!k||k===t.lastDetail||(t.lastDetail=k,ob(s,k))}},w=(b,x)=>dy(b,x,M,_,{draftPath:Cn.relative(M.workspace,Cn.join(Rr(M.workspace,n),b.report_file)).split(Cn.sep).join("/")});try{let b=Bv-Date.now();b>0&&(y(`Waiting ${Math.ceil(b/1e3)}s for the model provider's rate limit to clear`),await new Promise(C=>setTimeout(C,b+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,y("Calculating changed files and affected behavior"));let x=await hS(M.workspace,e),k=await sg(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(k)w(k,x),y("Recovered completed stage report from connector storage");else{if(d=await uS(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),d&&y("Restoring interrupted agent session"),k=await i1(x,M,_,{previousSessionId:d}),p)throw new Error(p);a=!0,await og(M.workspace,n,x,k)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let S=C=>fetch(k0(M.server_url,M.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:JSON.stringify(C),signal:AbortSignal.timeout(qT)}),T=await C1(k,{submit:C=>O1(C,S,{isActive:()=>m()&&!sn,onRetry:(I,j)=>{y("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${Dn(I)} Retrying in ${Math.round(j/1e3)}s without rerunning the agent.`)}}),payloadFor:C=>r==="synthesis"?ig(M.workspace,n,C,{expectedSourceRevision:e.source_revision}):yS(C),rejectionFor:C=>ya(C,"the assessment"),correct:async(C,I)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!C.correctAfterRejection)throw new Error(`${I} The connector could not start the required agent correction.`);return C.correctAfterRejection(I)},onCorrected:async C=>{if(p)throw new Error(p);a=!0,await pS(M.workspace,n,r);let I=await og(M.workspace,n,x,C);return w(I,x),t.phase="delivering",t.lastMessage="Delivering corrected stage result",I}});if(p)throw new Error(p);k=T.result;let R=T.response;if(!R.ok)throw new Error(await ya(R,"the assessment"));if(l=!0,Ou.record("assessment stage","completed",{durationMs:Date.now()-o,usage:k.usage}),r==="synthesis"){let C=await R.json(),I=await mS(M.workspace,n,e,k,C.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${Cn.relative(M.workspace,I)}.`);try{let j=await Bu(M.workspace);j.committed&&console.log(`Assessment committed to Git as ${j.revision.slice(0,8)}.`)}catch(j){console.error(`The assessment is saved locally but could not be committed to Git: ${j.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(b){let x=p||Dn(b),k=x1(e,b),S=A1(b),$=k1(b);S&&(await dS(M.workspace,n,r).catch(R=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${R.message}`)}),d=null);let T=!p&&(d||S)&&(S||b1(b))&&k<$;if(m()&&T){t.phase="starting",t.lastMessage=S?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=E1(e,b);let R=$1(b,k);Il(b)&&(Bv=Math.max(Bv,Date.now()+R)),console.warn(`[assessment:${r}] ${S?"Agent session became unusable":"Agent session interrupted"}: ${x} ${S?"Starting a fresh session from the saved draft":`Resuming session ${d}`} in ${Math.round(R/1e3)}s (${k+1}/${$}).`),await new Promise(C=>setTimeout(C,R))}else m()&&(u=await g({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:x}));T||(Ou.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${x}`))}finally{clearInterval(v),hn.clearStatus(s),r==="synthesis"&&l&&Gv.delete(n),m()&&(cr.delete(t.key),R1(gc,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),kc())}}async function Rre(e){let t=String(e.run_id||"");li+=1;try{Wo&&await Wo;let n=await ZT(M.workspace,String(e.base_revision||""),String(e.head_revision||""),String(e.integration_branch||"")||null);if(n.applied){console.log(`Accepted Goal Run ${t} applied to the connected repository at ${n.revision} (${n.method}).`),await yc();return}console.warn(`Accepted Goal Run ${t} remains on its review branch. ${n.reason}`)}catch(n){console.error(`Accepted Goal Run ${t} could not be integrated: ${Dn(n)}`)}finally{li-=1,kc()}}function Ore(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error;return t}catch{Ut('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function Ut(e){console.error(e),process.exit(1)}yM().catch(e=>console.error(`Saved connector work: ${e.message}`));
|