@engineeros/connector 1.55.0 → 1.55.1
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.
|
@@ -495,7 +495,7 @@ ${o.join(`
|
|
|
495
495
|
|
|
496
496
|
`)}`}return r}function Dm(e,t){let n=String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^## ${n}\\s*$\\n([\\s\\S]*?)(?=^## |\\s*$)`,"m").exec(String(e||""))?.[1]?.trim()||""}async function ji(e){try{return await Yr(e,"utf8")}catch(t){if(t?.code==="ENOENT")return"";throw t}}function zA(e,t){let n=String(e||""),r=null,o="";return n.startsWith("capability:")?(o="Capability",r=String(t||"").match(/^### Capability:\s*(.+?)\s*$/m)):n.startsWith("compliance:")&&(o="Compliance",r=String(t||"").match(/^### Compliance Framework:\s*(.+?)\s*$/m)),r?`${o} \u2014 ${r[1].trim()}`:String(e||"assessment").replace(/[:_-]+/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function GA(e,t,n){let r=String(t.observed_head_revision||"").trim().toLowerCase();return/^[a-f0-9]{7,64}$/.test(r)?r.slice(0,16):Ni(String(e.source_revision||n)).slice(0,16)}function Fl(e,t){return je.join(e,`${ln(t)}.session.json`)}function Ni(e){return OA("sha256").update(e).digest("hex")}function Ii(e){return{stage:e.stage,report_markdown:typeof e.report_markdown=="string"?Fm(e.report_markdown):e.report_markdown,observed_head_revision:e.observed_head_revision??null,changed_files:e.changed_files??[],change_impact_markdown:e.change_impact_markdown??null,model:e.model??null,usage:e.usage??null}}var BA=/^### [A-Z][\w -]*:\s*\S/,Xr="[A-Z][A-Za-z0-9/&()'-]*(?: [A-Za-z0-9/&()'-]+){0,3}",HA=[new RegExp(`^[-*+]\\s+\\*\\*(${Xr}):\\*\\*\\s*(.*)$`),new RegExp(`^[-*+]\\s+\\*\\*(${Xr})\\*\\*:\\s*(.*)$`),new RegExp(`^[*+]\\s+(${Xr}):\\s*(.*)$`),new RegExp(`^\\*\\*(${Xr}):\\*\\*\\s*(.*)$`),new RegExp(`^\\*\\*(${Xr})\\*\\*:\\s*(.*)$`),new RegExp(`^(${Xr}):\\s+(\\S.*)$`)];function Fm(e){let t=!1,n=!1;return String(e??"").split(`
|
|
497
497
|
`).map(r=>{if(/^\s*(```|~~~)/.test(r)&&(n=!n),n)return r;if(/^#{1,3} /.test(r))return t=BA.test(r),r;if(!t)return r;for(let o of HA){let s=o.exec(r);if(s)return`- ${s[1]}: ${s[2].trim()}`.trimEnd()}return r}).join(`
|
|
498
|
-
`)}var Sr=["--",".",":(exclude).engineeros"],VA=qA(WA),JA=5e3,Zr=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;async function rr(e,t){try{let{stdout:n}=await VA("git",t,{cwd:e,windowsHide:!0,maxBuffer:16777216});return n.trim()}catch{return null}}function XA(e){let t=String(e??"").trim();if(!t)return null;let n,r;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))try{let o=new URL(t);n=o.hostname,r=o.pathname}catch{return null}else{let o=t.match(/^(?:[^@/\\\s]+@)?([^:/\\\s]{2,}):([^\\].*)$/);if(!o)return null;[,n,r]=o}return r=r.replaceAll("\\","/").replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/i,""),!n||!r?null:`${n}/${r}`.toLowerCase().slice(0,512)}async function Um(e){let t=await rr(e,["symbolic-ref","--short","-q","HEAD"]),n=(await rr(e,["rev-list","-n",String(JA),"HEAD"])??"").split(/\r?\n/).filter(i=>Zr.test(i)),r=await rr(e,["remote","get-url","origin"])||await rr(e,["remote","get-url",(await rr(e,["remote"])??"").split(/\r?\n/)[0]||"origin"]),o=XA(r);if(!o&&n.length){let i=(await rr(e,["rev-list","--max-parents=0","HEAD"])??"").split(/\r?\n/).filter(a=>Zr.test(a)).sort();i.length&&(o=`root:${i[0]}`)}let s=n.length?await rr(e,["log","-1","--format=%H","HEAD",...Sr]):null;return{branch:t?t.slice(0,255):null,repository_identity:o,ancestor_revisions:n,content_head_revision:s&&Zr.test(s)?s:null,committed_assessment:n.length?await ZA(e):null}}function KA(e){let t=new Set;for(let n of Array.isArray(e)?e.map(String):[])n==="capability_catalog"||n.startsWith("capability:")?t.add("capabilities"):n==="compliance_catalog"||n.startsWith("compliance:")?t.add("project_compliance"):n!=="synthesis"&&t.add(n);return[...t]}var YA=8e6;async function ZA(e){let t=a=>rr(e,["show",`HEAD:.engineeros/assessment/${a}`]),n;try{n=JSON.parse(await t("assessment-state.json")??"")}catch{return null}let r=String(n?.accepted_head_revision??"").trim().toLowerCase(),o=await t("assessment.md");if(n?.version!==1||!Zr.test(r)||!o?.startsWith("# Workspace Assessment"))return null;let s=[];for(let a of Array.isArray(n.stages)?n.stages:[]){let c=a==="synthesis"?o:await t(`sections/${ln(a)}.md`);c&&s.push({key:String(a),report_markdown:c})}return o.length+s.reduce((a,c)=>a+c.report_markdown.length,0)>YA?null:{head_revision:r,scopes:Array.isArray(n.scopes)?n.scopes.map(String):KA(n.stages),report_markdown:o,stage_reports:s}}async function Ul(e,t,n,r,o,s=""){e.verificationCache||={};let i=`${n}:${r}${s?`:${s}`:""}`,a=e.verificationCache[i];if(a?.status==="completed")return a.turn;if(a)throw new Error(`Verification for ${r} at ${n} was interrupted. Inspect its saved evidence before creating a new revision; automatic replay is blocked.`);e.verificationCache[i]={status:"running"},await t();let c=await o();return e.verificationTurns.push(c),e.verificationCache[i]={...e.verificationCache[i],status:"completed",turn:c},await t(),c}async function zm(e,t,n,r){if(e.testRuns||={},e.testRuns[n])return e.testRuns[n];let o=await r();return e.testRuns[n]=o,await t(),o}import QA from"node:os";var eT=[[/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g,"<redacted private key>"],[/\bbearer\s+[A-Za-z0-9._\-~+/]{8,}=*/gi,"<redacted>"],[/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|pwd|authorization)(["']?\s*[=:]\s*["']?)((?!<redacted>)[^\s"',&]{4,})/gi,"$1$2<redacted>"],[/\b(sk-|ghp_|gho_|ghs_|github_pat_|glpat-|xox[baprs]-|AKIA|AIza)[A-Za-z0-9._\-]{8,}/g,"$1<redacted>"],[/\beyJ[A-Za-z0-9._-]{10,}/g,"<redacted>"],[/(?<=[a-z][a-z0-9+.\-]
|
|
498
|
+
`)}var Sr=["--",".",":(exclude).engineeros"],VA=qA(WA),JA=5e3,Zr=/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;async function rr(e,t){try{let{stdout:n}=await VA("git",t,{cwd:e,windowsHide:!0,maxBuffer:16777216});return n.trim()}catch{return null}}function XA(e){let t=String(e??"").trim();if(!t)return null;let n,r;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t))try{let o=new URL(t);n=o.hostname,r=o.pathname}catch{return null}else{let o=t.match(/^(?:[^@/\\\s]+@)?([^:/\\\s]{2,}):([^\\].*)$/);if(!o)return null;[,n,r]=o}return r=r.replaceAll("\\","/").replace(/^\/+/,"").replace(/\/+$/,"").replace(/\.git$/i,""),!n||!r?null:`${n}/${r}`.toLowerCase().slice(0,512)}async function Um(e){let t=await rr(e,["symbolic-ref","--short","-q","HEAD"]),n=(await rr(e,["rev-list","-n",String(JA),"HEAD"])??"").split(/\r?\n/).filter(i=>Zr.test(i)),r=await rr(e,["remote","get-url","origin"])||await rr(e,["remote","get-url",(await rr(e,["remote"])??"").split(/\r?\n/)[0]||"origin"]),o=XA(r);if(!o&&n.length){let i=(await rr(e,["rev-list","--max-parents=0","HEAD"])??"").split(/\r?\n/).filter(a=>Zr.test(a)).sort();i.length&&(o=`root:${i[0]}`)}let s=n.length?await rr(e,["log","-1","--format=%H","HEAD",...Sr]):null;return{branch:t?t.slice(0,255):null,repository_identity:o,ancestor_revisions:n,content_head_revision:s&&Zr.test(s)?s:null,committed_assessment:n.length?await ZA(e):null}}function KA(e){let t=new Set;for(let n of Array.isArray(e)?e.map(String):[])n==="capability_catalog"||n.startsWith("capability:")?t.add("capabilities"):n==="compliance_catalog"||n.startsWith("compliance:")?t.add("project_compliance"):n!=="synthesis"&&t.add(n);return[...t]}var YA=8e6;async function ZA(e){let t=a=>rr(e,["show",`HEAD:.engineeros/assessment/${a}`]),n;try{n=JSON.parse(await t("assessment-state.json")??"")}catch{return null}let r=String(n?.accepted_head_revision??"").trim().toLowerCase(),o=await t("assessment.md");if(n?.version!==1||!Zr.test(r)||!o?.startsWith("# Workspace Assessment"))return null;let s=[];for(let a of Array.isArray(n.stages)?n.stages:[]){let c=a==="synthesis"?o:await t(`sections/${ln(a)}.md`);c&&s.push({key:String(a),report_markdown:c})}return o.length+s.reduce((a,c)=>a+c.report_markdown.length,0)>YA?null:{head_revision:r,scopes:Array.isArray(n.scopes)?n.scopes.map(String):KA(n.stages),report_markdown:o,stage_reports:s}}async function Ul(e,t,n,r,o,s=""){e.verificationCache||={};let i=`${n}:${r}${s?`:${s}`:""}`,a=e.verificationCache[i];if(a?.status==="completed")return a.turn;if(a)throw new Error(`Verification for ${r} at ${n} was interrupted. Inspect its saved evidence before creating a new revision; automatic replay is blocked.`);e.verificationCache[i]={status:"running"},await t();let c=await o();return e.verificationTurns.push(c),e.verificationCache[i]={...e.verificationCache[i],status:"completed",turn:c},await t(),c}async function zm(e,t,n,r){if(e.testRuns||={},e.testRuns[n])return e.testRuns[n];let o=await r();return e.testRuns[n]=o,await t(),o}import QA from"node:os";var eT=[[/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g,"<redacted private key>"],[/\bbearer\s+[A-Za-z0-9._\-~+/]{8,}=*/gi,"<redacted>"],[/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|pwd|authorization)(["']?\s*[=:]\s*["']?)((?!<redacted>)[^\s"',&]{4,})/gi,"$1$2<redacted>"],[/\b(sk-|ghp_|gho_|ghs_|github_pat_|glpat-|xox[baprs]-|AKIA|AIza)[A-Za-z0-9._\-]{8,}/g,"$1<redacted>"],[/\beyJ[A-Za-z0-9._-]{10,}/g,"<redacted>"],[/(:\/\/)(?<=[a-z][a-z0-9+.\-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi,"$1<redacted>@"]],tT=4,Gm=new Set;function nT(e){let t=String(e??"");return t.length<tT?[]:[...new Set([t,encodeURIComponent(t),Buffer.from(t).toString("base64")])]}function un(e){for(let t of e??[])for(let n of nT(t))Gm.add(n)}function Mi(e){let t=String(e??"");for(let n of[...Gm].sort((r,o)=>o.length-r.length))t=t.split(n).join("<redacted>");return t}function Ne(e,{home:t=QA.homedir()}={}){let n=Mi(e);for(let[r,o]of eT)n=n.replace(r,o);return t&&t.length>1&&(n=n.split(t).join("~")),n}var rT=1e4,Bm=5,oT=500,sT=Object.freeze(["ENGINEEROS_TARGET_ENV","ENGINEEROS_BASE_URL","BASE_URL","ENGINEEROS_API_URL","ENGINEEROS_TEST_USERNAME","ENGINEEROS_TEST_PASSWORD","ENGINEEROS_TEST_TOKEN"]),iT=e=>/^ENGINEEROS_/i.test(e)||/^BASE_URL$/i.test(e),aT=/^[A-Za-z_][A-Za-z0-9_]*$/;function Er(e){return typeof e=="string"&&e?e:null}function Wm(e){let t=e?.credentials??{};return{username:Er(t.username),password:Er(t.password),token:Er(t.token)}}function Xo(e){if(!e)return{};let t={};for(let[i,a]of Object.entries(e.variables??{}))aT.test(i)&&!iT(i)&&typeof a=="string"&&(t[i]=a);let{username:n,password:r,token:o}=Wm(e),s=(i,a)=>{a&&(t[i]=a)};return s("ENGINEEROS_TARGET_ENV",Er(e.name)),s("ENGINEEROS_BASE_URL",Er(e.base_url)),s("BASE_URL",Er(e.base_url)),s("ENGINEEROS_API_URL",Er(e.api_url)),s("ENGINEEROS_TEST_USERNAME",n),s("ENGINEEROS_TEST_PASSWORD",r),s("ENGINEEROS_TEST_TOKEN",o),t}function zl(e){return Object.values(Wm(e)).filter(Boolean)}function qm(e){let{test_environment:t,...n}=e??{};return t?(un(zl(t)),{assignment:{...n,test_environment_ref:{id:t.id,name:t.name,kind:t.kind,variable_names:Object.keys(Xo(t))}},targetEnvironment:t}):{assignment:n,targetEnvironment:null}}function Gl(e){if(!e)return"";let t=e.variable_names?.length?e.variable_names:sT;return["## Target environment",`These tests run against the deployed ${e.kind||"test"} environment \`${e.name}\`, not only the local workspace. When the connector runs the test commands it sets these environment variables: ${t.map(n=>`\`${n}\``).join(", ")}.`,"Read the application's address from `ENGINEEROS_BASE_URL` (also `BASE_URL`), its API from `ENGINEEROS_API_URL` when set, and sign in with `ENGINEEROS_TEST_USERNAME`, `ENGINEEROS_TEST_PASSWORD` or `ENGINEEROS_TEST_TOKEN` when set. Never hard-code a URL, user name, password or token in a test, a fixture or a configuration file, and never print them. Their values are not given to you; when you run tests yourself without them, point them at the local application instead."].join(`
|
|
499
499
|
|
|
500
500
|
`)}function cT(e,t){let n=new URL(String(e??""));if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error("The environment's URL must start with http:// or https://.");if(!t)return n;let r=new URL(n),[o,s=""]=String(t).split("?",2);return r.pathname=`${n.pathname.replace(/\/+$/,"")}/${o.replace(/^\/+/,"")}`,r.search=s?`?${s}`:"",r}function Hm(e){return String(e??"").slice(0,oT)||null}async function Qr(e,{fetchImpl:t=fetch,timeoutMs:n=rT,clock:r=()=>performance.now()}={}){let o;try{o=cT(e?.base_url,e?.health_check_path)}catch(c){return{status:"unreachable",http_status:null,latency_ms:null,message:Hm(c.message)}}let s=r(),i=(c,l,u)=>({status:c,http_status:l,latency_ms:Math.max(0,Math.round(r()-s)),message:Hm(u)}),a=AbortSignal.timeout(n);try{let c=o;for(let l=0;;l+=1){let u=await t(c,{method:"GET",redirect:"manual",signal:a,headers:{"user-agent":"EngineerOS-connector-health-check"}});await u.body?.cancel?.().catch(()=>{});let d=u.headers?.get?.("location");if(u.status>=300&&u.status<400&&d){let p=new URL(d,c);if(p.hostname!==o.hostname||!["http:","https:"].includes(p.protocol))return i("unhealthy",u.status,`Redirects to another host (${p.hostname||p.protocol}); not followed.`);if(l>=Bm)return i("unhealthy",u.status,`More than ${Bm} redirects.`);c=p;continue}return u.status<400?i("healthy",u.status,`Responded ${u.status}.`):i("unhealthy",u.status,`Responded ${u.status}.`)}}catch(c){let u=c?.name==="TimeoutError"||c?.name==="AbortError"?`No response within ${Math.round(n/1e3)} seconds.`:c?.cause?.code||c?.cause?.message||c?.message||"The request failed.";return i("unreachable",null,u)}}function Vm(e){return e?.status==="unreachable"||(e?.http_status??0)>=500}import{mkdir as tR,rm as Yl,stat as nR}from"node:fs/promises";import Wt from"node:path";import{stripVTControlCharacters as rR}from"node:util";import{readdir as ST,readFile as ET,stat as kT}from"node:fs/promises";import Wl from"node:path";import{readFile as lT,stat as uT}from"node:fs/promises";import eo from"node:path";var dT=40*1024*1024,pT=20,fT=5e3,hT=[["coverage/lcov.info","lcov"],["lcov.info","lcov"],["coverage/coverage-summary.json","istanbul"],["coverage/coverage-final.json","istanbul"],["coverage/cobertura-coverage.xml","cobertura"],["coverage.xml","cobertura"],["cobertura.xml","cobertura"],["coverage.json","coverage.py"],["target/site/jacoco/jacoco.xml","jacoco"],["build/reports/jacoco/test/jacocoTestReport.xml","jacoco"]],qe=e=>{let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>=0?t:0};function mT(e,t,n){let r=String(n).replace(/\\/g,"/"),o=eo.isAbsolute(r)?r:eo.join(t,r),s=eo.relative(e,o).replace(/\\/g,"/");return s.startsWith("..")?r:s}function Pi(e){return{lines_covered:e.reduce((t,n)=>t+n.lines_covered,0),lines_total:e.reduce((t,n)=>t+n.lines_total,0)}}function gT(e){let t=[],n=0,r=0,o=null;for(let s of String(e).split(/\r?\n/)){let i=s.trim();i.startsWith("SF:")?o={path:i.slice(3),lines_covered:0,lines_total:0}:o&&i.startsWith("LF:")?o.lines_total=qe(i.slice(3)):o&&i.startsWith("LH:")?o.lines_covered=qe(i.slice(3)):i.startsWith("BRF:")?n+=qe(i.slice(4)):i.startsWith("BRH:")?r+=qe(i.slice(4)):o&&i==="end_of_record"&&(t.push(o),o=null)}return{...Pi(t),branches_covered:n?r:null,branches_total:n||null,files:t}}var kr=(e,t)=>new RegExp(`\\b${t}="([^"]*)"`).exec(e)?.[1];function wT(e){let t=/<coverage\b[^>]*>/.exec(e)?.[0]??"",n=new Map;for(let a of e.matchAll(/<class\b[^>]*>([\s\S]*?)<\/class>/g)){let c=kr(a[0],"filename");if(!c)continue;let l=[...a[1].matchAll(/<line\b[^>]*\bhits="(\d+)"/g)],u=n.get(c)??{path:c,lines_covered:0,lines_total:0};u.lines_total+=l.length,u.lines_covered+=l.filter(d=>Number(d[1])>0).length,n.set(c,u)}let r=[...n.values()],o=Pi(r),s=kr(t,"lines-valid"),i=kr(t,"branches-valid");return{lines_covered:s!==void 0?qe(kr(t,"lines-covered")):o.lines_covered,lines_total:s!==void 0?qe(s):o.lines_total,branches_covered:i?qe(kr(t,"branches-covered")):null,branches_total:i?qe(i):null,files:r}}function yT(e){let t=JSON.parse(e);if(t.total?.lines){let s=Object.entries(t).filter(([i])=>i!=="total").map(([i,a])=>({path:i,lines_covered:qe(a.lines?.covered),lines_total:qe(a.lines?.total)}));return{lines_covered:qe(t.total.lines.covered),lines_total:qe(t.total.lines.total),branches_covered:t.total.branches?qe(t.total.branches.covered):null,branches_total:t.total.branches?qe(t.total.branches.total):null,files:s}}let n=0,r=0,o=Object.values(t).map(s=>{let i=new Map;for(let[a,c]of Object.entries(s.statementMap??{})){let l=c?.start?.line;l!==void 0&&i.set(l,(i.get(l)??!1)||Number(s.s?.[a])>0)}for(let a of Object.values(s.b??{}))n+=a.length,r+=a.filter(c=>Number(c)>0).length;return{path:s.path,lines_covered:[...i.values()].filter(Boolean).length,lines_total:i.size}});return{...Pi(o),branches_covered:n?r:null,branches_total:n||null,files:o}}function _T(e){let t=JSON.parse(e);if(!t.files||!t.totals)throw new Error("Not a coverage.py JSON report.");let n=Object.entries(t.files).map(([o,s])=>({path:o,lines_covered:qe(s.summary?.covered_lines),lines_total:qe(s.summary?.num_statements)})),r=t.totals.num_branches;return{lines_covered:qe(t.totals.covered_lines),lines_total:qe(t.totals.num_statements),branches_covered:r?qe(t.totals.covered_branches):null,branches_total:r?qe(r):null,files:n}}function vT(e){let t=(i,a)=>{let l=[...i.matchAll(new RegExp(`<counter\\b[^>]*\\btype="${a}"[^>]*/>`,"g"))].at(-1)?.[0];return l?{missed:qe(kr(l,"missed")),covered:qe(kr(l,"covered"))}:null},n=[];for(let i of e.matchAll(/<package\b[^>]*\bname="([^"]*)"[^>]*>([\s\S]*?)<\/package>/g))for(let a of i[2].matchAll(/<sourcefile\b[^>]*\bname="([^"]*)"[^>]*>([\s\S]*?)<\/sourcefile>/g)){let c=t(a[2],"LINE");c&&n.push({path:`${i[1]}/${a[1]}`,lines_covered:c.covered,lines_total:c.missed+c.covered})}let r=e.slice(e.lastIndexOf("</package>")+1),o=t(r,"LINE"),s=t(r,"BRANCH");return{...o?{lines_covered:o.covered,lines_total:o.missed+o.covered}:Pi(n),branches_covered:s?s.covered:null,branches_total:s?s.missed+s.covered:null,files:n}}var bT={lcov:gT,cobertura:wT,istanbul:yT,"coverage.py":_T,jacoco:vT};function Bl(e,t,{root:n,reportPath:r}){let o;try{o=bT[e](t)}catch{return null}let s=eo.dirname(r);return{lines_covered:o.lines_covered,lines_total:o.lines_total,branches_covered:o.branches_covered,branches_total:o.branches_total,files:o.files.slice(0,fT).map(i=>({...i,path:mT(n,s,i.path)}))}}async function Jm(e,t=[""],{headCommittedAt:n=null}={}){let r=[],o=new Set;for(let s of[...new Set(["",...t])])for(let[i,a]of hT){if(r.length>=pT)return r;let c=eo.posix.join(s,i);if(o.has(c))continue;o.add(c);let l=eo.join(e,c),u=await uT(l).catch(()=>null);if(!u?.isFile()||u.size>dT)continue;let d=Bl(a,await lT(l,"utf8"),{root:e,reportPath:l});d?.lines_total&&r.push({format:a,path:c,generated_at:u.mtime.toISOString(),stale:n!==null&&u.mtime.getTime()<n.getTime(),...d})}return r}var $T=4e3,xT=6,AT=40*1024*1024,Xm=1e3,TT=300,Hl=300,RT=new Set([".git","node_modules",".venv","venv","__pycache__",".next",".turbo",".cache",".pnpm-store",".mypy_cache",".pytest_cache",".ruff_cache",".gradle",".idea",".vscode","vendor"]),Km=new Map([["lcov.info","lcov"],["coverage-summary.json","istanbul"],["coverage-final.json","istanbul"],["cobertura-coverage.xml","cobertura"],["coverage.xml","cobertura"],["cobertura.xml","cobertura"],["coverage.json","coverage.py"],["jacoco.xml","jacoco"],["jacocotestreport.xml","jacoco"]]);async function CT(e,t){let n=[],r=[{directory:e,depth:0}],o=0;for(;r.length&&o<$T;){let{directory:s,depth:i}=r.shift();o+=1;let a=await ST(s,{withFileTypes:!0}).catch(()=>[]);for(let c of a){let l=Wl.join(s,c.name);if(c.isDirectory()){i<xT&&!RT.has(c.name)&&r.push({directory:l,depth:i+1});continue}if(!c.isFile())continue;let u=c.name.toLowerCase();if(!u.endsWith(".xml")&&!Km.has(u))continue;let d=await kT(l).catch(()=>null);d&&d.mtimeMs>=t&&d.size<=AT&&n.push(l)}}return n}var $r=(e,t)=>{let n=new RegExp(`\\b${t}="([^"]*)"`).exec(e)?.[1];return n===void 0?void 0:Ym(n)};function Ym(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}function Li(e,t){return Ne(String(e??"").slice(0,t*4)).replace(/\s+/g," ").trim().slice(0,t).replace(/[\ud800-\udbff]$/,"")}function OT(e,t){if(!/<testsuites?\b/.test(e))return[];let n=[];for(let r of e.matchAll(/<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g)){let o=r[1],s=r[2]??"",i=$r(o,"name");if(!i)continue;let a=/<(failure|error)\b([^>]*?)(?:\/>|>([\s\S]*?)<\/\1>)/.exec(s),c=/<skipped\b/.test(s),l=Number($r(o,"time"));n.push({name:Li(i,Hl),classname:$r(o,"classname")?Li($r(o,"classname"),Hl):null,file:$r(o,"file")?Li($r(o,"file"),Hl):null,status:a?"failed":c?"skipped":"passed",duration_ms:Number.isFinite(l)?Math.round(l*1e3):null,message:a&&Li($r(a[0],"message")??Ym(a[3]??""),TT)||null,report:t})}return n}async function Di(e,t){let n=[],r=[];for(let o of await CT(e,t)){let s=Wl.relative(e,o).replace(/\\/g,"/"),i=Wl.basename(o).toLowerCase(),a=await ET(o,"utf8").catch(()=>null);if(!a)continue;let c=Km.get(i);if(c){let l=Bl(c,a,{root:e,reportPath:o});l?.lines_total&&r.push({format:c,path:s,stale:!1,generated_at:new Date().toISOString(),...l});continue}n.length<Xm&&n.push(...OT(a,s).slice(0,Xm-n.length))}return{test_cases:n,coverage:r}}import{readdir as Vl,readFile as IT,stat as jT}from"node:fs/promises";import ve from"node:path";var NT=["pyproject.toml","setup.cfg","setup.py","pytest.ini","tox.ini","package.json","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts"],MT=new Set([".git",".engineeros",".venv","venv","node_modules","dist","build","target","__pycache__",".next"]),PT=3,Jl=new Set(["python","python3","py"]),LT=[".venv","venv"],DT=/^(?:pyproject\.toml|setup\.cfg|setup\.py|pipfile(?:\.lock)?|poetry\.lock|uv\.lock|pdm\.lock|requirements[\w.-]*\.txt|package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|pnpm-workspace\.yaml|bun\.lockb?)$/i,no="ENVIRONMENT_BLOCKER";async function to(e){try{return await jT(e),!0}catch{return!1}}var ql=new Map([["--junitxml",null],["--junit-xml",null],["--outputFile",null],["--outputFile.junit",null],["--test-reporter-destination",null],["--junitfile",null],["--report-junit-path",null],["--out",null],["--logger",/(?:^|;)\s*LogFilePath=([^;]+)/i],["--reporter-options",/(?:^|,)\s*mochaFile=([^,]+)/],["--reporter-option",/(?:^|,)\s*mochaFile=([^,]+)/]]),FT=new Set(["stdout","stderr"]),UT=new Set(["-k","-m","-p","-o","-n","-W","--tb","--maxfail","--deselect","--grep","-g","-t","--testNamePattern","--test-name-pattern","--reporter","--test-reporter","--durations","-e","--eval",...ql.keys()]),zT=new Set(["-k","-m","-t","-g","--grep","--testNamePattern","--test-name-pattern","--filter","-run","--tests"]),GT=new Set(["pnpm","yarn","npm","bun"]),BT=new Set(["npm","npx","pnpm","yarn","bun","go","cargo","mvn","gradle","gradlew","make","dotnet","deno"]),HT=/[\\/]|\.[A-Za-z0-9]+$/,WT=/\.[A-Za-z0-9]+$/;function It(e){return ve.basename(String(e??"")).toLowerCase().replace(/\.(cmd|exe|bat)$/,"")}function Fi(e){let t=BT.has(It(e[0])),n=[];for(let r=1;r<e.length;r++){let o=e[r];if(UT.has(o)){r+=1;continue}!o||o.startsWith("-")||/^[a-z]+:\/\//i.test(o)||t&&!HT.test(o)||n.push(o.split("::")[0].replace(/\/\.\.\.$/,""))}return n}function rg(e){return Jl.has(It(e[0]))&&e[1]==="-m"?e.slice(2):e}function Ui(e){let t=rg(e),n=It(t[0]);return t.slice(1).some(r=>{let o=r.split("=")[0];return zT.has(o)&&!(o==="--filter"&>.has(n))})}function Xl(e){if(e.some(n=>n.includes("::")))return!0;let t=Fi(rg(e));return t.length>0&&t.every(n=>WT.test(n))}var qT={npm:["--prefix"],pnpm:["-C","--dir"],yarn:["--cwd"]};function VT(e){let t=qT[It(e[0])]??[];for(let n=1;n<e.length&&e[n]!=="--";n++){let[r,o]=e[n].split(/=(.*)/s);if(t.includes(r))return String(o??e[n+1]??"").replace(/\\/g,"/")}return""}function og(e){let t=VT(e),n=[];for(let r=1;r<e.length;r++){let[o,s]=e[r].split(/=(.*)/s);if(!ql.has(o))continue;let i=s??e[++r];if(!i)continue;let a=ql.get(o),c=(a?a.exec(i)?.[1]:i)?.trim();!c||FT.has(c)||n.push(t&&!ve.isAbsolute(c)?ve.posix.join(t,c.replace(/\\/g,"/")):c)}return n}async function sg(e,t="",n=0){let r=[],o;try{o=await Vl(ve.join(e,t),{withFileTypes:!0})}catch{return r}if(t&&o.some(s=>s.isFile()&&NT.includes(s.name))&&r.push(t),n>=PT)return r;for(let s of o)s.isDirectory()&&!MT.has(s.name)&&!s.name.startsWith(".")&&r.push(...await sg(e,ve.join(t,s.name),n+1));return r}async function Zm(e,t){let n=0;for(let r of t)await to(ve.resolve(e,r))&&(n+=1);return n}function ig(e,t){let n=ve.relative(t,e),r=n&&!n.startsWith("..")?n.split(ve.sep):[];return r.map((o,s)=>ve.join(t,...r.slice(0,r.length-s))).concat(t)}function Qm(e,t,n){return n==="win32"?ve.join(e,"Scripts",`${t}.exe`):ve.join(e,"bin",t)}async function JT(e,t,n){let r=n==="win32"?[ve.join(e,"Lib")]:(await Vl(ve.join(e,"lib")).catch(()=>[])).filter(o=>/^python\d/.test(o)).map(o=>ve.join(e,"lib",o));for(let o of r)if(await to(ve.join(o,"site-packages",t,"__main__.py")))return!0;return!1}async function XT(e,t,n,r){let o=e==="py.test"?"pytest":e.replace(/-/g,"_");for(let s of ig(t,n))for(let i of LT){let a=ve.join(s,i),c=Qm(a,"python",r);if(Jl.has(e)){if(await to(c))return{base:s,environment:a,argv:[c]};continue}if(await to(c)&&await JT(a,o,r))return{base:s,environment:a,argv:[c,"-m",o]};let l=Qm(a,e,r);if(await to(l))return{base:s,environment:a,argv:[l]}}return null}async function KT(e,t,n,r){for(let o of ig(t,n)){let s=ve.join(o,"node_modules"),i=ve.join(s,".bin",r==="win32"?`${e}.cmd`:e);if(await to(i))return{base:o,environment:s,argv:[i]}}return null}async function eg(e,t,n,r){return await XT(e,t,n,r)??(Jl.has(e)?null:await KT(e,t,n,r))}async function tg(e){return(await Vl(e,{withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&DT.test(n.name)).map(n=>n.name)}function ng(e){return e.toString("latin1").replace(/\r\n/g,`
|
|
501
501
|
`)}async function YT(e,t,n,r){let o=[],s=ve.relative(n,r).split(ve.sep).filter(Boolean);for(let i=0;i<=s.length;i++){let a=ve.join(n,...s.slice(0,i)),c=new Set([...await tg(ve.join(e,a)),...await tg(ve.join(t,a))]);for(let l of[...c].sort()){let[u,d]=await Promise.all([e,t].map(p=>IT(ve.join(p,a,l)).catch(()=>null)));(!u||!d||ng(u)!==ng(d))&&o.push(ve.join(a,l).split(ve.sep).join("/"))}}return o}function ZT(e,t){let n=ve.relative(t,e);return(n&&!n.startsWith("..")&&!ve.isAbsolute(n)?n:e).split(ve.sep).join("/")}function QT(e,t,n){let r=ve.relative(t,e);return(r.startsWith("..")||ve.isAbsolute(r)?e:ve.relative(n,e)).split(ve.sep).join("/")}function eR(e,t){let n=String(t??"").trim().replace(/\\/g,"/").replace(/^\.\/+/,"").replace(/\/+$/,"");if(!n||n===".")return null;let r=ve.resolve(e,n),o=ve.relative(e,r);if(!o||o.startsWith("..")||ve.isAbsolute(o))throw new Error(`the Proof directory \`${n}\` is outside the repository`);return r}async function Kl(e,t,{platform:n=process.platform,directory:r="",source:o=null}={}){let s=Fi(e),i=t,a=eR(t,r);if(a)i=a;else if(s.length){let u=await Zm(t,s);if(u<s.length){let d={count:u,directories:[]};for(let p of await sg(t)){let f=await Zm(ve.join(t,p),s);f>d.count?d={count:f,directories:[p]}:f===d.count&&f>u&&d.directories.push(p)}d.directories.length===1&&(i=ve.join(t,d.directories[0]))}}let c=ve.relative(t,i),l=null;if(!/[\\/]/.test(e[0])){let u=It(e[0]);if(l=await eg(u,i,t,n),!l&&o&&ve.resolve(o)!==ve.resolve(t)){let d=await eg(u,ve.join(o,c),o,n);if(d){let p=await YT(t,o,ve.relative(o,d.base),c);if(p.length)throw Object.assign(new Error(`this worktree has no installed environment for \`${e[0]}\`, and the source checkout's \`${ZT(d.environment,o)}\` was installed from different dependencies (${p.map(f=>`\`${f}\``).join(", ")} differ), so the command cannot run with matching dependencies. Install them in the worktree, or make those files match, then resume`),{code:no});l=d}}}return{argv:l?[...l.argv,...e.slice(1)]:e,cwd:i,directory:c.split(ve.sep).join("/"),launcher:l?[QT(l.argv[0],t,i),...l.argv.slice(1)].join(" "):null}}function Ko(e){let t=[];return e.directory&&t.push(`from \`${e.directory}\``),e.launcher&&t.push(`with \`${e.launcher}\``),t.join(" ")}var oR=4e3,sR=900*1e3,iR=64e3,zi=124,mg=127,aR=1e3,cR=Fc,lR=/[|&;<>`$(){}*?~#\r\n]/,uR=/^[A-Za-z_][A-Za-z0-9_]*=/,Tr=".engineeros-junit.xml";function Ft(e=process.env){let t=Number(e.ENGINEEROS_TEST_COMMAND_TIMEOUT_MS);return Number.isFinite(t)&&t>0?Math.floor(t):sR}function dt(e){let t=String(e??"").trim().replace(/^`([^`]+)`$/,"$1").trim(),n=[],r="",o=!1,s=null;for(let i of t)if(s)if(i===s)s=null;else{if(s==='"'&&/[$`]/.test(i))throw new Error("a double-quoted argument contains shell expansion ($ or a backtick)");r+=i}else if(i==='"'||i==="'")s=i,o=!0;else if(/\s/.test(i))o&&n.push(r),r="",o=!1;else{if(lR.test(i))throw new Error(`it uses shell syntax (${JSON.stringify(i)}) that is not run without a shell`);r+=i,o=!0}if(s)throw new Error("it has an unterminated quote");if(o&&n.push(r),!n.length)throw new Error("it is empty");if(uR.test(n[0]))throw new Error("it starts with an environment assignment instead of an executable");return n}var dR={passed:"passed",failed:"failed",errors:"failed",error:"failed",skipped:"skipped"};function pR(e){let t={passed:0,failed:0,skipped:0},n=!1;for(let[,r,o]of e.matchAll(/(\d+)\s+(passed|failed|errors?|skipped)\b/g))t[dR[o]]+=Number(r),n=!0;return n?t:null}var fR=[{name:"node:test",parse(e){let t={};for(let[,n,r]of e.matchAll(/^\s*(?:#|ℹ)\s+(pass|fail|skipped)\s+(\d+)\s*$/gm))t[{pass:"passed",fail:"failed",skipped:"skipped"}[n]]=Number(r);return"passed"in t&&"failed"in t?{passed:t.passed,failed:t.failed,skipped:t.skipped??0}:null}},{name:"pytest",parse:e=>ag(e,/^(?:=+ )?(?:\d+ \w+(?:, )?)+ in [\d.]+s.*$/gm)},{name:"vitest/jest",parse:e=>ag(e,/^\s*Tests:?\s+.*\d+ (?:passed|failed|skipped).*$/gm)}];function ag(e,t){let n=[...e.matchAll(t)].at(-1)?.[0];return n?pR(n):null}function hR(e){for(let{parse:t}of fR){let n=t(String(e??""));if(n)return n}return{passed:null,failed:null,skipped:null}}function or(e,{cwd:t,timeoutMs:n,onChild:r,env:o,input:s}){return new Promise(i=>{let a=Date.now(),c="",l=!1,u=!1,d=!1,p=[],f=_=>{if(!u){u=!0;for(let k of p)clearTimeout(k);g.stdout.destroy(),g.stderr.destroy(),y?.(),i({exitCode:_,durationMs:Date.now()-a,output:rR(c),timedOut:l,notFound:d})}},h=_=>{c=(c+_).slice(-iR)},g=Ot(e[0],e.slice(1),{cwd:t,stdio:[s==null?"ignore":"pipe","pipe","pipe"],...o?{env:{...process.env,...o}}:{}}),y=r?.(g);s!=null&&g.stdin.end(String(s)),g.stdout.setEncoding("utf8"),g.stderr.setEncoding("utf8"),g.stdout.on("data",h),g.stderr.on("data",h),p.push(setTimeout(()=>{l=!0,h(`
|
|
@@ -993,7 +993,7 @@ It is checked with the provider and stored in this machine's protected vault
|
|
|
993
993
|
(Windows Data Protection, the macOS Keychain or the Linux Secret Service).
|
|
994
994
|
EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function wG(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(`
|
|
995
995
|
`),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
|
|
996
|
-
`)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 lE=Symbol("missing");function yG(e,t){return new Promise(n=>{let r=mG(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?lE:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function cE(e,t){for(let n of Bs){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 uE(e,t,n,{vault:r=Cp(),run:o=_c,fetchImpl:s=fetch,secret:i=wG,interactive:a=yG,install:c=yc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(gG),n.help?0:2;if(e==="integrations")return cE(l,(await Sc({run:o,vault:r})).providers),0;let d=t[0];if(!Bs.includes(d))return u(`Unknown provider ${d}. Choose one of: ${Bs.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Ur[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 h=await a(f,["auth","login"]);if(h===lE){let g=await Eo(f);if(!g){l(`Installing the ${Us[f].label} ${Us[f].version} for the connector...`);try{g=(await c(f)).path}catch(y){return u(y.message),1}}h=await a(g,["auth","login"])}return h?(u(`${h} ${bc[d]} is how this machine signs in to ${d}.`),1):(cE(l,{[d]:(await Sc({run:o,vault:r})).providers[d]}),0)}let p=ht[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Op(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await Ip(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}import{spawn as _G}from"node:child_process";async function dE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=_G,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=Qn(await kt(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await vG(o,c.entry,i,t);if(l===zo){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 kt(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await cl(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 vG(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Wr]:"1",[rl]:r.entry,[ol]: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 wr="1.55.
|
|
996
|
+
`)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 lE=Symbol("missing");function yG(e,t){return new Promise(n=>{let r=mG(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?lE:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function cE(e,t){for(let n of Bs){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 uE(e,t,n,{vault:r=Cp(),run:o=_c,fetchImpl:s=fetch,secret:i=wG,interactive:a=yG,install:c=yc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(gG),n.help?0:2;if(e==="integrations")return cE(l,(await Sc({run:o,vault:r})).providers),0;let d=t[0];if(!Bs.includes(d))return u(`Unknown provider ${d}. Choose one of: ${Bs.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Ur[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 h=await a(f,["auth","login"]);if(h===lE){let g=await Eo(f);if(!g){l(`Installing the ${Us[f].label} ${Us[f].version} for the connector...`);try{g=(await c(f)).path}catch(y){return u(y.message),1}}h=await a(g,["auth","login"])}return h?(u(`${h} ${bc[d]} is how this machine signs in to ${d}.`),1):(cE(l,{[d]:(await Sc({run:o,vault:r})).providers[d]}),0)}let p=ht[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Op(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await Ip(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}import{spawn as _G}from"node:child_process";async function dE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=_G,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=Qn(await kt(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await vG(o,c.entry,i,t);if(l===zo){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 kt(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await cl(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 vG(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Wr]:"1",[rl]:r.entry,[ol]: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 wr="1.55.1",Cc="1.55.1",kG=3e5,Oc=["queued","running","reporting"],$G=5e3,jp={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."},Np={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."},xG=6e4,AG=3e4,TG=60*6e4,Mp={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Pp={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:Xe,positional:wt,flags:Se}=mb(process.argv.slice(2));Xe==="version"&&(console.log(wr),process.exit(0));var Kn=null,gt=!1,yn=null,kE=!1,$E=null,Vp=null,st=null,Zs=null,Hp,pE,fE,qs,Ao,xE=hc({getWorkspace:()=>A.workspace,onRecorded:e=>yS(A,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}`))}),RG=iE({getWorkspace:()=>A.workspace,huntSignIns:xE}),Vs=_b();Xe==="results"&&(wt[0]!=="upload"&&(console.log(ac),process.exit(Se.help||!wt[0]?0:2)),process.exit(await eS(Se)));(Xe==="connect"||Xe==="disconnect"||Xe==="integrations")&&process.exit(await uE(Xe,wt,Se,{fetchImpl:rE}));if(Xe==="runner"){let e=bt.resolve(Se.workspace||process.cwd()),t=wt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?bt.join(bt.dirname(He(e,Se["run-id"])),"worker.log"):bt.join(e,".engineeros","runner","service.log");SG(bt.dirname(n),{recursive:!0});let r=(...s)=>$s(n,`${EG(...s)}
|
|
997
997
|
`),o=(s,i,a)=>($s(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(Se["keep-awake"]!==void 0){if(!["on","off"].includes(Se["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await ut(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await vn({...n,runner_keep_awake:Se["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await Ka(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 M0(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await vo(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await lr(e),null,2)):t==="serve"?await F0(e):t==="worker"?await U0(e,Se["run-id"]):Fe("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){Fe(Gd(n,e).message)}}Se["assessment-workers"]!==void 0&&Fe("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(Xe==="tools"){try{let e=W0(Se),t=wt[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=wt[1];r||Fe(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await Lu(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 us(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:wt[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await Nu(e,t,wt[1]);let n=await Gt(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){Fe(e.message)}process.exit(process.exitCode||0)}if(Xe==="agents"){let e;try{e=await Qu()}catch(n){Fe(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await ps(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(Xe==="agent"){let e=wt[0],t=wt[1]||"check";(!e||!["check","install"].includes(t))&&Fe("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await fs(e):await ps(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){Fe(n instanceof Error?n.message:String(n))}process.exit(0)}if(Xe==="mcp"){let e=Se.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=Se["run-id"]||wt[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await ut(e);await jb({config:n,runId:t,version:wr,input:process.stdin,output:process.stdout}),process.exit(0)}if(Xe==="context-mcp"){let e=Se["config-workspace"]||Se.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await ut(e);t||Fe("This workspace is not paired with EngineerOS."),await Hb({config:t,workspace:Se.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:wr,input:process.stdin,output:process.stdout}),process.exit(0)}if(Xe==="status"){let e=await ut(Se.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(Xe==="doctor"){let e=bt.resolve(Se.workspace||process.cwd()),t=await ut(e),n=await Tb(e),r=await Io(t||{workspace:e},e,op(n));console.log(np(r)),process.exit(r.status==="failed"?1:0)}if(Xe==="update"){let e=wt[0]||"status";try{let t=il(process.argv[1],Cc),n=await ll(In(),t,{action:e,policy:wt[1]??null});console.log(Bo(ul(n,t,{supervised:!0})))}catch(t){Fe(`${t.message}
|
|
998
998
|
Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var To=Xe==="hunt-host";if(To)try{Se.workspace=H0(wt,Se)}catch(e){Fe(e.message)}if((Xe==="start"||Xe==="pair"||To)&&process.env[Wr]!=="1"&&Ke(Cc))try{process.exit(await dE({root:In(),bundled:{version:Cc,entry:bt.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:bt.resolve(Se.workspace||process.cwd())}))}catch(e){Fe(`The connector process could not be started: ${e.message}`)}if(To){try{await q0(Se.workspace,wt[0]?Se.agent:null)}catch(e){Fe(e.message)}Xe=wt[0]?"pair":"start"}var A,Gr,Js;if(Xe==="pair"){let e=wt[0];e||Fe("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=Se.url;t||Fe("Pairing requires --url with the EngineerOS backend address."),Se.agent&&Se["agent-command"]&&Fe("Use either --agent or --agent-command, not both.");let n=Se["agent-protocol"]||(Se["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||Fe(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(Se.agent||Se["agent-command"])&&Fe("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{Se.agent&&(await ps(Se.agent),r=await ed(Se.agent))}catch(o){Fe(o instanceof Error?o.message:String(o))}A={server_url:dl(t),workspace:bt.resolve(Se.workspace||process.cwd()),onboard:Se.onboard===!0,onboarding_pending:Se.onboard===!0,hunt_host:To,agent_protocol:n,agent_command:Se["agent-command"]||null,agent_args:KG(Se["agent-args"]),agent_name:Se["agent-name"]||null,...r,skip_git_repo_check:To||Se["skip-git-repo-check"]===!0,name:Se.name||`${bG.hostname()} - ${bt.basename(bt.resolve(Se.workspace||process.cwd()))}`},Js=await ut(A.workspace),Gr={type:"pair",pairing_code:e,name:A.name,capabilities:{},...Vf(Js,A.server_url)}}else Xe==="start"?(A=await ut(Se.workspace||process.cwd()),A||Fe("This connector is not paired. Create a pairing command in EngineerOS first."),To&&!A.hunt_host&&Fe("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),Gr={type:"authenticate",connector_id:A.connector_id,token:A.token}):Fe("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, or `mcp`.");var AE=z0(A,{reportError:e=>console.error(e)}),gr=0,Ic=!1,Xs=null,yt=new Map,Lp=0,Dp=new Set,Ro=[],mt=new Map,ot,Wp,xc,Tn=null,Ac=!1,TE=0,Fp=null,Up=[],Tc,RE,Hs=1e3,Co,hE=0,zp=!1,Vn=!1,en,$o=!1,jc=!1,qp=0;function Ec(e){return qp+=1,e.finally(()=>{qp-=1})}var xo,zr=0;function Ks({exitCode:e=0}={}){if(zr=Math.max(zr,e),xo)return xo;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),xo=CG().finally(()=>clearTimeout(t)),xo}async function CG(){if(gt=!0,Zs?.stop(),Kn?.stop(),Vp?.stop(),$E?.stop(),clearInterval(Hp),st?.stop(),RE?.(),clearTimeout(Tc),clearInterval(Wp),clearInterval(xc),await Promise.all([...[...yt.values()].map(e=>At(e.child))]),await Promise.all([...mt.values()].map(Kp)),await qs?.cancelAll(),await Ao?.abortAll(),await ds(),await rf().catch(e=>{zr=Math.max(zr,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),ot?.close(),zr&&zr!==zo){let e;await Promise.race([(async()=>{await Kn?.drain(),await Io(A,A.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(zr)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{Ks()});var mE=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{mE||(mE=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await Ks({exitCode:1}))});st=df();process.on("exit",()=>{Zs?.stop(),st.stop()});st.banner(`EngineerOS connector ${wr}`,[A.workspace,A.server_url]);Kn=yb({actions:{refresh_tool_inventory:async()=>{Ee.tool_inventory=await Gt(A.workspace),Pt()},restart_goal_runner:()=>vo(A.workspace)},onNotify:()=>Io(A,A.workspace),explain:async e=>{if(!await Ys())return null;let{reading:t}=await p0(A,e);return t},onUpdate:e=>Ab(A.workspace,e)});$E=Cb({render:(e,t)=>st.write(e,t),onRecord:e=>Kn.observe(e)});Vp=Ob({workspace:A.workspace,onRecord:e=>{Kn.observe(e),st.line(e.channel,e.level,e.message)}});Kn.start();A.hunt_host||Vp.start();st.live&&!A.hunt_host&&(Hp=setInterval(()=>{OG().catch(()=>{})},$G),Hp.unref?.());var Gp=new Set;async function OG(){if(A.hunt_host)return;pE??=Fd(A.workspace);let{jobs:e}=await pE(),t=new Set,n=e.filter(r=>r.status!=="queued"&&Oc.includes(r.status)).length;for(let r of e){if(!Oc.includes(r.status))continue;t.add(r.runId),Gp.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;st.status(`goal:${r.runId}`,o,IG(r),{agent:r.status!=="queued",link:Xs&&`${Xs}/goals`}),st.step(`goal:${r.runId}`,r.activity?.message)}for(let r of Gp)t.has(r)||(Gp.delete(r),st.clearStatus(`goal:${r}`))}function IG(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function Ys({ignoreBugHunt:e=!1}={}){if(gt||yt.size>0||mt.size>0||gr>0||(qs?.active??0)>0||!e&&(Ao?.active??0)>0)return!1;try{let{jobs:t}=await lr(A.workspace);return!gt&&!t.some(n=>Oc.includes(n.status))}catch{return!1}}try{let e=A.hunt_host?{}:await Br(A.workspace);e.committed&&(A.onboarding_pending=!0,A.connector_id&&await vn(A),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await jE(e)}var CE=await kt(In()).then(e=>e.policy!=="manual",()=>!1),Me;try{Me=await Ss(A,A.workspace)}catch(e){await jE(e)}console.log(`Using ${Me.name} through ${Me.protocol} (${Me.version}).`);var Ee=rc(A,Me,await Gt(A.workspace)),Xn=Wf({running:il(process.argv[1],Cc),supervised:process.env[Wr]==="1",isIdle:async()=>!gt&&yt.size===0&&Ro.length===0&&mt.size===0&&gr===0&&qp===0&&!$o&&!jc&&!Ac,restart:()=>Ks({exitCode:zo}),onChange:e=>{Ee.runtime_update=e,ot?.readyState===WebSocket.OPEN&&Pt()}});try{await Xn.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}A={...A,execution_profiles:Me.executionProfiles??null};Xe==="pair"&&Js?.connector_id||await vn(A);Ee.agent_session={...Ee.agent_session,status:"checking",message:`Checking that ${Me.name} can answer.`};Ee.bug_hunt_browser=!1;Gr.capabilities=Ee;console.log(zn(A.worker_limit)===null?`Workers: automatic, ${ho()} ${Me.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${zn(A.worker_limit)} ${Me.name} workers side by side, set with /workers.`);var Oo=e=>Gn(A,e),gE=Wa(Oo,{signature:b0});async function jG(){let e=await lr(A.workspace).catch(()=>({service:null,jobs:[]}));return{version:wr,now:Date.now(),workspace:A.workspace,config_path:Ht(A.workspace),config:A,agent:Me,automatic_worker_limit:ho(),worker_limit:zn(A.worker_limit),connection:{state:NG(),server_url:A.server_url,last_error:en||null},work:{assessments:[...yt.values()].map(t=>({stage:t.stage,message:t.lastMessage,started_at:t.startedAt})),prompts:[...mt.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,started_at:t.startedAt})),integrations:gr},runner:e,runtime_update:Xn.report(),health:Kn?.health()??null,activity:Vs.snapshot()}}function NG(){return gt||Vn?"stopped":ot?.readyState===WebSocket.OPEN?"connected":"connecting"}var MG={async cancelPrompt(e){let t=[...mt.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=>IE(e),setVerbose(e){return e===Ic?`Detailed agent activity is already ${e?"on":"off"}.`:(Jp(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"?(Xn.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 Xn.command(e),Bo(await Xn.refresh()))}};Zs=Eb({ui:st,snapshot:jG,actions:MG});Zs&&console.log(Sb());await OE();var wE=new Set;async function OE(){if(gt||Vn)return;console.log(`Connecting ${A.name} to ${A.server_url}`),Vn=!1,en=void 0;let e=new WebSocket(A.server_url);ot=e;let t=Gg(e,A.server_url,{onTimeout:r=>{ot===e&&(en=r,console.error(r),Bp())}});RE=t,e.addEventListener("open",()=>{if(ot!==e){e.close();return}try{if(Pg(ot,e,Gr))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){en=$t(r),console.error(`Could not authenticate the WebSocket connection: ${en}`);try{e.close()}catch{}Bp()}}),e.addEventListener("message",r=>{if(ot!==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: ${$t(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){gt=!0,Vn=!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=Js?.connector_id===r.connector.id;if(A=Jf(A,Js,r.connector.id,r.token),await vn(A),r.connector?.capabilities?.http_updates!==!0){gt=!0,Vn=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}Gr={type:"authenticate",connector_id:A.connector_id,token:A.token,capabilities:Ee},console.log(s?`Reconnected existing workspace connector ${A.connector_id}; assessment history is preserved.`:`Paired. Connector ${A.connector_id} is online.`),_E(r);return}if(r.type==="authenticated"){t();let s=A.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(Co?`Reconnected after ${Oe(Date.now()-Co)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),Co=void 0,_E(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){jc||LG(r);return}if(r.type==="workspace.refresh"){Nc();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await IE(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){Jp(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(Jn=!1,Ee.bug_hunt_browser=!1,Pt());try{Ee.tool_inventory=await us(A.workspace,r,void 0,{confirmLocal:i=>Zs?.confirm(i)??!1,log:Rc}),s&&(Jn=!0),Ee.bug_hunt_browser=Fr(Ee.tool_inventory)&&Jn,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Ee.tool_inventory})),Pt(),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 Lu(A.workspace,r,{onStatus:async()=>{Ee.tool_inventory=await Gt(A.workspace),Pt()}});Ee.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:Ee.tool_inventory})),Pt(),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"){Qr(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===sE){Ec(RG(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),aE(A,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}`;Td(Ro,yt.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Qs();return}if(r.type==="prompt.execute"){let s=mt.get(r.prompt_id);s?DE(r)>s.executionRevision&&await qG(s,r):LE(r);return}if(r.type==="prompt.cancel"){let s=mt.get(r.prompt_id);s&&await Kp(s);return}if(r.type==="agent.warm"){FG(r);return}if(r.type==="run.available"){if(A.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await AE.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${bt.join(A.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${$t(s)}`)}return}if(r.type==="goal.cleanup"){try{await D0(A.workspace),await vo(A.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){XG(r);return}if(r.type==="run.cancelled"){await Dd(A.workspace,r.run_id);return}if(r.type===aw){qs??=ww({getConfig:()=>A,onTestsCommitted:()=>Nc()}),Ec(qs.handle(r));return}if(r.type===cw){await qs?.cancel(r);return}if(r.type===AS){Ao??=IS({getConfig:()=>A,isIdle:()=>Ys({ignoreBugHunt:!0}),recordedSignIns:xE,activity:{status:st.status,step:Xp,finish:st.finish}}),Ec(Ao.handle(r));return}if(r.type===TS){Ao?.stop(r);return}if(r.type===tS){fE??=nS({getConfig:()=>A}),Ec(fE.handle(r));return}if(r.type==="connector.update"){PG(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await Ks();return}if(r.type==="connector.revoked"){gt=!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||($o=!1);return}if(r.type==="connection.error"){Vn=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);wE.has(o)||(wE.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${wr}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),ot!==e||xo)return;let o=Lg(r);if(!o.retry||Vn||gt){console.error(o.message),o.retry&&Vn&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),Ks();return}en=en?`${o.message} ${en}`:o.message,Bp()}),e.addEventListener("error",r=>{ot===e&&(en=Mg(r),console.error(`WebSocket connection to ${A.server_url} failed: ${en}`))})}async function PG(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=Xn.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 Xn.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 LG(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";jc=!0,console.log(`Starting interactive ${Me.name} provider ${n}.`);try{await(n==="logout"?zg:Ug)(Me,A.workspace),Me=await Ss(A,A.workspace),Ee=rc(A,Me,Ee.tool_inventory),Gr.capabilities=Ee,ot.readyState===WebSocket.OPEN&&(ot.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:Ee.agent_session})),ot.close(1e3,`Provider ${n} completed`)),console.log(`${Me.name} provider ${n} completed.`)}catch(r){let o=$t(r).slice(0,500);ot.readyState===WebSocket.OPEN&&ot.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{jc=!1}}function Bp(){if(gt||Vn||Tc)return;let e=en?` Last error: ${en}`:"",t=Co?` Offline for ${Oe(Date.now()-Co)}.`:"";Co??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(Hs/1e3)}s.`),Tc=setTimeout(()=>{Tc=void 0,OE()},Hs),Hs=Math.min(3e4,Hs*2)}async function Nc(){if(!A.hunt_host&&!($o||ot.readyState!==WebSocket.OPEN)){$o=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await m0(A.workspace),t=await h0(A.workspace,A.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(qr(A.server_url,A.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A.token}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(await Hi(n,"the workspace"));let r=await n.json();A={...A,onboarding_pending:!1,last_snapshot_head:e.head_revision??A.last_snapshot_head},await vn(A),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.`);try{let o=await Ti(A.workspace,A.connector_id);console.log(`Built the local context index: ${o.total_files.toLocaleString()} file(s) ready for assignment context.`)}catch(o){console.error(`Local context index build failed: ${o.message}`)}$o=!1}catch(e){$o=!1,console.error(`Workspace assessment failed: ${$t(e)}`)}}}var DG=6e4,yE=0;async function FG(e){if(A.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?A.sessions?.[t]:void 0,r=[];Date.now()-yE>DG&&(yE=Date.now(),r.push(Ti(A.workspace,A.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),A.agent_protocol==="acp"&&r.push(Hy(A.workspace,A,{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(`${Me?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Pt(){let e=n0(yt);gE.update({type:"assessment.workers",assessment_workers:e,tool_inventory:Ee.tool_inventory,runtime_update:Ee.runtime_update,agent_session:Ee.agent_session,bug_hunt_browser:Ee.bug_hunt_browser,...Ua(A.worker_limit)}),gE.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function IE(e){let t=zn(e);return t===zn(A.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(A={...A,worker_limit:t},await vn(A),Qs(),Pt(),t===null?`Workers are automatic again: up to ${ho()} side by side for this machine's CPU and memory, for ${Ms} (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: ${Ms}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function Jp(e){if(e!==Ic){if(Ic=e,!e)for(let t of yt.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."),Pt()}}function Xp(e,t){st.step(e,t)&&Ic&&console.log(`[${e}] ${t}`)}function UG(){clearInterval(xc);let e=!1,t=()=>{e||yt.size>0||mt.size>0||(e=!0,Io(A,A.workspace).finally(()=>{e=!1}))};t(),xc=setInterval(t,kG),xc.unref?.()}async function Io(e,t,n=Kn?.healthChecks()??[]){let r=await fb({config:e,workspace:t,version:wr,insights:n,agentSession:yn,probes:{inspectAgent:(o,s)=>gt?Me:Ss(o,s),inspectTools:o=>gt?Ee.tool_inventory:Gt(o),runnerStatus:lr}});try{kE=(await hb(e,r,Gn))?.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 jE(e){if(gt)return xo;let t=e instanceof Error?e.message:String(e),n=await Io(A,A.workspace).catch(()=>null);n&&console.error(np(n)),Fe(t)}function _E(e){Jp(e.connector?.activity_log_enabled===!0),Xs=e.project_url??null,Hs=1e3,GG(),ME(),Xn.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),BG(),A.onboarding_pending&&Nc()}var Ws=null,Jn=!1,NE=0,zG=Date.now();async function GG(){return Ws||(Ws=(async()=>{CE&&await xy(A.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Rc("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await V0(A.workspace,{log:Rc}),Jn=!0,Ee.tool_inventory=await Gt(A.workspace),Ee.bug_hunt_browser=Fr(Ee.tool_inventory)&&Jn,Rc(`Bug Hunter's browser is ready (${Oe(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${Oe(Date.now()-e)}: ${t.message}`),Ee.bug_hunt_browser=!1}Pt()})(),Ws)}function Rc(e){console.log(`[browser] ${e}`)}async function ME(){if(yn?.state!=="checking"){NE=Date.now(),Ee.agent_session={...Ee.agent_session,status:"checking",message:`Checking that ${Me.name} can answer.`},Pt(),yn={state:"checking",detail:`Asking ${Me.name} one question to confirm its session.`},console.log(`Checking that ${Me.name} can answer before accepting work.`);try{await a0(A,Me.name),yn={state:"ready",detail:`${Me.name} answered; its session is usable.`},Ee.agent_session={...Ee.agent_session,status:"authenticated",message:yn.detail},console.log(yn.detail)}catch(e){yn={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:A.hunt_host?X0(A.agent_id||A.agent_protocol):lo(A.agent_id||A.agent_protocol)},Ee.agent_session={...Ee.agent_session,status:"logged_out",message:yn.remedy},console.error(`${yn.detail}
|
|
999
999
|
${yn.remedy}`)}Pt(),await Io(A,A.workspace).catch(()=>null)}}function BG(){clearInterval(Wp);let e=!1,t=0,n=0,r=!1,o=()=>{Xn.tick(),HG(),A.hunt_host&&Ws&&Date.now()-NE>=J0(zG)&&mt.size===0&&yt.size===0&&!(Ao?.active>0)&&ME(),!A.hunt_host&&!r&&js(Pp.id)&&(r=!0,AE.flush().then(()=>$c(Pp)).catch(s=>kc(Pp,s)).finally(()=>{r=!1})),yt.size>0&&Pt(),!A.hunt_host&&!Tn&&Date.now()-t>=xG&&js(jp.id)&&(t=Date.now(),PE().then(()=>$c(jp)).catch(s=>kc(jp,s))),!A.hunt_host&&kE&&!Ac&&js(Np.id)&&Date.now()-TE>=jw&&(Ac=!0,WG().then(()=>$c(Np)).catch(s=>kc(Np,s)).finally(()=>{Ac=!1})),!e&&Date.now()-n>=AG&&js(Mp.id)&&(e=!0,n=Date.now(),Gt(A.workspace).then(async s=>{if(Ee.tool_inventory=s,!Jn&&Fr(s))try{await(await yr(await dr(A.workspace))).close(),Jn=!0}catch{Jn=!1}Ee.bug_hunt_browser=Fr(s)&&Jn,Pt(),$c(Mp)}).catch(s=>kc(Mp,s)).finally(()=>{e=!1}))};o(),Wp=setInterval(o,1e4),UG()}async function HG(){if(!(!CE||A.agent_protocol!=="acp"||!A.agent_id||zp||yn?.state==="checking"||Date.now()-hE<TG)){zp=!0;try{if(!await Ys())return;hE=Date.now();let e,t=await Zy(A,{verify:async r=>{e=await Ss(r,A.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===A||gt)return;A={...t,execution_profiles:e.executionProfiles??null},await vn(A),Me=e;let n=rc(A,Me,Ee.tool_inventory);if(Object.assign(Ee,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),Gr.capabilities=Ee,!await Ys())return;await ds(),ot?.readyState===WebSocket.OPEN&&ot.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{zp=!1}}}function kc(e,t){let n=ab(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 $c(e){cb(e.id)&&console.log(`${e.title} recovered.`)}async function WG(){if(A.hunt_host||!await Ys())return;TE=Date.now();let{jobs:e}=await lr(A.workspace).catch(()=>({jobs:[]})),t=await Nw(A.workspace,{jobs:e});if(!Mw(t))return;let n=`${t.fingerprint}:${Up.join(",")}`,r=Fp?.key===n,o=r?Fp.candidates:await f0(A,t,Up);Fp={key:n,candidates:o};let s=await Oo(Dw(t,o,{version:wr}));Array.isArray(s?.refused)&&(Up=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 mr=null,vE=null;async function PE(){if(!A.hunt_host){if(Tn)return Tn;Tn=(async()=>{let e=await $w(A,{knownRevision:mr?.revision??null});if(e.unchanged||(mr=e),vE===mr.revision)return mr;let{jobs:t}=await lr(A.workspace);return!t.some(r=>Oc.includes(r.status))&&gr===0&&yt.size===0&&(await oa(A.workspace,mr),vE=mr.revision),mr})();try{return await Tn}finally{Tn=null,Qs()}}}function bE(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)),mt.get(e)?.events.push(n)}var SE=null;function Qs(){let e=ot.readyState===WebSocket.OPEN,t=yt.values().next().value,n=zn(A.worker_limit)??Math.min(ho(),Rd(t?.workerLimit??Ro[0]?.worker_limit)),r=e&&!Tn&&gr===0?Vv(Ro,yt.size,n):[];for(let s of r){let i=`${s.assessment_id}:${s.stage}`,a={kind:"assessment",key:i,runId:s.assessment_id,stage:s.stage,child:null,controller:null,resumeAssignment:null,phase:"starting",progressPercent:5,lastMessage:`Starting ${s.stage} assessment stage`,startedAt:Date.now(),workerLimit:Rd(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};yt.set(i,a),JG(s,a)}r.length>0&&Pt();let o=Jv({queued:Ro,running:yt.size,workerLimit:n,connected:e,designSync:!!Tn,integrations:gr});o&&o!==SE&&console.log(o),SE=o}function Mc(e){let t=Cd(e);return t?`${Me.name} on ${t}`:Me.name}async function LE(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s={runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:k0(Oo),executionRevision:DE(e),sessionKey:za(e),sessionId:null,replacement:null};mt.set(t,s);let i,a=g=>{let y=g?JSON.stringify(g):null;!y||y===i||mt.get(t)!==s||(i=y,bE(t,g))},c=`${r} \xB7 ${Mc(e)}`,l=i0(e,Me.name);bE(t,{kind:"status",message:l});let u=Number(e.answer_within_seconds),d=u>0?o+u*1e3:void 0;console.log([`[${n}] ${l} for ${r}.`,`${Me.name} can reason for several minutes without reporting a step.`,...d?[Gc(d,o)]:[]].join(" ")),st.status(n,c,o,{link:Xs,answerBy:d});let p=g=>{let y=Hv(g),_=Ir(g);mt.get(t)===s&&Xp(n,_??y?.message);let k=g.type==="forge.output"?null:_;a(y??(k?{kind:"status",message:k}:null))},f="failed",h=[r];try{Ga(e)||(p({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await Cw(PE,{pinned:!!e.local_design_context,last:mr,onFallback:(k,v)=>p({type:"connector.step",message:`Design context not refreshed (${k.message}); continuing with ${v?"the copy synced earlier":"none"}`})})});let g=await Dv(e,A,{onProcess:k=>{mt.get(t)===s&&(s.child=k)},onController:k=>{mt.get(t)===s&&(s.controller=k)},onSession:k=>{s.sessionId=k},onEvent:p},{signal:s.cancellation.signal});if(s.stoppedHere)throw new Error(EE);let y=g.singleTurn?Xf(A.sessions,g.sessionKey):pl(A.sessions,g.sessionKey,g.sessionId);if(JSON.stringify(y)!==JSON.stringify(A.sessions||{})&&(A={...A,sessions:y},await vn(A)),s.cancelled)return;await s.events.close().catch(k=>{console.error(`[${n}] Prompt progress delivery: ${k.message} The agent has finished; submitting its complete response separately.`)});let _=await Ha(Oo,{type:"prompt.completed",prompt_id:t,execution_revision:s.executionRevision,content:g.content,model:g.model,session_id:g.sessionId,usage:g.usage});_||console.error(`[${n}] ${Nd}`),Vs.record("prompt","completed",{durationMs:Date.now()-o,usage:g.usage}),f=_?"finished":"undelivered",h=[ri(g.usage),r]}catch(g){let y=s.stoppedHere?EE:$t(g);if(Vs.record("prompt","failed",{durationMs:Date.now()-o}),s.stoppedHere&&(f="cancelled"),!s.cancelled){try{await Ha(Oo,{type:"prompt.failed",prompt_id:t,execution_revision:s.executionRevision,message:y})||console.error(`[${n}] ${Nd}`)}catch(_){console.error(`[${n}] Prompt failure delivery: ${_.message}`)}console.error(y)}}finally{s.events.stop();let g=s.replacement;g?(f="replaced",h=[`continuing on ${Mc(g)}`,r]):s.cancelled&&(f="cancelled"),st.finish(n,f,h),mt.get(t)===s&&mt.delete(t),g&&VG(s,g)}}var EE="Cancelled from the connector terminal by the person running it.";async function Kp(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function DE(e){return Number(e.execution_revision)||1}async function qG(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 ${Mc(t)}.`),await Kp(e))}function VG(e,t){e.sessionId&&(A={...A,sessions:pl(A.sessions,e.sessionKey,e.sessionId)},vn(A).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),LE(t)}async function JG(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 ${Mc(e)}.`),!Dp.has(n)){Dp.add(n);try{let w=await zv(A.workspace);if(!w.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let S=w.accepted_head_revision?w.current_head_revision?w.current_head_revision!==w.accepted_head_revision?`The workspace is now at commit \`${w.current_head_revision}\`; the accepted assessment is from \`${w.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${w.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 ${w.stages.length||"no"} section(s). ${S}`)}}catch(w){console.error(`Assessment freshness check failed: ${w.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,d=null,p=null,f=null,h=new Set,g=()=>!gt&&yt.get(t.key)===t,y=async w=>{try{return await Ha(Oo,w)||console.warn(`[${s}] ${S0}`),!0}catch(S){return console.error(`Assessment failure delivery: ${S.message}`),!1}},_=(w,{milestone:S=!0}={})=>{if(!g()||S&&f===w)return;S&&(f=w,h.has(w)||(h.add(w),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${w}.`));let m=String(w).slice(0,500);t.progressPercent=c,t.lastMessage=m,st.status(s,m,o,{link:Xs})};_(`Starting ${r} assessment stage`);let k=setInterval(()=>{let w=Date.now(),S=w-t.lastActivityAt,m=i&&!a?Bv(r,S):null;if(!d&&m){d=m,console.error(`[assessment:${r}] ${d}`),Ba(t.controller,t.child);return}d||Kn.observe({at:w,level:"info",message:st.status(s,`${t.lastMessage} \xB7 last agent activity ${Oe(S)} ago (${t.eventCount.toLocaleString()} events)`,o)})},15e3),v={onSession:async w=>{g()&&(p=String(w),await Am(A.workspace,n,r,w,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:w=>{g()&&(t.controller=w)},onProcess:w=>{g()&&(t.child=w,i=!0,t.phase!=="correcting"&&(t.phase="running",_("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:w=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let S=Gv(w);if(S&&_(S),!g())return;let m=Ir(w);!m||m===t.lastDetail||(t.lastDetail=m,Xp(s,m))}},b=(w,S)=>xd(w,S,A,v,{draftPath:bt.relative(A.workspace,bt.join(Dt(A.workspace,n),w.report_file)).split(bt.sep).join("/")});try{let w=Lp-Date.now();w>0&&(_(`Waiting ${Math.ceil(w/1e3)}s for the model provider's rate limit to clear`),await new Promise(C=>setTimeout(C,w+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,_("Calculating changed files and affected behavior"));let S=await Im(A.workspace,e),m=await Ll(A.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(m)b(m,S),_("Recovered completed stage report from connector storage");else{if(p=await Tm(A.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),p&&_("Restoring interrupted agent session"),m=await Lv(S,A,v,{previousSessionId:p}),d)throw new Error(d);a=!0,await Pl(A.workspace,n,S,m)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let $=C=>fetch(Zf(A.server_url,A.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A.token}`},body:JSON.stringify(C),signal:AbortSignal.timeout(Sv)}),O=await s0(m,{submit:C=>o0(C,$,{isActive:()=>g()&&!gt,onRetry:(P,M)=>{_("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${$t(P)} Retrying in ${Math.round(M/1e3)}s without rerunning the agent.`)}}),payloadFor:C=>r==="synthesis"?Dl(A.workspace,n,C,{expectedSourceRevision:e.source_revision}):Pm(C),rejectionFor:C=>Hi(C,"the assessment"),correct:async(C,P)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!C.correctAfterRejection)throw new Error(`${P} The connector could not start the required agent correction.`);return C.correctAfterRejection(P)},onCorrected:async C=>{if(d)throw new Error(d);a=!0,await Cm(A.workspace,n,r);let P=await Pl(A.workspace,n,S,C);return b(P,S),t.phase="delivering",t.lastMessage="Delivering corrected stage result",P}});if(d)throw new Error(d);m=O.result;let T=O.response;if(!T.ok)throw new Error(await Hi(T,"the assessment"));if(l=!0,Vs.record("assessment stage","completed",{durationMs:Date.now()-o,usage:m.usage}),r==="synthesis"){let C=await T.json(),P=await jm(A.workspace,n,e,m,C.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${bt.relative(A.workspace,P)}.`);try{let M=await ci(A.workspace);M.committed&&console.log(`Assessment committed to Git as ${M.revision.slice(0,8)}.`)}catch(M){console.error(`The assessment is saved locally but could not be committed to Git: ${M.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(w){let S=d||$t(w),m=Zv(e,w),$=t0(w),x=Kv(w);$&&(await Rm(A.workspace,n,r).catch(T=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${T.message}`)}),p=null);let O=!d&&(p||$)&&($||Xv(w))&&m<x;if(g()&&O){t.phase="starting",t.lastMessage=$?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=Qv(e,w);let T=e0(w,m);Es(w)&&(Lp=Math.max(Lp,Date.now()+T)),console.warn(`[assessment:${r}] ${$?"Agent session became unusable":"Agent session interrupted"}: ${S} ${$?"Starting a fresh session from the saved draft":`Resuming session ${p}`} in ${Math.round(T/1e3)}s (${m+1}/${x}).`),await new Promise(C=>setTimeout(C,T))}else g()&&(u=await y({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:S}));O||(Vs.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${S}`))}finally{clearInterval(k),st.clearStatus(s),r==="synthesis"&&l&&Dp.delete(n),g()&&(yt.delete(t.key),r0(Ro,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),Qs())}}async function XG(e){let t=String(e.run_id||"");gr+=1;try{Tn&&await Tn;let n=await Rv(A.workspace,String(e.base_revision||""),String(e.head_revision||""),String(e.integration_branch||"")||null);if(n.applied){console.log(`Accepted Goal Run ${t} applied to the connected repository at ${n.revision} (${n.method}).`),await Nc();return}console.warn(`Accepted Goal Run ${t} remains on its review branch. ${n.reason}`)}catch(n){console.error(`Accepted Goal Run ${t} could not be integrated: ${$t(n)}`)}finally{gr-=1,Qs()}}function KG(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error;return t}catch{Fe('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function Fe(e){console.error(e),process.exit(1)}
|