@engineeros/connector 1.59.45 → 1.59.46
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.
|
@@ -738,7 +738,7 @@ ${o}`:""}`)}closed(){this.disposeInBackground()}disposeInBackground(){this.dispo
|
|
|
738
738
|
`)}),E=new Promise((A,R)=>{let j=(T,I=x)=>{if(!w){w=!0,h&&clearTimeout(h);for(let $ of u.values())$.reject(T||new Error("Codex app-server stopped."));u.clear(),T?R(Yo(T,{finalMessage:m||[...g.values()].map($=>$.text).filter(Boolean).join(`
|
|
739
739
|
|
|
740
740
|
`),output:_.slice(-2e4),model:r.model||y?.model||"codex-app-server",sessionId:p,resumed:!!o,usage:b,route_receipt:y},{protocol:"codex_app_server",stopReason:I,diagnostics:_})):A({finalMessage:m,output:_.slice(-2e4),model:r.model||"codex-app-server",sessionId:p,resumed:!!o,usage:b,route_receipt:y})}};l.once("error",j),l.once("close",T=>{w||j(new Error(`Codex app-server exited before completing the turn (code ${T??1}). ${_||l.engineerOsInputError?.message||""}`))}),PT.createInterface({input:l.stdout}).on("line",T=>{let I;try{I=JSON.parse(T)}catch{return}if(I.id!==void 0){let M=u.get(I.id);if(!M)return;u.delete(I.id),M.method==="turn/start"&&I.result?.turn?.id&&(f=I.result.turn.id),I.error?M.reject(new Error(I.error.message||"Codex app-server request failed.")):M.resolve(I.result);return}let $=I.params||{};if(I.method==="item/agentMessage/delta"&&typeof $.delta=="string"){if($.threadId!==p||f&&$.turnId!==f)return;let M=g.get($.itemId)??{text:"",phase:null};M.text+=$.delta,g.set($.itemId,M),s.onEvent?.({type:"codex.agent_message_delta",delta:$.delta})}else if(I.method==="item/started"||I.method==="item/completed"){if($.threadId!==p||f&&$.turnId!==f)return;$.item?.type==="agentMessage"&&g.set($.item.id,{text:$.item.text,phase:$.item.phase}),s.onEvent?.({type:`codex.${I.method}`,item:$.item,threadId:$.threadId})}else if(I.method==="turn/plan/updated")s.onEvent?.({type:"codex.turn/plan/updated",plan:$.plan,threadId:$.threadId});else if(I.method==="thread/tokenUsage/updated"){if($.threadId&&$.threadId!==p||$.turnId&&f&&$.turnId!==f)return;let M=$.tokenUsage||$.usage||$,C=M.total||$.total,P=M.last||$.last;o&&C&&P?(v??=MT($s(C),$s(P)),b=MT($s(C),v)):b=$s(o?null:C||P||M),s.onEvent?.({type:"codex.usage",update:$}),b&&h&&j(S)}else if(I.method==="turn/completed"&&$.threadId===p){if(f&&$.turn?.id!==f)return;let M=[...g.values()].reverse();m=(M.find(P=>P.phase==="final_answer")??M.find(P=>P.phase==null))?.text??"",$.turn?.status==="failed"?(S=new Error($.turn?.error?.message||"Codex turn failed."),x="failed",b?j(S):h||(h=setTimeout(()=>j(S),250))):m.trim()?b?j():h||(h=setTimeout(()=>{j()},250)):j(new Error("Codex completed without returning a response."))}}),l.stderr.setEncoding("utf8"),l.stderr.on("data",T=>{_=`${_}${T}`.slice(-2e4)}),(async()=>{try{let T=await k("initialize",{clientInfo:{name:Ny,title:"EngineerOS Connector",version:"0.11.0"}});l.stdin.write(`${JSON.stringify({method:"initialized"})}
|
|
741
|
-
`);let I=o?await k("thread/resume",{threadId:o,cwd:e,sandbox:n,approvalPolicy:"never",model:r.model||null,...r.reasoning_effort?{config:{model_reasoning_effort:r.reasoning_effort}}:{}}):await k("thread/start",{cwd:e,sandbox:n,approvalPolicy:"never",model:r.model||null,ephemeral:!1,...r.reasoning_effort?{config:{model_reasoning_effort:r.reasoning_effort}}:{}});y={source:"codex_app_server",user_agent:T.userAgent||null,runtime_version:E5(T.userAgent),model:I.model||null,provider:I.modelProvider||I.thread?.modelProvider||null,effort:I.reasoningEffort||null},p=I.thread.id,await s.onSession?.(p),s.onEvent?.({type:"thread.started",thread_id:p}),f=(await k("turn/start",{threadId:p,input:[{type:"text",text:ni(t,!!o)}],effort:r.reasoning_effort||null})).turn.id}catch(T){j(T instanceof Error?T:new Error(String(T)))}})()}).finally(()=>Ct(l).catch(()=>{}));return{child:l,completed:E,cancel:async()=>{if(p&&f&&!w)try{await k("turn/interrupt",{threadId:p,turnId:f})}catch{}await Ct(l)}}}function MT(e,t){if(!e)return null;if(!t)return e;let n=Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Math.max(0,o-(t[r]??0))]));return n.total_tokens>0?n:null}N();import{readFileSync as A5}from"node:fs";var My=Object.freeze({research:Object.freeze({sandboxMode:"read-only",skill:"project-research"}),assessment:Object.freeze({sandboxMode:"workspace-write",skill:"assessment-maintenance"}),planning:Object.freeze({sandboxMode:"read-only",defaultSkill:"delivery-planning",skills:Object.freeze(["delivery-planning","product-discovery","experience-design","solution-design","requirements-and-acceptance"])}),implementation:Object.freeze({sandboxMode:"workspace-write",skill:"implementation"}),verification:Object.freeze({sandboxMode:"read-only",skill:"independent-verification"})}),T5=new Set(["implementation","verification"]),FT=new Map,BT=V??null,Py=Object.freeze(Object.keys(My)),R5=Object.freeze([...new Set(Py.flatMap(e=>WT(My[e])))]);function zT(){return{agent_roles:[...Py],agent_skills:[...R5]}}function cf({agentRole:e,agentDefinition:t,prompt:n,sandboxMode:r,requiredOutputHeading:o,contextPack:s,memoryPack:i,selfContained:a=!1}){let c=qT(e,t,r),l=HT(n),u=VT(o),d=["# EngineerOS Agent Assignment","","## Active Role","",`- Role: ${c.title}`,`- Access: ${c.access}`,`- Responsibility: ${c.instruction}`,`- Permitted native tools: ${!a&&c.tools.length?c.tools.join(", "):"none"}`,"- User-facing language: refer to yourself neutrally as the Agent. Do not expose internal role, harness, provider, or coding-agent terminology unless the user asks.","- Recovery rule: resolve routine errors within the assigned scope and execution budget using saved work. For response-contract corrections, preserve evidence, failed checks and verdicts; do not repeat implementation or expand scope. Never discard an error merely to report success. Report unavailable prerequisites clearly and request approval for scope expansion."];a?d.push("","## Self-Contained Request","","-
|
|
741
|
+
`);let I=o?await k("thread/resume",{threadId:o,cwd:e,sandbox:n,approvalPolicy:"never",model:r.model||null,...r.reasoning_effort?{config:{model_reasoning_effort:r.reasoning_effort}}:{}}):await k("thread/start",{cwd:e,sandbox:n,approvalPolicy:"never",model:r.model||null,ephemeral:!1,...r.reasoning_effort?{config:{model_reasoning_effort:r.reasoning_effort}}:{}});y={source:"codex_app_server",user_agent:T.userAgent||null,runtime_version:E5(T.userAgent),model:I.model||null,provider:I.modelProvider||I.thread?.modelProvider||null,effort:I.reasoningEffort||null},p=I.thread.id,await s.onSession?.(p),s.onEvent?.({type:"thread.started",thread_id:p}),f=(await k("turn/start",{threadId:p,input:[{type:"text",text:ni(t,!!o)}],effort:r.reasoning_effort||null})).turn.id}catch(T){j(T instanceof Error?T:new Error(String(T)))}})()}).finally(()=>Ct(l).catch(()=>{}));return{child:l,completed:E,cancel:async()=>{if(p&&f&&!w)try{await k("turn/interrupt",{threadId:p,turnId:f})}catch{}await Ct(l)}}}function MT(e,t){if(!e)return null;if(!t)return e;let n=Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Math.max(0,o-(t[r]??0))]));return n.total_tokens>0?n:null}N();import{readFileSync as A5}from"node:fs";var My=Object.freeze({research:Object.freeze({sandboxMode:"read-only",skill:"project-research"}),assessment:Object.freeze({sandboxMode:"workspace-write",skill:"assessment-maintenance"}),planning:Object.freeze({sandboxMode:"read-only",defaultSkill:"delivery-planning",skills:Object.freeze(["delivery-planning","product-discovery","experience-design","solution-design","requirements-and-acceptance"])}),implementation:Object.freeze({sandboxMode:"workspace-write",skill:"implementation"}),verification:Object.freeze({sandboxMode:"read-only",skill:"independent-verification"})}),T5=new Set(["implementation","verification"]),FT=new Map,BT=V??null,Py=Object.freeze(Object.keys(My)),R5=Object.freeze([...new Set(Py.flatMap(e=>WT(My[e])))]);function zT(){return{agent_roles:[...Py],agent_skills:[...R5]}}function cf({agentRole:e,agentDefinition:t,prompt:n,sandboxMode:r,requiredOutputHeading:o,contextPack:s,memoryPack:i,selfContained:a=!1}){let c=qT(e,t,r),l=HT(n),u=VT(o),d=["# EngineerOS Agent Assignment","","## Active Role","",`- Role: ${c.title}`,`- Access: ${c.access}`,`- Responsibility: ${c.instruction}`,`- Permitted native tools: ${!a&&c.tools.length?c.tools.join(", "):"none"}`,"- User-facing language: refer to yourself neutrally as the Agent. Do not expose internal role, harness, provider, or coding-agent terminology unless the user asks.","- Recovery rule: resolve routine errors within the assigned scope and execution budget using saved work. For response-contract corrections, preserve evidence, failed checks and verdicts; do not repeat implementation or expand scope. Never discard an error merely to report success. Report unavailable prerequisites clearly and request approval for scope expansion."];a?d.push("","## Self-Contained Request","","- Answer from the Assignment and any application tool results supplied by EngineerOS. Native workspace inspection, file reads, searches and coding-agent tool calls are prohibited.","- Application tools are separate from native tools. If the Assignment lists an application tool protocol, request missing evidence through its structured Markdown requests before declaring it unavailable. EngineerOS validates and executes each request under the existing grants and approvals, then supplies its result for the next response. Never claim a requested action completed before receiving that result.","- If no listed application tool can obtain essential evidence, or its result reports a denied or failed operation, state the exact missing prerequisite. Do not bypass permissions, unresolved scope decisions or approval requirements."):T5.has(e)&&d.push("","## Tool Use","","- Every tool request resends this whole conversation. Let a long command such as a test run finish within the call that starts it, with a long enough timeout or wait, instead of checking on it repeatedly."),u||d.push("","## Interaction Contract","",a?"- Infer the current project situation from the Assignment before responding.":"- Infer the current project situation from the assignment and workspace evidence before responding.","- Lead with the useful answer or outcome. Do not narrate routine searches, tool calls, or internal work.","- When one next activity clearly follows and would help, offer exactly one short, concrete suggestion. Do not force a next step when none is useful.","- Ask a question only when a consequential choice cannot be resolved from available evidence.","- If the Assignment defines a response format, follow it exactly instead of adding conversational guidance.");let p=String(s||"").trim(),f=String(i||"").trim();return d.push("","## Active Skill","",I5(c.skill)),p&&d.push("","## Workspace Context","",p),f&&d.push("","## Session Memory","",f),d.push("","## Assignment","",l),u&&d.push("","## Final Response Contract","","- Return only the structured Markdown required by the Assignment.",`- The first non-whitespace line must be exactly: ${u}`,"- Do not add a preamble, status message, commentary, or code fence.","- Do not append a conversational summary or next activity."),d.join(`
|
|
742
742
|
`)}function GT({agentRole:e,agentDefinition:t,prompt:n,sandboxMode:r,sourceContext:o}){let s=qT(e,t,r),i=HT(n),a=["# EngineerOS Follow-up","","This message continues your current session. You already hold the earlier turns and the role, skill and workspace context they were sent with. Build on what you established: open only the files this message needs, and do not survey the workspace again.","","## Active Role","",`- Role: ${s.title}`,`- Access: ${s.access}`],c=String(o||"").trim();return c&&a.push("","## Project Evidence","",c),a.push("","## Message","",i),a.join(`
|
|
743
743
|
`)}function qT(e,t,n){let r=My[e];if(!r)throw new Error(`EngineerOS assignment has an unsupported agent_role. Expected one of: ${Py.join(", ")}.`);if(r.sandboxMode!==n)throw new Error(`EngineerOS ${e} role requires ${r.sandboxMode} access, but the assignment requested ${n}.`);return O5(t,e,r)}function HT(e){let t=String(e||"").trim();if(!t)throw new Error("EngineerOS assignment is missing prompt_markdown.");return t}function O5(e,t,n){if(!e||typeof e!="object")throw new Error("EngineerOS assignment is missing agent_definition.");if(e.role!==t||e.access!==n.sandboxMode)throw new Error("EngineerOS agent_definition does not match the assigned role and access.");if(!WT(n).includes(e.skill))throw new Error(`EngineerOS ${t} role does not allow the ${e.skill} skill.`);if(typeof e.title!="string"||!e.title.trim()||typeof e.instruction!="string"||!e.instruction.trim()||!Array.isArray(e.tools))throw new Error("EngineerOS agent_definition is incomplete.");return e}function WT(e){return e.skills??[e.defaultSkill??e.skill]}function iu(e,t){let n=VT(t);if(!n)throw new Error("EngineerOS structured output requires a heading contract.");let r=String(e||"").trim();if(!r)throw new Error("Agent completed without returning a response.");let o={"# Verification Report":"## Proof 1","# Review Report":"## Verdict","# Workspace Assessment":"## Executive Summary","# Workspace Assessment Delta":"## Updated Executive Summary","# Assessment Stage: Architecture":"## Architecture Summary","# Assessment Stage: Capability Catalog":"## Capability Catalog","# Assessment Stage: Capabilities":"## Observed Capabilities","# Assessment Stage: Quality":"## Quality Summary","# Assessment Stage: Synthesis":"## Executive Summary"}[n];if(o&&(r.startsWith(o)||C5(r,n)))return`${n}
|
|
744
744
|
|
|
@@ -1014,7 +1014,7 @@ Content-Length: 0\r
|
|
|
1014
1014
|
`)[0])}`)}let Kt=await gt.text().catch(()=>"");if(en(),U.blockedRequest)throw new Le("blocked",U.blockedRequest);let yn=null;try{yn=JSON.parse(Kt)}catch{yn=null}return U.response={status:gt.status(),text:Kt,json:yn,ms:c()-Xe},{method:we,url:K}}let $r=async z=>{let Q=[...new Set([...String(z??"").matchAll(lY)].map(te=>te[1]))],ue=String(z??"");for(let te of Q){let we=f[te];if(we===void 0||we==="")throw new Le("blocked",`Set ${te} on the hunt host (\`engineeros-connector secret set ${te} --project ${R??"<project id>"}\`).`);let K;try{K=await eh({value:String(we),now:c,sleep:xr})}catch{throw new Le("blocked",`${te} is not a valid authenticator secret.`)}ue=ue.replaceAll(`{totp:${te}}`,K)}return ue};async function Br(z,Q=Je,{signingIn:ue=!1}={}){if(en(),U.blockedRequest)throw new Le("blocked",U.blockedRequest);let te={action:z.action,target:ss(await $r(z.target),Q),data:ss(await $r(z.data),Q),check:ss(z.check,Q)};if(en(),te.action==="fill"&&!ue&&yC(te.data).blocked)throw new Le("blocked",K_);if(oe&&(["use account","run","open app"].includes(te.action)||te.action==="press"&&/enter/i.test(te.data)))throw new Le("blocked","Public pages only permits signed-out browsing and read-only request steps, without submitting.");if(w){if(!["open","request","wait for"].includes(te.action)||te.action==="request"&&!/^GET\s+/.test(te.target)||te.data)throw new Le("blocked","This action is not production-safe.");await xr(1e3)}if(!ue){let K=Mr(te,J);if(K)throw new Le("blocked",`Refused by the rule of engagement "${K}".`)}let we=te.check?os(te.check):[];switch(te.action){case"open app":{if(_.app_surface!=="electron")throw new Le("blocked","open app requires an Electron or WebDriver hunter.");if(process.env.ENGINEEROS_HUNT_HOST!=="dedicated")throw new Le("blocked","Electron requires ENGINEEROS_HUNT_HOST=dedicated on a VM or spare machine.");if(oe||w||[ie,t.api_url].some(K=>/^https?:/i.test(K??"")))throw new Le("blocked","Electron cannot enforce this web target's approved socket destinations. Use the managed local browser for protected web testing.");if(ut)throw new Le("needs_repair","Open the app once per case.");y("Local Electron actions are available; Electron network transport is not qualified for protected web testing."),ut=await b({executablePath:_.app_path,args:_.app_arguments||[],cwd:l}),_e?.aborted&&(await Xt(),en()),await ft();break}case"use account":Ge(await me(te.target.trim()));break;case"open":{await ft();let K=it(te.target.trim(),ie),Ee=Xe=>new Le("blocked",`${U.account.role}'s recorded sign-in has expired or was signed out: opening ${K} led to ${Xe}. Record it again in Bug Hunter Setup.`),ve;try{ve=await U.page.goto(K,{waitUntil:"domcontentloaded",timeout:L.navigation})}catch(Xe){let gt=String(Xe.message).split(`
|
|
1015
1015
|
`)[0];throw U.account?.storage_state&&/ERR_BLOCKED_BY_CLIENT/.test(gt)?Ee("another site"):new Le("blocked",`Opening ${K} failed: ${Mt(gt)}`)}if(await zt(),U.account?.storage_state&&wh(K,U.page.url(),pe))throw Ee(Mt(U.page.url(),200));await Fr({requested:K,reopen:async()=>{ve=await U.page.goto(K,{waitUntil:"domcontentloaded",timeout:L.navigation}),await zt()}}),await Lr();let Fe=ve?.status?.()??200;if(Fe>=500)throw new Le("failed",`The server answered ${Fe} for ${K}.`,`server error ${Fe}`);break}case"click":case"hover":case"check":case"uncheck":case"fill":case"select":{await ft();let K=await Gn(eo(te.target));await Bo(async()=>{te.action==="click"?await K.click({timeout:L.action}):te.action==="hover"?await K.hover({timeout:L.action}):te.action==="check"?await K.check({timeout:L.action}):te.action==="uncheck"?await K.uncheck({timeout:L.action}):te.action==="fill"?await K.fill(te.data,{timeout:L.action}):await K.selectOption({label:te.data},{timeout:L.action})}),te.action==="click"&&await zt();break}case"press":{if(await ft(),te.target.trim()){let K=await Gn(eo(te.target));await Bo(()=>K.press(te.data.trim(),{timeout:L.action}))}else await Bo(()=>U.page.keyboard.press(te.data.trim()));await zt();break}case"go back":await ft(),await Bo(()=>U.page.goBack({timeout:L.navigation})),await zt();break;case"reload":await ft(),await Bo(()=>U.page.reload({timeout:L.navigation})),await zt(),await Lr();break;case"set viewport":{await ft();let[K,Ee]=(te.data||te.target).trim().toLowerCase().split("x").map(Number);await U.page.setViewportSize({width:K,height:Ee});break}case"wait for":await ft();break;case"request":{await ft();let{method:K,url:Ee}=await xo(te.target,te.data);if(U.response.status>=500&&!we.some(ve=>["status","status_below","status_in"].includes(ve.kind)))throw new Le("failed",`The server answered ${U.response.status} for ${K} ${Ee}.`,`status was ${U.response.status}: ${Mt(U.response.text,200)}`);break}case"poll":{await ft();let K=c()+(Number(te.data.trim())||JK)*1e3;for(;;){await xo(te.target,"");let Ee=[];for(let ve of we){let Fe=await gs(ve);Fe!==null&&Ee.push(Fe)}if(!Ee.length)break;if(c()>=K)throw new Le("failed",`It never answered as expected: ${Ee.join("; ")}.`,Ee.join("; "));await xr(XK)}return zn()}case"set device":{if(U.page)throw new Le("needs_repair","Set the device before opening a page or using an account.");if(_.device_cloud_url){yt=te.data.trim(),lt.hasTouch=!0;break}let K=te.data.trim().toLowerCase(),Ee=Object.entries(g).find(([Xe])=>Xe.toLowerCase()===K);if(!Ee)throw new Le("needs_repair",`${te.data.trim()} is not a device the browser knows; use a name such as iPhone 13 or Pixel 7.`);let{defaultBrowserType:ve,...Fe}=Ee[1];Object.assign(lt,Fe);break}case"tap":{if(await ft(),!lt.hasTouch)throw new Le("needs_repair","tap needs a touch device; set one with set device first.");let K=await Gn(eo(te.target));await Bo(()=>K.tap({timeout:L.action})),await zt();break}case"set locale":lt.locale=te.data.trim();break;case"set time zone":lt.timezoneId=te.data.trim();break;case"set network":{await ft();let K=te.data.trim().toLowerCase();fr.setNetwork(K),await U.context.setOffline(K==="offline"),K!=="offline"&&await(await U.context.newCDPSession(U.page)).send("Network.emulateNetworkConditions",K==="slow"?WK:VK);break}case"run":{let K;try{K=jn(te.target.trim())}catch(Fe){throw new Le("needs_repair",`\`${te.target}\` cannot run without a shell: ${Fe.message}`)}let Ee=xv.basename(K[0]).replace(/\.(exe|cmd|bat)$/i,"").toLowerCase();if(!H.has(Ee))throw new Le("blocked",`${K[0]} is not a program this hunter may run (${[...H].join(", ")||"none are allowed"}).`);let ve=await d(K,{onChild:Ia,cwd:l,timeoutMs:L.command,...u?{env:u}:{},...te.data?{input:te.data}:{}});if(ve.notFound)throw new Le("blocked",`${K[0]} is not installed on the hunt host.`);U.command={exitCode:ve.exitCode,output:De(String(ve.output??""))};break}case"use":{let K=Y.get(te.target.trim().toLowerCase());if(K?.builtin==="inbox"){if(!A)throw new Le("blocked","The test inbox is not set up on this hunt host.");U.command=await rh(A,te.data,dt);break}if(!K)throw new Le("blocked",`${te.target.trim()} is not an instrument approved for this environment (${[...Y.keys()].join(", ")||"none are"}).`);let Ee=K.env??[],ve=Ee.filter(Yt=>f[Yt]===void 0);if(ve.length)throw new Le("blocked",`Set ${ve.join(", ")} on the hunt host to use ${K.name}.`);let Fe=Object.fromEntries(Ee.map(Yt=>[Yt,String(f[Yt])])),Xe={...Q,...Fe,data:te.data,since:new Date(dt).toISOString()},gt=(K.command??[]).map(Yt=>ss(String(Yt),Xe)),Kt=await d(gt,{onChild:Ia,cwd:l,timeoutMs:L.command,env:{...u??process.env,...Fe}});if(Kt.notFound)throw new Le("blocked",`${gt[0]} is not installed on the hunt host.`);let yn=String(Kt.output??"");for(let Yt of Object.values(Fe))Yt&&(yn=yn.replaceAll(Yt,"[secret]"));U.command={exitCode:Kt.exitCode,output:De(yn)};break}case"wait until":{let K=/^step\s+(\d+)$/i.exec(te.target.trim()),Ee=K?sl[Number(K[1])-1]:dt;if(Ee===void 0)throw new Le("needs_repair",`wait until counts from step ${K[1]}, which has not run yet.`);let ve=Ee+(Xf(te.data)??0);if(ve-c()>YK)throw new Le("needs_repair","wait until may wait at most three hours.");ve>c()&&await xr(ve-c());break}case"crawl":{await ft();let K=Math.min(Number(te.data)||Ev,ZK),Ee=U.account?.role??null,ve=c(),Fe=()=>c()<ve+Math.min(L.crawl+U.scanMs,3*L.crawl),Xe=He?[]:[{url:it(te.target.trim()||"/",ie),from:null,source:"link"}],gt=[];for(let G of ph(ae,J))try{gt.push({url:it(G.path,ie),from:null,source:G.source,seed:!0})}catch{}let Kt=gt.some(G=>G.url.includes("/#/")),yn=new Set(he),Yt=new Set(he),xn=new Map,Go=!1,Hn=new Map,Et={pages:0,server_errors:[],broken_links:[],routes:[],scripts:[],controls_explored:0,explore_blocked_writes:0,explore_stopped_pages:0,explore_stopped_time:0};U.crawl=Et;let Ze=[],St=null,or=async()=>{let[G,re]=await Promise.all([U.page.title(),U.page.evaluate(Ei)]);return`${G??""}\0${re.elements.join("")}`},qo=async()=>{let G=`__engineeros_probe_${Math.random().toString(36).slice(2,8)}`;try{return await U.page.goto(it(Kt?`/#/${G}`:`/${G}`,ie),{waitUntil:"domcontentloaded",timeout:L.navigation}),await zt(),await or()}catch{return!1}};for(;(Xe.length||gt.length)&&Et.pages<K&&Fe()&&!Z();){en();let G=gt.length&&(Go||!Xe.length)?gt.shift():Xe.shift();Go=!Go;let re=to(new URL(G.url));if(re===null)continue;let ge=Ou(re);if(yn.has(re)||(Hn.get(ge)??0)>=eY||(yn.add(re),Hn.set(ge,(Hn.get(ge)??0)+1),Mr({action:"open",target:re,data:"",check:""},J)))continue;G.seed&&St===null&&(St=await qo()),U.path=G.from,U.pathRole=Ee;let $e={path:re.slice(0,300),source:G.source,status:null,outcome:"reached",from_path:G.from?G.from.slice(0,300):null},Pe=(Ot,ct=null)=>{G.from&&(Et.broken_links.push({from:G.from,url:G.url,status:Ot}),fr.note("broken_link",G.from,{url:G.url,status:Ot,error:ct,message:`A link to ${re} ${Ot?`answers ${Ot}`:"cannot be opened"}`}))},Ie;try{Ie=await U.page.goto(G.url,{waitUntil:"domcontentloaded",timeout:L.navigation})}catch(Ot){let ct=String(Ot.message).split(`
|
|
1016
1016
|
`)[0];/ERR_(?!BLOCKED_BY_CLIENT)[A-Z_]+/.test(ct)&&Pe(null,ct),Et.routes.push({...$e,outcome:"error"});continue}await zt(),Ee&&await Fr({requested:G.url,crawling:!0,reopen:async()=>{Ie=await U.page.goto(G.url,{waitUntil:"domcontentloaded",timeout:L.navigation}),await zt()}}).catch(()=>!1),await Lr();let je=Ie?.status?.()??200;$e.status=je;let tt=je===404||je===410;if(await(async()=>{if(!Ee||tt)return!1;if(je===403)return!0;if(je>=400)return!1;try{let[Ot,ct,Gt]=await Promise.all([U.page.title(),U.page.evaluate(Ei),U.page.evaluate(()=>document.querySelector("h1")?.innerText??"")]);return aY.test(`${Ot??""} ${Gt??""}`)&&ct.elements.length<=cY}catch{return!1}})()){Et.routes.push({...$e,outcome:"forbidden"});continue}let xe=to(new URL(U.page.url())),Be=je===401||je===403||wh(G.url,U.page.url(),pe)||xe!==re&&xi({key:xe,elements:(await U.page.evaluate(Ei).catch(()=>({elements:[]}))).elements});if(Be){if(Et.routes.push({...$e,outcome:"sign_in"}),G.seed){let Ot=new URL(U.page.url()),ct=`${Ot.origin}${je===401||je===403?`:${je}`:to(Ot)}`,Gt=(xn.get(ct)??0)+1;xn.set(ct,Gt),Gt>=3&>.length&&(Et.deferred_seeds=gt.length,gt.length=0)}if(je===401||je===403)continue}else if(G.seed){if(tt||St&&await or()===St){Et.routes.push({...$e,outcome:"not_found"});continue}}else if(tt){Pe(je),Et.routes.push({...$e,outcome:"not_found"});continue}else je>=400&&je!==401&&je!==403&&Pe(je);let qe=new URL(U.page.url()),_t=to(qe);if(Be||Et.routes.push({...$e,outcome:je>=500?"error":"reached"}),_t===null||!pe.has(qe.hostname.toLowerCase())||Yt.has(_t))continue;Yt.add(_t),Et.pages+=1,Be&&_t!==re&&Et.routes.push({path:_t.slice(0,300),source:"navigation",status:je,outcome:"reached",from_path:null}),je>=500&&Et.server_errors.push(_t),await zn(),await Xs();let Pt=await U.page.evaluate(hI).catch(()=>[]);Ze.push({key:_t,url:U.page.url(),links:Array.isArray(Pt)?Pt.length:0});for(let Ot of Array.isArray(Pt)?Pt:[]){let ct;try{ct=new URL(Ot,qe)}catch{continue}!/^https?:$/.test(ct.protocol)||!pe.has(ct.hostname.toLowerCase())||dh(ct.href,J)&&(gI.test(ct.hash)||(ct.hash=""),yn.has(to(ct))||Xe.push({url:ct.toString(),from:_t,source:"link"}))}}if(await Se(),Re&&!w&&Ze.length&&!Z()){let G=c(),re=()=>Z()||c()-G>=L.explore,ge=[...Ze].sort((Pe,Ie)=>Pe.links-Ie.links),$e=async Pe=>{await U.page.goto(Pe.url,{waitUntil:"domcontentloaded",timeout:L.navigation}).catch(()=>{}),await zt()};U.exploring=!0;try{for(let Pe=0;Pe<ge.length&&!Et.explore_stopped_time;Pe+=1){if(en(),re()){Et.explore_stopped_time=1;break}let Ie=ge[Pe];try{await U.page.goto(Ie.url,{waitUntil:"domcontentloaded",timeout:L.navigation})}catch{continue}await zt();let je=await U.page.evaluate(tI).catch(()=>[]),{chosen:tt,cut:Ut}=nI(Array.isArray(je)?je:[],{forbidden:J,limit:hv});Ut&&(Et.explore_stopped_pages+=1);let xe=0;for(let Be of tt){if(en(),re()){Et.explore_stopped_time=1;break}let qe=Be.role?U.page.getByRole(Be.role,{name:Be.name,exact:!0}):U.page.getByText(Be.name,{exact:!0});if(await qe.count()!==1)continue;let _t=(await U.page.evaluate(Ei)).elements;try{await qe.click({timeout:L.action})}catch{}Et.controls_explored+=1,await xr(L.exploreSettle),await zt();let Pt=U.page.url(),Ot=null,ct=!1;try{let xt=new URL(Pt);Ot=to(xt),ct=pe.has(xt.hostname.toLowerCase())}catch{}if(Ot!==null&&Ot!==Ie.key&&ct){!Yt.has(Ot)&&Et.pages<K&&(Yt.add(Ot),yn.add(Ot),U.path=Ie.key,U.pathRole=Ee,Et.pages+=1,Et.routes.push({path:Ot.slice(0,300),source:"navigation",status:200,outcome:"reached",from_path:Ie.key.slice(0,300)}),await zn(),await Xs(),xe=0,ge.push({key:Ot,url:Pt,links:0})),await $e(Ie);continue}let Gt=(await U.page.evaluate(Ei)).elements,bt=Gt.filter(xt=>!_t.includes(xt));if(bt.length>=2){let xt={key:Ie.key.slice(0,300),origin:new URL(U.page.url()).origin,title:Mt(await U.page.title().catch(()=>""),300),elements:[...new Set([..._t,...Gt])].slice(0,kv).map(Ce=>Mt(Ce,200)),role:Ee};i(xt),W(xt)}if(await Xs(),bt.length)xe=0,await $e(Ie);else if(++xe>=3){re()&&(Et.explore_stopped_time=1);break}}}}finally{U.exploring=!1}Et.explore_blocked_writes=U.blockedWrites}Et.scripts=fr.scripts(),Et.remaining_routes=[...Xe,...gt].flatMap(G=>{let re=to(new URL(G.url));return re&&!yn.has(re)?[{path:re,source:G.source}]:[]});return}case"remember":{let K=te.data.trim(),Ee=te.target.trim();if(Ee==="url")await ft(),Q[K]=U.page.url();else if(/^output(?:\s+field\s+|$)/i.test(Ee)){if(!U.command)throw new Le("needs_repair","Nothing was run before this step to remember output from.");let ve=Ee.replace(/^output\s*(?:field\s+)?/i,"");if(!ve)Q[K]=U.command.output.trim();else{let Fe=null;try{Fe=JSON.parse(U.command.output)}catch{Fe=null}let Xe=Fe===null?{found:!1}:Pu(Fe,ve);if(!Xe.found)throw new Le("needs_repair",`The last output has no field ${ve} to remember.`);Q[K]=Dc(Xe.value)}}else if(/^field\s+/i.test(Ee)){let ve=Ee.replace(/^field\s+/i,""),Fe=U.response?Pu(U.response.json,ve):{found:!1};if(!Fe.found)throw new Le("needs_repair",`The last response has no field ${ve} to remember.`);Q[K]=Dc(Fe.value)}else{await ft();let ve=await Gn(eo(Ee));Q[K]=String(await ve.innerText()).trim()}break}default:throw new Le("needs_repair",`\`${te.action}\` is not an action.`)}en(),await So(we),await zn()}let zo=async()=>(await fr.settled(),{execution_context:{browser:ut?"electron":"chromium",browser_version:typeof(ut||e)?.version=="function"?(ut||e).version():null,role:U.account?.role??"",context_sha256:jK("sha256").update(JSON.stringify(sn)).digest("hex")},signals:fr.signals(),api_calls:w?[]:fr.apiCalls(),vitals:ln,scanned:Gi,scan_ms:U.scanMs});try{for(let[z,Q]of q.slice(0,We===null?q.length:We-1).entries())try{if(U.step=z+1,await Br(Q),U.blockedRequest)throw new Le("blocked",U.blockedRequest);sl[z]=c(),await Xs()}catch(ue){let te=U.blockedRequest?new Le("blocked",U.blockedRequest):ue instanceof Le?ue:_e?.aborted?new Le("blocked",Mt(_e.reason?.message??"The hunt was stopped; remaining actions were not run.")):new Le("failed",Mt(ue.message));U.crawl||await zn({final:!0}).catch(()=>{});let we=await Na(),K=we?[{label:"after",step:z+1,media_type:"image/jpeg",data_base64:we}]:[];return Ve={outcome:te.outcome,failed_step:z+1,message:`${B} step ${z+1}: ${Mt(te.message,1e3)}`,observed:te.observed?Mt(te.observed,1e3):null,duration_ms:c()-dt,evidence:[...K,...pr],...await zo(),...U.crawl?{crawl:U.crawl}:{}}}return U.crawl||await zn({final:!0}).catch(()=>{}),Ve={outcome:"passed",failed_step:null,message:null,observed:null,duration_ms:c()-dt,evidence:pr,...await zo(),...U.crawl?{crawl:U.crawl}:{}}}finally{if(Ve&&ee){if(Ve.cleanup={state:"not_required",from_step:null,reason:null},We!==null){let ue=Mt(ss(ee.test_data,{unique:Je.unique}),1e3),te=We;Ve.cleanup={state:"completed",from_step:We,reason:null,test_data_scope:ue};try{en(),U.blockedRequest=null;for(let[we,K]of q.slice(We-1).entries()){if(te=We+we,/\{[A-Za-z_][A-Za-z0-9_]*\}/.test(ss(K.target+" "+K.data,Je)))throw new Error("Cleanup needs an identifier that this case did not observe. Resolve the owned test data before retrying.");if(await Br(K),U.blockedRequest)throw new Error("Cleanup was refused by this run's scope.")}}catch(we){Ve.cleanup={state:"pending",from_step:We,reason:`The approved cleanup could not complete: ${Mt(we.message,500)} Resolve this case's owned test data before another attempt.`,primary_outcome:Ve.outcome,primary_failed_step:Ve.failed_step,primary_message:Ve.message,test_data_scope:ue},Ve.outcome="blocked",Ve.failed_step=te,Ve.message=Ve.cleanup.reason}}Object.assign(Ve,await zo()),Ve.duration_ms=c()-dt}if(!_e?.aborted){for(let ue of nt.values())if(ue.account?.storage_state)try{let te=new Set(ue.account.sign_in_binding.origins),we=Ps(ue.page.url(),te)?await ue.page.evaluate(vv):null,K=ue.account.storage_state.sessionStorage??[],Ee=_a(await ue.context.storageState({indexedDB:!0}),te,we?[...K.filter(ve=>ve.origin!==we.origin),we]:K);await O(ue.account,Ee),ue.account.storage_state=Ee}catch{y("The case evidence was retained, but its renewed sign-in could not be kept. Check the protected store before the next run.")}}_e?.removeEventListener("abort",dr);let Q=(await Promise.allSettled([Bn,Xt()])).find(ue=>ue.status==="rejected");if(Q)throw Q.reason}}return{run:async(q,B)=>{let W=async()=>{if(M)return{outcome:"blocked",failed_step:1,message:"A preceding case has unfinished cleanup. Resolve its owned test data before resuming.",duration_ms:0,evidence:[]};let ee=await jt(q,B);return ee.cleanup?.state==="pending"&&(M=!0),ee};if(!n.some(ee=>ee.storage_state)&&B?.caseMetadata?.effects!=="test_data_write")return W();let le=$,X;$=new Promise(ee=>{X=ee}),await le;try{return await W()}finally{X()}}}}Tr();import mn from"node:path";import{mkdirSync as Woe}from"node:fs";import{format as Voe}from"node:util";In();N();cn();In();import{createHash as uY}from"node:crypto";import{readFile as dY,readdir as pY,rm as fY}from"node:fs/promises";import Du from"node:path";import{isDeepStrictEqual as hY}from"node:util";var mY=new Set(["prompt.completed","prompt.failed"]),$v=e=>uY("sha256").update(e).digest("hex"),vh=new Map,Lc=new Map,yI=e=>$v(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([r],[o])=>r.localeCompare(o))):n));function bh(e,t){let r=(vh.get(e)??Promise.resolve()).catch(()=>{}).then(t).finally(()=>{vh.get(e)===r&&vh.delete(e)});return vh.set(e,r),r}function _I(e){if(!e.connector_id||!e.server_url||!e.workspace)throw new Error("Restore the paired connector configuration before delivering saved prompt results.");let t=JSON.stringify([e.server_url,e.connector_id,Du.resolve(e.workspace)]);return Du.join(Du.dirname(Mn(e.workspace)),"prompt-results",$v(t))}function kh(e,t){if(!mY.has(t.type)||!t.prompt_id)throw new Error("Only final prompt results belong in the prompt outbox.");return Du.join(_I(e),`${$v(JSON.stringify([t.prompt_id,t.execution_revision??1]))}.json`)}async function Sh(e){try{return JSON.parse(await dY(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw t}}function vI({getConfig:e,send:t,onRetained:n=()=>{}}){let r;function o(a,c){let l=Date.now();for(let[u,d]of Lc)d.expires<=l&&Lc.delete(u);if(c&&Lc.has(a)&&Lc.get(a).digest!==yI(c))throw new Error(`A different final result was already acknowledged for this prompt revision. Original evidence retained in EngineerOS; receipt: ${a}.`);return Lc.has(a)?{status:"delivered",file:a}:null}async function s(a,c){let l=JSON.parse(JSON.stringify(c)),u=await Sh(a);if(!u){u={update:l,saved_at:new Date().toISOString()};try{await Oe(a,JSON.stringify(u),{replace:!1})}catch(d){if(d.code!=="EEXIST")throw d;if(u=await Sh(a),!u)throw new Error(`Another connector delivered or changed this prompt result. Reconcile its existing receipt before retrying: ${a}`)}}if(!hY(u.update,l))throw new Error(`A different final result already exists for this prompt revision. Original evidence retained at ${a}.`);return{file:a,record:u}}async function i(a,c){if(c.rejection)return{status:"rejected",file:a,reason:c.rejection};try{return await t(c.update),Lc.set(a,{expires:Date.now()+36e5,digest:yI(c.update)}),await fY(a,{force:!0}),{status:"delivered",file:a}}catch(l){if(l.retryable===!1){let d=l.message||"EngineerOS rejected this prompt result.";return await Oe(a,JSON.stringify({...c,rejection:d})),n({status:"rejected",file:a,reason:d}),{status:"rejected",file:a,reason:d}}let u={status:"pending",file:a,reason:l.message};return n(u),u}}return{save(a){let c=kh(e(),a);return bh(c,()=>o(c,a)?{file:c,record:null}:s(c,a))},deliver(a){let c=kh(e(),a);return bh(c,async()=>{let l=o(c,a);if(l)return l;let{record:u}=await s(c,a);return i(c,u)})},replay(a){let c=kh(e(),{...a,type:"prompt.completed"});return bh(c,async()=>{let l=o(c);if(l)return l;let u=await Sh(c);return u?i(c,u):null})},flush(){if(r)return r;let a=_I(e());return r=(async()=>{let c;try{c=await pY(a)}catch(l){if(l.code==="ENOENT")return;throw l}for(let l of c.filter(u=>/^[a-f0-9]{64}\.json$/.test(u))){let u=Du.join(a,l);if((await bh(u,async()=>{let p=await Sh(u);if(!p||p.rejection)return null;if(u!==kh(e(),p.update))throw new Error(`Saved prompt result has an invalid identity: ${u}`);return i(u,p)}))?.status==="pending")break}})().finally(()=>{r=void 0}),r}}}N();function bI({capacity:e}){let t=[],n=0;function r(){for(;t.length&&n<Math.max(0,e());){let o=t.shift();o.signal?.removeEventListener("abort",o.abort),n++;let s=!1;o.resolve(()=>{s||(s=!0,n--,r())})}}return{get running(){return n},get waiting(){return t.length},drain:r,acquire({signal:o,onWaiting:s=()=>{}}={}){return o?.throwIfAborted(),new Promise((i,a)=>{let c={resolve:i,reject:a,signal:o,abort:null};c.abort=()=>{let l=t.indexOf(c);l<0||(t.splice(l,1),o.removeEventListener("abort",c.abort),a(o.reason))},o?.addEventListener("abort",c.abort,{once:!0}),t.push(c),r(),t.includes(c)&&s()})}}}N();Ma();N();var Lu=new Map;function Uu(e,t=Date.now()){let n=Lu.get(e);return!n||t>=n.retryAt}function kI(e,t,n,{remedy:r=null,now:o=Date.now()}={}){let s=Lu.get(e),i=(s?.failures??0)+1,a=Math.min(3e4*2**(i-1),6e5),c={id:e,title:t,remedy:r,message:gY(n),failures:i,firstFailedAt:s?.firstFailedAt??o,retryAt:o+a,retryInMs:a};return Lu.set(e,c),c}function SI(e){return Lu.delete(e)}function xI(e=Date.now()){return[...Lu.values()].map(t=>({...t,status:t.failures>=5?"failed":"warning",retryInMs:Math.max(t.retryAt-e,0)}))}function gY(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}In();var Av=22,wY=500,yY=300,_Y=20,EI={ok:0,warning:1,failed:2},AI={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."}},vY=360*6e4,$I=new WeakMap,bY="connector.diagnostics";function kY(e){return e.reduce((t,n)=>EI[n.status]>EI[t]?n.status:t,"ok")}async function TI({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=[SY(a),xY(e),await Fu("backend","EngineerOS backend",()=>EY(e,i)),await Fu("coding_agent","Coding agent",()=>$Y(e,t,r.inspectAgent,i)),...s?[TY(s)]:[],...r.connectorJobs?[await Fu("local_execution","Local testing work",()=>RY(r.connectorJobs))]:[],await Fu("tool_registry","Tool registry",()=>OY(t,r.inspectTools)),...e?.hunt_host?[]:[await Fu("goal_runner","Goal runner",()=>CY(t,r.runnerStatus,{serviceStatus:r.macRunnerStatus}))],...xI().map(IY),...o.map(l=>Vt(l.id,l.title,l.status,l.detail,l.remedy))].slice(0,_Y);return{checked_at:new Date().toISOString(),connector_version:String(n).slice(0,50),status:kY(c),checks:c}}function Tv(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(`
|
|
1017
|
-
`)}async function RI(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:bY,...t})??{}}function SY(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=Av?Vt("node_runtime","Node runtime","ok",`Node ${e}.`):Vt("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${Av} this connector requires.`,`Install Node ${Av} or later, then start the connector again.`)}function xY(e){return e?.connector_id&&e.token?Vt("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):Vt("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function EY(e,t){if(!e?.server_url)return Vt("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=qk(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return Vt("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${Rv(s)}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return Vt("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"?Vt("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):Vt("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function $Y(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 AY(o.protocol,r):null;return a&&Ro(a,i)>0?Vt("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,AI[o.protocol].remedy):Vt("coding_agent","Coding agent","ok",s)}catch(o){return Vt("coding_agent","Coding agent","failed",Rv(o),null)}}async function AY(e,t){let n=AI[e];if(!n)return null;let r=$I.get(t)??new Map;$I.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<vY)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;vn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function TY({state:e,detail:t,remedy:n=null}){return Vt("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function RY(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return Vt("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${o.blocked_report?.error?.message||o.error||o.checkpoint?.error||"An execution or report was refused; its original evidence remains saved on this machine."}`,"Inspect the saved connector job and its first blocked report on this machine. Fix the reported cause, then explicitly retry report delivery; do not rerun completed tests or delete their evidence.")}let r=t.flatMap(o=>Object.values(o.checkpoint?.server_effects??{}).flatMap(s=>s.response?.projection_warnings??[]));return r.length?Vt("local_execution","Local testing work","warning",`${r.length} result(s) were retained as history only. ${r[0].reason}`,"Inspect the saved result receipt and its execution context. History-only results do not verify a pass or resolve a finding; preserve their evidence and supply the reported prerequisite before a new authorized execution."):Vt("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function OY(e,t){let n=await t(e);if(n?.error)return Vt("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 Vt("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function CY(e,t,{platform:n=process.platform,serviceStatus:r=HO}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return Vt("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 Vt("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 Vt("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 Vt("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 Vt("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function IY(e){return Vt(e.id,e.title,e.status,`Failing since ${oo(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Fu(e,t,n){try{return await n()}catch(r){return Vt(e,t,"failed",Rv(r),null)}}function Vt(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,wY),remedy:o?String(o).slice(0,yY):null}}function Rv(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import qY from"node:path";N();import jY from"node:path";var CI=2,NY=300*1e3,MY={pytest:40,"node:test":40,vitest:60,jest:60},PY=3,DY=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),LY=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),OI=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 xh(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function II(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function UY(e){let t=String(e?.name??"");return LY.has(t)?{support:"helper"}:DY.has(t)?{support:"run"}:OI.has(t)?{support:"skipped",reason:OI.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var Ov=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),FY=(e,t)=>!t||e.startsWith(`${t}/`);function BY(e,t){let n=null;for(let r of t)r.name!==e.framework||!FY(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function zY(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>NY&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function jI({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(Ov)):null,i=[];for(let l of e){let u=UY(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:Ov(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:Ov(u.file)})))s&&!s.has(l.file)||BY(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=GY(l,r);l.shards=u.map(({files:d,packages:p},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:d,directory:l.root,packages:p}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(PY,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function GY(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=jY.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:[]}]:zY(e.files,{perShard:MY[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var HY=2;function Eh(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=zE(t.protocol);return{agent_protocols:[t.protocol],coding_agent:!0,connector_jobs:!0,self_contained_prompts:1,bug_hunt_development_v1:!0,...e.hunt_host?{hunt_host:!0}:{},capability_delivery:!e.hunt_host,goal_plan_review:!e.hunt_host&&(t.protocol==="codex"||e.agent_id==="codex-acp"&&e.agent_modes?.["read-only"]==="read-only"||e.agent_id==="claude-acp"&&e.agent_modes?.["read-only"]==="plan"||e.agent_id==="opencode"&&(!e.agent_modes?.["read-only"]||e.agent_modes["read-only"]==="plan")),measured_test_evidence:!e.hunt_host,test_automation_task:!e.hunt_host,test_checks:!e.hunt_host&&String(process.env.ENGINEEROS_TEST_CHECKS??"").trim().toLowerCase()!=="off",test_automation_workers:!e.hunt_host,model_probe:!0,test_schedules:!e.hunt_host,quality_baseline:!e.hunt_host&&xh(e),quality_baseline_contract:CI,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_scenarios:hC,bug_hunt_specialists:1,bug_hunt_actions:[...Jf],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:$i(n),bug_hunt_sign_in:ya,bug_hunt_inputs:1,bug_hunt_checks:[...J_],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_recovery:e.hunt_host?0:1,goal_run_contract:HY,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.45",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:Df,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:qY.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...mu(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...zT(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();cn();Zi();import{createHash as MI}from"node:crypto";import{readFile as WY}from"node:fs/promises";import VY from"node:os";import Iv from"node:path";var JY=/^[A-Z_][A-Z0-9_]*$/,XY=80,KY=64,NI="hunt-secret-";function zu(e){return typeof e=="string"&&e.length>0&&e.length<=XY&&JY.test(e)}function $h(e){let t=`${NI}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=KY?t:`${NI}h${MI("sha256").update(String(e)).digest("hex").slice(0,40)}`}function YY(e){let t=MI("sha256").update(Iv.resolve(e??process.cwd())).digest("hex").slice(0,16);return Iv.join(VY.homedir(),".engineeros","hunt-secrets",t)}function Cv(e){if(!zu(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function Gu({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??YY(e),o=t??sr({directory:r}),s=Iv.join(r,"names.json");async function i(){let u;try{u=await WY(s,"utf8")}catch(d){if(d?.code==="ENOENT")return[];throw d}try{let d=JSON.parse(u);return(Array.isArray(d?.names)?d.names:[]).filter(zu)}catch{return[]}}let a=Promise.resolve(),c=u=>{let d=a.then(async()=>{let p=new Set(await i());u(p),await Oe(s,`${JSON.stringify({names:[...p].sort()},null,2)}
|
|
1017
|
+
`)}async function RI(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:bY,...t})??{}}function SY(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=Av?Vt("node_runtime","Node runtime","ok",`Node ${e}.`):Vt("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${Av} this connector requires.`,`Install Node ${Av} or later, then start the connector again.`)}function xY(e){return e?.connector_id&&e.token?Vt("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):Vt("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function EY(e,t){if(!e?.server_url)return Vt("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=qk(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return Vt("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${Rv(s)}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return Vt("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"?Vt("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):Vt("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function $Y(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 AY(o.protocol,r):null;return a&&Ro(a,i)>0?Vt("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,AI[o.protocol].remedy):Vt("coding_agent","Coding agent","ok",s)}catch(o){return Vt("coding_agent","Coding agent","failed",Rv(o),null)}}async function AY(e,t){let n=AI[e];if(!n)return null;let r=$I.get(t)??new Map;$I.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<vY)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;vn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function TY({state:e,detail:t,remedy:n=null}){return Vt("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function RY(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return Vt("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${o.blocked_report?.error?.message||o.error||o.checkpoint?.error||"An execution or report was refused; its original evidence remains saved on this machine."}`,"Inspect the saved connector job and its first blocked report on this machine. Fix the reported cause, then explicitly retry report delivery; do not rerun completed tests or delete their evidence.")}let r=t.flatMap(o=>Object.values(o.checkpoint?.server_effects??{}).flatMap(s=>s.response?.projection_warnings??[]));return r.length?Vt("local_execution","Local testing work","warning",`${r.length} result(s) were retained as history only. ${r[0].reason}`,"Inspect the saved result receipt and its execution context. History-only results do not verify a pass or resolve a finding; preserve their evidence and supply the reported prerequisite before a new authorized execution."):Vt("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function OY(e,t){let n=await t(e);if(n?.error)return Vt("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 Vt("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function CY(e,t,{platform:n=process.platform,serviceStatus:r=HO}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return Vt("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 Vt("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 Vt("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 Vt("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 Vt("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function IY(e){return Vt(e.id,e.title,e.status,`Failing since ${oo(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Fu(e,t,n){try{return await n()}catch(r){return Vt(e,t,"failed",Rv(r),null)}}function Vt(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,wY),remedy:o?String(o).slice(0,yY):null}}function Rv(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}N();import qY from"node:path";N();import jY from"node:path";var CI=2,NY=300*1e3,MY={pytest:40,"node:test":40,vitest:60,jest:60},PY=3,DY=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),LY=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),OI=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 xh(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function II(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function UY(e){let t=String(e?.name??"");return LY.has(t)?{support:"helper"}:DY.has(t)?{support:"run"}:OI.has(t)?{support:"skipped",reason:OI.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}var Ov=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),FY=(e,t)=>!t||e.startsWith(`${t}/`);function BY(e,t){let n=null;for(let r of t)r.name!==e.framework||!FY(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function zY(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>NY&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function jI({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(Ov)):null,i=[];for(let l of e){let u=UY(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:Ov(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:Ov(u.file)})))s&&!s.has(l.file)||BY(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=GY(l,r);l.shards=u.map(({files:d,packages:p},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:d,directory:l.root,packages:p}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(PY,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function GY(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=jY.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:[]}]:zY(e.files,{perShard:MY[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var HY=2;function Eh(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=zE(t.protocol);return{agent_protocols:[t.protocol],coding_agent:!0,connector_jobs:!0,self_contained_prompts:1,bug_hunt_development_v1:!0,...e.hunt_host?{hunt_host:!0}:{},capability_delivery:!e.hunt_host,goal_plan_review:!e.hunt_host&&(t.protocol==="codex"||e.agent_id==="codex-acp"&&e.agent_modes?.["read-only"]==="read-only"||e.agent_id==="claude-acp"&&e.agent_modes?.["read-only"]==="plan"||e.agent_id==="opencode"&&(!e.agent_modes?.["read-only"]||e.agent_modes["read-only"]==="plan")),measured_test_evidence:!e.hunt_host,test_automation_task:!e.hunt_host,test_checks:!e.hunt_host&&String(process.env.ENGINEEROS_TEST_CHECKS??"").trim().toLowerCase()!=="off",test_automation_workers:!e.hunt_host,model_probe:!0,test_schedules:!e.hunt_host,quality_baseline:!e.hunt_host&&xh(e),quality_baseline_contract:CI,quality_map:!e.hunt_host,workspace_head:!e.hunt_host,bug_hunt:!0,bug_hunt_scenarios:hC,bug_hunt_specialists:1,bug_hunt_actions:[...Jf],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:$i(n),bug_hunt_sign_in:ya,bug_hunt_inputs:1,bug_hunt_checks:[...J_],bug_hunt_secret_names:[...r],resumable_runs:!e.hunt_host,goal_recovery:e.hunt_host?0:1,goal_run_contract:HY,delivery_tasks:{protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.59.46",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:Df,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:qY.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},...mu(e.worker_limit),agent_session:s,provider_login:{supported:i,mode:i?"connector_terminal":null},...zT(),...n?{tool_inventory:n}:{},execution_profiles:{...o,models:(o.model_profiles||[]).map(a=>a.id)}}}N();cn();Zi();import{createHash as MI}from"node:crypto";import{readFile as WY}from"node:fs/promises";import VY from"node:os";import Iv from"node:path";var JY=/^[A-Z_][A-Z0-9_]*$/,XY=80,KY=64,NI="hunt-secret-";function zu(e){return typeof e=="string"&&e.length>0&&e.length<=XY&&JY.test(e)}function $h(e){let t=`${NI}${String(e).toLowerCase().replace(/_/g,"-")}`;return t.length<=KY?t:`${NI}h${MI("sha256").update(String(e)).digest("hex").slice(0,40)}`}function YY(e){let t=MI("sha256").update(Iv.resolve(e??process.cwd())).digest("hex").slice(0,16);return Iv.join(VY.homedir(),".engineeros","hunt-secrets",t)}function Cv(e){if(!zu(e))throw new Error("A secret name uses capital letters, digits and underscores, for example ADMIN_TOTP_SECRET.");return e}function Gu({workspace:e=process.cwd(),vault:t,directory:n}={}){let r=n??YY(e),o=t??sr({directory:r}),s=Iv.join(r,"names.json");async function i(){let u;try{u=await WY(s,"utf8")}catch(d){if(d?.code==="ENOENT")return[];throw d}try{let d=JSON.parse(u);return(Array.isArray(d?.names)?d.names:[]).filter(zu)}catch{return[]}}let a=Promise.resolve(),c=u=>{let d=a.then(async()=>{let p=new Set(await i());u(p),await Oe(s,`${JSON.stringify({names:[...p].sort()},null,2)}
|
|
1018
1018
|
`)});return a=d.catch(()=>{}),d},l={directory:r,async get(u){Cv(u);let d=await o.get(e,$h(u));return typeof d=="string"&&d!==""?d:null},async set(u,d){if(Cv(u),typeof d!="string"||d==="")throw new Error("A secret needs a value.");await o.put(e,$h(u),d),await c(p=>p.add(u))},async remove(u){Cv(u),await o.delete(e,$h(u)),await c(d=>d.delete(u))},async names(){return(await i()).sort()},async has(u){return zu(u)?!!await o.has(e,$h(u)):!1},async values(u){let d={};for(let p of[...new Set(u??[])]){if(!zu(p))continue;let f=await l.get(p);f!==null&&(d[p]=f)}return d}};return l}async function PI({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(`
|
|
1019
1019
|
`),c?o(c):r(s)},a=c=>{for(let l of c){if(l==="\r"||l===`
|
|
1020
1020
|
`||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 Bu=(e,t)=>(t?.(e),{ok:!1,message:e});async function DI({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 Bu("Use `secret set NAME`, `secret list` or `secret remove NAME`.",i);let c=Gu({workspace:n,vault:o,directory:s});try{if(e==="list"){let d=await c.names();return a(!0,d.length?d.join(`
|
|
@@ -1252,7 +1252,7 @@ It is checked with the provider and stored in this machine's protected vault
|
|
|
1252
1252
|
(Windows Data Protection, the macOS Keychain or the Linux Secret Service).
|
|
1253
1253
|
EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function Boe(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(`
|
|
1254
1254
|
`),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
|
|
1255
|
-
`)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 pP=Symbol("missing");function zoe(e,t){return new Promise(n=>{let r=Uoe(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?pP:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function dP(e,t){for(let n of ud){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 fP(e,t,n,{vault:r=qb(),run:o=pm,fetchImpl:s=fetch,secret:i=Boe,interactive:a=zoe,install:c=cm,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(Foe),n.help?0:2;if(e==="integrations")return dP(l,(await mm({run:o,vault:r})).providers),0;let d=t[0];if(!ud.includes(d))return u(`Unknown provider ${d}. Choose one of: ${ud.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=$a[d];if(e==="disconnect")return l(`${d} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let m=await a(f,["auth","login"]);if(m===pP){let g=await Mi(f);if(!g){l(`Installing the ${rd[f].label} ${rd[f].version} for the connector...`);try{g=(await c(f)).path}catch(_){return u(_.message),1}}m=await a(g,["auth","login"])}return m?(u(`${m} ${hm[d]} is how this machine signs in to ${d}.`),1):(dP(l,{[d]:(await mm({run:o,vault:r})).providers[d]}),0)}let p=er[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Hb(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),m=await Wb(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${m.account?` as ${m.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}N();import{spawn as Goe}from"node:child_process";async function hP({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=Goe,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ti(await wr(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await qoe(o,c.entry,i,t);if(l===yl){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let d=await wr(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await ig(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${p.version}.`);continue}catch(p){s(`Automatic rollback failed: ${p.message}`)}}return l??1}}function qoe(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Da]:"1",[tg]:r.entry,[ng]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,d)=>{l(),o({code:u,signal:d})})})}var zi="1.59.
|
|
1255
|
+
`)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 pP=Symbol("missing");function zoe(e,t){return new Promise(n=>{let r=Uoe(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?pP:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function dP(e,t){for(let n of ud){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 fP(e,t,n,{vault:r=qb(),run:o=pm,fetchImpl:s=fetch,secret:i=Boe,interactive:a=zoe,install:c=cm,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(Foe),n.help?0:2;if(e==="integrations")return dP(l,(await mm({run:o,vault:r})).providers),0;let d=t[0];if(!ud.includes(d))return u(`Unknown provider ${d}. Choose one of: ${ud.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=$a[d];if(e==="disconnect")return l(`${d} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let m=await a(f,["auth","login"]);if(m===pP){let g=await Mi(f);if(!g){l(`Installing the ${rd[f].label} ${rd[f].version} for the connector...`);try{g=(await c(f)).path}catch(_){return u(_.message),1}}m=await a(g,["auth","login"])}return m?(u(`${m} ${hm[d]} is how this machine signs in to ${d}.`),1):(dP(l,{[d]:(await mm({run:o,vault:r})).providers[d]}),0)}let p=er[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Hb(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),m=await Wb(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${m.account?` as ${m.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}N();import{spawn as Goe}from"node:child_process";async function hP({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=Goe,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ti(await wr(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await qoe(o,c.entry,i,t);if(l===yl){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let d=await wr(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await ig(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${p.version}.`);continue}catch(p){s(`Automatic rollback failed: ${p.message}`)}}return l??1}}function qoe(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Da]:"1",[tg]:r.entry,[ng]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,d)=>{l(),o({code:u,signal:d})})})}var zi="1.59.46",km="1.59.46",Joe=3e5,Sm=["queued","running","reporting"],Xoe=5e3,Vb={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."},Jb={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."},Koe=6e4,Yoe=3e4,Zoe=60*6e4,Xb={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Kb={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:rn,positional:on,flags:Ke}=LI(process.argv.slice(2));rn==="version"&&(console.log(zi),process.exit(0));var Js=null,gn=!1,tr=null,md=null,RP=!1,OP=null,f0=null,wn=null,vd=null,c0,mP,gd,Yb,gP,Xc,nl,CP=Jh({getWorkspace:()=>D.workspace,onRecorded:e=>XN(D,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}`))}),Qoe=lP({getWorkspace:()=>D.workspace,getConfig:()=>D,huntSignIns:CP}),wd=zI();rn==="results"&&(on[0]!=="upload"&&(console.log(Nh),process.exit(Ke.help||!on[0]?0:2)),process.exit(await Kj(Ke)));(rn==="connect"||rn==="disconnect"||rn==="integrations")&&process.exit(await fP(rn,on,Ke,{fetchImpl:iP}));if(rn==="delivery"){let e=mn.resolve(Ke.workspace||process.cwd());try{if(on[0]==="execute")await rC(Ke.input);else if(on[0]==="worker"){let t=await Pn(e);if(!t)throw new Error("Restore the paired connector configuration before reporting or executing delivery work.");await jO(t,Ke["attempt-id"])}else if(on[0]==="probe"){let t=await Lf().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(Xn(t)),process.exit(1)}}if(rn==="runner"){let e=mn.resolve(Ke.workspace||process.cwd()),t=on[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?mn.join(mn.dirname(un(e,Ke["run-id"])),"worker.log"):mn.join(e,".engineeros","runner","service.log");Woe(mn.dirname(n),{recursive:!0});let r=(...s)=>gu(n,`${Voe(...s)}
|
|
1256
1256
|
`),o=(s,i,a)=>(gu(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(Ke["keep-awake"]!==void 0){if(!["on","off"].includes(Ke["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await Pn(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await Hr({...n,runner_keep_awake:Ke["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await GO(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 WO(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await fa(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await vi(e),null,2)):t==="serve"?await KO(e):t==="worker"?await YO(e,Ke["run-id"]):Jt("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){Jt(z_(n,e).message)}}Ke["assessment-workers"]!==void 0&&Jt("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(rn==="secret")try{let e=W_(Ke),t=on[0]||"list",n=await DI({action:t,name:on[1],workspace:e,readValue:()=>PI({label:`Value for ${on[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){Jt(e.message)}if(rn==="tools"){try{let e=W_(Ke),t=on[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=on[1];r||Jt(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await py(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 ly(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:on[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await cy(e,t,on[1]);let n=await kr(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){Jt(e.message)}process.exit(process.exitCode||0)}if(rn==="agents"){let e;try{e=await Oy()}catch(n){Jt(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await ru(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(rn==="agent"){let e=on[0],t=on[1]||"check";(!e||!["check","install"].includes(t))&&Jt("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await ou(e):await ru(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){Jt(n instanceof Error?n.message:String(n))}process.exit(0)}if(rn==="mcp"){let e=Ke.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=Ke["run-id"]||on[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await Pn(e);await ij({config:n,runId:t,version:zi,input:process.stdin,output:process.stdout}),process.exit(0)}if(rn==="context-mcp"){let e=Ke["config-workspace"]||Ke.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await Pn(e);t||Jt("This workspace is not paired with EngineerOS."),await Fj({config:t,workspace:Ke.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:zi,input:process.stdin,output:process.stdout}),process.exit(0)}if(rn==="status"){let e=await Pn(Ke.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(rn==="doctor"){let e=mn.resolve(Ke.workspace||process.cwd()),t=await Pn(e),n=await QI(e),r=await Ca(t||{workspace:e},e,jv(n));console.log(Tv(r)),process.exit(r.status==="failed"?1:0)}if(rn==="update"){let e=on[0]||"status";try{let t=og(process.argv[1],km),n=await ag(qr(),t,{action:e,policy:on[1]??null});console.log(vl(cg(n,t,{supervised:!0})))}catch(t){Jt(`${t.message}
|
|
1257
1257
|
Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var Yc=rn==="hunt-host";if(Yc){try{Ke.workspace=iC(on,Ke)}catch(e){Jt(e.message)}!on[0]&&mn.resolve(Ke.workspace)!==mn.resolve(process.cwd())&&console.log(`This hunt host still keeps its files in ${Ke.workspace}. To keep everything in ${process.cwd()}, pair it again from here with a new pairing command.`)}if((rn==="start"||rn==="pair"||Yc)&&process.env[Da]!=="1"&&vn(km))try{process.exit(await hP({root:qr(),bundled:{version:km,entry:mn.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:mn.resolve(Ke.workspace||process.cwd())}))}catch(e){Jt(`The connector process could not be started: ${e.message}`)}if(Yc){try{await aC(Ke.workspace,on[0]?Ke.agent:null)}catch(e){Jt(e.message)}rn=on[0]?"pair":"start"}var D,Oa,yd;if(rn==="pair"){let e=on[0];e||Jt("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=Ke.url;t||Jt("Pairing requires --url with the EngineerOS backend address."),Ke.agent&&Ke["agent-command"]&&Jt("Use either --agent or --agent-command, not both.");let n=Ke["agent-protocol"]||(Ke["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||Jt(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(Ke.agent||Ke["agent-command"])&&Jt("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{Ke.agent&&(await ru(Ke.agent),r=await Cy(Ke.agent))}catch(o){Jt(o instanceof Error?o.message:String(o))}D={server_url:dg(t),workspace:mn.resolve(Ke.workspace||process.cwd()),onboard:Ke.onboard===!0,onboarding_pending:Ke.onboard===!0,hunt_host:Yc,...Ke["knowledge-dir"]?{knowledge_dir:mn.resolve(Ke["knowledge-dir"])}:{},agent_protocol:n,agent_command:Ke["agent-command"]||null,agent_args:xse(Ke["agent-args"]),agent_name:Ke["agent-name"]||null,...r,skip_git_repo_check:Yc||Ke["skip-git-repo-check"]===!0,name:Ke.name||`${Hoe.hostname()} - ${mn.basename(mn.resolve(Ke.workspace||process.cwd()))}`},yd=await Pn(D.workspace),Oa={type:"pair",pairing_code:e,name:D.name,capabilities:{},...Pk(yd,D.server_url)}}else rn==="start"?(D=await Pn(Ke.workspace||process.cwd()),D||Jt("This connector is not paired. Create a pairing command in EngineerOS first."),Yc&&!D.hunt_host&&Jt("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),Ke["knowledge-dir"]&&(D={...D,knowledge_dir:mn.resolve(Ke["knowledge-dir"])},await Hr(D)),D.token||Jt("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),Oa={type:"authenticate",connector_id:D.connector_id,token:D.token}):Jt("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var IP=ZO(D,{reportError:e=>console.error(e)}),Fi=0,xm=!1,Ra=null,ur=new Map,Zb=0,Qb=new Set,Zc=[],nr=new Map,hn,l0,ym,ms=null,_m=!1,jP=0,e0=null,t0=[],vm,NP,pd=1e3,Qc,wP=0,n0=!1,hs=!1,bo,Li=!1,Em=!1,u0=0;function Pi(e){return u0+=1,e.finally(()=>{u0-=1})}var Kc,Ta=0;function rl({exitCode:e=0}={}){if(Ta=Math.max(Ta,e),Kc)return Kc;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Kc=ese().finally(()=>clearTimeout(t)),Kc}async function ese(){if(gn=!0,vd?.stop(),Js?.stop(),f0?.stop(),OP?.stop(),clearInterval(c0),wn?.stop(),NP?.(),clearTimeout(vm),clearInterval(l0),clearInterval(ym),await Promise.all([...[...ur.values()].map(e=>vr(e.child))]),await Promise.all([...nr.values()].map(g0)),await Xc?.cancelAll(),await gd?.stop(),await nl?.abortAll(),await nu(),await x0().catch(e=>{Ta=Math.max(Ta,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),hn?.close(),Ta&&Ta!==yl){let e;await Promise.race([(async()=>{await Js?.drain(),await Ca(D,D.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Ta)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{rl()});var yP=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{yP||(yP=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await rl({exitCode:1}))});wn=O0();process.on("exit",()=>{vd?.stop(),wn.stop()});wn.banner(`EngineerOS connector ${zi}`,[D.workspace,D.server_url]);Js=BI({actions:{refresh_tool_inventory:async()=>{st.tool_inventory=await kr(D.workspace),Dr()},restart_goal_runner:()=>fa(D.workspace)},onNotify:()=>Ca(D,D.workspace),explain:async e=>{if(!await Ws())return null;let{reading:t}=await XR(D,e);return t},onUpdate:e=>ZI(D.workspace,e)});OP=tj({render:(e,t)=>wn.write(e,t),onRecord:e=>Js.observe(e)});f0=nj({workspace:D.workspace,onRecord:e=>{Js.observe(e),wn.line(e.channel,e.level,e.message)}});Js.start();D.hunt_host||f0.start();wn.live&&!D.hunt_host&&(c0=setInterval(()=>{tse().catch(()=>{})},Xoe),c0.unref?.());var r0=new Set;async function tse(){if(D.hunt_host)return;mP??=U_(D.workspace);let{jobs:e}=await mP(),t=new Set,n=e.filter(r=>r.status!=="queued"&&Sm.includes(r.status)).length;for(let r of e){if(!Sm.includes(r.status))continue;t.add(r.runId),r0.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;wn.status(`goal:${r.runId}`,r.activity?.message||o,nse(r),{agent:r.status!=="queued",link:Ra&&`${Ra}/goals`,phase:o}),wn.step(`goal:${r.runId}`,r.activity?.message)}for(let r of r0)t.has(r)||(r0.delete(r),wn.clearStatus(`goal:${r}`))}function nse(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function Ws({ignoreBugHunt:e=!1}={}){if(gn||ur.size>0||nr.size>0||Fi>0||(Xc?.active??0)>0||(gd?.active??0)>0||!e&&(nl?.active??0)>0)return!1;try{let{jobs:t}=await vi(D.workspace);return!gn&&!t.some(n=>Sm.includes(n.status))}catch{return!1}}try{let e=D.hunt_host?{}:await Pa(D.workspace);e.committed&&(D.onboarding_pending=!0,D.connector_id&&await Hr(D),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await BP(e)}var MP=await wr(qr()).then(e=>e.policy!=="manual",()=>!1),Dt;try{Dt=await fu(D,D.workspace)}catch(e){await BP(e)}console.log(`Using ${Dt.name} through ${Dt.protocol} (${Dt.version}).`);console.log(`System time: ${oo()} (${Intl.DateTimeFormat().resolvedOptions().timeZone}).`);var PP=async()=>Gu({workspace:D.workspace}).names().catch(()=>[]),st=Eh(D,Dt,await kr(D.workspace),{secretNames:await PP()}),Vs=kk({workspace:D.workspace,running:og(process.argv[1],km),supervised:process.env[Da]==="1",isIdle:async()=>!gn&&ur.size===0&&Zc.length===0&&nr.size===0&&Fi===0&&u0===0&&!Li&&!Em&&(nl?.active??0)===0&&(gd?.active??0)===0&&!_m,restart:()=>rl({exitCode:yl}),onChange:e=>{st.runtime_update=e,hn?.readyState===WebSocket.OPEN&&Dr()}});try{await Vs.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}D={...D,execution_profiles:Dt.executionProfiles??null};rn==="pair"&&yd?.connector_id||await Hr(D);st.agent_session={...st.agent_session,status:"checking",message:`Checking that ${Dt.name} can answer.`};st.bug_hunt_browser=!1;Oa.capabilities=st;console.log(Rs(D.worker_limit)===null?`Workers: automatic, ${gc()} ${Dt.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Rs(D.worker_limit)} ${Dt.name} workers side by side, set with /workers.`);var _d=Ju({getConfig:()=>D}),ol=async e=>{let t;try{t=await Cs(D,e)}catch(n){throw[401,403].includes(n.status)&&(hs=!0,console.error("EngineerOS withdrew this connector's authorization. Local work is stopping; saved reports are retained."),rl()),n}return t?.execution_sync&&await rse(t.execution_sync),t},_P=Cf(ol,{signature:iO}),el=vI({getConfig:()=>D,send:ol,onRetained:({status:e,file:t,reason:n})=>console.error(`Prompt result ${e==="pending"?"saved for automatic delivery":"rejected; original evidence retained"}: ${t}${n?` (${n})`:""}`)}),d0=bI({capacity:()=>mu(D.worker_limit).worker_limit-ur.size}),o0,s0=!1,dd,hd=new Map,p0=new Set,i0;function Ui(){return gd??=oN({getConfig:()=>D,jobStore:_d,canRun:()=>Ws()}),nl??=NM({getConfig:()=>({...D,tool_inventory:st.tool_inventory}),jobStore:_d,recordedSignIns:CP,isIdle:()=>Ws({ignoreBugHunt:!0}),canRun:async e=>{if(!await Ws({ignoreBugHunt:!0}))return!1;let t=e.assignment;return t.kind!=="production_check"&&tr?.state!=="ready"?!1:t.surface?.app_surface==="webdriver"||st.bug_hunt_browser===!0},activity:{status:wn.status,step:m0,agents:wn.agents,finish:wn.finish}}),{scheduledTests:gd,bugHunts:nl}}async function rse(e){let t=Ui(),n=[];for(let r of e.jobs??[])await _d.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}`;p0.has(o)||hd.set(o,r)}DP()}function DP(){i0||gn||(i0=(async()=>{let e=Ui();for(;hd.size&&!gn;){let[t,n]=hd.entries().next().value;hd.delete(t),p0.add(t);try{if(n.type==="bug_hunt.grant")await e.bugHunts.configure(n);else if(n.type===Uh)await e.scheduledTests.configure(n);else if(n.type===_b)await e.bugHunts.handle(n);else if(n.type===Lh)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{p0.delete(t)}}})().finally(()=>{i0=null}))}async function LP(){if(!(!D.connector_id||!D.token||gn))return dd||(dd=(async()=>{let e=Ui();await Promise.all([e.bugHunts.start(),e.scheduledTests.start()]);let t=await _d.list();for(let n of t)if(n.kind==="bug_hunt_grant"&&n.status==="provisioning"){let r=n.checkpoint?.pending_context??n.assignment;hd.set(`bug_hunt.grant:${n.id}`,r)}DP(),t.some(n=>["authorized","queued","running"].includes(n.status)&&Date.parse(n.execution_lease.expires_at)>Date.now())&&(GP(),Am()),wse()})().catch(e=>{throw dd=null,e}),dd)}async function ose(){let e=await vi(D.workspace).catch(()=>({service:null,jobs:[]}));return{version:zi,now:Date.now(),workspace:D.workspace,config_path:Mn(D.workspace),config:D,agent:Dt,automatic_worker_limit:gc(),worker_limit:Rs(D.worker_limit),connection:{state:sse(),server_url:D.server_url,last_error:bo||null},work:{assessments:[...ur.values()].map(t=>({stage:t.stage,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:Dt.name})),prompts:[...nr.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:Dt.name})),integrations:Fi},runner:e,runtime_update:Vs.report(),health:Js?.health()??null,activity:wd.snapshot()}}function sse(){return gn||hs?"stopped":hn?.readyState===WebSocket.OPEN?"connected":"connecting"}var ise={async cancelPrompt(e){let t=[...nr.values()].find(n=>n.runId.startsWith(e));return t?(t.stoppedHere=!0,t.cancellation.abort(),await t.controller?.completed.catch(()=>{}),`Stopping prompt ${e} (${t.purpose}); EngineerOS will be told it was cancelled here.`):`Prompt ${e} finished before it could be stopped.`},setWorkers:e=>FP(e),setVerbose(e){return e===xm?`Detailed agent activity is already ${e?"on":"off"}.`:(h0(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"?(Vs.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 Vs.command(e),vl(await Vs.refresh()))}};vd=WI({ui:wn,snapshot:ose,actions:ise});vd&&console.log(HI());await UP();var vP=new Set;async function UP(){if(gn||hs)return;console.log(`Connecting ${D.name} to ${D.server_url}`),hs=!1,bo=void 0;let e=new WebSocket(D.server_url);hn=e;let t=WE(e,D.server_url,{onTimeout:r=>{hn===e&&(bo=r,console.error(r),a0())}});NP=t,e.addEventListener("open",()=>{if(hn!==e){e.close();return}try{if(FE(hn,e,Oa))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){bo=Xn(r),console.error(`Could not authenticate the WebSocket connection: ${bo}`);try{e.close()}catch{}a0()}}),e.addEventListener("message",r=>{if(hn!==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: ${Xn(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){gn=!0,hs=!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=yd?.connector_id===r.connector.id;if(D=Dk(D,yd,r.connector.id,r.token),await Hr(D),r.connector?.capabilities?.http_updates!==!0){gn=!0,hs=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}Oa={type:"authenticate",connector_id:D.connector_id,token:D.token,capabilities:st},console.log(s?`Reconnected existing workspace connector ${D.connector_id}; assessment history is preserved.`:`Paired. Connector ${D.connector_id} is online.`),xP(r);return}if(r.type==="authenticated"){t();let s=D.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(Qc?`Reconnected after ${$t(Date.now()-Qc)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),Qc=void 0,xP(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){Em||cse(r);return}if(r.type==="workspace.refresh"){tl();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await FP(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){h0(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(Hs=!1,st.bug_hunt_browser=!1,Dr());try{st.tool_inventory=await ly(D.workspace,r,void 0,{confirmLocal:i=>vd?.confirm(i)??!1,log:bm}),s&&(Hs=!0),st.bug_hunt_browser=$i(st.tool_inventory)&&Hs,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:st.tool_inventory})),Dr(),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 py(D.workspace,r,{onStatus:async()=>{st.tool_inventory=await kr(D.workspace),Dr()}});st.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:st.tool_inventory})),Dr(),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"){ai(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===cP){Pi(Qoe(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),uP(D,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}`;f_(Zc,ur.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Bi();return}if(r.type==="prompt.execute"){let s=nr.get(r.prompt_id);s?WP(r)>s.executionRevision&&await vse(s,r):!await el.replay(r)&&!nr.has(r.prompt_id)&&HP(r);return}if(r.type==="prompt.cancel"){let s=nr.get(r.prompt_id);s&&await g0(s);return}if(r.type==="agent.warm"){fse(r);return}if(r.type==="run.available"){if(D.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await IP.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${mn.join(D.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${Xn(s)}`)}return}if(r.type==="delivery.task.start"||r.type==="delivery.task.cancel"){if(D.hunt_host)throw new Error("Pair a repository connector before dispatching delivery tasks.");await CO(D.workspace,D.connector_id,r),await fa(D.workspace);return}if(r.type==="goal.cleanup"){try{await XO(D.workspace),await fa(D.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){Sse(r);return}if(r.type==="run.cancelled"){await L_(D.workspace,r.run_id);return}if(r.type===q$){Xc??=Gw({getConfig:()=>D,onTestsCommitted:()=>tl()}),Pi(Xc.handle(r));return}if(r.type===H$){Xc??=Gw({getConfig:()=>D,onTestsCommitted:()=>tl()}),await Xc.cancel(r);return}if(r.type===_b){Pi(Ui().bugHunts.handle(r)).catch(s=>console.error(`Bug Hunter assignment: ${s.message}`));return}if(r.type==="bug_hunt.grant"){Pi(Ui().bugHunts.configure(r)).catch(s=>console.error(`Bug Hunter settings: ${s.message}`));return}if(r.type===$M){nl?.stop(r);return}if(r.type===Lh){Pi(Ui().scheduledTests.handle(r)).catch(s=>console.error(`Scheduled test assignment: ${s.message}`));return}if(r.type===Uh){Pi(Ui().scheduledTests.configure(r)).catch(s=>console.error(`Scheduled test settings: ${s.message}`));return}if(r.type===lN){Yb??=yN({getConfig:()=>D}),Pi(Yb.handle(r));return}if(r.type===uN){await Yb?.cancel(r);return}if(r.type===vN){gP??=bN({getConfig:()=>D,isIdle:()=>Ws(),agentTurn:vR}),Pi(gP.handle(r));return}if(r.type==="connector.update"){ase(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await rl();return}if(r.type==="connector.revoked"){gn=!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||(Li=!1);return}if(r.type==="connection.error"){hs=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);vP.has(o)||(vP.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${zi}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),hn!==e||Kc)return;let o=BE(r);if(!o.retry||hs||gn){console.error(o.message),o.retry&&hs&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),rl();return}bo=bo?`${o.message} ${bo}`:o.message,a0()}),e.addEventListener("error",r=>{hn===e&&(bo=UE(r),console.error(`WebSocket connection to ${D.server_url} failed: ${bo}`))})}async function ase(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=Vs.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 Vs.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 cse(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";Em=!0,console.log(`Starting interactive ${Dt.name} provider ${n}.`);try{await(n==="logout"?HE:qE)(Dt,D.workspace),Dt=await fu(D,D.workspace),tr=null,st=Eh(D,Dt,st.tool_inventory,{secretNames:await PP()}),Oa.capabilities=st,hn.readyState===WebSocket.OPEN&&(hn.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:st.agent_session})),hn.close(1e3,`Provider ${n} completed`)),console.log(`${Dt.name} provider ${n} completed.`)}catch(r){let o=Xn(r).slice(0,500);hn.readyState===WebSocket.OPEN&&hn.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{Em=!1}}function a0(){if(gn||hs||vm)return;let e=bo?` Last error: ${bo}`:"",t=Qc?` Offline for ${$t(Date.now()-Qc)}.`:"";Qc??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(pd/1e3)}s.`),vm=setTimeout(()=>{vm=void 0,UP()},pd),pd=Math.min(3e4,pd*2)}async function tl(){if(!D.hunt_host&&!(Li||hn.readyState!==WebSocket.OPEN)){Li=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await QR(D.workspace),t=await ZR(D.workspace,D.last_head_reported??D.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(yr(D.server_url,D.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D.token}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(await ec(n,"the workspace"));let r=await n.json(),o=r.source_revision;D={...D,onboarding_pending:!1,last_snapshot_head:e.head_revision??D.last_snapshot_head,last_head_reported:e.head_revision??D.last_head_reported,last_head_branch:e.head_revision?e.branch??null:D.last_head_branch},await Hr(D),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 Fv({workspace:D.workspace,connectorId:D.connector_id,snapshot:e,refresh:Ha,buildMap:(a,c)=>Ch(D.workspace,a,{head:c.head_revision,branch:c.branch}),log:a=>console.error(a)});if(s&&o){let a=await fetch(Fk(D.server_url,D.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D.token}`},body:JSON.stringify({source_revision:o,quality_map_base64:s.base64})});a.ok?await Ih(D.workspace,D.connector_id,s.map).catch(()=>{}):console.error(await ec(a,"the workspace quality map"))}i&&console.log(`Built the local context index: ${i.total_files.toLocaleString()} file(s) ready for assignment context.`),Li=!1}catch(e){Li=!1,console.error(`Workspace assessment failed: ${Xn(e)}`)}}}var lse=8e6,bP,kP="";async function use({current:e,previous:t}){if(Li||hn?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=mn.resolve(D.workspace),r=async()=>{D={...D,last_head_reported:e.head,last_head_branch:e.branch??null},await Hr(D)},o=await Uv(D.workspace,D.connector_id),s=async()=>{if(await tl(),D.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let{index:i}=await Ha(D.workspace,D.connector_id),a=null,c=await Rj({previous:{head:t.head,branch:t.branch??null},current:e,compare:(p,f)=>v_(D.workspace,p,f),inventoryDelta:p=>AS(n,Object.entries(i.files).map(([f,m])=>({path:f,size:m.size})),p),mapDelta:async()=>(a=await Ch(D.workspace,i,{head:e.head,branch:e.branch}),Lv(o,a)),contentHead:(await hp(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)>lse)return s();let u=await fetch(Bk(D.server_url,D.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D.token}`},body:l});if(!u.ok)throw new Error(await ec(u,"the new commit"));let d=await u.json().catch(()=>({}));if(d.needs_snapshot)return s();await r(),a&&await Ih(D.workspace,D.connector_id,a).catch(()=>{}),console.log(`Reported ${c.report.reason==="branch_switch"?"the switch to ":"commit "}${e.head.slice(0,7)}${d.flagged_cases?`: ${d.flagged_cases} test case(s) to check again`:""}.`)}function dse(){D.hunt_host||D.onboarding_pending||Li||hn?.readyState!==WebSocket.OPEN||(bP??=Tj({readHead:()=>Aj(D.workspace),getLastReported:()=>({head:D.last_head_reported??D.last_snapshot_head,branch:D.last_head_branch}),onChange:use,onError:e=>{e.message!==kP&&(kP=e.message,console.error(`The new commit could not be reported yet: ${Xn(e)}`))}}),bP.poll().catch(()=>{}))}var pse=6e4,SP=0;async function fse(e){if(D.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?D.sessions?.[t]:void 0,r=[];Date.now()-SP>pse&&(SP=Date.now(),r.push(Ha(D.workspace,D.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),D.agent_protocol==="acp"&&r.push(ST(D.workspace,D,{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(`${Dt?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Dr(){gn||!D.connector_id||!D.token||(s0=!0,!o0&&(o0=(async()=>{do s0=!1,await hse();while(s0&&!gn)})().catch(e=>console.error(`Connector synchronization: ${e.message}`)).finally(()=>{o0=null})))}async function hse(){let e=UR(ur),t=await _d.snapshot();_P.update({type:"assessment.workers",assessment_workers:e,tool_inventory:st.tool_inventory,runtime_update:st.runtime_update,agent_session:st.agent_session,bug_hunt_browser:st.bug_hunt_browser,connector_jobs:t.jobs,...mu(D.worker_limit)}),await _P.flush()}async function FP(e){let t=Rs(e);return t===Rs(D.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(D={...D,worker_limit:t},await Hr(D),Bi(),Dr(),t===null?`Workers are automatic again: up to ${gc()} side by side for this machine's CPU and memory, for ${Hu} (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: ${Hu}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function h0(e){if(e!==xm){if(xm=e,!e)for(let t of ur.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."),Dr()}}function m0(e,t,n=null){wn.step(e,t,n)&&xm&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function mse(){clearInterval(ym);let e=!1,t=()=>{e||ur.size>0||nr.size>0||(e=!0,Ca(D,D.workspace).finally(()=>{e=!1}))};t(),ym=setInterval(t,Joe),ym.unref?.()}async function Ca(e,t,n=Js?.healthChecks()??[]){let r=await TI({config:e,workspace:t,version:zi,insights:[...n,...md?[md]:[]],agentSession:tr,probes:{inspectAgent:(o,s)=>gn?Dt:fu(o,s),inspectTools:o=>gn?st.tool_inventory:kr(o),runnerStatus:vi,connectorJobs:()=>Ju({getConfig:()=>e}).list()}});try{RP=(await RI(e,r,Cs))?.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 BP(e){if(gn)return Kc;let t=e instanceof Error?e.message:String(e),n=await Ca(D,D.workspace).catch(()=>null);n&&console.error(Tv(n)),Jt(t)}function xP(e){el.flush().catch(t=>console.error(`Saved prompt result delivery: ${t.message}`)),h0(e.connector?.activity_log_enabled===!0),Ra=e.project_url??null,pd=1e3,GP(),Am(),Vs.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),LP().catch(t=>console.error(`Saved connector work: ${t.message}`)),D.onboarding_pending&&tl()}var fd=null,Hs=!1,zP=0,gse=Date.now();async function GP(){return fd||(fd=(async()=>{MP&&await sT(D.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{bm("Checking Bug Hunter's installed Playwright runtime; provisioning is an explicit tools setup operation.");let t=await Zs(await Ds(D.workspace),{log:bm});try{st.bug_hunt_browser_diagnostics=await $d(t,{workspace:D.workspace})}finally{await t.close()}Hs=!0,md=null,st.tool_inventory=await kr(D.workspace),st.bug_hunt_browser=$i(st.tool_inventory)&&Hs,bm(`Bug Hunter's browser is ready (${$t(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${$t(Date.now()-e)}: ${t.message}`),st.bug_hunt_browser=!1,md={id:"hunt_browser",title:"Bug Hunter browser",status:"failed",detail:t.message,remedy:`Run engineeros-connector tools setup playwright --workspace "${D.workspace}", then restart this connector to retry browser setup.`},Ca(D,D.workspace).catch(()=>null)}Dr()})(),fd)}function bm(e){console.log(`[browser] ${e}`)}async function Am(){if(!["checking","ready"].includes(tr?.state)){zP=Date.now(),st.agent_session={...st.agent_session,status:"checking",message:`Checking that ${Dt.name} can answer.`},Dr(),tr={state:"checking",detail:`Asking ${Dt.name} one question to confirm its session.`},console.log(`Checking that ${Dt.name} can answer before accepting work.`);try{await qR(D,Dt.name),tr={state:"ready",detail:`${Dt.name} answered; its session is usable.`},st.agent_session={...st.agent_session,status:"authenticated",message:tr.detail},console.log(tr.detail)}catch(e){tr={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:D.hunt_host?lC(D.agent_id||D.agent_protocol):dc(D.agent_id||D.agent_protocol)},st.agent_session={...st.agent_session,status:"logged_out",message:tr.remedy},console.error(`${tr.detail}
|
|
1258
1258
|
${tr.remedy}`)}Dr(),tr.state==="ready"&&(Bi(),Ui().bugHunts.wake().catch(e=>console.error(`Bug Hunter local scheduler: ${e.message}`))),await Ca(D,D.workspace).catch(()=>null)}}function wse(){clearInterval(l0);let e=!1,t=0,n=0,r=!1,o=()=>{hn?.readyState===WebSocket.OPEN&&el.flush().catch(s=>console.error(`Saved prompt result delivery: ${s.message}`)),Vs.tick(),yse(),dse(),fd&&(tr===null||D.hunt_host&&tr?.state==="failed"&&Date.now()-zP>=cC(gse))&&Ws().then(s=>{if(s)return Am()}),!D.hunt_host&&!r&&Uu(Kb.id)&&(r=!0,IP.flush().then(()=>wm(Kb)).catch(s=>gm(Kb,s)).finally(()=>{r=!1})),Dr(),!D.hunt_host&&!ms&&Date.now()-t>=Koe&&Uu(Vb.id)&&(t=Date.now(),qP().then(()=>wm(Vb)).catch(s=>gm(Vb,s))),!D.hunt_host&&RP&&!_m&&Uu(Jb.id)&&Date.now()-jP>=SA&&(_m=!0,_se().then(()=>wm(Jb)).catch(s=>gm(Jb,s)).finally(()=>{_m=!1})),!e&&Date.now()-n>=Yoe&&Uu(Xb.id)&&(e=!0,n=Date.now(),kr(D.workspace).then(async s=>{if(st.tool_inventory=s,!Hs&&$i(s))try{let i=await Zs(await Ds(D.workspace));try{st.bug_hunt_browser_diagnostics=await $d(i,{workspace:D.workspace})}finally{await i.close()}Hs=!0}catch{Hs=!1}st.bug_hunt_browser=$i(s)&&Hs,st.bug_hunt_browser&&(md=null),Dr(),wm(Xb)}).catch(s=>gm(Xb,s)).finally(()=>{e=!1}))};o(),l0=setInterval(o,1e4),mse()}async function yse(){if(!(!MP||D.agent_protocol!=="acp"||!D.agent_id||n0||tr?.state==="checking"||Date.now()-wP<Zoe)){n0=!0;try{if(!await Ws())return;wP=Date.now();let e,t=await CT(D,{verify:async r=>{e=await fu(r,D.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===D||gn)return;D={...t,execution_profiles:e.executionProfiles??null},await Hr(D),Dt=e,tr=null;let n=Eh(D,Dt,st.tool_inventory);if(Object.assign(st,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),Oa.capabilities=st,!await Ws())return;await nu(),Am(),hn?.readyState===WebSocket.OPEN&&hn.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{n0=!1}}}function gm(e,t){let n=kI(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 wm(e){SI(e.id)&&console.log(`${e.title} recovered.`)}async function _se(){if(D.hunt_host||!await Ws())return;jP=Date.now();let{jobs:e}=await vi(D.workspace).catch(()=>({jobs:[]})),t=await xA(D.workspace,{jobs:e});if(!EA(t))return;let n=`${t.fingerprint}:${t0.join(",")}`,r=e0?.key===n,o=r?e0.candidates:await KR(D,t,t0);e0={key:n,candidates:o};let s=await ol(TA(t,o,{version:zi}));Array.isArray(s?.refused)&&(t0=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 Di=null,EP=null;async function qP(){if(!D.hunt_host){if(ms)return ms;ms=(async()=>{let e=await mA(D,{knownRevision:Di?.revision??null});if(e.unchanged||(Di=e),EP===Di.revision)return Di;let{jobs:t}=await vi(D.workspace);return!t.some(r=>Sm.includes(r.status))&&Fi===0&&ur.size===0&&(await Wp(D.workspace,Di),EP=Di.revision),Di})();try{return await ms}finally{ms=null,Bi()}}}function $P(e,t){if(!t)return;let n={type:"prompt.event",prompt_id:e,kind:t.kind};t.message&&(n.message=String(t.message).slice(0,500)),t.delta&&(n.delta=String(t.delta).slice(0,5e4)),t.status&&(n.status=String(t.status).slice(0,100)),nr.get(e)?.events.push(n)}var AP=null;function Bi(){d0.drain();let e=hn.readyState===WebSocket.OPEN,t=ur.values().next().value,n=Rs(D.worker_limit)??Math.min(gc(),h_(t?.workerLimit??Zc[0]?.worker_limit)),r=e&&!ms&&Fi===0?OR(Zc,ur.size,Math.max(0,n-d0.running)):[];for(let s of r){let i=`${s.assessment_id}:${s.stage}`,a={kind:"assessment",key:i,runId:s.assessment_id,stage:s.stage,child:null,controller:null,resumeAssignment:null,phase:"starting",progressPercent:5,lastMessage:`Starting ${s.stage} assessment stage`,startedAt:Date.now(),workerLimit:h_(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};ur.set(i,a),kse(s,a)}r.length>0&&Dr();let o=CR({queued:Zc,running:ur.size,workerLimit:n,connected:e,designSync:!!ms,integrations:Fi});o&&o!==AP&&console.log(o),AP=o}function $m(e){let t=m_(e);return t?`${Dt.name} on ${t}`:Dt.name}async function HP(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s=`${r} \xB7 ${$m(e)}`,i=GR(e,Dt.name),a={runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:dO(ol),executionRevision:WP(e),sessionKey:Rf(e),sessionId:null,phase:"preparing",lastMessage:s,replacement:null};nr.set(t,a);let c=!1,l,u=uO(ol,{type:"prompt.heartbeat",prompt_id:t,execution_revision:a.executionRevision},{onError:w=>{c&&pi(w)||console.error(`[${n}] Prompt heartbeat: ${w.message}`)}}),d,p=w=>{let h=w?JSON.stringify(w):null;c||!h||h===d||nr.get(t)!==a||(d=h,$P(t,w))},f=Number(e.answer_within_seconds),m=f>0?o+f*1e3:void 0;console.log([`[${n}] ${i} for ${r}.`,`${Dt.name} can reason for several minutes without reporting a step.`,...m?[Pm(m,o)]:[]].join(" ")),$P(t,{kind:"status",message:i}),wn.status(n,s,o,{link:Ra,answerBy:m,phase:a.phase});let g=w=>{if(c)return;let h=AR(w),y=$R(w),S=la(w);nr.get(t)===a&&(y&&(a.phase=y),(S??h?.message)&&(a.lastMessage=S??h?.message),wn.status(n,a.lastMessage,o,{link:Ra,answerBy:m,phase:a.phase}),m0(n,S??h?.message));let x=w.type==="forge.output"?null:S;p(h??(x?{kind:"status",message:x}:null))},_="failed",b=[r],v;try{v=await d0.acquire({signal:a.cancellation.signal,onWaiting:()=>g({type:"connector.step",message:"Waiting for an available connector worker"})}),Of(e)||(g({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await vA(qP,{pinned:!!e.local_design_context,last:Di,onFallback:(x,k)=>g({type:"connector.step",message:`Design context not refreshed (${x.message}); continuing with ${k?"the copy synced earlier":"none"}`})})});let w=await yR(e,D,{onProcess:x=>{nr.get(t)===a&&(a.child=x)},onController:x=>{nr.get(t)===a&&(a.controller=x)},onSession:x=>{a.sessionId=x},onEvent:g},{signal:a.cancellation.signal});if(v(),Bi(),a.stoppedHere)throw new Error(TP);if(a.cancelled)return;let h={type:"prompt.completed",prompt_id:t,execution_revision:a.executionRevision,content:w.content,model:w.model,session_id:w.sessionId,usage:w.usage};await el.save(h),c=!0,a.events.stop(),l=u.stop(),a.phase="delivering",a.lastMessage="Delivering completed response",wn.status(n,a.lastMessage,o,{link:Ra,phase:a.phase,agent:!1});let y=w.singleTurn?Lk(D.sessions,w.sessionKey):pg(D.sessions,w.sessionKey,w.sessionId);if(JSON.stringify(y)!==JSON.stringify(D.sessions||{})&&(D={...D,sessions:y},await Hr(D)),a.cancelled)return;let S=await el.deliver(h);wd.record("prompt","completed",{durationMs:Date.now()-o,usage:w.usage}),_=S.status==="delivered"?"finished":"undelivered",b=[xd(w.usage),r]}catch(w){let h=a.stoppedHere?TP:Xn(w);if(wd.record("prompt","failed",{durationMs:Date.now()-o}),a.stoppedHere&&(_="cancelled"),!a.cancelled&&!c){try{await el.deliver({type:"prompt.failed",prompt_id:t,execution_revision:a.executionRevision,message:h})}catch(y){console.error(`[${n}] Prompt failure delivery: ${y.message}`)}console.error(h)}else c&&(_="undelivered",console.error(`[${n}] ${h} The original completed result remains saved for delivery.`))}finally{v?.(),Bi(),await(l??u.stop()),a.events.stop();let w=a.replacement;w?(_="replaced",b=[`continuing on ${$m(w)}`,r]):a.cancelled&&(_="cancelled"),wn.finish(n,_,b),nr.get(t)===a&&nr.delete(t),w&&bse(a,w)}}var TP="Cancelled from the connector terminal by the person running it.";async function g0(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function WP(e){return Number(e.execution_revision)||1}async function vse(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 ${$m(t)}.`),await g0(e))}function bse(e,t){e.sessionId&&(D={...D,sessions:pg(D.sessions,e.sessionKey,e.sessionId)},Hr(D).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),HP(t)}async function kse(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 ${$m(e)}.`),!Qb.has(n)){Qb.add(n);try{let y=await SR(D.workspace);if(!y.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let S=y.accepted_head_revision?y.current_head_revision?y.current_head_revision!==y.accepted_head_revision?`The workspace is now at commit \`${y.current_head_revision}\`; the accepted assessment is from \`${y.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${y.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 ${y.stages.length||"no"} section(s). ${S}`)}}catch(y){console.error(`Assessment freshness check failed: ${y.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,d=null,p=null,f=null,m=new Set,g=()=>!gn&&ur.get(t.key)===t,_=async y=>{try{return await cO(ol,y)||console.warn(`[${s}] ${aO}`),!0}catch(S){return console.error(`Assessment failure delivery: ${S.message}`),!1}},b=(y,{milestone:S=!0}={})=>{if(!g()||S&&f===y)return;S&&(f=y,m.has(y)||(m.add(y),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${y}.`));let x=String(y).slice(0,500);t.progressPercent=c,t.lastMessage=x,wn.status(s,x,o,{link:Ra,phase:t.phase,agent:!a})};b(`Starting ${r} assessment stage`);let v=setInterval(()=>{let y=Date.now(),S=y-t.lastActivityAt,x=i&&!a?ER(r,S):null;if(!d&&x){d=x,console.error(`[assessment:${r}] ${d}`),__(t.controller,t.child);return}d||Js.observe({at:y,level:"info",message:wn.status(s,`${t.lastMessage} \xB7 last agent activity ${$t(S)} ago (${t.eventCount.toLocaleString()} events)`,o,{phase:t.phase,agent:!a})})},15e3),w={onSession:async y=>{g()&&(p=String(y),await Dx(D.workspace,n,r,y,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:y=>{g()&&(t.controller=y)},onProcess:y=>{g()&&(t.child=y,i=!0,t.phase!=="correcting"&&(t.phase="running",b("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:y=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let S=xR(y);if(S&&b(S),!g())return;let x=la(y);!x||x===t.lastDetail||(t.lastDetail=x,m0(s,x))}},h=(y,S)=>d_(y,S,D,w,{draftPath:mn.relative(D.workspace,mn.join(Jr(D.workspace,n),y.report_file)).split(mn.sep).join("/")});try{let y=Zb-Date.now();y>0&&(b(`Waiting ${Math.ceil(y/1e3)}s for the model provider's rate limit to clear`),await new Promise(O=>setTimeout(O,y+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,b("Calculating changed files and affected behavior"));let S=await zx(D.workspace,e),x=await nw(D.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(x)h(x,S),b("Recovered completed stage report from connector storage");else{if(p=await Lx(D.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),p&&b("Restoring interrupted agent session"),x=await wR(S,D,w,{previousSessionId:p}),d)throw new Error(d);a=!0,await tw(D.workspace,n,S,x)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let k=O=>fetch(Gk(D.server_url,D.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D.token}`},body:JSON.stringify(O),signal:AbortSignal.timeout(Z1)}),E,R=await zR(x,{submit:O=>BR(O,k,{isActive:()=>g()&&!gn,readAcknowledgement:async T=>{let I=await T.json();if(r==="synthesis"&&I?.status==="completed"&&(typeof I.report_markdown!="string"||!I.report_markdown.trim().startsWith(`# Workspace Assessment
|