@engineeros/connector 1.67.6 → 1.67.8

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.
@@ -1708,7 +1708,7 @@ description: Independently verify an EngineerOS Goal at the supplied revision ag
1708
1708
  For Story delivery, verify the connected user workflow across all required frontend and backend layers, including API integration and persistence where applicable. A UI-only screen or an unused endpoint fails acceptance when both layers are required. Existing working behavior may satisfy a layer without changes; judge the observed workflow rather than requiring changes in every layer. For UI changes, check the saved experience design, available design tokens (colors, typography, spacing, borders and interaction states), and reuse of existing UI primitives. Report missing integration or replacement styles that bypass those tokens as concrete findings.
1709
1709
 
1710
1710
  Return an independent verdict and residual risks. Do not modify files, install dependencies, repair failures, commit, or push while verifying.
1711
- `}});function ru(e){let t=[...e],n=t.shift(),r=[],o={};for(;t.length;){let s=t.shift();if(!s.startsWith("--")){r.push(s);continue}let i=s.slice(2);if(i==="auto-agents"||i.startsWith("auto-agents=")){if(Object.hasOwn(o,"auto-agents"))throw new Error("Pass --auto-agents only once with an explicit comma-separated selection.");let a=i.startsWith("auto-agents=")?i.slice(12):t[0];if(!a||a.startsWith("--"))throw new Error("--auto-agents needs an explicit comma-separated list such as codex-cli,forge.");o["auto-agents"]=a,i==="auto-agents"&&t.shift();continue}if(j3.has(i)){let a=o[i]??[];for(;t.length&&!t[0].startsWith("--");)a.push(t.shift());o[i]=a;continue}o[i]=I3.has(i)?!0:t.shift()}return{command:n,positional:r,flags:o}}var I3,j3,Tm=V(()=>{M();I3=new Set(["onboard","skip-git-repo-check","strict","help"]),j3=new Set(["junit","coverage"])});var Ss,ou,Rm=V(()=>{M();Ss="1.67.6",ou="1.67.6"});import{createRequire as N3}from"node:module";function ob(e,t){return!M3.has(t?.code)||!String(t.message).includes(e)?t:new Error(`This feature needs the ${e} package, which is not installed with this connector. Reinstall it without --omit=optional: npm install --global @engineeros/connector@latest`,{cause:t})}function $a(e){let t;return()=>{if(t)return t;try{t=P3(e)}catch(n){throw ob(e,n)}return t}}var P3,M3,su=V(()=>{M();P3=N3(import.meta.url),M3=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"])});import{randomUUID as U3}from"node:crypto";import{chmod as q3,link as F3,mkdir as z3,open as B3,rename as H3,rm as G3}from"node:fs/promises";import W3 from"node:path";function ib(e){return process.platform==="win32"&&K3.has(e?.code)}async function X3(e,t){let n=Date.now()+V3;for(;;)try{await H3(e,t);return}catch(r){if(!ib(r)||Date.now()>=n)throw r;await new Promise(o=>setTimeout(o,J3))}}async function He(e,t,{replace:n=!0}={}){await z3(W3.dirname(e),{recursive:!0,mode:448});let r=`${e}.${U3()}.tmp`;try{let o=await B3(r,"wx",384);try{await o.writeFile(t,"utf8"),await o.sync()}finally{await o.close()}process.platform!=="win32"&&await q3(r,384),n?await X3(r,e):await F3(r,e)}finally{await G3(r,{force:!0})}}var V3,J3,K3,An=V(()=>{M();V3=5e3,J3=50,K3=new Set(["EPERM","EACCES","EBUSY"])});import{mkdir as Y3,mkdtemp as Q3,readFile as Z3,rm as eV,writeFile as tV}from"node:fs/promises";import xs from"node:path";import nV from"node:os";import{execFile as rV}from"node:child_process";import{promisify as oV}from"node:util";function _o(e){return String(e??"").trim().replaceAll("\\","/").replace(/^\.\//,"")}function Un(e){return String(e??"").split("\0").map(_o).filter(Boolean)}async function Wt(e){let t=xs.join(xs.resolve(e),".engineeros"),n=xs.join(t,".gitignore");await Y3(t,{recursive:!0,mode:448});let r="";try{r=await Z3(n,"utf8")}catch(s){if(s?.code!=="ENOENT")throw s}if(r.split(/\r?\n/).some(s=>s.trim()==="*"))return;let o=r&&!r.endsWith(`
1711
+ `}});function ru(e){let t=[...e],n=t.shift(),r=[],o={};for(;t.length;){let s=t.shift();if(!s.startsWith("--")){r.push(s);continue}let i=s.slice(2);if(i==="auto-agents"||i.startsWith("auto-agents=")){if(Object.hasOwn(o,"auto-agents"))throw new Error("Pass --auto-agents only once with an explicit comma-separated selection.");let a=i.startsWith("auto-agents=")?i.slice(12):t[0];if(!a||a.startsWith("--"))throw new Error("--auto-agents needs an explicit comma-separated list such as codex-cli,forge.");o["auto-agents"]=a,i==="auto-agents"&&t.shift();continue}if(j3.has(i)){let a=o[i]??[];for(;t.length&&!t[0].startsWith("--");)a.push(t.shift());o[i]=a;continue}o[i]=I3.has(i)?!0:t.shift()}return{command:n,positional:r,flags:o}}var I3,j3,Tm=V(()=>{M();I3=new Set(["onboard","skip-git-repo-check","strict","help"]),j3=new Set(["junit","coverage"])});var Ss,ou,Rm=V(()=>{M();Ss="1.67.8",ou="1.67.8"});import{createRequire as N3}from"node:module";function ob(e,t){return!M3.has(t?.code)||!String(t.message).includes(e)?t:new Error(`This feature needs the ${e} package, which is not installed with this connector. Reinstall it without --omit=optional: npm install --global @engineeros/connector@latest`,{cause:t})}function $a(e){let t;return()=>{if(t)return t;try{t=P3(e)}catch(n){throw ob(e,n)}return t}}var P3,M3,su=V(()=>{M();P3=N3(import.meta.url),M3=new Set(["MODULE_NOT_FOUND","ERR_MODULE_NOT_FOUND"])});import{randomUUID as U3}from"node:crypto";import{chmod as q3,link as F3,mkdir as z3,open as B3,rename as H3,rm as G3}from"node:fs/promises";import W3 from"node:path";function ib(e){return process.platform==="win32"&&K3.has(e?.code)}async function X3(e,t){let n=Date.now()+V3;for(;;)try{await H3(e,t);return}catch(r){if(!ib(r)||Date.now()>=n)throw r;await new Promise(o=>setTimeout(o,J3))}}async function He(e,t,{replace:n=!0}={}){await z3(W3.dirname(e),{recursive:!0,mode:448});let r=`${e}.${U3()}.tmp`;try{let o=await B3(r,"wx",384);try{await o.writeFile(t,"utf8"),await o.sync()}finally{await o.close()}process.platform!=="win32"&&await q3(r,384),n?await X3(r,e):await F3(r,e)}finally{await G3(r,{force:!0})}}var V3,J3,K3,An=V(()=>{M();V3=5e3,J3=50,K3=new Set(["EPERM","EACCES","EBUSY"])});import{mkdir as Y3,mkdtemp as Q3,readFile as Z3,rm as eV,writeFile as tV}from"node:fs/promises";import xs from"node:path";import nV from"node:os";import{execFile as rV}from"node:child_process";import{promisify as oV}from"node:util";function _o(e){return String(e??"").trim().replaceAll("\\","/").replace(/^\.\//,"")}function Un(e){return String(e??"").split("\0").map(_o).filter(Boolean)}async function Wt(e){let t=xs.join(xs.resolve(e),".engineeros"),n=xs.join(t,".gitignore");await Y3(t,{recursive:!0,mode:448});let r="";try{r=await Z3(n,"utf8")}catch(s){if(s?.code!=="ENOENT")throw s}if(r.split(/\r?\n/).some(s=>s.trim()==="*"))return;let o=r&&!r.endsWith(`
1712
1712
  `)?`
1713
1713
  `:"";await tV(n,`${r}${o}*
1714
1714
  `,{encoding:"utf8",mode:384})}function FR(){return[...[...jR].filter(e=>e!==".git").map(e=>`${e}/`),...NR,...[...PR].map(e=>`*${e}`),".env",".env.*",...LR.map(e=>`!${e}`),"*service-account*.json",...MR,...DR.map(e=>`*${e}`)]}function Nr(e){let t=_o(e);if(!t||t===".."||t.startsWith("../")||xs.isAbsolute(t))return!1;let n=t.split("/");if(n.some(o=>jR.has(o.toLowerCase()))||NR.some(o=>t.toLowerCase().startsWith(o)))return!1;let r=n.at(-1)?.toLowerCase()??"";return PR.has(xs.posix.extname(r))?!1:LR.includes(r)?!0:!(r===".env"||r.startsWith(".env.")||MR.includes(r)||/service-account.*\.json$/.test(r)||DR.some(o=>r.endsWith(o)))}function Om(e){let t=xs.posix.basename(e).toLowerCase();return qR.has(t)||UR.has(xs.posix.extname(t))}function Oc(e){let t=_o(e).toLowerCase(),n=xs.posix.basename(t),r=xs.posix.extname(n);return qR.has(n)?"manifest":wp.has(n)?"lockfile":t.startsWith(".github/workflows/")||[".gitlab-ci.yml","azure-pipelines.yml","docker-compose.yml","docker-compose.yaml","dockerfile","jenkinsfile"].includes(n)?"workflow":/(^|\/)(tests|__tests__)\//.test(t)||n.startsWith("test_")||n.includes(".test.")||n.includes(".spec.")||/^(jest|vitest|pytest|playwright|cypress)(\.|$)/.test(n)?"test":/(^|\/)(security|compliance|policy|policies)(\/|\.|$)/.test(t)?"security_configuration":iV.has(n)||/(^|\/)(eslint|ruff|mypy|tsconfig|biome|prettier)/.test(t)?"repository_configuration":sV.has(n)?"entrypoint":/(^|\/)(api|routes|controllers)\//.test(t)||n.endsWith(".d.ts")||n.includes("openapi")||n.includes("swagger")?"public_api":r===".md"||t.startsWith("docs/")||/(^|\/)(architecture|operations|runbook|deployment)(\/|\.|$)/.test(t)?"documentation":UR.has(r)?"source":"other"}async function zR(e){let t=await Q3(xs.join(nV.tmpdir(),"engineeros-inventory-")),n={cwd:e,windowsHide:!0,timeout:3e4,maxBuffer:32*1024*1024};try{await IR("git",["init","--bare","--quiet","--template=",t],n);let r=[`--git-dir=${t}`,`--work-tree=${xs.resolve(e)}`,"ls-files","-z","--others","--exclude-standard"];return Un((await IR("git",r,n)).stdout)}catch(r){throw new Error(`Cannot enumerate workspace safely. Provide working Git to apply its ignore rules: ${r.message}`,{cause:r})}finally{await eV(t,{recursive:!0,force:!0})}}var IR,jR,NR,PR,MR,DR,LR,wp,sV,iV,UR,qR,Nn=V(()=>{M();IR=oV(rV),jR=new Set([".agents",".claude",".codex",".engineeros",".forge",".gemini",".git",".ssh",".docker",".kube",".next",".pytest_cache",".ruff_cache",".venv","__pycache__","build","coverage","dist","node_modules","target","vendor"]),NR=[".github/skills/"],PR=new Set([".7z",".a",".bin",".class",".dll",".dylib",".exe",".gz",".jar",".lib",".o",".obj",".pyc",".pyo",".rar",".so",".tar",".tgz",".war",".zip"]),MR=[".npmrc",".netrc","credentials","credentials.json",".envrc",".pypirc",".git-credentials","id_rsa","id_ed25519","id_ecdsa","id_dsa"],DR=[".key",".pem",".p12",".pfx",".env",".tfstate",".tfstate.backup",".tfvars",".tfvars.json",".jks",".keystore"],LR=[".env.example",".env.sample"],wp=new Set(["cargo.lock","composer.lock","go.sum","package-lock.json","pnpm-lock.yaml","poetry.lock","uv.lock","yarn.lock"]),sV=new Set(["app.py","index.ts","index.tsx","main.py","main.ts","main.tsx","manage.py","server.py"]),iV=new Set([".dockerignore",".editorconfig",".gitattributes",".gitignore","lerna.json","makefile","nx.json","turbo.json"]),UR=new Set([".c",".cpp",".cs",".go",".h",".java",".js",".jsx",".mjs",".php",".py",".rb",".rs",".sql",".ts",".tsx"]),qR=new Set(["cargo.toml","composer.json","go.mod","package.json","pom.xml","pyproject.toml","requirements.txt"])});import{readFile as aV}from"node:fs/promises";async function qe(e){try{return JSON.parse(await aV(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Rt(e,t){await He(e,JSON.stringify(t))}var Pr=V(()=>{M();An()});import cV from"node:os";function dV(e){let t=String(e??"");return t.length<uV?[]:[...new Set([t,encodeURIComponent(t),Buffer.from(t).toString("base64")])]}function qn(e){for(let t of e??[])for(let n of dV(t))cb.add(n)}function BR(){return[...cb]}function qi(e){let t=String(e??"");for(let n of[...cb].sort((r,o)=>o.length-r.length))t=t.split(n).join("<redacted>");return t}function HR(e){if(!/^\s*[\[{]/.test(e)||e.length>3e5)return e;try{let t=!1,n=(o,s=0)=>{if(typeof o=="string"&&s<=30){let a=HR(o);return a!==o&&(t=!0),a}if(!o||typeof o!="object"||s>30)return o;if(Array.isArray(o))return o.map(a=>n(a,s+1));let i=typeof o.name=="string"&&ab.test(o.name)&&"value"in o;return Object.fromEntries(Object.entries(o).map(([a,c])=>ab.test(a)||i&&a==="value"?(t=!0,[a,"<redacted>"]):[a,n(c,s+1)]))},r=n(JSON.parse(e));return t?JSON.stringify(r):e}catch{return e}}function Ee(e,{home:t=cV.homedir()}={}){let n=qi(HR(String(e??"")));n=n.replace(/https?:\/\/[^\s<>"'()]+/gi,r=>{try{let o=new URL(r),s=!1;for(let i of o.searchParams.keys())(ab.test(i)||/^(?:code|state|session|session_id|sig|signature|jwt|client_secret|x-amz-(?:signature|security-token|credential)|x-goog-(?:signature|credential))$/i.test(i))&&(o.searchParams.set(i,"<redacted>"),s=!0);return s?o.toString():r}catch{return r}});for(let[r,o]of lV)n=n.replace(r,o);return t&&t.length>1&&(n=n.split(t).join("~")),n}var yp,ab,lV,uV,cb,Gt=V(()=>{M();yp="(?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|token|secret|password|passwd|pwd|authorization|proxy-authorization|cookie|set-cookie|cookies)",ab=new RegExp(`^${yp}$`,"i"),lV=[[/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g,"<redacted private key>"],[new RegExp(String.raw`(["']${yp}["']\s*:\s*)"(?:\\.|[^"\\])*"`,"gi"),'$1"<redacted>"'],[/(\b(?:cookie|set-cookie|authorization|proxy-authorization)\s*:\s*)[^\r\n]+/gi,"$1<redacted>"],[/\bbearer\s+[A-Za-z0-9._\-~+/]{8,}=*/gi,"<redacted>"],[new RegExp(String.raw`\b(${yp})(["']?\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>@"]],uV=4,cb=new Set});function lb(e){if(e==null)return null;if(!e||typeof e!="object"||!["verification","implementation","setup","baseline"].includes(e.action)||!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Goal recovery requires a supported action and a positive recovery revision.");let t=typeof e.note=="string"?Ee(e.note).trim().slice(0,4e3):"";return{action:e.action,revision:e.revision,head_revision:e.head_revision??null,...t?{note:t}:{}}}function WR(e){e?.status==="running"&&(e.usage_uncertain=!0,e.usage_note=GR)}async function VR(e,t,n,{maxRepairAttempts:r,implementationMessage:o,environmentRef:s,executionSetup:i,reserveRepair:a}={}){let c=lb(n);if(!c||c.revision<=(e.recovery?.revision??0))return!1;if(c.action==="verification"&&!e.implementationComplete)throw new Error("Implementation is incomplete. Resume the saved work or choose implementation recovery before verifying it.");let l=!e.implementationComplete&&!e.result;if(c.action==="implementation"&&!l&&(e.repairAttempts||0)>=r)throw new Error("The implementation repair allowance is exhausted. Review the saved change and findings, then create a follow-up Goal for the remaining work.");if(c.action==="implementation"&&!l){if(!a)throw new Error("Implementation recovery requires a server repair reservation before another turn.");await a("recovery",o||"Explicit implementation recovery")}let u=e.assignment?.test_environment_ref??null,p=s??null,d=s!==void 0&&(u?.id!==p?.id||u?.revision!==p?.revision)||JSON.stringify(e.assignment?.verification_setup??null)!==JSON.stringify(i??null);for(let f of Object.values(e.verificationCache??{}))WR(f);return(e.recoveryHistory||=[]).push({...c,requested_at:new Date().toISOString(),previous_result:e.result??null,previous_failure:e.failure??null,previous_verification:e.lastVerification??null,previous_environment_ref:u,environment_ref:p,environment_changed:d,previous_verification_setup:e.assignment?.verification_setup??null,verification_setup:i??null}),e.recovery={...c,environment_changed:d},e.assignment&&s!==void 0&&(e.assignment.test_environment_ref=s),e.assignment&&(e.assignment.verification_setup=i??null),e.result=null,c.action==="implementation"&&(e.implementationComplete=!1,l||(e.implementationPhase="repair"),e.implementationMessage=[e.implementationMessage,o].filter(Boolean).join(`
@@ -1720,7 +1720,7 @@ ${f.stderr||""}`),g=Math.min(1e3,250*2**d);if(!h||performance.now()+g>=l||(o(g),
1720
1720
  `).at(-1).slice(0,300)||"Update preparation failed.";throw await Ta(e,s=>{s.status="failed",s.error=`${t.version}: ${o}`.slice(0,300),s.failed=[...new Set([t.version,...s.failed])].slice(0,kp),jc(s,"failed",t.version,o)}),new Error(`Connector ${t.version} was not prepared; the running version stays active. ${o}`)}}async function KV(e,t){let{stdout:n}=await HV(process.execPath,[e,"version"],{timeout:6e4,windowsHide:!0,env:{...process.env,[Ra]:""}});if(n.trim()!==t)throw new Error(`The installed connector started as ${n.trim().slice(0,40)||"nothing"}, not ${t}.`)}async function XV(e,t){return Mo(e,async()=>(await Um(e),Ta(e,async n=>{if(!n.prepared)throw new Error("No verified connector update is prepared. Check for updates first.");let r=Oa(n,t.bundled);if($s(n.prepared.version,r.version)<=0)throw new Error(`Connector ${r.version} is already newer than the prepared ${n.prepared.version}.`);return n.previous={version:r.version,entry:r.entry,at:xp()},n.active=n.prepared,n.prepared=null,n.available?.version===n.active.version&&(n.available=null),n.confirmed=!1,n.status="idle",n.error=null,jc(n,"activated",n.active.version,`Replacing ${r.version} once the connector is idle.`),await YV(e,[n.active.version,n.previous.version]),n.active})))}async function YV(e,t){let n=await xb(e,"install");try{let r=so.join(e,"runner-releases");for(let s of await nO(r).catch(i=>{if(i.code==="ENOENT")return[];throw i}))t.push(...JSON.parse(await Fm(so.join(r,s),"utf8")));let o=await nO(bp(e)).catch(()=>[]);for(let s of o)Jn(s)&&!t.includes(s)&&await iO(so.join(bp(e),s),{recursive:!0,force:!0}).catch(()=>{})}finally{n()}}async function $b(e,t,{automatic:n=!1,reason:r=null}={}){return Mo(e,async()=>(await Um(e),Ta(e,o=>{let s=Oa(o,t.bundled),i=o.previous;if(!i||!zm(i.entry))throw new Error("No previous verified connector version is kept on this machine to roll back to.");if(Jn(t.bundled.version)&&$s(i.version,t.bundled.version)<0)throw new Error(`The installed connector is ${t.bundled.version}; reinstall ${Ic}@${i.version} to go below it.`);return o.active=i,o.previous={version:s.version,entry:s.entry,at:xp()},o.confirmed=!0,o.error=null,o.failed=o.failed.filter(a=>a!==i.version),$s(s.version,i.version)>0&&(o.failed=[...new Set([s.version,...o.failed])].slice(0,kp)),n&&(o.status="rolled_back",o.error=`${s.version} stopped before connecting; ${i.version} restored.`),jc(o,"rolled_back",i.version,r??`Rolled back from ${s.version}.`),o.active})))}async function QV(e,t){let n=await io(e);n.confirmed||n.active?.version!==t.version||await Ta(e,r=>{r.confirmed||r.active?.version!==t.version||(r.confirmed=!0,(r.status==="failed"||r.status==="rolled_back")&&(r.status="idle"),jc(r,"completed",t.version,"Connected to EngineerOS on the new version."))})}async function ZV(e,t){if(!vb.includes(t))throw new Error(`Use one of: ${vb.join(", ")}.`);return Ta(e,n=>(n.policy!==t&&jc(n,"policy",null,`Update policy set to ${t}.`),n.policy=t,t))}async function lO(e,t,{request:n=null,fetchLatest:r,execute:o,smokeTest:s}={}){let i=await io(e);if(!Jn(t.bundled.version))throw new Error("This connector runs from source; update it with git instead.");if(i.policy==="manual"&&!n)return i;let a=!i.checked_at||Date.now()-Date.parse(i.checked_at)>=BV;(n||a)&&await cO(e,t,{fetchLatest:r}),i=await io(e);let c=i.available;if(!c){if(n==="apply")throw new Error(`Connector ${Oa(i,t.bundled).version} is the latest release.`);return i}let l=n==="apply";if(c.compatibility==="incompatible"){if(l)throw new Error(`Connector ${c.version} cannot run here: ${c.note}`);return i}return(l||i.policy!=="manual"&&c.update_type!=="major"&&!i.failed.includes(c.version))&&i.prepared?.version!==c.version&&(await JV(e,c,{execute:o,smokeTest:s}),i=await io(e)),(l||WV(i))&&await XV(e,t),io(e)}async function Ab(e,t,{action:n,policy:r=null},o={}){if(!oO.includes(n))throw new Error(`Use one of: ${oO.join(", ")}.`);if(n!=="status"&&!Jn(t.bundled.version))throw new Error("This connector runs from source; update it with git instead.");return n==="check"?await cO(e,t,o):n==="apply"?await lO(e,t,{...o,request:"apply"}):n==="rollback"?await $b(e,t):n==="policy"&&await ZV(e,r),io(e)}function uO({root:e=yr(),running:t,supervised:n,isIdle:r,restart:o,onChange:s=()=>{},log:i=console.log,deps:a={},workspace:c=process.cwd()}){let l=Promise.resolve(),u=0,p=!1,d=!1,f=null,h=null,g=w=>{let m=l.then(w);return l=m.catch(()=>{}),m};async function v(){let w=Tb(await io(e),t,{supervised:n});return JSON.stringify(w)!==JSON.stringify(h)&&(h=w,s(w)),w}let y=Promise.resolve();async function b(){if(!(!n||d))return Mo(e,async()=>{let w=Oa(await io(e),t.bundled);if(w.version!==t.version){if(await Um(e),await Aa(c),!await r()){f!==w.version&&i(`Connector ${w.version} is ready; automatic process handover waits for running work or queued assessments. Keep this terminal open; no manual restart or re-pairing is needed.`),f=w.version;return}d=!0,i(`Switching this connector from ${t.version} to ${w.version}. Goal runs continue in their own processes.`),await o()}})}async function E(){await v().catch(w=>i(`Connector update state: ${w.message}`)),y=y.then(b).catch(w=>i(`Connector update restart: ${w.message}`)),await y}return{report:()=>h,refresh:v,async tick(){Jn(t.bundled.version)&&!p&&Date.now()>=u&&(p=!0,u=Date.now()+e8,g(()=>lO(e,t,a)).catch(w=>{u=Date.now()+t8,i(`Connector update check failed; retrying in 15 minutes: ${w.message}`)}).finally(()=>{p=!1,E()})),await E()},async command(w){if(w.action==="status")return io(e);try{return await g(()=>Ab(e,t,w,a))}finally{E()}},async confirm(){await QV(e,t),await v()}}}function iu(e){let t=[`Connector ${e.target_version}${e.target_version===e.current_version?"":` (this process runs ${e.current_version})`} \xB7 policy ${e.policy} \xB7 ${e.status.replaceAll("_"," ")}`];return e.available_version&&t.push(`Available: ${e.available_version} (${e.update_type}, ${e.compatibility})${e.note?` - ${e.note}`:""}`),e.prepared_version&&t.push(`Prepared and verified: ${e.prepared_version}; activate it with update apply.`),e.rollback_version&&t.push(`Rollback kept: ${e.rollback_version}`),e.error&&t.push(`Last problem: ${e.error}`),t.push(`Checked: ${e.checked_at??"never"}`),t.join(`
1721
1721
  `)}function Tb(e,t,{supervised:n}){let r=Oa(e,t.bundled),o="up_to_date";e.status==="preparing"?o="preparing":r.version!==t.version?o="activating":!e.confirmed&&e.active?.version===t.version?o="monitoring":e.status==="failed"||e.status==="rolled_back"?o=e.status:e.prepared?o="ready":e.available&&(o="available");let s=e.previous&&zm(e.previous.entry)&&(!Jn(t.bundled.version)||$s(e.previous.version,t.bundled.version)>=0)?e.previous.version:null;return{current_version:t.version,target_version:r.version,available_version:e.available?.version??null,update_type:e.available?.update_type??null,compatibility:e.available?.compatibility??null,note:e.available?.note??null,prepared_version:e.prepared?.version??null,rollback_version:s,policy:e.policy,status:o,restart_scope:n?"connector_process":"manual_restart",checked_at:e.checked_at,error:e.error,history:e.history.slice(0,10)}}var Ic,Sp,Ra,kb,Sb,vb,BV,kp,HV,qm,_b,aO,bb,bp,rO,xp,oO,e8,t8,Nc=V(()=>{M();An();oo();wb();_p();vp();Ic="@engineeros/connector",Sp=75,Ra="ENGINEEROS_CONNECTOR_SUPERVISED",kb="ENGINEEROS_CONNECTOR_BUNDLED_ENTRY",Sb="ENGINEEROS_CONNECTOR_BUNDLED_VERSION",vb=["manual","approve","auto-patch","auto-minor"],BV=360*60*1e3,kp=20,HV=zV(MV),qm=zn.string().refine(Jn,"Use a stable semantic version."),_b=zn.object({version:qm,entry:zn.string().min(1).max(1e3),at:zn.string().datetime()}).strict(),aO=zn.object({version:zn.literal(1),policy:zn.enum(vb),active:_b.nullable(),previous:_b.nullable(),prepared:_b.nullable(),confirmed:zn.boolean(),available:zn.object({version:qm,integrity:zn.string().refine(Cc),update_type:zn.enum(["patch","minor","major"]),compatibility:zn.enum(["compatible","warning","incompatible"]),note:zn.string().max(300).nullable()}).strict().nullable(),checked_at:zn.string().datetime().nullable(),status:zn.enum(["idle","preparing","failed","rolled_back"]),error:zn.string().max(300).nullable(),failed:zn.array(qm).max(kp),history:zn.array(zn.object({at:zn.string().datetime(),event:zn.enum(["available","prepared","activated","completed","failed","rolled_back","policy"]),version:qm.nullable(),detail:zn.string().max(300).nullable()}).strict()).max(kp)}).strict();bb=e=>so.join(e,"runtime.json"),bp=e=>so.join(e,"versions"),rO=e=>so.join(e,"node_modules","@engineeros","connector","bin","engineeros-connector.mjs"),xp=()=>new Date().toISOString();oO=["status","check","apply","rollback","policy"];e8=6e4,t8=15*6e4});function Qo(e=Date.now()){let t=new Date(e),n=(s,i=2)=>String(Math.abs(s)).padStart(i,"0"),r=-t.getTimezoneOffset(),o=r>=0?"+":"-";return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}.${n(t.getMilliseconds(),3)}${o}${n(Math.trunc(r/60))}:${n(r%60)}`}var au=V(()=>{M()});function Rb({monotonic:e=()=>performance.now(),wall:t=Date.now,gapMs:n=3e4}={}){let r=e(),o=t(),s=0,i=0;return()=>{let a=e(),c=t(),l=a-r>n||c-o-(a-r)>n;return l?i++:s+=Math.max(0,a-r),r=a,o=c,{now:s,generation:i,gap:l}}}function dO(e=Rb()){let t=new Map,n=(r,o,s)=>{let{now:i,generation:a}=e(),c=t.get(r);return(!c||c.token!==o?.token)&&(c={token:o?.token,heartbeatAt:i,failureAt:i},t.set(r,c)),(c.generation!==a||c.heartbeat!==s?.at)&&(c.heartbeatAt=i),c.failure!==s?.failure?.since&&(c.failureAt=i),c.generation=a,c.heartbeat=s?.at,c.failure=s?.failure?.since,{heartbeatAge:i-c.heartbeatAt,failureAge:i-c.failureAt}};return n.retain=r=>{for(let o of t.keys())r.has(o)||t.delete(o)},n}var pO=V(()=>{M()});import{createHash as n8}from"node:crypto";import{spawn as r8}from"node:child_process";import{existsSync as o8,readFileSync as s8}from"node:fs";import{lstat as i8,readFile as a8,unlink as c8}from"node:fs/promises";import wO from"node:path";function yO(e){if(!l8.test(String(e)))throw new Error("A credential id must be lowercase letters, digits and dashes.");return e}function _O(e,t){return t||_r(e).replace(/\.json$/,".tool-credentials")}function Gm(e,t,n){return wO.join(_O(e,n),`${yO(t)}.dpapi`)}function Ep(e,t,n){return`${n8("sha256").update(wO.resolve(_O(e,n))).digest("hex").slice(0,24)}:${yO(t)}`}function d8(e,t,n=""){return new Promise((r,o)=>{let s=r8(e,t,{stdio:["pipe","pipe","pipe"],windowsHide:!0}),i=[],a=0,c="",l=setTimeout(()=>{s.kill(),o(new Error(`${e} did not finish within ${fO/1e3} seconds.`))},fO);s.stdout.on("data",u=>{a+=u.length,a>u8?s.kill():i.push(u)}),s.stderr.on("data",u=>{c.length<2e3&&(c+=u.toString("utf8"))}),s.stdin.on("error",()=>{}),s.once("error",u=>{clearTimeout(l),o(u)}),s.once("close",u=>{clearTimeout(l),r({code:u,stdout:Buffer.concat(i).toString("utf8"),stderr:c})}),s.stdin.end(n)})}async function vO(e,t){let n;try{n=await e("powershell.exe",p8,t)}catch{throw new Error("Windows credential protection could not start PowerShell.")}if(n.code!==0)throw new Error("Windows credential protection failed.");return n.stdout}async function mO(e,t){let n=(await vO(e,t)).trim();if(!n)throw new Error("Windows credential protection returned nothing: antivirus may be blocking PowerShell on this machine.");return n}function gO(e,t,n=!1){let r=!n;return{help:n?m8:void 0,async available(){return r||(r=await vO(t,`exit 0
1722
1722
  `).then(()=>!0,()=>!1)),r},async put(o,s,i){let a=Gm(o,s,e);await He(a,await mO(t,f8(JSON.stringify(i))))},async get(o,s){let i;try{i=await a8(Gm(o,s,e),"utf8")}catch(c){if(c?.code==="ENOENT")return null;throw c}if(!i.trim())return null;let a=await mO(t,h8(i.trim()));return JSON.parse(Buffer.from(a,"base64").toString("utf8"))},async has(o,s){try{let i=await i8(Gm(o,s,e));return i.isFile()&&i.size>0}catch(i){if(i?.code==="ENOENT")return!1;throw i}},async delete(o,s){try{await c8(Gm(o,s,e))}catch(i){if(i?.code!=="ENOENT")throw i}}}}function g8(e,t){let n=(o,s,i)=>t("security",["find-generic-password","-s",Pc,"-a",Ep(o,s,e),...i?["-w"]:[]]),r=async(o,s)=>(await n(o,s,!1)).code===0;return{async available(){return!0},async put(o,s,i){let a=`add-generic-password -U -s "${Pc}" -a "${Ep(o,s,e)}" -w "${Ob(i)}"
1723
- `;if((await t("security",["-i"],a)).code!==0||!await r(o,s))throw new Error("The macOS Keychain did not store the credential. Unlock the login keychain and try again.")},async get(o,s){let i=await n(o,s,!0);if(i.code===hO)return null;if(i.code!==0)throw new Error("The macOS Keychain could not be read. Unlock the login keychain and try again.");return Cb(i.stdout)},has:r,async delete(o,s){let i=await t("security",["delete-generic-password","-s",Pc,"-a",Ep(o,s,e)]);if(i.code!==0&&i.code!==hO)throw new Error("The macOS Keychain could not remove the credential.")}}}function w8(e,t){let n=(o,s)=>["service",Pc,"account",Ep(o,s,e)],r=async(o,s)=>{try{return await t("secret-tool",o,s)}catch(i){throw i?.code==="ENOENT"?new Error(Wm):i}};return{help:Wm,async available(){try{let o=await r(["lookup","service",Pc,"account","availability-probe"]);return o.code===0||!o.stderr.trim()}catch{return!1}},async put(o,s,i){if((await r(["store",`--label=${Pc}`,...n(o,s)],Ob(i))).code!==0)throw new Error(`The Secret Service did not store the credential. ${Wm}`)},async get(o,s){let i=await r(["lookup",...n(o,s)]);if(i.code!==0||!i.stdout.trim()){if(i.stderr.trim())throw new Error(`The Secret Service could not be read. ${Wm}`);return null}return Cb(i.stdout)},async has(o,s){let i=await r(["lookup",...n(o,s)]);return i.code===0&&!!i.stdout.trim()},async delete(o,s){await r(["clear",...n(o,s)])}}}function _8(e,t){let n,r,o=async(s,i)=>(n??=await t(),new n(Pc,Ep(s,i,e),{linux:{store:"secret-service"}}));return{kind:"native",async available(){if(r===void 0)try{await(await o("","availability-probe")).getPassword(),r=!0}catch{r=!1}return r},async put(s,i,a){await(await o(s,i)).setPassword(Ob(a))},async get(s,i){let a=await(await o(s,i)).getPassword();return a?Cb(a):null},async has(s,i){return!!await(await o(s,i)).getPassword()},async delete(s,i){await(await o(s,i)).deletePassword()}}}function v8(e){let t=new Set,n=new Map,r=null,o=async c=>(n.has(c)||n.set(c,c.available().catch(()=>!1)),n.get(c)),s=async()=>{let c=await Promise.all(e.map(o));return e.filter((l,u)=>c[u])};async function*i(){for(let c of e)!t.has(c)&&await o(c)&&(yield c)}let a={help:e.find(c=>c.help)?.help,get kind(){return r?.kind??null},async available(){for await(let c of i())return r??=c,!0;return!1},async put(c,l,u){let p=null;for await(let d of i()){try{await d.put(c,l,u)}catch(h){p??=h,t.add(d),r===d&&(r=null);continue}r=d;let f=(await s()).filter(h=>h!==d);await Promise.all(f.map(h=>h.delete(c,l).catch(()=>{})));return}throw new Error(`The credential was not saved in protected storage.${p?` ${p.message}`:""}${a.help?` ${a.help}`:""}`,{cause:p})},async get(c,l){let u=null;for(let p of await s()){let d;try{d=await p.get(c,l)}catch(f){u??=f;continue}if(d!=null)return p!==r&&await a.put(c,l,d).catch(()=>{}),d}if(u)throw u;return null},async has(c,l){for(let u of await s())if(await u.has(c,l).catch(()=>!1))return!0;return!1},async delete(c,l){let u=(await Promise.allSettled((await s()).map(p=>p.delete(c,l)))).find(p=>p.status==="rejected");if(u)throw u.reason}};return a}function b8(e){return{available:async()=>!1,put:async()=>{throw new Error(`Secure credential storage is not supported on ${e}.`)},get:async()=>null,has:async()=>!1,delete:async()=>{}}}function k8(e=process.platform,t=()=>s8("/proc/sys/kernel/osrelease","utf8"),n=o8){if(e!=="linux"||n("/.dockerenv")||n("/run/.containerenv"))return e;try{return/microsoft/i.test(t())?"wsl":e}catch{return e}}function S8(e,t,n){return t==="win32"?gO(e,n):t==="wsl"?gO(e,n,!0):t==="darwin"?g8(e,n):t==="linux"?w8(e,n):null}function Kr({directory:e,platform:t=k8(),run:n=d8,keyring:r=y8}={}){let o=S8(e,t,n);o&&(o.kind="platform-tool",o.help??=t==="darwin"?"Unlock the macOS login Keychain and restart the connector.":"Enable Windows Credential Manager or current-user Data Protection and restart the connector.");let i=[r&&t!=="wsl"&&o?_8(e,r):null,o].filter(Boolean);return i.length?v8(i):b8(t)}var l8,Pc,fO,u8,hO,p8,f8,h8,m8,Ob,Cb,Wm,y8,Mc=V(()=>{M();An();Tn();l8=/^[a-z][a-z0-9-]{0,63}$/,Pc="EngineerOS connector",fO=1e4,u8=256e3,hO=44;p8=["-NoProfile","-NonInteractive","-Command","-"],f8=e=>["Add-Type -AssemblyName System.Security",`$bytes = [Convert]::FromBase64String('${Buffer.from(e,"utf8").toString("base64")}')`,"$cipher = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser)","[Console]::Out.Write([Convert]::ToBase64String($cipher))",""].join(`
1723
+ `;if((await t("security",["-i"],a)).code!==0||!await r(o,s))throw new Error("The macOS Keychain did not store the credential. Unlock the login keychain and try again.")},async get(o,s){let i=await n(o,s,!0);if(i.code===hO)return null;if(i.code!==0)throw new Error("The macOS Keychain could not be read. Unlock the login keychain and try again.");return Cb(i.stdout)},has:r,async delete(o,s){let i=await t("security",["delete-generic-password","-s",Pc,"-a",Ep(o,s,e)]);if(i.code!==0&&i.code!==hO)throw new Error("The macOS Keychain could not remove the credential.")}}}function w8(e,t){let n=(o,s)=>["service",Pc,"account",Ep(o,s,e)],r=async(o,s)=>{try{return await t("secret-tool",o,s)}catch(i){throw i?.code==="ENOENT"?new Error(Wm):i}};return{help:Wm,async available(){try{let o=await r(["lookup","service",Pc,"account","availability-probe"]);return o.code===0||!o.stderr.trim()}catch{return!1}},async put(o,s,i){if((await r(["store",`--label=${Pc}`,...n(o,s)],Ob(i))).code!==0)throw new Error(`The Secret Service did not store the credential. ${Wm}`)},async get(o,s){let i=await r(["lookup",...n(o,s)]);if(i.code!==0||!i.stdout.trim()){if(i.stderr.trim())throw new Error(`The Secret Service could not be read. ${Wm}`);return null}return Cb(i.stdout)},async has(o,s){let i=await r(["lookup",...n(o,s)]);return i.code===0&&!!i.stdout.trim()},async delete(o,s){await r(["clear",...n(o,s)])}}}function _8(e,t){let n,r,o=async(s,i)=>(n??=await t(),new n(Pc,Ep(s,i,e),{linux:{store:"secret-service"}}));return{kind:"native",async available(){if(r===void 0)try{await(await o("","availability-probe")).getPassword(),r=!0}catch{r=!1}return r},async put(s,i,a){await(await o(s,i)).setPassword(Ob(a))},async get(s,i){let a=await(await o(s,i)).getPassword();return a?Cb(a):null},async has(s,i){return!!await(await o(s,i)).getPassword()},async delete(s,i){await(await o(s,i)).deletePassword()}}}function v8(e){let t=new Set,n=new Map,r=null,o=async c=>(n.has(c)||n.set(c,c.available().catch(()=>!1)),n.get(c)),s=async()=>{let c=await Promise.all(e.map(o));return e.filter((l,u)=>c[u])};async function*i(){for(let c of e)!t.has(c)&&await o(c)&&(yield c)}let a={help:e.find(c=>c.help)?.help,get kind(){return r?.kind??null},async available(){for await(let c of i())return r??=c,!0;return!1},async put(c,l,u){let p=null;for await(let d of i()){try{await d.put(c,l,u)}catch(h){p??=h,t.add(d),r===d&&(r=null);continue}r=d;let f=(await s()).filter(h=>h!==d);await Promise.all(f.map(h=>h.delete(c,l).catch(()=>{})));return}throw new Error(`The credential was not saved in protected storage.${p?` ${p.message}`:""}${a.help?` ${a.help}`:""}`,{cause:p})},async get(c,l){let u=await s();if(!u.length)throw new Error(`Protected credential storage is unavailable; saved credentials may still exist. Restore access to the original store before retrying.${a.help?` ${a.help}`:""}`);let p=null;for(let d of u){let f;try{f=await d.get(c,l)}catch(h){p??=h;continue}if(f!=null)return d!==r&&await a.put(c,l,f).catch(()=>{}),f}if(p)throw p;return null},async has(c,l){for(let u of await s())if(await u.has(c,l).catch(()=>!1))return!0;return!1},async delete(c,l){let u=(await Promise.allSettled((await s()).map(p=>p.delete(c,l)))).find(p=>p.status==="rejected");if(u)throw u.reason}};return a}function b8(e){return{available:async()=>!1,put:async()=>{throw new Error(`Secure credential storage is not supported on ${e}.`)},get:async()=>null,has:async()=>!1,delete:async()=>{}}}function k8(e=process.platform,t=()=>s8("/proc/sys/kernel/osrelease","utf8"),n=o8){if(e!=="linux"||n("/.dockerenv")||n("/run/.containerenv"))return e;try{return/microsoft/i.test(t())?"wsl":e}catch{return e}}function S8(e,t,n){return t==="win32"?gO(e,n):t==="wsl"?gO(e,n,!0):t==="darwin"?g8(e,n):t==="linux"?w8(e,n):null}function Kr({directory:e,platform:t=k8(),run:n=d8,keyring:r=y8}={}){let o=S8(e,t,n);o&&(o.kind="platform-tool",o.help??=t==="darwin"?"Unlock the macOS login Keychain and restart the connector.":"Enable Windows Credential Manager or current-user Data Protection and restart the connector.");let i=[r&&t!=="wsl"&&o?_8(e,r):null,o].filter(Boolean);return i.length?v8(i):b8(t)}var l8,Pc,fO,u8,hO,p8,f8,h8,m8,Ob,Cb,Wm,y8,Mc=V(()=>{M();An();Tn();l8=/^[a-z][a-z0-9-]{0,63}$/,Pc="EngineerOS connector",fO=1e4,u8=256e3,hO=44;p8=["-NoProfile","-NonInteractive","-Command","-"],f8=e=>["Add-Type -AssemblyName System.Security",`$bytes = [Convert]::FromBase64String('${Buffer.from(e,"utf8").toString("base64")}')`,"$cipher = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser)","[Console]::Out.Write([Convert]::ToBase64String($cipher))",""].join(`
1724
1724
  `),h8=e=>["Add-Type -AssemblyName System.Security",`$cipher = [Convert]::FromBase64String('${e.replace(/[^A-Za-z0-9+/=]/g,"")}')`,"$bytes = [Security.Cryptography.ProtectedData]::Unprotect($cipher, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser)","[Console]::Out.Write([Convert]::ToBase64String($bytes))",""].join(`
1725
1725
  `);m8="WSL keeps credentials with Windows Data Protection, which needs Windows interop: check that `powershell.exe` runs from this shell.";Ob=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64"),Cb=e=>JSON.parse(Buffer.from(e.trim(),"base64").toString("utf8"));Wm="Linux needs the Secret Service to keep credentials: install `secret-tool` (libsecret-tools) and run a keyring such as GNOME Keyring or KWallet.";y8=async()=>(await import("@napi-rs/keyring")).AsyncEntry});import{createHash as SO}from"node:crypto";import{constants as bO}from"node:fs";import{lstat as x8,open as E8}from"node:fs/promises";import $8 from"node:os";import kO from"node:path";async function T8(e,t,n,r){let o=Jm.get(t);if(o?.fingerprint===n)return o.token;let s;try{s=await EO(r).get(e,xO)}catch(i){throw new Error(`The connector token could not be read from this machine's credential store. ${i.message}`)}if(!(typeof s!="string"||$O(s)!==n))return Jm.set(t,{fingerprint:n,token:s}),s}async function R8(e,t,n,r){let o=$O(n);return Jm.get(t)?.fingerprint===o||(await EO(r).put(e,xO,n),Jm.set(t,{fingerprint:o,token:n})),o}function _r(e=process.cwd()){let t=SO("sha256").update(kO.resolve(e)).digest("hex").slice(0,24);return kO.join($8.homedir(),".engineeros","connectors",`${t}.json`)}function Ib(e){let t=new URL(e);if(t.protocol==="http:"&&(t.protocol="ws:"),t.protocol==="https:"&&(t.protocol="wss:"),!["ws:","wss:"].includes(t.protocol))throw new Error("EngineerOS URL must use http, https, ws, or wss.");if(t.protocol==="ws:"&&!O8.has(t.hostname))throw new Error(`EngineerOS URL ${t.host} must use https:// (or wss://). Plain http:// and ws:// are allowed only for localhost, 127.0.0.1, and [::1] because the connector token is sent with every request. Pair again with an HTTPS URL.`);return t.pathname="/api/v1/agent-connectors/ws",t.search="",t.hash="",t.toString()}function AO(e,t){return!e?.connector_id||!e.token||e.server_url!==t?{}:{existing_connector_id:e.connector_id,existing_token:e.token}}function TO(e,t,n,r){let o=t?.connector_id===n?t:{},s=o.agent_protocol===e.agent_protocol&&(o.agent_id||o.agent_command||null)===(e.agent_id||e.agent_command||null)&&(o.agent_version||null)===(e.agent_version||null);return{...o,...e,connector_id:n,token:r,sessions:s?o.sessions||{}:{}}}function jb(e,t,n){let{[t]:r,...o}=e||{},s=Object.entries(o).slice(-(C8-1));return Object.fromEntries([...s,[t,n]])}function RO(e,t){let{[t]:n,...r}=e||{};return r}function OO(e,t,n){let r=new URL(e);return r.protocol=r.protocol==="wss:"?"https:":"http:",r.pathname=`/api/v1/agent-connectors/${t}/runs/${n}/result`,r.toString()}function pr(e,t){let n=new URL(e);return n.protocol=n.protocol==="wss:"?"https:":"http:",n.pathname=`/api/v1/agent-connectors/${t}/workspace`,n.toString()}function CO(e,t){return`${pr(e,t)}/quality-map`}function IO(e,t){let n=new URL(e);return n.protocol=n.protocol==="wss:"?"https:":"http:",n.pathname=`/api/v1/agent-connectors/${t}/workspace/head`,n.toString()}function jO(e,t){let n=new URL(e);return n.protocol=n.protocol==="wss:"?"https:":"http:",n.pathname=`/api/v1/agent-connectors/${t}/integration-results`,n.toString()}function NO(e,t,n){let r=new URL(e);return r.protocol=r.protocol==="wss:"?"https:":"http:",r.pathname=`/api/v1/agent-connectors/${t}/assessment/${n}/result`,r.toString()}function PO(e,t,n){let r=new URL(e);return r.protocol=r.protocol==="wss:"?"https:":"http:",r.pathname=`/api/v1/agent-connectors/${t}/bug-hunt-objects/${encodeURIComponent(n)}`,r.search="",r.toString()}function MO(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/api/health",t.toString()}function DO(e,t){let n=new URL(e);return n.protocol=n.protocol==="wss:"?"https:":"http:",n.pathname=`/api/v1/agent-connectors/${t}/artifact-tools`,n.toString()}function LO(e,t){let n=new URL(e);return n.protocol=n.protocol==="wss:"?"https:":"http:",n.pathname=`/api/v1/agent-connectors/${t}/scoreboard-tools`,n.toString()}function I8(e,t,n,{uid:r=process.getuid?.(),label:o="Connector settings"}={}){if(e.isSymbolicLink())throw new Error(`${o} file ${n} must not be a symbolic link.`);if(!e.isFile()||!t.isFile())throw new Error(`${o} path ${n} must be a regular file.`);if(Number.isInteger(e.dev)&&Number.isInteger(e.ino)&&Number.isInteger(t.dev)&&Number.isInteger(t.ino)&&(e.dev!==t.dev||e.ino!==t.ino))throw new Error(`${o} file ${n} changed while it was being opened.`);if(r!==void 0){if(t.uid!==r)throw new Error(`${o} file ${n} must be owned by the current user.`);if((t.mode&63)!==0)throw new Error(`${o} file ${n} must not be accessible by group or other users.`)}}async function Nb(e,{label:t="Connector settings",uid:n=process.getuid?.()}={}){let r=await x8(e);if(r.isSymbolicLink())throw new Error(`${t} file ${e} must not be a symbolic link.`);let o=bO.O_RDONLY|(bO.O_NOFOLLOW??0),s;try{s=await E8(e,o)}catch(i){throw i?.code==="ELOOP"?new Error(`${t} file ${e} must not be a symbolic link.`):i}try{let i=await s.stat();return I8(r,i,e,{uid:n,label:t}),await s.readFile("utf8")}finally{await s.close()}}async function yn(e=process.cwd(),{vault:t}={}){let n=_r(e),r;try{r=JSON.parse(await Nb(n))}catch(i){if(i?.code==="ENOENT")return null;throw i}if(r?.server_url&&Ib(r.server_url),typeof r?.token=="string"&&r.token)return await bn({...r,workspace:r.workspace??e},{vault:t}),r;let{token_fingerprint:o,...s}=r??{};return o?{...s,token:await T8(e,n,o,t)}:r}function bn(e,{vault:t}={}){let n=_r(e.workspace),{token:r,token_fingerprint:o,...s}=e,i=(Vm.get(n)??Promise.resolve()).catch(()=>{}).then(async()=>{let a=r?{...s,token_fingerprint:await R8(e.workspace,n,r,t)}:s;return He(n,`${JSON.stringify(a,null,2)}
1726
1726
  `)}).finally(()=>{Vm.get(n)===i&&Vm.delete(n)});return Vm.set(n,i),i}var Vm,xO,Jm,A8,EO,$O,O8,C8,Tn=V(()=>{M();An();Mc();Vm=new Map,xO="connector-token",Jm=new Map,A8=null,EO=e=>e??(A8??=Kr()),$O=e=>SO("sha256").update(e).digest("hex").slice(0,16);O8=new Set(["localhost","127.0.0.1","[::1]"]);C8=100});import{execFile as j8}from"node:child_process";import{lstat as Pb,mkdir as N8,readFile as P8,readdir as M8,realpath as UO,writeFile as D8}from"node:fs/promises";import Zs from"node:path";function Mr(e,t,{input:n,allowFailure:r=!1}={}){return new Promise((o,s)=>{let i=j8("git",["--literal-pathspecs",...t],{cwd:e,maxBuffer:33554432},(a,c,l)=>{a&&(!r||typeof a.code!="number")?s(new Error(a.code==="ENOENT"?"Install Git before connecting this workspace.":`Local Git ${t[0]} failed: ${l.trim()||a.message}`,{cause:a})):o({code:a?.code??0,stdout:c,stderr:l})});i.stdin.on("error",()=>{}),i.stdin.end(n)})}function zO(e,t){let n=Zs.resolve(e),o=(Km.get(n)??Promise.resolve()).catch(()=>{}).then(()=>t(n));return Km.set(n,o),o.finally(()=>{Km.get(n)===o&&Km.delete(n)})}function vr(e){return/^\.engineeros\/design\/projects\/[a-f0-9-]{36}\/(?:INDEX\.md|[a-z0-9-]+\/[a-z0-9-]+\/[a-z0-9-]+\.md)$/.test(e)||/^\.engineeros\/design\/[0-9]{2}-[a-z0-9-]+\/[a-z0-9-]+\.md$/.test(e)||/^\.engineeros\/assessment\/(?:assessment\.md|assessment-state\.json|(?:sections|changes)\/[A-Za-z0-9_-]+\.md)$/.test(e)}async function BO(e){let t=[];async function n(r){let o;try{o=await M8(r,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}for(let s of o){if(s.isSymbolicLink()||s.name.startsWith("."))continue;let i=Zs.join(r,s.name);if(s.isDirectory())await n(i);else if(s.isFile()){let a=Zs.relative(e,i).split(Zs.sep).join("/");vr(a)&&t.push(a)}}}for(let r of[".engineeros",".engineeros/design",".engineeros/assessment"])try{if((await Pb(Zs.join(e,r))).isSymbolicLink())throw new Error(`Artifact directory ${r} must not be a symbolic link.`)}catch(o){if(o.code!=="ENOENT")throw o}return await n(Zs.join(e,".engineeros","design")),await n(Zs.join(e,".engineeros","assessment")),t}async function Mb(e,t,n=!1){t.length&&await Mr(e,["add",...n?["-f"]:[],"--pathspec-from-file=-","--pathspec-file-nul"],{input:HO(t)})}function Ca(e){return zO(e,async t=>{await N8(t,{recursive:!0});let n=await Mr(t,["rev-parse","--is-inside-work-tree"],{allowFailure:!0}),r=!1;if(n.code!==0){let f=await Pb(Zs.join(t,".git")).catch(g=>{if(g.code==="ENOENT")return null;throw g}),h=await Mr(t,["rev-parse","--is-bare-repository"],{allowFailure:!0});if(f||h.stdout.trim()==="true")throw new Error("This workspace has Git metadata but is not a usable working repository. Repair it before reconnecting.");await Mr(t,["init","--initial-branch=main"]),r=!0}else if(n.stdout.trim()!=="true")throw new Error("Select a Git working directory, not a bare repository.");await Mr(t,["config","--local","core.longpaths","true"]);let o=await Mr(t,["rev-parse","--verify","HEAD"],{allowFailure:!0});if(o.code===0)return{initialized:r,committed:!1,revision:o.stdout.trim()};let s=(await Mr(t,["rev-parse","--show-toplevel"])).stdout.trim();if(Zs.relative(await UO(s),await UO(t))!=="")throw new Error("The enclosing Git repository has no initial commit. Connect its root directory to initialize it first.");let i=await BO(t),a=Zs.join(t,".gitignore");try{if((await Pb(a)).isSymbolicLink())throw new Error("Project .gitignore must not be a symbolic link.")}catch(f){if(f.code!=="ENOENT")throw f}let c="";try{c=await P8(a,"utf8")}catch(f){if(f.code!=="ENOENT")throw f}let l=new Set(c.split(/\r?\n/)),u=FR().filter(f=>!l.has(f));if(u.length&&await D8(a,`${c}${c&&!c.endsWith(`
@@ -2036,8 +2036,8 @@ ${d}
2036
2036
  `)}function w1(e,t){let n=String(e??"").replace(/\s+/g," ").trim();return n.length<=t?n||"none":`${n.slice(0,t)}\u2026`}function TK(e){if(e.length<=XC)return e;let t=e.slice(-XC),n=t.indexOf(`
2037
2037
  ### `);return n>=0&&(t=t.slice(n+1)),t}var k1,GC,WC,S1,VC,d9,p9,x1,f9,E1,JC,n0,h9,$1,m9,g9,w9,y9,r0,_9,v9,b9,KC,k9,S9,Fc,x9,E9,i0,o0,$9,pg,A9,T9,R9,m0,XC,O9,C9,YC,I9,j9,N9,P9,M9,D9,L9,U9,QC,ZC,e1,t1,o1,s1,fg,V9,J9,K9,X9,rK,dK,pK,d1,l0,fK,p1,u0,_K,ri=V(()=>{M();au();Ia();An();Nn();ei();cg();Rp();Zo();k1=5,GC=2e4,WC=512*1024,S1=1024*1024,VC=128,d9=128,p9=64,x1=32,f9=128,E1=20,JC=24e3,n0=256,h9=8e3,$1=2500,m9=12e4,g9=40,w9=8,y9=8,r0=3,_9=4,v9=4200,b9="source-map.md",KC=200,k9=120,S9=200,Fc=15,x9=8,E9=.5,i0=50,o0=12,$9=6e3,pg=6,A9=25,T9=2500,R9=14e3,m0="sessions",XC=16384,O9=5,C9=4096,YC=400,I9=3,j9=10080*60*1e3,N9=720*60*60*1e3,P9={source:1,entrypoint:1,public_api:1,documentation:.9,test:.7,manifest:.5,workflow:.5,repository_configuration:.5,security_configuration:.5,other:.4,lockfile:0},M9=2,D9=12,L9=[/(^|\/)test-results\//i,/^docs\/delivery\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\//i],U9=new Set("a an and are as at be been being but by can could did do does done for from had has have how into is it its may might must need needs no not of on or our our should so than that the their them then there these they this those to too use used using very was were what when where which while who why will with would you your about after all also any before between both during each every here how just make made more most need next now once only other over same should some such take then through under until up upon via want wants well when work works".split(/\s+/));QC=new WeakMap;ZC=1.2,e1=.75;t1=new WeakMap;o1=/^[0-9A-Za-z][0-9A-Za-z._\/~^@{}-]{0,199}$/;s1=new WeakMap,fg=new WeakMap;V9=[".js",".jsx",".mjs",".cjs",".ts",".tsx",".py"],J9=[".js",".ts",".tsx",".mjs"];K9=/(^|\/)(?:tsconfig[^/]*|jsconfig)\.json$/i,X9=256*1024;rK=/\bTC[-_][A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*/g;dK=[["engineeros_grep","exact text or a regular expression across the workspace; matching files first, then `path:line: text`"],["engineeros_read_symbol","the lines of one indexed function, class or heading"],["engineeros_outline","a file's indexed symbols with their lines"],["engineeros_search","the files most related to a description"],["engineeros_similar","existing functions that may already do what you need"],["engineeros_blast_radius","the files importing a file or one of its symbols"],["engineeros_recall","what earlier EngineerOS sessions in this workspace concluded"]],pK={claude:"your `Grep` tool",opencode:"your `grep` tool",gemini:"your own file-content search tool"},d1={codex:"agents.md",opencode:"agents.md",claude:"claude.md",gemini:"gemini.md"},l0={"claude.md":"Claude Code","gemini.md":"Gemini CLI"},fK=new Set(["agents.md",...Object.keys(l0)]),p1=new Set(["contributing.md",".cursorrules"]);u0=new Set([".js",".jsx",".mjs",".cjs",".ts",".tsx"]),_K=[[/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s+([A-Za-z_$][\w$]*)/,"function"],[/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/,"class"],[/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/,"const"],[/^\s*(?:export\s+)?(?:type|interface|enum)\s+([A-Za-z_$][\w$]*)/,"type"]]});function Kn(e={},t={}){e??={},t??={};let n=!!(e.model_source||e.runtime_id||t.runtime_id),r=!!(e.reasoning_source||n);return{model:n?e.model_source==="provider_reported"?e.model??null:null:e.model??t.model??null,...n?{requested_model:e.requested_model??t.model??null,model_source:e.model_source??"unverified"}:{},...e.runtime_id??t.runtime_id?{runtime_id:e.runtime_id??t.runtime_id}:{},reasoning_effort:r?e.reasoning_source==="provider_reported"?e.reasoning_effort??null:null:e.reasoning_effort??t.reasoning_effort??null,...r?{requested_reasoning_effort:e.requested_reasoning_effort??t.reasoning_effort??null,reasoning_source:e.reasoning_source??"unverified"}:{}}}var vu=V(()=>{M()});import{createHash as RK}from"node:crypto";import{mkdir as ku,readFile as zc,readdir as OK,rm as CK,stat as IK,unlink as X1}from"node:fs/promises";import fn from"node:path";function Uo(e,t){return fn.join(fn.resolve(e),".engineeros","assessment",".work")}function R0(e){return fn.join(fn.resolve(e),".engineeros","assessment")}function Q1(e){return fn.join(R0(e),"sections")}function Z1(e,t){return fn.join(Q1(e),`${Ts(t)}.md`)}function _g(e){return e.unchanged_from_revision||e.observed_head_revision||null}async function O0(e,t,n,r){DK(n,r),await Wt(e);let o=Uo(e,t);await ku(o,{recursive:!0,mode:448});let s=Ts(r.stage),i=`${s}.md`,a=`${s}.result.json`,c=String(r.report_markdown).trim(),l={assessment_id:t,stage:r.stage,report_file:i,report_sha256:bg(c),source_revision:n.source_revision??null,observed_head_revision:r.observed_head_revision??null,unchanged_from_revision:r.unchanged_from_revision??null,changed_files:r.changed_files??[],change_impact_markdown:r.change_impact_markdown??null,...Kn(r),usage:r.usage??null,agent_session_id:r.agent_session_id??null};return await He(fn.join(o,i),`${c}
2038
2038
  `),await He(fn.join(o,a),`${JSON.stringify(l,null,2)}
2039
- `),{...l,report_markdown:c}}async function C0(e,t,n,{expectedHeadRevision:r,expectedSourceRevision:o}={}){let s=Uo(e,t),i=fn.join(s,`${Ts(n)}.result.json`);try{let a=JSON.parse(await zc(i,"utf8"));if(a.assessment_id!==t)return null;if(a.stage!==n)throw new Error(`Assessment spool metadata does not match stage '${n}'.`);if(r&&_g(a)!==r||o&&a.source_revision!==o)return null;let c=`${Ts(n)}.md`;if(a.report_file!==c)throw new Error(`Assessment spool metadata for '${n}' contains an invalid report path.`);let l=(await zc(fn.join(s,a.report_file),"utf8")).trim();if(bg(l)!==a.report_sha256)throw new Error(`Assessment spool report for '${n}' failed its integrity check.`);return{...a,report_markdown:l}}catch(a){if(a?.code==="ENOENT")return null;throw a}}async function eI(e,t,n,r,{sourceRevision:o,targetHeadRevision:s,runtimeId:i="default"}={}){let a=String(r||"").trim();if(!a)throw new Error(`Assessment stage '${n}' returned an empty session id.`);let c=Uo(e,t);await ku(c,{recursive:!0,mode:448});let l={assessment_id:t,stage:n,agent_session_id:a,runtime_id:i,source_revision:String(o||"").trim()||null,target_head_revision:String(s||"").trim()||null};try{let u=JSON.parse(await zc(wg(c,n),"utf8"));if((u.runtime_id??"default")!==i&&u.assessment_id===t&&u.stage===n){let{previous_checkpoints:p=[],...d}=u;l.previous_checkpoints=[...p,d].slice(-3)}else u.previous_checkpoints&&(l.previous_checkpoints=u.previous_checkpoints)}catch(u){if(u.code!=="ENOENT")throw u}return await He(wg(c,n),`${JSON.stringify(l,null,2)}
2040
- `),l}async function tI(e,t,n,{expectedHeadRevision:r,expectedSourceRevision:o,expectedRuntimeId:s}={}){let i=Uo(e,t);try{let a=JSON.parse(await zc(wg(i,n),"utf8"));if(a.assessment_id!==t)return null;if(a.stage!==n)throw new Error(`Assessment session checkpoint does not match stage '${n}'.`);if(s&&(a.runtime_id??"default")!==s||r&&a.target_head_revision!==r||o&&a.source_revision!==o)return null;let c=String(a.agent_session_id||"").trim();if(!c)throw new Error(`Assessment session checkpoint for '${n}' has no session id.`);return c}catch(a){if(a?.code==="ENOENT")return null;throw a}}async function nI(e,t,n){try{await X1(wg(Uo(e,t),n))}catch(r){if(r?.code!=="ENOENT")throw r}}async function rI(e,t,n){let r=Uo(e,t),o=Ts(n);await Promise.all([fn.join(r,`${o}.md`),fn.join(r,`${o}.result.json`)].map(async s=>{try{await X1(s)}catch(i){if(i?.code!=="ENOENT")throw i}}))}async function oI(e,t,{expectedHeadRevision:n,expectedSourceRevision:r}={}){let o=Uo(e,t),s;try{s=await OK(o)}catch(a){if(a?.code==="ENOENT")return[];throw a}return(await Promise.all(s.filter(a=>a.endsWith(".result.json")).map(async a=>{let c=JSON.parse(await zc(fn.join(o,a),"utf8"));return C0(e,t,c.stage,{expectedHeadRevision:n,expectedSourceRevision:r})}))).filter(Boolean).sort((a,c)=>a.stage.localeCompare(c.stage))}async function sI(e,t){let n=String(t.prompt_markdown||"");await Wt(e);let r=Uo(e,t.assessment_id),o=fn.join(r,`${Ts(t.stage)}.md`);if(await ku(r,{recursive:!0,mode:448}),!await IK(o).then(()=>!0,p=>{if(p?.code==="ENOENT")return!1;throw p})){let p=Z1(e,t.stage),d=await vg(p),f=String(t.existing_artifact_markdown||"").trim(),h=d||LK(f,t.required_output_heading,t.required_sections||[]);h&&await He(o,`${h.trim()}
2039
+ `),{...l,report_markdown:c}}async function C0(e,t,n,{expectedHeadRevision:r,expectedSourceRevision:o}={}){let s=Uo(e,t),i=fn.join(s,`${Ts(n)}.result.json`);try{let a=JSON.parse(await zc(i,"utf8"));if(a.assessment_id!==t)return null;if(a.stage!==n)throw new Error(`Assessment spool metadata does not match stage '${n}'.`);if(r&&_g(a)!==r||o&&a.source_revision!==o)return null;let c=`${Ts(n)}.md`;if(a.report_file!==c)throw new Error(`Assessment spool metadata for '${n}' contains an invalid report path.`);let l=(await zc(fn.join(s,a.report_file),"utf8")).trim();if(bg(l)!==a.report_sha256)throw new Error(`Assessment spool report for '${n}' failed its integrity check.`);return{...a,report_markdown:l}}catch(a){if(a?.code==="ENOENT")return null;throw a}}async function eI(e,t,n,r,{sourceRevision:o,targetHeadRevision:s,runtimeId:i="default",routingRevision:a}={}){let c=String(r||"").trim();if(!c)throw new Error(`Assessment stage '${n}' returned an empty session id.`);let l=Uo(e,t);await ku(l,{recursive:!0,mode:448});let u={assessment_id:t,stage:n,agent_session_id:c,runtime_id:i,...a?{routing_revision:a}:{},source_revision:String(o||"").trim()||null,target_head_revision:String(s||"").trim()||null};try{let p=JSON.parse(await zc(wg(l,n),"utf8"));if(((p.runtime_id??"default")!==i||p.routing_revision!==a)&&p.assessment_id===t&&p.stage===n){let{previous_checkpoints:d=[],...f}=p;u.previous_checkpoints=[...d,f].slice(-3)}else p.previous_checkpoints&&(u.previous_checkpoints=p.previous_checkpoints)}catch(p){if(p.code!=="ENOENT")throw p}return await He(wg(l,n),`${JSON.stringify(u,null,2)}
2040
+ `),u}async function tI(e,t,n,{expectedHeadRevision:r,expectedSourceRevision:o,expectedRuntimeId:s,expectedRoutingRevision:i}={}){let a=Uo(e,t);try{let c=JSON.parse(await zc(wg(a,n),"utf8"));if(c.assessment_id!==t)return null;if(c.stage!==n)throw new Error(`Assessment session checkpoint does not match stage '${n}'.`);if(s&&(c.runtime_id??"default")!==s||i&&c.routing_revision!==i||r&&c.target_head_revision!==r||o&&c.source_revision!==o)return null;let l=String(c.agent_session_id||"").trim();if(!l)throw new Error(`Assessment session checkpoint for '${n}' has no session id.`);return l}catch(c){if(c?.code==="ENOENT")return null;throw c}}async function nI(e,t,n){try{await X1(wg(Uo(e,t),n))}catch(r){if(r?.code!=="ENOENT")throw r}}async function rI(e,t,n){let r=Uo(e,t),o=Ts(n);await Promise.all([fn.join(r,`${o}.md`),fn.join(r,`${o}.result.json`)].map(async s=>{try{await X1(s)}catch(i){if(i?.code!=="ENOENT")throw i}}))}async function oI(e,t,{expectedHeadRevision:n,expectedSourceRevision:r}={}){let o=Uo(e,t),s;try{s=await OK(o)}catch(a){if(a?.code==="ENOENT")return[];throw a}return(await Promise.all(s.filter(a=>a.endsWith(".result.json")).map(async a=>{let c=JSON.parse(await zc(fn.join(o,a),"utf8"));return C0(e,t,c.stage,{expectedHeadRevision:n,expectedSourceRevision:r})}))).filter(Boolean).sort((a,c)=>a.stage.localeCompare(c.stage))}async function sI(e,t){let n=String(t.prompt_markdown||"");await Wt(e);let r=Uo(e,t.assessment_id),o=fn.join(r,`${Ts(t.stage)}.md`);if(await ku(r,{recursive:!0,mode:448}),!await IK(o).then(()=>!0,p=>{if(p?.code==="ENOENT")return!1;throw p})){let p=Z1(e,t.stage),d=await vg(p),f=String(t.existing_artifact_markdown||"").trim(),h=d||LK(f,t.required_output_heading,t.required_sections||[]);h&&await He(o,`${h.trim()}
2041
2041
  `)}let i=fn.relative(e,o).split(fn.sep).join("/"),a=[`- Path: \`${fn.resolve(o)}\``,"- This file is the only writable project path for this assignment.","- Read it first when it exists, preserve all still-correct content, and edit only what current evidence changes.","- Create it only when no prior artifact exists. The completed file must contain the entire required artifact.","- Do not return the artifact in chat; finish with a short confirmation after saving the file."].join(`
2042
2042
  `);if(n=n.includes(K1)?n.replace(K1,a):`${n.trim()}
2043
2043
 
@@ -2146,7 +2146,7 @@ ${o}`:""}`)}closed(){this.disposeInBackground()}disposeInBackground(){this.dispo
2146
2146
  `).trim()}function RN(e,t){let n=`${t} ${e.slice(-1e3)}`.trim();return EQ.test(e)?`${xQ} ${n}`:n}function $Q(e,t){let n=ss(e);return RN(n,`Forge exited with code ${t}.`)}function AQ(e){let t=ss(e);return RN(t,"Forge completed without returning a response.")}async function ON(e=process.cwd(),t={}){let n=t.command||nw(),r=t.runCommand||rw,o=await r(n,["--version"],e);if(o.code!==0)throw new Error("Forge is unavailable. Install it from https://forgecode.dev, run `forge provider login`, then restart this connector.");let s=await r(n,["list","agent","--porcelain"],e);if(s.code!==0)throw new Error(`Forge could not list its agents. Run \`forge provider login\`, then restart this connector. ${ss(s.stderr)}`.trim());let i=new Set(yQ(s.stdout)),a=[...new Set(Object.values(Ak))].filter(c=>!i.has(c));if(a.length>0)throw new Error(`Forge does not provide the ${a.join(" and ")} agent EngineerOS uses to separate read-only work from editing. Run \`forge update\`, then restart this connector.`);return{command:n,version:o.stdout.trim().slice(0,100)||"unknown"}}function CN({workspace:e,prompt:t,sandbox:n,previousSessionId:r,profile:o={},callbacks:s={},mcpServer:i,command:a=nw(),spawnProcess:c=kr,runCommand:l=rw,createSessionId:u=pQ}){tg("forge",s);let p=mQ(n),d=r||u(),f=new AbortController,h=kQ(o),g=(m,_,S)=>l(m,_,S,{signal:f.signal}),v=c(a,["--agent",p,"--conversation-id",d],{cwd:e,env:{...process.env,...wQ(i,e),...h},windowsHide:!0,stdio:["pipe","pipe","pipe"]});Promise.resolve(s.onSession?.(d)).catch(()=>{});let y=r?$k(g,a,d,e):Promise.resolve(null);y.then(()=>v.stdin.end(ja(t,!!r)));let b="";for(let m of[v.stdout,v.stderr])m.setEncoding("utf8"),m.on("data",_=>{b=`${b}${_}`.slice(-2e4)});fQ.createInterface({input:v.stdout}).on("line",m=>{let _=ss(m);_&&s.onEvent?.({type:"forge.output",line:_})});let E=new Promise((m,_)=>{let S=!1;v.once("error",k=>{S=!0,_(si(k,{sessionId:d,model:o.model||`forge/${p}`,resumed:!!r},{protocol:"forge",stopReason:"spawn_error",diagnostics:ss(b)}))}),v.once("close",k=>{S||(async()=>{let x="";try{if(k!==0)throw new Error($Q(b,k));f.signal.throwIfAborted();let R=await g(a,["conversation","show",d,"--md"],e);if(R.code!==0)throw new Error(`Forge could not read back the response for conversation ${d}. ${ss(R.stderr)}`.trim());if(x=R.stdout.trim(),!x)throw new Error(AQ(b));m({finalMessage:x,output:ss(b).slice(-2e4),model:o.model||await tw(g,a,"model",e)||`forge/${p}`,sessionId:d,resumed:!!r,usage:EN(await y,await $k(g,a,d,e),{resumed:!!r}),route_receipt:o.delivery_receipt?{source:"forge_launch_environment",provider:h.FORGE_SESSION__PROVIDER_ID||null,model:h.FORGE_SESSION__PROVIDER_ID&&h.FORGE_SESSION__MODEL_ID?`${h.FORGE_SESSION__PROVIDER_ID}/${h.FORGE_SESSION__MODEL_ID}`:null,effort:h.FORGE_REASONING__EFFORT||null,runtime_version:/(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec((await g(a,["--version"],e)).stdout||"")?.[1]||null}:null})}catch(R){_(si(R,{finalMessage:x,output:ss(b).slice(-2e4),sessionId:d,model:o.model||`forge/${p}`,resumed:!!r,usage:EN(await y,await $k(g,a,d,e),{resumed:!!r})},{protocol:"forge",stopReason:k!==0?"process_error":"response_error",diagnostics:ss(b)}))}})()})}),w=async()=>{f.abort(),await Kt(v)};return v.engineerOsCancel=w,{child:v,completed:E,cancel:w}}async function tw(e,t,n,r){let o=await e(t,["config","get",n],r);return o.code===0?_Q(o.stdout):null}async function $k(e,t,n,r){try{let o=await e(t,["conversation","stats",n,"--porcelain"],r);return o.code===0?SQ(o.stdout):null}catch{return null}}function rw(e,t,n,{timeoutMs:r=3e4,signal:o}={}){return o?.throwIfAborted(),new Promise((s,i)=>{let a=kr(e,t,{cwd:n,env:process.env,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),c="",l="",u=!1,p=h=>{u=!0,Kt(a).then(()=>i(h),i)},d=()=>p(o.reason);o?.addEventListener("abort",d,{once:!0});let f=setTimeout(()=>{p(new Error(`Forge command '${t.join(" ")}' timed out after ${r} ms. Inspect the agent and retry from saved work.`))},r);a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),a.stdout.on("data",h=>c+=h),a.stderr.on("data",h=>l+=h),a.once("error",h=>{clearTimeout(f),o?.removeEventListener("abort",d),s({code:127,stdout:c,stderr:h.message})}),a.once("close",h=>{clearTimeout(f),o?.removeEventListener("abort",d),u||s({code:h??1,stdout:c,stderr:l})})})}var Ak,hQ,$N,xN,xQ,EQ,Tk=V(()=>{M();Jc();Bi();Wi();os();cg();Dr();Ak=Object.freeze({"read-only":"sage","workspace-write":"forge"}),hQ=/\u001b\[[0-9;]*[A-Za-z]/g;$N="engineeros";xN=Object.freeze(["none","minimal","low","medium","high","xhigh","max"]);xQ="Forge is not authenticated. Run `forge provider login`, then restart the EngineerOS connector.",EQ=/no provider (?:is )?(?:configured|signed in)|provider (?:is )?not (?:configured|signed in|authenticated)|unauthori[sz]ed|invalid api key|missing api key|token_expired|authentication token|sign(?:ing)? in again/i});import{spawn as TQ}from"node:child_process";function Te(e,t,n,r={}){return new Promise((o,s)=>{let i=TQ(e,t,{cwd:n,shell:!1,windowsHide:!0}),a="",c="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",l=>a+=l),i.stderr.on("data",l=>c+=l),i.once("error",s),i.once("close",l=>{let u={code:l??1,stdout:a,stderr:c};l===0||r.allowFailure?o(u):s(new Error(`${e} ${t.join(" ")} failed: ${c||a}`))})})}var Ki=V(()=>{M()});import{readFileSync as RQ}from"node:fs";import{open as OQ}from"node:fs/promises";import ow from"node:path";function CQ(e,t){return/requires a newer version of Codex/i.test(e)?"The configured model requires a newer Codex CLI. Run `npm install -g @openai/codex@latest`, verify with `codex --version`, then restart the EngineerOS connector and retry the assessment.":/not logged in|login required|authentication required/i.test(e)?"Codex CLI is not authenticated. Run `codex login`, then restart the EngineerOS connector.":`Codex exited with code ${t}. ${e.slice(-1e3)}`}function IN(e){return ow.join(ow.resolve(e),".engineeros","agent-termination-block.json")}function Ok(e){let t=ow.resolve(e),n=Rk.get(t),r=IN(t);if(!n)try{n=JSON.parse(RQ(r,"utf8"))}catch(o){if(o.code==="ENOENT")return;throw Object.assign(new Error(`The saved agent termination blocker cannot be read at ${r}. Verify the original agent processes have stopped and resolve that blocker before starting more agent work.`,{cause:o}),{code:"AGENT_TERMINATION_UNCONFIRMED",termination_unconfirmed:!0})}throw Object.assign(new Error(`Agent process termination remains unconfirmed${n.agent_pid?` for PID ${n.agent_pid}`:""}. Stop and verify all reported original agent processes, then resolve ${r} and restart the connector before starting more agent work.`),{code:"AGENT_TERMINATION_UNCONFIRMED",termination_unconfirmed:!0,agent_pid:n.agent_pid})}async function IQ(e,t){if(!e)return;let n=ow.resolve(e),r={at:new Date().toISOString(),agent_pid:t.agent_pid,original_error:{message:t.original_error?.message??(t.original_error==null?null:String(t.original_error)),stack:t.original_error?.stack??null},termination_error:{message:t.termination_error?.message??null,stack:t.termination_error?.stack??null}};Rk.has(n)||Rk.set(n,r),await Wt(n);let o;try{o=await OQ(IN(n),"wx",384),await o.writeFile(JSON.stringify(r),"utf8"),await o.sync()}catch(s){if(s.code!=="EEXIST")throw s}finally{await o?.close()}}async function aw(e,{signal:t,workspace:n}={}){let r=null,o,s=null,i=new Promise((l,u)=>{o=u}),a=()=>{r||(r=Promise.resolve().then(()=>Ck(e)),r.then(()=>o(t.reason??new Error("The connected agent turn was cancelled.")),l=>o(l)))},c=null;Promise.resolve(e.completed).then(l=>{c=l},l=>{c=l?.turn??null}),t?.addEventListener("abort",a,{once:!0}),t?.aborted&&a();try{let l=await Promise.race([e.completed,i]);return t?.throwIfAborted(),l}catch(l){throw s=l,Rs(l)||!c?.usage?l:Object.assign(new Error(l?.message??"The connected agent turn was cancelled.",{cause:l}),{name:l?.name??"Error",usage:c.usage,model:c.model??null})}finally{if(t?.removeEventListener("abort",a),r)try{await r}catch(l){let u=t?.reason??s,p=Object.assign(new Error(`Agent termination could not be confirmed: ${l.message}.${u?.message?` Original failure: ${u.message}`:""} Work ownership must stay blocked until its process is stopped.`,{cause:u??l}),{code:"AGENT_TERMINATION_UNCONFIRMED",termination_unconfirmed:!0,original_error:u,termination_error:l,agent_pid:e.child?.pid??null});try{await IQ(n,p)}catch(d){p.fence_error=d,p.message+=` The persistent blocker could not be saved: ${d.message}. Keep this connector stopped until the original process is verified.`}throw p}}}async function Ck(e,t=e?.child){if(typeof e?.cancel!="function"){await Ur(t);return}Promise.resolve().then(()=>e.cancel()).catch(()=>{});let n;try{await Promise.race([e.completed.then(()=>!0,()=>!0),new Promise(o=>{n=setTimeout(()=>o(!1),2e3)})])||await Ur(t)}finally{clearTimeout(n)}}async function Ur(e){if(e){if(typeof e.engineerOsCancel=="function"){await e.engineerOsCancel();return}await Kt(e)}}function jQ(e,t,n,r,o={},s,i=!1,a){if(!a?.runId)return SN({workspace:e,prompt:t,sandbox:n,profile:o,previousSessionId:s,callbacks:r,configArgs:jN(a)});let c=ju(),l=MQ({workspace:e,sandbox:n,profile:o,previousSessionId:s,skipGitRepoCheck:i,mcpServer:a}),u=kr(c,l,{cwd:e,env:process.env,windowsHide:!0,stdio:["pipe","pipe","pipe"]});u.stdin.end(ja(t,!!s));let p="",d="",f="",h=s||"",g=o.model||"codex-cli",v=null,y=null,b=null,E=Promise.resolve(),w;u.stdout.setEncoding("utf8"),u.stdout.on("data",_=>{p=`${p}${_}`.slice(-sw),d+=_;let S=d.split(/\r?\n/);d=S.pop()??"";for(let k of S)if(k.trim())try{let x=JSON.parse(k);if(x.type==="thread.started"&&typeof x.thread_id=="string"&&(h=x.thread_id,E=Promise.resolve().then(()=>r.onSession?.(h)).catch(R=>{w=R})),x.type==="item.completed"&&x.item?.type==="agent_message"&&typeof x.item.text=="string"&&(f=x.item.text),x.type==="turn.completed"){let R=NQ(x,o);g=R.model,v=R.reported_model,y=R.reported_reasoning_effort,b=R.usage}r.onEvent?.(x)}catch{r.onEvent?.({type:"agent.output",message:k.slice(0,500)})}}),u.stderr.setEncoding("utf8"),u.stderr.on("data",_=>{p=`${p}${_}`.slice(-sw),r.onEvent?.({type:"agent.stderr",message:_.trim().slice(0,500)})});let m=new Promise((_,S)=>{let k=(x,R)=>{let T=si(x,{output:p,finalMessage:f,sessionId:h,model:g,usage:b,resumed:!!s},{protocol:"codex",stopReason:R,diagnostics:p});T.turn.reported_model=v,T.turn.reported_reasoning_effort=y,S(T)};u.once("error",x=>k(x,"process_error")),u.once("close",x=>{E.then(()=>{w?k(w,"checkpoint_error"):x===0&&h?_({output:p,finalMessage:f,sessionId:h,model:g,reported_model:v,reported_reasoning_effort:y,usage:b}):x===0?k(new Error("Agent completed without announcing a resumable session id."),"missing_session"):k(new Error(CQ(p,x)),`exit_${x}`)})})});return{child:u,completed:m}}function NQ(e,t={}){let n=e?.model??e?.turn?.model,r=e?.usage??e?.turn?.usage,o=Ji(r),s=typeof n=="string"&&n.trim()?n.trim():null,i=e?.reasoning_effort??e?.reasoningEffort??e?.turn?.reasoningEffort??e?.turn?.reasoning_effort;return{model:s||t.model||"codex-cli",reported_model:s,reported_reasoning_effort:typeof i=="string"&&i.trim()?i.trim():null,usage:o}}function iw(e,t){if(t&&!PQ.test(t))throw new Error(`Codex ${e} ${JSON.stringify(String(t).slice(0,80))} is invalid. Use only letters, digits, and . _ : / - characters.`);return t}function MQ({workspace:e,sandbox:t,profile:n={},previousSessionId:r,skipGitRepoCheck:o=!1,mcpServer:s}){let i=["--json",...eg()];o&&i.push("--skip-git-repo-check"),n.model&&i.push("--model",iw("model",n.model)),n.reasoning_effort&&i.push("--config",`model_reasoning_effort=${Jp(n.reasoning_effort)}`),i.push(...jN(s));let a=["--sandbox",t,"-C",e];return r?["exec",...a,"resume",...i,iw("session id",r),"-"]:["exec",...i,...a,"-"]}function jN(e){let t=[];if(e?.runId){let n=[e.connectorBin,"mcp","--workspace",e.workspace,"--run-id",e.runId];t.push("--config",`mcp_servers.engineeros.command=${Jp(process.execPath)}`,"--config",`mcp_servers.engineeros.args=[${n.map(Jp).join(",")}]`)}if(e?.contextServer){let n=[e.contextServer.connectorBin,"context-mcp","--workspace",e.contextServer.workspace,"--config-workspace",e.contextServer.configWorkspace];t.push("--config",`mcp_servers.engineeros_context.command=${Jp(process.execPath)}`,"--config",`mcp_servers.engineeros_context.args=[${n.map(Jp).join(",")}]`)}return t}function DQ(e,t,n){return{connectorBin:process.argv[1],workspace:e.workspace,runId:n,contextServer:{connectorBin:process.argv[1],workspace:t,configWorkspace:e.workspace}}}function Ua(e){return String(e||"").replace(/^Warning: Exceeded skills context budget(?: of \d+%)?\. All skill descriptions were removed and \d+ additional skills? (?:was|were) not included in the model-visible skills list\.\s*/i,"")}function Jp(e){let t=String(e);if(t.includes("'''"))throw new Error("Codex configuration values cannot contain three consecutive apostrophes.");return`'''${t}'''`}function LQ(e,t={},n={}){let r=e.route_receipt,o=n.agent_protocol==="acp"&&r?.source==="acp_session_configuration"||n.agent_protocol==="codex"&&r?.source==="codex_app_server",s=o?r.model:n.agent_protocol==="codex"?e.reported_model:null,i=typeof s=="string"&&s.trim()?s:null,a=t.model??n.execution_profiles?.model_profiles?.find(p=>p.is_default)?.id??null,c=o?r.effort:n.agent_protocol==="codex"?e.reported_reasoning_effort:null,l=typeof c=="string"&&c.trim()?c:null,u=t.reasoning_effort??n.execution_profiles?.model_profiles?.find(p=>p.id===a)?.default_reasoning_effort??null;return{...e,model:i,requested_model:a,model_source:i?"provider_reported":"unverified",reasoning_effort:l,requested_reasoning_effort:u,reasoning_source:l?"provider_reported":"unverified"}}function is(e,t,n,r,o,s={},i,a){Ok(r?.workspace??e),r=lo(r,s);let c=r.agent_runtime_id,l=!!(s.runtime_id||r.runtime_root?.runtime_catalog),u=o??{};o={...u,onEvent:f=>u.onEvent?.({...f,...l?{runtime_id:c}:{}})};let p=f=>({...LQ(f,s,r),...l?{runtime_id:c}:{}}),d=f=>({...f,completed:f.completed.then(p,h=>{throw h?.turn&&Object.assign(h.turn,p(h.turn)),h})});return r.agent_protocol==="forge"?d(CN({workspace:e,prompt:t,sandbox:n,previousSessionId:i,profile:s,callbacks:o,mcpServer:a?.runId?{workspace:r.workspace,runId:a.runId}:void 0})):r.agent_protocol==="acp"?d(hN(e,t,r,o,{persistent:a?.persistentAcp===!0,sessionKey:a?.sessionKey?Vc(a.sessionKey,c):void 0,retain:a?.retain===!0,previousSessionId:i,sandbox:n,profile:s,runId:a?.runId,tools:a?.tools!==!1,role:a?.role,verificationAccess:a?.verificationAccess})):d(jQ(e,t,n,o,s,i,r.skip_git_repo_check===!0,DQ(r,e,a?.runId)))}function NN(e,t,n){return new Promise(r=>{let o=Os(e,t,{cwd:n,env:process.env,windowsHide:!0}),s="",i="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",a=>s+=a),o.stderr.on("data",a=>i+=a),o.once("error",a=>r({code:127,stdout:s,stderr:a.message})),o.once("close",a=>r({code:a??1,stdout:s,stderr:i}))})}async function cw(e){await Te("git",["add","-A"],e);let t=await Te("git",["diff","--cached","--name-only","-z","HEAD","--"],e);return Un(t.stdout).sort()}var sw,Rk,PQ,Xi=V(()=>{M();Bi();Wi();Dr();Jc();Ek();Tk();Nn();Ki();os();sw=2e4;Rk=new Map;PQ=/^[A-Za-z0-9._:/-]+$/});import PN from"node:os";import UQ from"node:path";async function LN(e){let t=await uI(e);if(!t.exists)return t;let n=await Te("git",["rev-parse","HEAD"],e,{allowFailure:!0});return{...t,current_head_revision:n.code===0&&n.stdout.trim().slice(0,128)||null}}function UN(e){return!e||typeof e!="object"?null:e.type==="assessment.output_correction"?"Completing the required stage report structure":e.type==="agent.connected"?"Connected agent is ready to inspect the workspace":e.type==="acp.plan"?"Organizing the repository assessment plan":e.type==="acp.agent_thought_chunk"?"Reasoning through the current implementation":e.type==="acp.agent_message_chunk"?"Drafting the stage report":e.type==="acp.tool_call"||e.type==="acp.tool_call_update"?uw(e.update?.title):e.type==="turn.started"?"Reviewing repository structure and current Git state":e.type==="forge.output"?uw(e.line):e.type==="item.started"?e.item?.type==="command_execution"?uw(e.item.command):e.item?.type==="mcp_tool_call"?"Tracing architecture and code relationships":e.item?.type==="web_search"?"Checking an external technical reference":null:e.type==="item.completed"&&e.item?.type==="agent_message"?"Synthesizing findings and highest-return actions":null}function Yc(e){if(!e||typeof e!="object")return null;if(e.type==="connector.step")return Yi(e.message);if(e.type==="forge.output")return Yi(e.line);if(e.type==="acp.tool_call"||e.type==="acp.tool_call_update")return Yi(e.update?.title);if(e.type==="acp.plan"){let t=Array.isArray(e.update?.entries)?e.update.entries:[],n=t.find(r=>r?.status==="in_progress")||t[0];return Yi(n?.content)}if(e.type==="item.started"||e.type==="item.completed"){let t=e.item||{};return t.type==="command_execution"?Yi(Array.isArray(t.command)?t.command.join(" "):t.command):t.type==="file_change"?Yi(`Changed ${(t.changes||[]).map(n=>n?.path).filter(Boolean).join(", ")}`):t.type==="mcp_tool_call"?Yi(`${t.server||"tool"} ${t.tool||""}`):t.type==="web_search"?Yi(t.query):null}return null}function Yi(e){let t=Ee(String(e??"")).replace(/\s+/g," ").trim();return t?t.length>jk?`${t.slice(0,jk-1)}\u2026`:t:null}function qN(e,t){return t<qQ?null:`The connected agent produced no activity for 10 minutes during ${e}. The stage was stopped instead of waiting indefinitely. Retry it after checking the agent terminal.`}function FN(e){if(!e||typeof e!="object")return null;if(e.type==="turn.started"||e.type==="agent.connected")return"preparing";if(e.type==="acp.plan"||e.type==="acp.agent_thought_chunk")return"planning";if(e.type==="acp.agent_message_chunk")return"delivering";if(e.type==="acp.tool_call"||e.type==="acp.tool_call_update")return lw(e.update?.title);if(e.type==="forge.output")return lw(e.line);if(e.type==="connector.step")return lw(e.message);if(e.type==="item.started"){if(e.item?.type==="command_execution"){let t=Array.isArray(e.item.command)?e.item.command.join(" "):e.item.command;return lw(t)}if(["mcp_tool_call","web_search"].includes(e.item?.type))return"inspecting"}return e.type==="item.completed"&&e.item?.type==="file_change"?"editing":e.type==="item.completed"&&e.item?.type==="agent_message"?"delivering":null}function lw(e){let t=String(e??"").toLowerCase();return t.trim()?/\b(test|pytest|vitest|jest|ruff|eslint|tsc|build|lint|verify|check)\b/.test(t)?"verifying":/\b(edit|write|patch|changed?|create|delete|remove|rename|move|implement|fix)\b/.test(t)?"editing":"inspecting":"inspecting"}function BQ(e){return!e||typeof e!="object"?null:e.type==="turn.started"?"Reviewing the request and workspace context":e.type==="item.started"?e.item?.type==="command_execution"?uw(e.item.command):e.item?.type==="mcp_tool_call"?"Checking connected project evidence":e.item?.type==="web_search"?"Checking an external technical reference":null:e.type==="item.completed"&&e.item?.type==="agent_message"?"Preparing the response":e.type==="agent.connected"?"Agent connected":e.type==="acp.tool_call"||e.type==="acp.tool_call_update"?"Agent is inspecting the workspace":e.type==="acp.agent_message_chunk"?"Preparing the response":null}function zN(e){if(!e||typeof e!="object")return null;if(e.type==="codex.agent_message_delta"&&typeof e.delta=="string"){let n=Ua(e.delta);return n?{kind:"message",delta:n}:null}if(e.type==="acp.agent_message_chunk"&&e.update?.content?.type==="text"){let n=Ua(e.update.content.text);return n?{kind:"message",delta:n}:null}if(e.type==="acp.agent_thought_chunk")return{kind:"thought",message:"Agent is reasoning through the request"};if(e.type==="acp.permission")return{kind:"permission",message:e.update?.title||"Agent requested workspace permission",status:e.update?.status};if(e.type==="codex.usage")return{kind:"usage",message:"Agent usage updated"};if(e.type==="acp.plan")return{kind:"plan",message:"Agent updated the working plan"};if(e.type==="acp.tool_call"||e.type==="acp.tool_call_update")return{kind:"tool",message:e.update?.title||"Agent is inspecting the workspace",status:e.update?.status};if(e.type==="item.completed"&&e.item?.type==="agent_message"){let n=Ua(e.item.text);return n?{kind:"message",delta:n}:null}if(e.type==="forge.output"){let n=GQ(e.line);return n?{kind:"tool",message:n}:null}let t=BQ(e);return t?{kind:"status",message:t}:null}function GQ(e){let t=HQ.exec(String(e??"").trim());return t?Yi(t[1]):null}function uw(e){let n=(Array.isArray(e)?e.join(" "):String(e||"")).replace(/\s+/g," ").trim().toLowerCase();return n?/\bgit\s+(status|log|diff|show|rev-parse)\b/.test(n)?"Comparing Git history and workspace changes":/\b(test|pytest|vitest|jest|ruff|eslint|tsc|build|lint)\b/.test(n)?"Checking verification and delivery signals":/\b(audit|dependency|dependencies|lockfile|package-lock|pnpm-lock|requirements)\b/.test(n)?"Reviewing dependencies and security signals":"Tracing architecture and code relationships":"Inspecting workspace source"}function Dk(e,t={}){let n=e?.stage,r=String(e?.required_output_heading||"").trim();if(!n||!r.startsWith("# Assessment Stage: "))throw new Error("EngineerOS assessment assignment has an unsupported stage.");return{...ef(e,{...e?.artifact_path?{}:{requiredOutputHeading:r},...t}),requiredOutputHeading:r}}async function Lk({completed:e,assignment:t,workspace:n,prompt:r,requiredOutputHeading:o,retry:s}){let i=l=>{let u=ni(l,o);for(let p of t.required_sections||[]){let d=String(p).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(!new RegExp(`^## ${d}\\s*$`,"m").test(u))throw new Error(`Assessment stage '${t.stage}' is missing required section '${p}'.`)}return u},a=async()=>i(await aI(n,t)),c=async l=>{let u=i(l.finalMessage);return await cI(n,t,u),a()};try{return{completed:e,correctionUsed:!1,report:await a()}}catch(l){if(!Ik(l))throw l;try{return{completed:e,correctionUsed:!1,report:await c(e)}}catch(d){if(!Ik(d))throw d}await lu(e,o,l);let u=await s(KQ(r,o,UQ.resolve(n,t.artifact_path),l.message),e.sessionId),p;try{let d;try{d=await a()}catch(f){if(!Ik(f))throw f;p=f,d=await c(u)}return{completed:{...u,usage:Nu(e.usage,u.usage)},correctionUsed:!0,report:d}}catch(d){throw new Error(`Agent did not complete the assigned assessment document after one automatic correction attempt. ${(p??d).message}`,{cause:d})}}}function pw(e){if(e?.usage)return!1;let t=String(e?.finalMessage??"").trim();return!t||t.length<=2e3&&WQ.test(t)}async function qa({completed:e,prompt:t,requiredOutputHeading:n,retry:r,validate:o=a=>a,protocol:s=null,retryTransport:i=!0}){let a=p=>o(ni(p.finalMessage,n)),c;try{return{completed:e,correctionUsed:!1,report:a(e)}}catch(p){if(!MN(p))throw p;c=p}let l=e;if(i&&pw(e)){l=await r(t,void 0,{kind:"transport"}),l={...l,usage:Nu(e.usage,l.usage)};try{return{completed:l,correctionUsed:!1,report:a(l)}}catch(p){if(!MN(p))throw p;if(c=p,pw(l))throw new Error(`Agent did not return the required report: the connection to the model failed twice. ${String(l.finalMessage??"").trim().slice(0,500)}`,{cause:p})}}let u;try{await lu(l,n,c),u=await r(ti({base:t,message:VQ(n,c.message),previousSessionId:l.sessionId,protocol:s}),l.sessionId,{kind:"format"})}catch(p){throw p.correctionExhausted=!0,p}try{return{completed:{...u,usage:Nu(l.usage,u.usage)},correctionUsed:!0,report:a(u)}}catch(p){throw Object.assign(new Error(`Agent did not return the required report after one automatic correction attempt. ${p.message}`,{cause:p}),{correctionExhausted:!0})}}function BN(e,t,n){return n?["## Rejected Assessment Document Recovery","","EngineerOS rejected the assigned assessment document because it was incomplete or violated its Markdown contract:","",String(e||"The assessment document was rejected.").trim(),"",`Read and edit \`${n}\` in place. Preserve every valid section and repair only the rejected content.`,"Do not re-inspect unrelated source, rewrite valid content, create a replacement report, or edit any other file.",`The first non-whitespace line in the saved file must be exactly: ${t}`,"Finish with a short confirmation after saving; do not return the document in chat."].join(`
2147
2147
  `):["## Rejected Stage Output Recovery","","EngineerOS rejected the previous stage report because it was incomplete or violated the structured Markdown contract:","",String(e||"The stage report was rejected.").trim(),"","Treat the previous stage report as the authoritative draft.","Copy every valid section and block unchanged; repair only the incomplete or invalid entries identified by EngineerOS validation.","Do not re-inspect the repository or replace valid evidence unless the validation error requires it.","Return the entire corrected structured Markdown stage report so EngineerOS can validate it atomically, not only the repaired fragment or missing tail.",`The first non-whitespace line must be exactly: ${t}`,"Do not return progress commentary, an explanation of the correction, or a code fence."].join(`
2148
2148
  `)}function VQ(e,t){return["## Incomplete Stage Output Recovery","","The previous turn ended without a complete stage deliverable. Return the entire structured Markdown stage report now.",...t?["### Report validation failure",...xu(t),"Repair the identified violation and return the complete report, including all required sections in their assigned order."]:[],"Use the saved response and evidence from the previous turn. Correct presentation only; do not rerun implementation, commands or checks, change a verdict, omit failed checks, or invent missing evidence. Report unavailable evidence explicitly.",`The first non-whitespace line of the final answer must be exactly: ${e}`,"Follow every section, inspection, and completeness rule in the Assignment.","Do not return progress commentary, an explanation of the correction, or a code fence."].join(`
2149
- `)}function MN(e){let t=e instanceof Error?e.message:"";return t.startsWith("Agent completed")||t.startsWith("Agent response")}function Nu(e,t){let n=[e,t].filter(r=>r&&typeof r=="object");return n.length?Object.fromEntries(Mk.map(r=>[r,n.reduce((o,s)=>o+(Number.isFinite(s[r])?s[r]:0),0)])):null}function Kp(e,t,n,{front:r=!1,activeWorkers:o=[]}={}){let s=[...e,...o,...t?[t]:[]].filter(l=>(l.assessment_id??l.runId)===n.assessment_id),i=[n.admitted_worker_limit,...s.map(l=>l.admitted_worker_limit??l.admittedWorkerLimit)].filter(l=>l!==void 0);if(i.length){let l=Math.min(...i.map(Qp));n={...n,admitted_worker_limit:l};for(let u of s)u.kind==="assessment"?u.admittedWorkerLimit=l:u.admitted_worker_limit=l}let a=l=>l?.assessment_id===n?.assessment_id&&l?.stage===n?.stage;if(t?.kind==="assessment"&&t.runId===n?.assessment_id&&t.stage===n?.stage){let l=a(t.resumeAssignment);return t.resumeAssignment=n,l?"duplicate":"deferred"}let c=e.find(a);return c?n.routing_revision&&n.routing_revision!==c.routing_revision?(Object.assign(c,n),"queued"):"duplicate":(r?e.unshift(n):e.push(n),"queued")}function HN(e,t,n,r=()=>!0){let o=Math.max(0,n-t);if(!o||!e.length)return[];if(e[0]?.parallelizable!==!0)return t===0&&r(e[0])?e.splice(0,1):[];let s=[];for(let i=0;s.length<o&&i<e.length&&e[i]?.parallelizable===!0;)r(e[i])?s.push(...e.splice(i,1)):i++;return s}function GN({queued:e,running:t,workerLimit:n,connected:r,designSync:o,integrations:s}){if(!e.length)return null;let i=`${e.length} assessment ${e.length===1?"stage is":"stages are"} waiting`;return r?o?`${i} for the design context sync to finish.`:s>0?`${i} for accepted work to finish integrating (in progress: ${s}).`:t>=n?`${i}: every assessment worker is busy (workers: ${n}).`:t>0&&e[0]?.parallelizable!==!0?`${i}: the next stage runs on its own once the running stages finish (running: ${t}).`:null:`${i}: the connector is reconnecting to EngineerOS.`}function Ik(e){let t=e instanceof Error?e.message:"";return t.startsWith("Assessment stage")||t.startsWith("Agent completed")||t.startsWith("Agent response")}function WN(e){return["# Continue Interrupted EngineerOS Assessment","","Continue the existing assessment task in this agent session from its last completed step.","Do not restart repository inspection or repeat work already present in the session context.","Continue editing the same assigned assessment Markdown file and preserve every still-correct section.","Finish with a short confirmation after the file satisfies the original stage contract; do not return the document in chat.","If the provider could not restore prior context, use the original contract below to complete only the missing work.","","## Original Stage Contract","",String(e||"").trim()].join(`
2149
+ `)}function MN(e){let t=e instanceof Error?e.message:"";return t.startsWith("Agent completed")||t.startsWith("Agent response")}function Nu(e,t){let n=[e,t].filter(r=>r&&typeof r=="object");return n.length?Object.fromEntries(Mk.map(r=>[r,n.reduce((o,s)=>o+(Number.isFinite(s[r])?s[r]:0),0)])):null}function Kp(e,t,n,{front:r=!1,activeWorkers:o=[]}={}){if(e.find(u=>u.assessment_id===n.assessment_id&&(u.routing_generation??0)>(n.routing_generation??0)))return"duplicate";let i=[...e,...o,...t?[t]:[]].filter(u=>(u.assessment_id??u.runId)===n.assessment_id),a=[n.admitted_worker_limit,...i.map(u=>u.admitted_worker_limit??u.admittedWorkerLimit)].filter(u=>u!==void 0);if(a.length){let u=Math.min(...a.map(Qp));n={...n,admitted_worker_limit:u};for(let p of i)p.kind==="assessment"?p.admittedWorkerLimit=u:p.admitted_worker_limit=u}let c=u=>u?.assessment_id===n?.assessment_id&&u?.stage===n?.stage;if(t?.kind==="assessment"&&t.runId===n?.assessment_id&&t.stage===n?.stage){let u=c(t.resumeAssignment);return t.resumeAssignment=n,u?"duplicate":"deferred"}let l=e.find(c);return l?n.routing_revision&&n.routing_revision!==l.routing_revision?(Object.assign(l,n),"queued"):"duplicate":(r?e.unshift(n):e.push(n),"queued")}function HN(e,t,n,r=()=>!0){let o=Math.max(0,n-t);if(!o||!e.length)return[];if(e[0]?.parallelizable!==!0)return t===0&&r(e[0])?e.splice(0,1):[];let s=[];for(let i=0;s.length<o&&i<e.length&&e[i]?.parallelizable===!0;)r(e[i])?s.push(...e.splice(i,1)):i++;return s}function GN({queued:e,running:t,workerLimit:n,connected:r,designSync:o,integrations:s}){if(!e.length)return null;let i=`${e.length} assessment ${e.length===1?"stage is":"stages are"} waiting`;return r?o?`${i} for the design context sync to finish.`:s>0?`${i} for accepted work to finish integrating (in progress: ${s}).`:t>=n?`${i}: every assessment worker is busy (workers: ${n}).`:t>0&&e[0]?.parallelizable!==!0?`${i}: the next stage runs on its own once the running stages finish (running: ${t}).`:null:`${i}: the connector is reconnecting to EngineerOS.`}function Ik(e){let t=e instanceof Error?e.message:"";return t.startsWith("Assessment stage")||t.startsWith("Agent completed")||t.startsWith("Agent response")}function WN(e){return["# Continue Interrupted EngineerOS Assessment","","Continue the existing assessment task in this agent session from its last completed step.","Do not restart repository inspection or repeat work already present in the session context.","Continue editing the same assigned assessment Markdown file and preserve every still-correct section.","Finish with a short confirmation after the file satisfies the original stage contract; do not return the document in chat.","If the provider could not restore prior context, use the original contract below to complete only the missing work.","","## Original Stage Contract","",String(e||"").trim()].join(`
2150
2150
  `)}function KQ(e,t,n,r){return[String(e||"").trim(),"","## Incomplete Assessment Document Recovery","",`The assigned artifact at \`${n}\` is missing or invalid: ${String(r||"unknown validation error")}`,...JQ.test(String(r||""))?["No file exists at that path, so the previous confirmation was not true. A chat reply saves nothing; create the file with a file-writing tool before confirming."]:[],"Continue the existing work and edit that same file in place. Do not restart the assessment or replace valid content.",`The first non-whitespace line in the saved file must be exactly: ${t}`,"Follow every section and validation rule in the assignment, then finish with a short confirmation."].join(`
2151
2151
  `)}function VN(e){let t=String(e?.message||e||"").toLowerCase();return["acp connection closed","acp agent ended the task with an error","app-server connection closed","app server connection closed","connection reset","econnreset","broken pipe","service unavailable","too many requests","rate limit","overloaded"].some(n=>t.includes(n))}function Xp(e){let t=String(e?.message||e||"").toLowerCase();return t.includes("rate limit")||t.includes("too many requests")}function JN(e){return Xp(e)?YQ:XQ}function KN(e){return Xp(e)?"connector_session_rate_limit_attempts":"connector_session_resume_attempts"}function XN(e,t){return Number(e?.[KN(t)]||0)}function e7(e){let t=String(e?.message||e||""),n=/attempted to call tool\s+['"`]?([\w.-]+)/i.exec(t)?.[1];if(n)return[dw,"",`The previous attempt ended because it called a tool named \`${n}\`, which was not available in that session.`,"Call only the tools listed as available to you, by their exact names, and edit the assigned file with the file-editing tools you were given."].join(`
2152
2152
  `);let r=/parameters for tool\s+['"`]?([\w.-]+)['"`]?\s+did not match schema(?:[^[]*\[([^\]]*)\])?/i.exec(t);return r?[dw,"",`The previous attempt ended because it called \`${r[1]}\` with arguments that did not match its schema${r[2]?` (${r[2].trim()})`:""}.`,"Pass every required argument by its exact name. To write the assigned file, prefer the plain file-writing tool over a patch."].join(`
@@ -2723,7 +2723,7 @@ EngineerOS never receives it; the running connector uses it when EngineerOS asks
2723
2723
  `),c=(l,u,p)=>(Vf(i,l),(typeof u=="function"?u:p)?.(),!0);process.stdout.write=process.stderr.write=c,console.log=console.error=console.warn=a}if(s==="install"){if(n["keep-awake"]!==void 0){if(!["on","off"].includes(n["keep-awake"]))throw new Error("Use --keep-awake on or off.");let i=await yn(o);if(!i)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await bn({...i,runner_keep_awake:n["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await sq(o)}`),process.platform==="darwin"&&console.log("macOS may show a Background Items Added notice. Manage the runner in System Settings > General > Login Items.")}else s==="uninstall"?(await cq(o),console.log("Goal runner service removed. Saved and queued jobs are kept.")):s==="start"?await la(o,{enable:!0}):s==="status"?console.log(JSON.stringify(await ca(o),null,2)):s==="serve"?await pq(o):s==="worker"?await fq(o,n["run-id"]):Ro("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(i){Ro(xE(i,o).message)}}if(n["assessment-workers"]!==void 0&&Ro("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment."),e==="secret")try{let o=TE(n),s=t[0]||"list",i=await Fq({action:s,name:t[1],workspace:o,readValue:()=>qq({label:`Value for ${t[1]}`}),write:a=>console.log(a)});process.exit(i.ok?0:1)}catch(o){Ro(o.message)}if(e==="tools"){try{let o=TE(n),s=t[0]||"list";if(["sign-in","auth-status","sign-out"].includes(s)){let a=t[1];a||Ro(`Usage: engineeros-connector tools ${s} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let c=await Fg(o,{type:"tools.auth",command_id:"00000000-0000-4000-8000-000000000001",action:{"sign-in":"sign_in","auth-status":"status","sign-out":"sign_out"}[s],provider_id:a,confirmed:s==="sign-out"});c.completion&&await c.completion}else["setup","upgrade","rollback"].includes(s)?await Ug(o,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:s,provider_id:t[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):s!=="list"&&await sk(o,s,t[1]);let i=await Lr(o);console.log(JSON.stringify(i,null,2)),process.exitCode=i.error?1:0}catch(o){Ro(o.message)}process.exit(process.exitCode||0)}if(e==="agents"){let o;try{o=await dx()}catch(i){Ro(i instanceof Error?i.message:String(i))}let s=await Promise.all(o.map(async i=>{try{return await Zu(i.id),`${i.id}: ready (${i.name} ${i.version}, ${i.distribution_type})`}catch(a){let c=a instanceof Error?a.message:String(a);return`${i.id}: setup needed (${i.name} ${i.version}, ${i.distribution_type}) - ${c}`}}));for(let i of s)console.log(i);process.exit(0)}if(e==="agent"){let o=t[0],s=t[1]||"check";(!o||!["check","install"].includes(s))&&Ro("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let i=s==="install"?await Lf(o):await Zu(o);console.log(`${i.name} is ready (${i.version}, ${i.distribution}).`)}catch(i){Ro(i instanceof Error?i.message:String(i))}process.exit(0)}if(e==="mcp"){let o=n.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),s=n["run-id"]||t[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,i=await yn(o);await Gq({config:i,runId:s,version:Ss,input:process.stdin,output:process.stdout}),process.exit(0)}if(e==="context-mcp"){let o=n["config-workspace"]||n.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),s=await yn(o);s||Ro("This workspace is not paired with EngineerOS."),await rF({config:s,workspace:n.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||s.workspace,version:Ss,input:process.stdin,output:process.stdout}),process.exit(0)}if(e==="history"){(n.help||t[0]!=="compact")&&(console.log(`Usage: engineeros-connector history compact [--workspace <folder>]
2724
2724
  Combines settled report files without deleting evidence or execution identities. Stop older connector versions before compacting.`),process.exit(n.help||!t[0]?0:2));let o=Ei.resolve(n.workspace||process.cwd()),s=await yn(o);if(!s)throw new Error("Restore this workspace's connector pairing and protected job key before compacting history.");let i=Us({getConfig:()=>s}),a=0,c=0;for(let l of await i.list()){let u=await i.compact(l.kind,l.id);a+=u.archived_events,c+=u.removed_files}console.log(`Archived ${a} reports; removed ${c} redundant files. All evidence and execution identities remain retained.`),process.exit(0)}if(e==="status"){let o=await yn(n.workspace||process.cwd());console.log(o?`Paired as ${o.name} (${o.connector_id}) for ${o.workspace}`:"Not paired"),process.exit(o?0:1)}if(e==="update"){let o=t[0]||"status";try{let s=Bm(process.argv[1],ou),i=await Ab(yr(),s,{action:o,policy:t[1]??null});console.log(iu(Tb(i,s,{supervised:!0})))}catch(s){Ro(`${s.message}
2725
2725
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}}function Ro(e){console.error(e),process.exit(1)}var jH=V(()=>{M();Xu();Ry();Aq();Xf();RE();oo();Tn();dl();rh();Bo();OE();Uy();Cu();jE();Zx();oF();mF();oc();yH();t_();Nc();Rm();Xi();CH();Qf();K_()});function NH(e,t,n){if(!Array.isArray(n))return 0;let r=new Set(n.filter(i=>i&&typeof i.assessment_id=="string"&&Oge.has(i.status)).map(i=>i.assessment_id)),o=new Set(t),s=0;for(let i=e.length-1;i>=0;i--)o.has(e[i])&&r.has(e[i].assessment_id)&&(e.splice(i,1),s++);return s}var Oge,PH=V(()=>{M();Oge=new Set(["failed","completed","stale","cancelled","superseded"])});async function MH({request:e,getConfig:t,persist:n,inspect:r,verify:o,authorize:s,needsReadiness:i=!1,now:a=Date.now}){let c=t(),l=La(c,e.id),u=l.agent_name||e.id,p=c.runtime_quota_probes?.[e.command_id];if(p&&p.runtime_id!==e.id)throw new Error("The quota check identity belongs to another runtime.");if(p)return{state:p.state==="checking"?"failed":p.state,message:p.state==="checking"?"The earlier check was interrupted; no automatic provider retry was made. Request another check explicitly.":p.message};let d=a(),f={runtime_id:e.id,state:"checking",message:"Quota check started.",observed_at:new Date(d).toISOString()};async function h(g,v,y){let b=t(),E=Object.fromEntries(Object.entries(b.runtime_quota_probes??{}).filter(([w])=>w!==e.command_id).slice(-255));await n({...b,runtime_quota_probes:{...E,[e.command_id]:{...f,state:g,message:v}},...y?{runtime_limits:{...b.runtime_limits,[e.id]:y}}:{}})}await h("checking","Quota check started.");try{if(e.recovery_id){if(!s)throw new Error("Retained requester authority cannot be revalidated.");await s(e.recovery_id,e.id)}let g=await r(l);if(g?.source==="provider_report"){if(Kc({runtime_limits:{default:g}})){let E="The provider still reports exhausted quota. No model turn was started.";return await h("failed",E,g),{state:"failed",message:E}}if(g.state==="available"){if(!i){let E="Provider quota metadata refreshed. No model turn was needed; other model allowances may differ.";return await h("applied",E,g),{state:"applied",message:E}}await h("checking","Quota metadata recovered; checking connector readiness once.",g)}}let v=t().runtime_limits?.[e.id];if(v?.state==="exhausted"&&v.source==="provider_report"&&Kc({runtime_limits:{default:v}},{},a())){let E="The structured provider limit could not be refreshed. Restore its quota metadata before retrying; no model turn was started.";return await h("failed",E),{state:"failed",message:E}}await o(l,u);let y=Zg(v,d,a()),b="One readiness request succeeded. Remaining quota is unknown; continue failed work explicitly.";return await h("applied",b,y),{state:"applied",message:b,verified:!0}}catch(g){let v=Qg(g,a()),y=v?"The provider still reports exhausted usage. The runtime remains paused.":"Quota recovery was not confirmed. Check provider sign-in and the connector terminal; no automatic retry will run.";return await h("failed",y,v),{state:"failed",message:y}}}var DH=V(()=>{M();os();ew()});function Cge(e){if(!e||Object.keys(e).some(n=>!["action","runtime_id","agent_id","agent_protocol","quota_group","recovery_id"].includes(n)))throw new Error("Choose a runtime action, identity and registered agent only.");if(!["add","enable","disable","refresh","retry","quota-group"].includes(e.action))throw new Error("Unsupported runtime action.");if(e.action!=="quota-group"&&e.quota_group!==void 0)throw new Error("Quota group belongs to its dedicated action.");if(e.action==="refresh"){if(e.runtime_id||e.agent_id||e.agent_protocol)throw new Error("Refresh does not accept launch settings.");return{action:"refresh"}}if(e.action==="retry"&&(typeof e.recovery_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e.recovery_id)))throw new Error("Remote quota checks need retained requester authority.");if(e.action!=="retry"&&e.recovery_id!==void 0)throw new Error("Recovery authority belongs only to quota checks.");let t={action:e.action,id:e.runtime_id,flags:{},...e.recovery_id?{recovery_id:e.recovery_id}:{}};return e.action==="quota-group"&&(t.flags["quota-group"]=e.quota_group??"none"),e.agent_id&&(t.flags.agent=e.agent_id),e.agent_protocol&&(t.flags["agent-protocol"]=e.agent_protocol),_l(t),t}function LH({getConfig:e,requestChange:t,isBusy:n=()=>!1}){let r=new Map;function o(i,a,c=null){let l=r.get(i.command_id);l&&Object.assign(l,{state:a,message:c})}function s(i,a=null){for(let c of r.values())c.state==="applying"&&Object.assign(c,{state:i,message:a})}return{list(){let i=e(),a={id:"default",...i};return{busy:n(),runtimes:[a,...i.agent_runtimes??[]].map(c=>{let l=c===a?"default":c.id,u=c===a||c.enabled!==!1,p=i.runtime_catalog?.find(d=>d.id===l);return{id:l,name:c.agent_name||p?.name||l,agent_protocol:c.agent_protocol??"codex",agent_id:c.agent_id??null,enabled:u,primary:c===a,status:u?p?.status??"unknown":"disabled",quota_group:i.runtime_quota_groups?.[l]??null,limits:i.runtime_limits?.[l]??p?.limits??null}}),changes:[...r.values()]}},request(i,a){if(typeof i!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(i))throw new Error("A runtime settings request needs its command identity.");if(r.get(i))return this.list();let l=Cge(a);if([...r.values()].filter(p=>["queued","applying"].includes(p.state)).length>=32)throw new Error("Wait for the queued runtime changes to finish.");for(let[p,d]of r){if(r.size<32)break;["queued","applying"].includes(d.state)||r.delete(p)}r.set(i,{command_id:i,action:l.action,runtime_id:l.id??null,state:"queued",message:null});try{t({...l,command_id:i})}catch(p){throw r.delete(i),p}return this.list()},beginRefresh(){for(let i of r.values())i.action==="refresh"&&i.state==="queued"&&(i.state="applying")},applying(i){o(i,"applying")},completed(i,a,c){o(i,a,c)},failed(i){o(i,"failed","Runtime change was not saved. Check the connector terminal, resolve the problem and try again.")},defer(){s("queued")},applied(){s("applied")},fail(){s("failed","Runtime discovery or saving could not be confirmed. Check the connector terminal before retrying.")}}}var UH=V(()=>{M();rh()});import{createHash as Ige}from"node:crypto";import{readdir as jge,rm as Nge}from"node:fs/promises";import fA from"node:path";function qH(e,{enqueue:t=ZU,ensure:n=la,send:r=pi,reportError:o=console.error}={}){let s=fA.join(e().workspace,".engineeros","runner","setup-reports"),i,a=async(c,l)=>{try{await r(e(),c)}catch(u){if(u.status!==404&&!Ka(u))throw u}l&&await Nge(l,{force:!0})};return{async dispatch({run_id:c,attempt:l}){let u=e();if(Fn(u.workspace,c),!Number.isSafeInteger(l)||l<0)throw new Error("Goal dispatch has no valid execution attempt. Update the EngineerOS backend and reconnect.");let p=!1;try{return await t(u.workspace,c),p=!0,await n(u.workspace),{queued:p,blocked:!1}}catch(d){let f=On(Ee(`${p?"Goal is queued; runner setup failed.":"Goal dispatch could not be saved. Check workspace write permissions and free disk space, then reconnect."} ${d.message||d}`)),h={type:"run.supervision",run_id:c,attempt:l,phase:"setup",state:"blocked",message:f,restarts:0,llm_attempted:!1},g=fA.join(s,`${Ige("sha256").update(JSON.stringify(h)).digest("hex")}.json`),v=!1;try{await Rt(g,h),v=!0}catch(y){o(`Could not retain runner setup report: ${On(Ee(y.message))}`)}try{await a(h,v?g:null)}catch(y){o(`Runner setup report was not delivered${v?"; saved locally for retry":" and could not be saved locally"}: ${On(Ee(y.message))}`)}return{queued:p,blocked:!0,message:f}}},flush(){return i||(i=(async()=>{let c=await jge(s).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=fA.join(s,l),p=await qe(u);p&&await a(p,u)}})().finally(()=>{i=void 0}),i)}}}var FH=V(()=>{M();Bo();oo();Wf();Gt();Pr();Xu()});import{createHash as Pge}from"node:crypto";import{readFile as Mge,readdir as Dge,rm as Lge}from"node:fs/promises";import Dl from"node:path";import{isDeepStrictEqual as Uge}from"node:util";function BH(e,t,n){if(e.factory_prompt?.version===1&&(t?.termination_unconfirmed===!0||t?.code==="AGENT_TERMINATION_UNCONFIRMED"))return null;let o=Rs(t),s=t?.turn;return{type:"prompt.failed",prompt_id:e.prompt_id,execution_revision:e.execution_revision??1,message:n,...o?.total_tokens>0?{usage:o,model:t?.model??s?.model??null}:{},...s?.model_source?{model:s.model??null,requested_model:s.requested_model??null,model_source:s.model_source}:{},...s?.reasoning_source?{reasoning_effort:s.reasoning_effort??null,requested_reasoning_effort:s.requested_reasoning_effort??null,reasoning_source:s.reasoning_source}:{},...s?.sessionId?{session_id:s.sessionId}:{},...s?.native_cost?{native_cost:s.native_cost}:{},...s?.runtime_id?{runtime_id:s.runtime_id}:{}}}function Vh(e,t){let r=(ev.get(e)??Promise.resolve()).catch(()=>{}).then(t).finally(()=>{ev.get(e)===r&&ev.delete(e)});return ev.set(e,r),r}function nv(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,Dl.resolve(e.workspace)]);return Dl.join(Dl.dirname(_r(e.workspace)),"prompt-results",Jh(t))}function tv(e,t){if(!qge.has(t.type)||!t.prompt_id)throw new Error("Only final prompt results belong in the prompt outbox.");return Dl.join(nv(e),`${Jh(JSON.stringify([t.prompt_id,t.execution_revision??1]))}.json`)}async function Ml(e){try{return JSON.parse(await Mge(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw t}}function HH({getConfig:e,send:t,onRetained:n=()=>{}}){let r,o=new Set,s=d=>Dl.join(nv(e()),`${Jh(JSON.stringify([d,"cancel"]))}.cancel.json`),i=d=>Dl.join(nv(e()),`${Jh(JSON.stringify([d,"execution"]))}.execution.json`);function a(d){let f={status:"execution_unknown",file:d,reason:"This Factory request previously started here. Inspect its original process and retained evidence; automatic replay is blocked."};return n(f),f}function c(d,f){let h=Date.now();for(let[g,v]of Fd)v.expires<=h&&Fd.delete(g);if(f&&Fd.has(d)&&Fd.get(d).digest!==zH(f))throw new Error(`A different final result was already acknowledged for this prompt revision. Original evidence retained in EngineerOS; receipt: ${d}.`);return Fd.has(d)?{status:"delivered",file:d}:null}async function l(d,f){let h=JSON.parse(JSON.stringify(f)),g=await Ml(d);if(!g){g={update:h,saved_at:new Date().toISOString()};try{await He(d,JSON.stringify(g),{replace:!1})}catch(v){if(v.code!=="EEXIST")throw v;if(g=await Ml(d),!g)throw new Error(`Another connector delivered or changed this prompt result. Reconcile its existing receipt before retrying: ${d}`)}}if(!Uge(g.update,h))throw new Error(`A different final result already exists for this prompt revision. Original evidence retained at ${d}.`);return{file:d,record:g}}async function u(d,f){if(f.rejection)return{status:"rejected",file:d,reason:f.rejection};try{return await t(f.update),Fd.set(d,{expires:Date.now()+36e5,digest:zH(f.update)}),await Lge(d,{force:!0}),{status:"delivered",file:d}}catch(h){if(h.retryable===!1){let v=h.message||"EngineerOS rejected this prompt result.";return await He(d,JSON.stringify({...f,rejection:v})),n({status:"rejected",file:d,reason:v}),{status:"rejected",file:d,reason:v}}let g={status:"pending",file:d,reason:h.message};return n(g),g}}let p={async cancel(d){if(typeof d!="string"||!d)throw new Error("Provide the cancelled prompt identity.");let f=s(d);o.add(f),await Vh(f,async()=>{let h=await Ml(f);if(h&&h.prompt_id!==d)throw new Error("The retained prompt cancellation differs.");h||await He(f,JSON.stringify({prompt_id:d}),{replace:!1})})},async offer(d,f){let h=await p.replay(d);if(h)return h;if(d.factory_prompt){let g=s(d.prompt_id),v=i(d.prompt_id),y=await Ml(g);if(y&&y.prompt_id!==d.prompt_id)throw new Error("The retained cancellation differs.");let b=await Ml(v);if(b&&b.prompt_id!==d.prompt_id)throw new Error("The retained execution differs.");if(b)return a(v);if(y||o.has(g))return p.deliver({type:"prompt.failed",prompt_id:d.prompt_id,execution_revision:d.execution_revision??1,message:"Factory planning was cancelled before the agent started."});try{await He(v,JSON.stringify({prompt_id:d.prompt_id}),{replace:!1})}catch(E){if(E.code==="EEXIST")return a(v);throw E}if(o.has(g))return a(v)}return f(),null},save(d){let f=tv(e(),d);return Vh(f,()=>c(f,d)?{file:f,record:null}:l(f,d))},deliver(d){let f=tv(e(),d);return Vh(f,async()=>{let h=c(f,d);if(h)return h;let{record:g}=await l(f,d);return u(f,g)})},replay(d){let f=tv(e(),{...d,type:"prompt.completed"});return Vh(f,async()=>{let h=c(f);if(h)return h;let g=await Ml(f);return g?u(f,g):null})},flush(){if(r)return r;let d=nv(e());return r=(async()=>{let f;try{f=await Dge(d)}catch(h){if(h.code==="ENOENT")return;throw h}for(let h of f.filter(g=>/^[a-f0-9]{64}\.json$/.test(g))){let g=Dl.join(d,h);if((await Vh(g,async()=>{let y=await Ml(g);if(!y||y.rejection)return null;if(g!==tv(e(),y.update))throw new Error(`Saved prompt result has an invalid identity: ${g}`);return u(g,y)}))?.status==="pending")break}})().finally(()=>{r=void 0}),r}};return p}var qge,Jh,ev,Fd,zH,GH=V(()=>{M();An();Tn();Wi();qge=new Set(["prompt.completed","prompt.failed"]),Jh=e=>Pge("sha256").update(e).digest("hex"),ev=new Map,Fd=new Map,zH=e=>Jh(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 WH({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()})}}}var VH=V(()=>{M()});function Xh(e,t=Date.now()){let n=Kh.get(e);return!n||t>=n.retryAt}function JH(e,t,n,{remedy:r=null,now:o=Date.now()}={}){let s=Kh.get(e),i=(s?.failures??0)+1,a=Math.min(3e4*2**(i-1),6e5),c={id:e,title:t,remedy:r,message:Fge(n),failures:i,firstFailedAt:s?.firstFailedAt??o,retryAt:o+a,retryInMs:a};return Kh.set(e,c),c}function KH(e){return Kh.delete(e)}function XH(e=Date.now()){return[...Kh.values()].map(t=>({...t,status:t.failures>=5?"failed":"warning",retryInMs:Math.max(t.retryAt-e,0)}))}function Fge(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}var Kh,hA=V(()=>{M();Kh=new Map});function Vge(e){return e.reduce((t,n)=>YH[n.status]>YH[t]?n.status:t,"ok")}async function eG({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=[Jge(a),Kge(e),await Yh("backend","EngineerOS backend",()=>Xge(e,i)),await Yh("coding_agent","Coding agent",()=>Yge(e,t,r.inspectAgent,i)),...s?[Zge(s)]:[],...r.connectorJobs?[await Yh("local_execution","Local testing work",()=>ewe(r.connectorJobs))]:[],await Yh("tool_registry","Tool registry",()=>twe(t,r.inspectTools)),...e?.hunt_host?[]:[await Yh("goal_runner","Goal runner",()=>nwe(t,r.runnerStatus,{serviceStatus:r.macRunnerStatus}))],...XH().map(rwe),...o.map(l=>En(l.id,l.title,l.status,l.detail,l.remedy))].slice(0,Hge);return{checked_at:new Date().toISOString(),connector_version:String(n).slice(0,50),status:Vge(c),checks:c}}function rv(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(`
2726
- `)}async function tG(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:Wge,...t})??{}}function Jge(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=mA?En("node_runtime","Node runtime","ok",`Node ${e}.`):En("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${mA} this connector requires.`,`Install Node ${mA} or later, then start the connector again.`)}function Kge(e){return e?.connector_id&&e.token?En("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):En("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function Xge(e,t){if(!e?.server_url)return En("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=MO(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return En("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${On(s,{network:!0})}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return En("backend","EngineerOS backend","failed",`${n} answered ${r.status}.`,"Check that the address points at the EngineerOS backend rather than another service.");let o=await r.json().then(s=>s?.status).catch(()=>{});return o&&o!=="healthy"?En("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):En("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function Yge(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 Qge(o.protocol,r):null;return a&&$s(a,i)>0?En("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,ZH[o.protocol].remedy):En("coding_agent","Coding agent","ok",s)}catch(o){return En("coding_agent","Coding agent","failed",nG(o),null)}}async function Qge(e,t){let n=ZH[e];if(!n)return null;let r=QH.get(t)??new Map;QH.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<Gge)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;Jn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function Zge({state:e,detail:t,remedy:n=null}){return En("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function ewe(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return En("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${o.blocked_report?.error?.message||o.error||o.checkpoint?.error||"An execution or report was refused; its original evidence remains saved on this machine."}`,"Inspect the saved connector job and its first blocked report on this machine. Fix the reported cause, then explicitly retry report delivery; do not rerun completed tests or delete their evidence.")}let r=t.flatMap(o=>Object.values(o.checkpoint?.server_effects??{}).flatMap(s=>s.response?.projection_warnings??[]));return r.length?En("local_execution","Local testing work","warning",`${r.length} result(s) were retained as history only. ${r[0].reason}`,"Inspect the saved result receipt and its execution context. History-only results do not verify a pass or resolve a finding; preserve their evidence and supply the reported prerequisite before a new authorized execution."):En("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function twe(e,t){let n=await t(e);if(n?.error)return En("tool_registry","Tool registry","warning",n.error,"Run `engineeros-connector tools list` in this workspace for the full registry state.");let r=n?.entries?.length||0;return En("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function nwe(e,t,{platform:n=process.platform,serviceStatus:r=aq}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return En("goal_runner","Goal runner","warning","The macOS Goal runner is disabled.",`Turn it on in System Settings > General > Login Items. ${a}`);if(!i.loaded)return En("goal_runner","Goal runner","warning",i.installed?"The macOS Goal runner is not loaded in this login session.":"The macOS Goal runner is not installed.",a);if(i.lastExitCode&&i.state!=="running")return En("goal_runner","Goal runner","warning",`The macOS Goal runner exited with status ${i.lastExitCode} (${i.state||"unknown state"}).`,`Read .engineeros/runner/launchd.log. For protected folders, allow node under Privacy & Security > Files and Folders, or move the workspace. ${a}`)}let{jobs:o}=await t(e),s=o.filter(i=>["failed","recovering"].includes(i.status));if(s.length){let i=s[0];return En("goal_runner","Goal runner","warning",`${s.length} local Goal job(s) need attention. ${i.runId} is ${i.status}${i.error?`: ${i.error}`:"."}`,"Open the Goal in EngineerOS, or read .engineeros/runs/<run-id>/activity.log in this workspace.")}return En("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function rwe(e){return En(e.id,e.title,e.status,`Failing since ${Qo(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Yh(e,t,n){try{return await n()}catch(r){return En(e,t,"failed",nG(r),null)}}function En(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,zge),remedy:o?String(o).slice(0,Bge):null}}function nG(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}var mA,zge,Bge,Hge,YH,ZH,Gge,QH,Wge,rG=V(()=>{M();Xu();au();hA();Tn();Bo();_p();mA=22,zge=500,Bge=300,Hge=20,YH={ok:0,warning:1,failed:2},ZH={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."}},Gge=360*6e4,QH=new WeakMap,Wge="connector.diagnostics"});import{rm as owe}from"node:fs/promises";function gA({stateFile:e,maxReportBytes:t=swe,now:n=Date.now,read:r=qe,write:o=Rt,remove:s=i=>owe(i,{force:!0})}={}){if(!e||typeof e!="string")throw new Oo("A diagnostics outbox state file is required.");if(!Number.isSafeInteger(t)||t<1)throw new Oo("maxReportBytes must be a positive safe integer.");let i=Promise.resolve(),a=d=>{let f=i.then(d,d);return i=f.catch(()=>{}),f};async function c(){let d=await r(e);return d==null?null:(awe(d,t),d)}async function l(d){return a(async()=>{iG(d,t);let f=new Date(n()).toISOString(),h={schema_version:sG,report:d,enqueued_at:f,attempts:0,last_attempt_at:null,last_error:null};return await o(e,h),ov(h)})}async function u(d){return a(async()=>{if(typeof d!="function")throw new Oo("A diagnostics delivery callback is required.");let f=await c();if(!f)return{status:"empty",pending:null};f.attempts=Math.max(0,Number(f.attempts)||0)+1,f.last_attempt_at=new Date(n()).toISOString(),f.last_error=null,await o(e,f);try{let h=await d(f.report);return h?.acknowledged!==!0?(f.last_error="EngineerOS did not acknowledge the diagnostics report.",await o(e,f),{status:"pending",pending:ov(f)}):(await s(e),{status:"delivered",acknowledgement:h,pending:null})}catch(h){return f.last_error=cG(h).slice(0,iwe),await o(e,f),{status:"pending",pending:ov(f)}}})}return{enqueue:l,flush:u,snapshot:()=>a(async()=>{let d=await c();return d?ov(d):null})}}function awe(e,t){if(!aG(e)||e.schema_version!==sG)throw new Oo("The diagnostics outbox state has an unsupported schema.");if(iG(e.report,t),!oG(e.enqueued_at))throw new Oo("The diagnostics outbox state has an invalid enqueue timestamp.");if(!Number.isSafeInteger(e.attempts)||e.attempts<0)throw new Oo("The diagnostics outbox state has an invalid attempt count.");if(e.last_attempt_at!==null&&!oG(e.last_attempt_at))throw new Oo("The diagnostics outbox state has an invalid attempt timestamp.");if(e.last_error!==null&&typeof e.last_error!="string")throw new Oo("The diagnostics outbox state has an invalid delivery error.")}function oG(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString()===e}function iG(e,t){if(!aG(e))throw new Oo("A diagnostics report object is required.");let n;try{n=JSON.stringify(e)}catch(o){throw new Oo(`The diagnostics report is not serializable: ${cG(o)}`)}if(n===void 0)throw new Oo("The diagnostics report is not serializable.");let r=Buffer.byteLength(n,"utf8");if(r>t)throw new Oo(`The diagnostics report is ${r} bytes; the outbox limit is ${t} bytes.`,"DIAGNOSTICS_OUTBOX_REPORT_TOO_LARGE")}function ov(e){return{report:e.report,enqueued_at:e.enqueued_at,attempts:Math.max(0,Number(e.attempts)||0),last_attempt_at:e.last_attempt_at??null,last_error:e.last_error??null}}function aG(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function cG(e){return(e instanceof Error?e.message:String(e??"")).trim()||"Diagnostics delivery failed without an error message."}var sG,swe,iwe,Oo,lG=V(()=>{M();Pr();sG=1,swe=256*1024,iwe=500,Oo=class extends Error{constructor(t,n="DIAGNOSTICS_OUTBOX_INVALID"){super(t),this.name="DiagnosticsOutboxError",this.code=n}}});import cwe from"node:path";function sv(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function pG(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function hwe(e){let t=String(e?.name??"");return fwe.has(t)?{support:"helper"}:pwe.has(t)?{support:"run"}:uG.has(t)?{support:"skipped",reason:uG.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}function gwe(e,t){let n=null;for(let r of t)r.name!==e.framework||!mwe(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function wwe(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>lwe&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function fG({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(wA)):null,i=[];for(let l of e){let u=hwe(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:wA(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:wA(u.file)})))s&&!s.has(l.file)||gwe(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=ywe(l,r);l.shards=u.map(({files:p,packages:d},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:p,directory:l.root,packages:d}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(dwe,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function ywe(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=cwe.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:[]}]:wwe(e.files,{perShard:uwe[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var dG,lwe,uwe,dwe,pwe,fwe,uG,wA,mwe,yA=V(()=>{M();dG=3,lwe=300*1e3,uwe={pytest:40,"node:test":40,vitest:60,jest:60},dwe=3,pwe=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),fwe=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),uG=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."]]);wA=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),mwe=(e,t)=>!t||e.startsWith(`${t}/`)});function iv(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g," ").slice(0,kwe)}function Swe(e){if(!e||typeof e!="object")throw new Error("A capability provider must be an object.");if(typeof e.id!="string"||!bwe.test(e.id))throw new Error(`Capability provider ID ${iv(e.id)} is not a stable lowercase identifier.`);if(!Number.isSafeInteger(e.version??1)||(e.version??1)<1)throw new Error(`Capability provider ${e.id} needs a positive integer protocol version.`);if(typeof e.fields!="function")throw new Error(`Capability provider ${e.id} must supply a fields inspector.`);if(e.readiness!==void 0&&typeof e.readiness!="function")throw new Error(`Capability provider ${e.id} readiness must be a function.`);if(e.dependsOn!==void 0&&!Array.isArray(e.dependsOn))throw new Error(`Capability provider ${e.id} dependsOn must be an array.`)}function xwe(e){let t=new Map(e.map(s=>[s.id,s])),n=new Set,r=new Set,o=(s,i)=>{if(!r.has(s)){if(n.has(s))throw new Error(`Capability dependency cycle: ${[...i,s].join(" -> ")}.`);n.add(s);for(let a of t.get(s).dependsOn??[]){if(!t.has(a))throw new Error(`Capability provider ${s} depends on unknown provider ${iv(a)}.`);o(a,[...i,s])}n.delete(s),r.add(s)}};for(let s of e)o(s.id,[])}function hG(e){let t=new Set,n=e.map(s=>{if(Swe(s),t.has(s.id))throw new Error(`Duplicate capability provider ${s.id}.`);return t.add(s.id),Object.freeze({...s,version:s.version??1,dependsOn:[...s.dependsOn??[]]})});xwe(n);function r(s={}){let i={},a=new Map;for(let c of n){let l=c.fields(s)??{};for(let[u,p]of Object.entries(l)){if(a.has(u))throw new Error(`Capability field ${u} is claimed by both ${a.get(u)} and ${c.id}.`);a.set(u,c.id),i[u]=p}}return i}function o(s={}){let i=new Map,a=c=>{if(i.has(c.id))return i.get(c.id);let l="healthy",u="";if(c.readiness)try{let d=c.readiness(s)??{};if(typeof d.then=="function")throw d.then(()=>{},()=>{}),new Error("readiness must be synchronous");l=vwe.has(d.state)?d.state:"unknown",u=iv(d.detail)}catch(d){l="unknown",u=iv(`Readiness inspection failed: ${d?.message??d}`)}if(l==="healthy"||l==="degraded"){let d=c.dependsOn.map(f=>a(n.find(h=>h.id===f))).find(f=>f.state!=="healthy"&&f.state!=="degraded");d&&(l="blocked",u=`Waiting for ${d.id}.`)}let p=Object.freeze({id:c.id,version:c.version,depends_on:[...c.dependsOn],state:l,...u?{detail:u}:{}});return i.set(c.id,p),p};return n.map(a)}return Object.freeze({ids:()=>n.map(s=>s.id),advertise:r,inspect:o})}var _we,vwe,bwe,kwe,mG=V(()=>{M();_we=Object.freeze(["healthy","degraded","blocked","disabled","unknown"]),vwe=new Set(_we),bwe=/^[a-z][a-z0-9_.]{0,63}$/,kwe=300});import Ewe from"node:path";function mc(e,t,n,{secretNames:r=[]}={}){return gG.advertise({config:e,codingAgent:t,toolInventory:n,secretNames:r})}function wG(e,t,n,{browserRuntime:r=null}={}){return gG.inspect({config:e,codingAgent:t,toolInventory:n,browserRuntime:r})}function _A(e){let t={runtime_quota_groups:e.runtime_quota_groups,multi_runtime_contract:e.multi_runtime_contract,default_runtime_id:e.default_runtime_id,agent_runtimes:e.agent_runtimes?.map(({discovered_at:n,limits:r,...o})=>o),execution_profiles:e.execution_profiles,goal_plan_review:e.goal_plan_review};return JSON.stringify(t,(n,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.keys(r).sort().map(o=>[o,r[o]])):r)}var $we,on,Awe,gG,yG=V(()=>{M();du();yA();Bo();ho();Pl();Zc();Xf();qh();W_();Iw();Qf();mG();os();Nf();$we=4,on=e=>!!e.hunt_host,Awe=[{id:"connection",fields:({config:e,codingAgent:t})=>({agent_protocols:[t.protocol],...t.runtimeCatalog?{multi_runtime_contract:Zj,default_runtime_id:"default",agent_runtimes:t.runtimeCatalog,agent_runtime_refresh:on(e)?0:1,agent_runtime_management:on(e)?0:1}:{},coding_agent:!0,connector_jobs:!0,assessment_worker_limit_contract:1,assessment_quota_contract:1,runtime_limits:e.runtime_limits??{},runtime_quota_groups:e.runtime_quota_groups??{},runtime_quota_controls:on(e)?0:1,http_updates:!0,platform:process.platform,workspace_name:Ewe.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},codex_cli:t.protocol==="codex"})},{id:"coding_agent",dependsOn:["connection"],readiness:({codingAgent:e})=>{if(Array.isArray(e.runtimeCatalog))return e.runtimeCatalog.some(n=>n.status==="ready")?{state:"healthy",detail:"An enabled runtime has available discovered capabilities. Live session verification and selected-runtime access checks remain separate admission requirements."}:e.runtimeCatalog.some(n=>n.status==="unknown")?{state:"unknown",detail:"Enabled runtime availability is not yet verified; restore a local sign-in or refresh its capabilities."}:{state:"blocked",detail:"No enabled runtime is available. Restore a local provider sign-in or installation, then refresh its capabilities."};let t=e.sessionStatus?.status;return t==="authenticated"?{state:"healthy"}:t==="logged_out"?{state:"blocked",detail:e.sessionStatus.message}:{state:"unknown",detail:e.sessionStatus?.message??"Agent authentication status was not reported."}},fields:({config:e,codingAgent:t})=>{let n=t.executionProfiles||{model_selection:!1,model_profiles:[],reasoning_efforts:[]},r=t.sessionStatus||{status:"unknown",message:"Agent authentication status was not reported.",login_command:null,logout_command:null},o=BM(t.protocol);return{tool_rule_kinds:wf({...e,agent_protocol:t.protocol}),self_contained_prompts:1,model_probe:!0,agent_warm:!on(e),...Yp(e.worker_limit),agent_session:r,provider_login:{supported:o,mode:o?"connector_terminal":null},...oC(),execution_profiles:{...n,models:(n.model_profiles||[]).map(s=>s.id)}}}},{id:"workspace",dependsOn:["connection"],fields:({config:e,toolInventory:t})=>({quality_map:!on(e),workspace_head:!on(e),product_stage_handover:!on(e),local_design_context:!on(e),workspace_opportunities:!on(e),...t?{tool_inventory:t}:{}})},{id:"goals",dependsOn:["coding_agent","workspace"],readiness:({config:e})=>on(e)?{state:"disabled",detail:"A dedicated hunt host does not run Goals."}:{state:"healthy"},fields:({config:e,codingAgent:t})=>({capability_delivery:!on(e),goal_plan_review:!on(e)&&(Array.isArray(t.runtimeCatalog)?t.runtimeCatalog.some(n=>n.status==="ready"&&n.capabilities?.goal_plan_review===!0):yk({...e,agent_protocol:t.protocol})),measured_test_evidence:!on(e),resumable_runs:!on(e),goal_recovery:on(e)?0:2,goal_run_contract:$we,runtime_transition_contract:on(e)?0:eN,proposal_context_contract:on(e)?0:1,factory_run_contract:on(e)?0:1,factory_prompt_contract:on(e)?0:1,release_deployment_contract:on(e)?0:1})},{id:"test_automation",dependsOn:["coding_agent","workspace"],readiness:({config:e})=>on(e)?{state:"disabled",detail:"A dedicated hunt host does not run test automation."}:{state:"healthy"},fields:({config:e})=>({test_automation_task:!on(e),test_automation_policy_contract:on(e)?0:dL,test_checks:!on(e)&&String(process.env.ENGINEEROS_TEST_CHECKS??"").trim().toLowerCase()!=="off",test_automation_workers:!on(e),test_schedules:!on(e),quality_baseline:!on(e)&&sv(e),quality_baseline_contract:dG,test_environments:!0})},{id:"bug_hunter",dependsOn:["connection"],readiness:({toolInventory:e,browserRuntime:t})=>(t?t.profile==="bug-hunter-browser-testing"&&t.state==="ready":Bh(e))?{state:"healthy"}:{state:"degraded",detail:t?.profile==="generic"?"This project's prerequisite profile does not provision a browser; non-browser hunts remain available.":`Browser runtime is ${t?.state??"not provisioned"}; non-browser hunts remain available.`},fields:({config:e,toolInventory:t,secretNames:n=[]})=>({...e.hunt_host?{hunt_host:!0}:{},bug_hunt_development_v1:!0,bug_hunt:!0,bug_hunt_scenarios:hz,bug_hunt_performance:1,bug_hunt_specialists:1,bug_hunt_actions:[...o_],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Bh(t),bug_hunt_sign_in:Nl,bug_hunt_flow_recording:tH,bug_hunt_write_only:3,bug_hunt_evidence:1,bug_hunt_inputs:1,bug_hunt_target_briefs:1,bug_hunt_page_turns:1,bug_hunt_checks:[...p$],bug_hunt_secret_names:[...n]})},{id:"delivery",dependsOn:["coding_agent"],fields:({config:e,codingAgent:t})=>({delivery_tasks:{specialist_contract:on(e)?0:1,scope_contract:on(e)?0:1,final_review_contract:on(e)?0:1,protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.67.6",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:Sy,isolation_hash:on(e)?null:yl(e.delivery_isolation),operations:on(e)?[]:["start","cancel"]}})},{id:"integrations",dependsOn:["connection"],fields:()=>({integrations:!0})}],gG=hG(Awe)});function bG({actions:e={},recoveryExecutor:t=null,onNotify:n=null,onUpdate:r=null,explain:o=null,clock:s=Date.now,interval:i=1e3}={}){let a=[],c=[],l=new Map,u=new Map,p=new Map,d="starting",f=s(),h=0,g=0,v="",y=!1,b,E=!1,w=j=>{j?.message&&(a.push(j),a.length>500&&(a.shift(),h+=1))},m=async()=>{let j=a.splice(0,a.length),P=!1;for(let L of j){c.push(L),c.length>200&&c.shift(),f=L.at;let A=Twe.find(le=>le.match.test(L.message));A&&(d=A.state);let D=Cwe.exec(L.message),B=D?L.message.slice(D[0].length):L.message,F=D&&Iwe.exec(B);if(F){k(D[2],Mwe(F),L);continue}if(L.level==="info"||Rwe.test(L.message))continue;let ee=jwe.find(le=>le.match.test(B));if(!ee&&L.level==="unknown")continue;let W=ee?null:Owe.find(le=>le.match.test(B));(W?S(W.area,L):_(L,{prefix:D,body:B,rule:ee}))&&(P=!0)}T(),await $(),x();let N=[...l.values()].map(L=>`${L.key}/${L.severity}/${L.occurrences}/${L.recoveryStatus}/${L.explanation?"read":"unread"}`).join("|");if(r&&N!==v){v=N;try{await r(I())}catch{}}if(!E&&P&&n&&s()-g>=6e4){g=s();try{await n(I())}catch{}}};function _(j,{prefix:P,body:N,rule:L}){let A=L?.area||(P?P[1]:"connector");return R(`${A}:${Nwe(N)}`,{area:A,recovery:L?.recovery||null,message:j.message,at:j.at,subject:P?.[2],severity:"warning",escalateAfter:L?.escalateAfter??3})}function S(j,P){let N=(u.get(j)||[]).filter(L=>P.at-L<6e5);return N.push(P.at),u.set(j,N),N.length<5?!1:R(`${j}:degradation`,{area:j,recovery:null,message:P.message,at:P.at,degraded:N.length,severity:"warning",escalateAfter:Number.POSITIVE_INFINITY})}function k(j,P,N){let L=p.get(j)||{running:0,samples:[]};if(P<L.running&&(L.samples=[...L.samples,L.running].slice(-5),l.delete(_G(j))),L.running=P,p.set(j,L),L.samples.length<2)return;let A=Dwe(L.samples);A<6e4||P<A*2||R(_G(j),{area:"assessment",recovery:null,message:`${j} has been running ${vG(P)}, about ${(P/A).toFixed(1)}x its usual ${vG(A)}.`,at:N.at,subject:j,severity:"warning",escalateAfter:Number.POSITIVE_INFINITY})}function x(){if(E||!o||y)return;let j=C().find(P=>P.severity==="failed"&&!P.asked&&(!P.recovery||P.recoveryStatus==="failed"||P.attempts>=3));j&&(y=!0,j.asked=!0,Promise.resolve(o({title:Qh[j.area].title,message:j.message,occurrences:j.occurrences,subjects:j.subjects,lines:c.slice(-40).map(P=>P.message)})).then(P=>{P?j.explanation=String(P).trim().slice(0,400):j.asked=!1}).catch(()=>{}).finally(()=>{y=!1}))}function R(j,P){let L=l.get(j)||{key:j,area:P.area,recovery:P.recovery,firstMessage:P.message,firstSeenAt:P.at,occurrences:0,subjects:[],severity:P.severity,attempts:0,lastAttemptAt:0,recoveryStatus:null,recoveryDetail:null,asked:!1,explanation:null};L.occurrences+=1,L.message=P.message,L.lastSeenAt=P.at,L.degraded=P.degraded??L.degraded,P.subject&&!L.subjects.includes(P.subject)&&(L.subjects=[...L.subjects,P.subject].slice(-5));let A=L.severity!=="failed"&&L.occurrences>=P.escalateAfter;if(A&&(L.severity="failed"),l.set(j,L),l.size>20){let D=[...l.values()].sort((B,F)=>B.lastSeenAt-F.lastSeenAt)[0];l.delete(D.key)}return A}function T(){let j=s();for(let[P,N]of l)j-N.lastSeenAt>=9e5&&l.delete(P);for(let[P,N]of u){let L=N.filter(A=>j-A<6e5);L.length?u.set(P,L):u.delete(P)}}async function $(){let j=s();for(let P of l.values()){let N=P.recovery?e[P.recovery]:null;if(!(E||!N||P.severity!=="failed"||P.attempts>=3||j-P.lastAttemptAt<3e5)){P.attempts+=1,P.lastAttemptAt=j;try{if(t?.supports(P.recovery)){let L=await t.execute({action:P.recovery,fingerprint:P.key,context:{area:P.area,message:P.message,occurrences:P.occurrences,subjects:[...P.subjects]}});P.recoveryStatus=L.status,P.recoveryDetail=L.detail||null}else await N(),P.recoveryStatus="ran",P.recoveryDetail=null}catch(L){P.recoveryStatus="failed",P.recoveryDetail=Pwe(L)}}}}function O(j){let N=[...l.values()].filter(L=>L!==j&&Qh[j.area].dependsOn.includes(L.area)&&L.firstSeenAt<=j.lastSeenAt&&j.firstSeenAt-L.firstSeenAt<=12e4).sort((L,A)=>L.firstSeenAt-A.firstSeenAt)[0];return N?`${Qh[N.area].title}: ${N.firstMessage}`:null}function C(){return[...l.values()].sort((j,P)=>(P.severity==="failed")-(j.severity==="failed")||P.occurrences-j.occurrences||P.lastSeenAt-j.lastSeenAt)}function I(){let j=s(),P=c.filter(L=>j-L.at<6e5),N=C().filter(L=>L.severity==="failed");return{generated_at:new Date(j).toISOString(),state:N.length&&!["reconnecting","stopped"].includes(d)?"degraded":d,activity:{window_seconds:6e5/1e3,last_activity_at:new Date(f).toISOString(),logged:P.length,warnings:P.filter(L=>L.level==="warning").length,errors:P.filter(L=>L.level==="error").length,dropped:h},incidents:C().map(L=>({id:L.key,area:L.area,title:Qh[L.area].title,severity:L.severity,message:L.message,occurrences:L.occurrences,subjects:L.subjects,first_seen_at:new Date(L.firstSeenAt).toISOString(),last_seen_at:new Date(L.lastSeenAt).toISOString(),probable_cause:O(L),agent_reading:L.explanation||null,remedy:Qh[L.area].remedy,recovery:L.recovery?{action:L.recovery,status:L.recoveryStatus||"pending",attempts:L.attempts,detail:L.recoveryDetail}:null}))}}return{observe:w,drain:m,health:I,healthChecks:()=>vA(I()),start(){b||(E=!1,b=setInterval(()=>{m()},i),b.unref?.())},stop(){E=!0,clearInterval(b),b=void 0}}}function vA(e){return(e?.incidents||[]).slice(0,5).map(t=>({id:`insight_${t.area}`.slice(0,64),title:`${t.title} (observed)`,status:t.severity,detail:[`${t.message}`,`Seen ${t.occurrences} time(s) since ${t.first_seen_at}${t.subjects.length?` across ${t.subjects.join(", ")}`:""}.`,t.probable_cause?`Probable cause: ${t.probable_cause}`:null,t.agent_reading?`Agent reading: ${t.agent_reading}`:null,t.recovery?`Recovery ${t.recovery.action}: ${t.recovery.status}${t.recovery.detail?` - ${t.recovery.detail}`:""}.`:null].filter(Boolean).join(" ").slice(0,500),remedy:t.remedy})).filter((t,n,r)=>r.findIndex(o=>o.id===t.id)===n)}function Nwe(e){return e.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<id>").replace(/\b[0-9a-f]{7,40}\b/gi,"<rev>").replace(/\d+(?:\.\d+)?/g,"<n>").replace(/\s+/g," ").trim().toLowerCase().slice(0,200)}function Pwe(e){return(e instanceof Error?e.message:String(e??"")).trim().slice(0,300)||"No detail was reported."}function _G(e){return`assessment:slow:${e}`}function Mwe(e){return(Number(e[1]||0)*60+Number(e[2]))*1e3}function Dwe(e){let t=[...e].sort((r,o)=>r-o),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function vG(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60);return n?`${n}m ${t%60}s`:`${t}s`}var Qh,Twe,Rwe,Owe,Cwe,Iwe,jwe,kG=V(()=>{M();Qh={backend:{title:"EngineerOS backend",dependsOn:[],remedy:"Check the network between this machine and EngineerOS, and that the backend is running."},coding_agent:{title:"Coding agent",dependsOn:[],remedy:"Run `engineeros-connector doctor` in this workspace; the agent reports what it needs."},assessment:{title:"Workspace assessment",dependsOn:["coding_agent","backend"],remedy:"Open the assessment in EngineerOS for the stage that stopped."},prompt:{title:"Connected prompt",dependsOn:["coding_agent","backend"],remedy:"Ask again in EngineerOS once the reported cause is fixed."},tooling:{title:"Tool registry",dependsOn:[],remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},goal_runner:{title:"Goal runner",dependsOn:["coding_agent"],remedy:"Read .engineeros/runs/<run-id>/activity.log in this workspace for the failing job."},workspace:{title:"Workspace repository",dependsOn:[],remedy:"Resolve the reported Git state in this workspace."},connector:{title:"Connector",dependsOn:["backend"],remedy:"Run `engineeros-connector doctor` in this workspace."}},Twe=[{match:/^Connecting .+ to /,state:"connecting"},{match:/^Connected and waiting for |^Reconnected after .+ offline|^Paired\. Connector .+ is online|^Reconnected existing workspace connector/,state:"connected"},{match:/^Connection unavailable|^WebSocket connection to .+ failed/,state:"reconnecting"},{match:/^This connector was revoked|^Connection rejected/,state:"stopped"}],Rwe=/failed \d+ time\(s\); retrying in \d+s/i,Owe=[{area:"backend",match:/^Connection unavailable|Retrying in \d+s|delivery failed/i},{area:"assessment",match:/is waiting for EngineerOS|Resuming session/i}],Cwe=/^\[(assessment|prompt):([^\]]+)\]\s*/,Iwe=/^(?:(\d+)m )?(\d+)s elapsed\b/,jwe=[{area:"connector",match:/^Connector stopping after an unhandled failure/,escalateAfter:1},{area:"coding_agent",match:/Agent session interrupted|is not authenticated|agent session|could not start the required agent|no output for/i},{area:"backend",match:/EngineerOS did not accept|is unreachable|answered \d{3}|^EngineerOS:|connector update|^Workspace assessment failed/i},{area:"assessment",match:/^Assessment (?:failure delivery|freshness|status)/i},{area:"prompt",match:/^Prompt (?:failure|progress) delivery/i},{area:"tooling",match:/^Tool (?:registry|authentication|inventory)/i,recovery:"refresh_tool_inventory"},{area:"goal_runner",match:/Runner setup failed|^Goal cleanup is pending|Goal Run .+ could not be integrated|^Supervisor cannot|^Goal cleanup will retry/i,recovery:"restart_goal_runner"},{area:"workspace",match:/Local Git|repository|commit/i}]});function AG({inspect:e,current:t,publish:n}={}){for(let[r,o]of Object.entries({inspect:e,current:t,publish:n}))if(typeof o!="function")throw new TypeError(`${r} must be a function.`);return{async run(){return{previous:structuredClone(t()),candidate:await e()}},async verify({result:r}){let o=await e();return xG(r?.candidate)!==xG(o)?{ok:!1,detail:"Tool inventory changed between inspection and verification."}:(await n(o),!0)},async rollback({result:r}){r?.previous!=null&&await n(r.previous)}}}function xG(e){return JSON.stringify(e,(t,n)=>t==="checked_at"?void 0:n)}function TG({restart:e,probe:t,wait:n=i=>new Promise(a=>setTimeout(a,i)),clock:r=Date.now,timeoutMs:o=15e3,pollMs:s=500}={}){for(let[i,a]of Object.entries({restart:e,probe:t,wait:n,clock:r}))if(typeof a!="function")throw new TypeError(`${i} must be a function.`);for(let[i,a]of Object.entries({timeoutMs:o,pollMs:s}))if(!Number.isSafeInteger(a)||a<1)throw new TypeError(`${i} must be a positive integer.`);return{async run(){return await e(),{restart_requested:!0}},async verify(){let i=zd(r())+o,a=null;for(;;){try{a=await t()}catch(l){a={live:!1,code:"RUNNER_PROBE_FAILED",detail:av(l)}}if(a?.live===!0)return!0;let c=zd(r());if(c>=i){let l=typeof a?.code=="string"?a.code:"RUNNER_NOT_LIVE",u=typeof a?.detail=="string"?a.detail:"No liveness detail was reported.";return{ok:!1,detail:`Goal runner did not become live before the verification deadline (${l}): ${u}`}}await n(Math.min(s,i-c))}},async rollback(){}}}function RG({stateFile:e,repairs:t,clock:n=Date.now,random:r=Math.random,maxAttempts:o=Lwe,baseDelayMs:s=Uwe,maxDelayMs:i=qwe,breakerFailures:a=Fwe,breakerResetMs:c=zwe,maxIncidents:l=Bwe,maxHistory:u=Hwe}={}){if(!e||typeof e!="string")throw new TypeError("A recovery state file is required.");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("A fixed recovery registry is required.");for(let[w,m]of Object.entries(t)){kA(w,"Recovery action");for(let _ of["run","verify","rollback"])if(typeof m?.[_]!="function")throw new TypeError(`Recovery ${w} must define ${_}().`)}for(let[w,m]of Object.entries({maxAttempts:o,baseDelayMs:s,maxDelayMs:i,breakerFailures:a,breakerResetMs:c,maxIncidents:l,maxHistory:u}))if(!Number.isSafeInteger(m)||m<(w.includes("Delay")||w.includes("Reset")?0:1))throw new TypeError(`${w} must be a bounded non-negative integer.`);if(s>i)throw new TypeError("baseDelayMs cannot exceed maxDelayMs.");let p,d=Promise.resolve(),f=w=>{let m=d.then(w,w);return d=m.catch(()=>{}),m};async function h(){return p||(p=qe(e).then(w=>Wwe(w))),p}async function g({action:w,fingerprint:m,context:_=null}={}){return f(async()=>{let S=t[w];if(!S)throw new Zh("RECOVERY_ACTION_NOT_APPROVED",`Recovery action ${kA(w,"Recovery action")} is not approved.`);let k=`${w}:${kA(m,"Failure fingerprint")}`,x=await h(),R=zd(n()),T=x.breakers[w]||Kwe();x.breakers[w]=T;let $=x.incidents[k]||Jwe(w,m);if(T.open_until>R)return bA("circuit_open",$,T.open_until,"Recovery circuit is open.");if($.attempts>=o)return bA("budget_exhausted",$,null,"Recovery retry budget is exhausted.");if($.next_attempt_at>R)return bA("cooldown",$,$.next_attempt_at,"Recovery is cooling down.");let O=$.attempts+1,C={...$,action:w,fingerprint:m,attempts:O,status:"running",last_attempt_at:R,next_attempt_at:R+v(O),detail:null};x.incidents[k]=C,y(x),await E(x);let I,j;try{I=await S.run({action:w,fingerprint:m,attempt:O,context:_})}catch(N){j=N}if(!j)try{let N=await S.verify({action:w,fingerprint:m,attempt:O,context:_,result:I});N!==!0&&N?.ok!==!0&&(j=new Error(Xwe(N)||"Independent verification did not pass."))}catch(N){j=N}if(!j)return C.status="verified",C.detail=null,C.verified_at=zd(n()),T.consecutive_failures=0,T.open_until=0,b(x,C),await E(x),SA(C);let P;try{await S.rollback({action:w,fingerprint:m,attempt:O,context:_,result:I,cause:j})}catch(N){P=N}return C.status=P?"rollback_failed":"rolled_back",C.detail=P?`${av(j)} Rollback failed: ${av(P)}`:av(j),T.consecutive_failures+=1,T.consecutive_failures>=a&&(T.open_until=zd(n())+c),b(x,C),await E(x),SA(C,T.open_until||null)})}function v(w){let m=Math.min(i,s*2**Math.max(0,w-1)),_=.75+Math.min(1,Math.max(0,Number(r())))*.5;return Math.min(i,Math.round(m*_))}function y(w){let m=Object.entries(w.incidents);m.length<=l||m.sort(([,_],[,S])=>_.last_attempt_at-S.last_attempt_at).slice(0,m.length-l).forEach(([_])=>delete w.incidents[_])}function b(w,m){w.history.push({action:m.action,fingerprint:m.fingerprint,attempt:m.attempts,status:m.status,at:zd(n()),detail:m.detail}),w.history=w.history.slice(-u)}async function E(w){await Rt(e,w)}return{execute:g,supports:w=>Object.hasOwn(t,w),async snapshot(){return structuredClone(await f(h))}}}function Wwe(e){if(e==null)return Vwe();if(e?.schema_version!==$G||!EG(e.incidents)||!EG(e.breakers)||!Array.isArray(e.history))throw new Zh("RECOVERY_STATE_INVALID","Recovery state is invalid; repair it before automatic recovery resumes.");return e}function Vwe(){return{schema_version:$G,incidents:{},breakers:{},history:[]}}function Jwe(e,t){return{action:e,fingerprint:t,attempts:0,status:"pending",last_attempt_at:0,next_attempt_at:0,verified_at:null,detail:null}}function Kwe(){return{consecutive_failures:0,open_until:0}}function bA(e,t,n,r){return{...SA(t,n),status:e,detail:r}}function SA(e,t=null){return{action:e.action,fingerprint:e.fingerprint,status:e.status,attempts:e.attempts,retry_at:t,detail:e.detail}}function kA(e,t){let n=typeof e=="string"?e.trim():"";if(!n||n.length>SG||/[\u0000-\u001f]/.test(n))throw new Zh("RECOVERY_INPUT_INVALID",`${t} must be between 1 and ${SG} printable characters.`);return n}function Xwe(e){return!e||typeof e!="object"?"":typeof e.detail=="string"?e.detail:""}function av(e){return((e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported.").slice(0,Gwe)}function zd(e){if(!Number.isSafeInteger(e)||e<0)throw new TypeError("clock must return a timestamp.");return e}function EG(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var $G,Lwe,Uwe,qwe,Fwe,zwe,Bwe,Hwe,SG,Gwe,Zh,OG=V(()=>{M();Pr();$G=1,Lwe=3,Uwe=3e5,qwe=36e5,Fwe=3,zwe=18e5,Bwe=100,Hwe=200,SG=200,Gwe=300,Zh=class extends Error{constructor(t,n,r){super(n,r),this.name="RecoveryExecutionError",this.code=t}}});function CG({clock:e=Date.now}={}){let t=e(),n=new Map,r=o=>{let s=n.get(o);return s||(s={kind:o,completed:0,failed:0,total_ms:0,longest_ms:0,last_at:null,input_tokens:0,output_tokens:0,total_tokens:0},n.set(o,s)),s};return{record(o,s,{durationMs:i=0,usage:a=null}={}){let c=r(o);s==="failed"?c.failed+=1:c.completed+=1;let l=Number.isFinite(i)?Math.max(0,i):0;c.total_ms+=l,c.longest_ms=Math.max(c.longest_ms,l),c.last_at=e();for(let u of Ywe(a))c.input_tokens+=u.input_tokens,c.output_tokens+=u.output_tokens,c.total_tokens+=u.total_tokens;return c},snapshot(){return{started_at:t,uptime_ms:e()-t,kinds:[...n.values()].map(o=>({...o}))}}}}function Ywe(e){return(Array.isArray(e)?e:[e]).filter(n=>n&&typeof n=="object").map(n=>{let r=xA(n.input_tokens),o=xA(n.output_tokens);return{input_tokens:r,output_tokens:o,total_tokens:xA(n.total_tokens)||r+o}}).filter(n=>n.total_tokens>0)}function xA(e){return Number.isFinite(e)&&e>0?Math.round(e):0}var IG=V(()=>{M()});import Qwe from"node:readline";function PG(){return jG}function Zwe(e,t,n={}){let[r,...o]=String(e).trim().split(/\s+/),s=NG.find(([i])=>i===r.toLowerCase());return s?s[2](t,o,n):`${r} is not a connector command. ${jG}`}function MG({ui:e,stdin:t=process.stdin,snapshot:n,actions:r,onInterrupt:o=()=>process.kill(process.pid,"SIGINT")}){if(!e.live||!t.isTTY||typeof t.setRawMode!="function")return null;let s="",i=!1,a,c=d=>{if(!a)return;clearTimeout(a.timer);let f=a.resolve;a=null,f(d)},l=()=>e.input(s.length?s:null),u=async d=>{i=!0,e.line("command","info",d);try{e.line("command","info",await Zwe(d,await n(),r))}catch(f){e.line("command","error",`${d} could not be answered: ${f instanceof Error?f.message:String(f)}`)}finally{i=!1}},p=(d,f={})=>{if(f.ctrl&&f.name==="s"){if(a)return;s&&(s="",l()),i||u("/agents");return}if(f.ctrl&&(f.name==="c"||f.name==="d")){if(s){s="",l();return}o();return}if(f.name==="return"||f.name==="enter"){let h=s.trim();if(s="",l(),!h)return;if(a){let g=h.toLowerCase()==="approve";c(g),e.line("command","info",g?"Local operation approved.":"Local operation declined.");return}if(i){e.line("command","info",`${h} was not read: the previous command is still being answered.`);return}u(h);return}if(f.name==="escape"){s="",l();return}if(f.name==="backspace"){s=s.slice(0,-1),l();return}f.ctrl||f.meta||!d||d.length!==1||d.codePointAt(0)<32||d.codePointAt(0)===127||(s+=d,l())};return Qwe.emitKeypressEvents(t),t.setRawMode(!0),t.resume(),t.unref?.(),t.on("keypress",p),{confirm(d){return a||i?Promise.resolve(!1):(s="",l(),e.line("command","warning",`${d}. Type approve to continue, or decline. Approval expires in 60 seconds.`),new Promise(f=>{a={resolve:f,timer:setTimeout(()=>c(!1),6e4)}}))},stop(){c(!1),t.off("keypress",p);try{t.setRawMode(!1)}catch{}s="",e.input(null)}}}function eye(){return["Connector commands. Ctrl+S opens /agents. Only /doctor, /cancel, /verbose, /workers and /update change anything; the rest only read.",...NG.map(([e,t])=>` ${e.padEnd(10)} ${t}`)].join(`
2726
+ `)}async function tG(e,t,n){return!e?.connector_id||!e.token?null:await n(e,{type:Wge,...t})??{}}function Jge(e){let t=Number.parseInt(String(e).replace(/^v/,""),10);return Number.isFinite(t)&&t>=mA?En("node_runtime","Node runtime","ok",`Node ${e}.`):En("node_runtime","Node runtime","failed",`Node ${e} is older than the Node ${mA} this connector requires.`,`Install Node ${mA} or later, then start the connector again.`)}function Kge(e){return e?.connector_id&&e.token?En("pairing","Workspace pairing","ok",`Paired as ${e.name||e.connector_id} for ${e.workspace}.`):En("pairing","Workspace pairing","failed","This workspace holds no connector credential.","Create a pairing command in EngineerOS and run it in this folder.")}async function Xge(e,t){if(!e?.server_url)return En("backend","EngineerOS backend","failed","No EngineerOS address is configured.","Pair this workspace with --url pointing at the EngineerOS backend.");let n=MO(e.server_url),r;try{r=await t(n,{signal:AbortSignal.timeout(1e4)})}catch(s){return En("backend","EngineerOS backend","failed",`${n} is unreachable from this machine: ${On(s,{network:!0})}`,"Check the address, the network between this machine and EngineerOS, and that the backend is running.")}if(!r.ok)return En("backend","EngineerOS backend","failed",`${n} answered ${r.status}.`,"Check that the address points at the EngineerOS backend rather than another service.");let o=await r.json().then(s=>s?.status).catch(()=>{});return o&&o!=="healthy"?En("backend","EngineerOS backend","warning",`${n} reports itself as ${o}.`,"Open Admin > System in EngineerOS for the failing dependency."):En("backend","EngineerOS backend","ok",`${n} is reachable.`)}async function Yge(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 Qge(o.protocol,r):null;return a&&$s(a,i)>0?En("coding_agent","Coding agent","warning",`${s} ${o.name} ${a} is available.`,ZH[o.protocol].remedy):En("coding_agent","Coding agent","ok",s)}catch(o){return En("coding_agent","Coding agent","failed",nG(o),null)}}async function Qge(e,t){let n=ZH[e];if(!n)return null;let r=QH.get(t)??new Map;QH.set(t,r);let o=r.get(e);if(o&&Date.now()-o.at<Gge)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;Jn(a)&&(s=a)}catch{}return r.set(e,{at:Date.now(),version:s}),s}function Zge({state:e,detail:t,remedy:n=null}){return En("agent_session","Coding agent session",e==="ready"?"ok":e==="checking"?"warning":"failed",t,n)}async function ewe(e){let t=await e(),n=t.filter(o=>o.status==="blocked");if(n.length){let o=n[0];return En("local_execution","Local testing work","failed",`${n.length} local testing job(s) are blocked. ${o.blocked_report?.error?.message||o.error||o.checkpoint?.error||"An execution or report was refused; its original evidence remains saved on this machine."}`,"Inspect the saved connector job and its first blocked report on this machine. Fix the reported cause, then explicitly retry report delivery; do not rerun completed tests or delete their evidence.")}let r=t.flatMap(o=>Object.values(o.checkpoint?.server_effects??{}).flatMap(s=>s.response?.projection_warnings??[]));return r.length?En("local_execution","Local testing work","warning",`${r.length} result(s) were retained as history only. ${r[0].reason}`,"Inspect the saved result receipt and its execution context. History-only results do not verify a pass or resolve a finding; preserve their evidence and supply the reported prerequisite before a new authorized execution."):En("local_execution","Local testing work","ok","No local testing jobs are blocked.")}async function twe(e,t){let n=await t(e);if(n?.error)return En("tool_registry","Tool registry","warning",n.error,"Run `engineeros-connector tools list` in this workspace for the full registry state.");let r=n?.entries?.length||0;return En("tool_registry","Tool registry","ok",`${r} provider(s) registered.`)}async function nwe(e,t,{platform:n=process.platform,serviceStatus:r=aq}={}){if(n==="darwin"){let i=await r(e),a=`Run engineeros-connector runner start --workspace "${e}".`;if(i.disabled)return En("goal_runner","Goal runner","warning","The macOS Goal runner is disabled.",`Turn it on in System Settings > General > Login Items. ${a}`);if(!i.loaded)return En("goal_runner","Goal runner","warning",i.installed?"The macOS Goal runner is not loaded in this login session.":"The macOS Goal runner is not installed.",a);if(i.lastExitCode&&i.state!=="running")return En("goal_runner","Goal runner","warning",`The macOS Goal runner exited with status ${i.lastExitCode} (${i.state||"unknown state"}).`,`Read .engineeros/runner/launchd.log. For protected folders, allow node under Privacy & Security > Files and Folders, or move the workspace. ${a}`)}let{jobs:o}=await t(e),s=o.filter(i=>["failed","recovering"].includes(i.status));if(s.length){let i=s[0];return En("goal_runner","Goal runner","warning",`${s.length} local Goal job(s) need attention. ${i.runId} is ${i.status}${i.error?`: ${i.error}`:"."}`,"Open the Goal in EngineerOS, or read .engineeros/runs/<run-id>/activity.log in this workspace.")}return En("goal_runner","Goal runner","ok",`${o.length} local Goal job(s) recorded, none stuck.`)}function rwe(e){return En(e.id,e.title,e.status,`Failing since ${Qo(e.firstFailedAt)} after ${e.failures} attempt(s); retrying in ${Math.round(e.retryInMs/1e3)}s. ${e.message}`,e.remedy)}async function Yh(e,t,n){try{return await n()}catch(r){return En(e,t,"failed",nG(r),null)}}function En(e,t,n,r,o=null){return{id:e,title:t,status:n,detail:String(r||"No detail was reported.").slice(0,zge),remedy:o?String(o).slice(0,Bge):null}}function nG(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}var mA,zge,Bge,Hge,YH,ZH,Gge,QH,Wge,rG=V(()=>{M();Xu();au();hA();Tn();Bo();_p();mA=22,zge=500,Bge=300,Hge=20,YH={ok:0,warning:1,failed:2},ZH={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."}},Gge=360*6e4,QH=new WeakMap,Wge="connector.diagnostics"});import{rm as owe}from"node:fs/promises";function gA({stateFile:e,maxReportBytes:t=swe,now:n=Date.now,read:r=qe,write:o=Rt,remove:s=i=>owe(i,{force:!0})}={}){if(!e||typeof e!="string")throw new Oo("A diagnostics outbox state file is required.");if(!Number.isSafeInteger(t)||t<1)throw new Oo("maxReportBytes must be a positive safe integer.");let i=Promise.resolve(),a=d=>{let f=i.then(d,d);return i=f.catch(()=>{}),f};async function c(){let d=await r(e);return d==null?null:(awe(d,t),d)}async function l(d){return a(async()=>{iG(d,t);let f=new Date(n()).toISOString(),h={schema_version:sG,report:d,enqueued_at:f,attempts:0,last_attempt_at:null,last_error:null};return await o(e,h),ov(h)})}async function u(d){return a(async()=>{if(typeof d!="function")throw new Oo("A diagnostics delivery callback is required.");let f=await c();if(!f)return{status:"empty",pending:null};f.attempts=Math.max(0,Number(f.attempts)||0)+1,f.last_attempt_at=new Date(n()).toISOString(),f.last_error=null,await o(e,f);try{let h=await d(f.report);return h?.acknowledged!==!0?(f.last_error="EngineerOS did not acknowledge the diagnostics report.",await o(e,f),{status:"pending",pending:ov(f)}):(await s(e),{status:"delivered",acknowledgement:h,pending:null})}catch(h){return f.last_error=cG(h).slice(0,iwe),await o(e,f),{status:"pending",pending:ov(f)}}})}return{enqueue:l,flush:u,snapshot:()=>a(async()=>{let d=await c();return d?ov(d):null})}}function awe(e,t){if(!aG(e)||e.schema_version!==sG)throw new Oo("The diagnostics outbox state has an unsupported schema.");if(iG(e.report,t),!oG(e.enqueued_at))throw new Oo("The diagnostics outbox state has an invalid enqueue timestamp.");if(!Number.isSafeInteger(e.attempts)||e.attempts<0)throw new Oo("The diagnostics outbox state has an invalid attempt count.");if(e.last_attempt_at!==null&&!oG(e.last_attempt_at))throw new Oo("The diagnostics outbox state has an invalid attempt timestamp.");if(e.last_error!==null&&typeof e.last_error!="string")throw new Oo("The diagnostics outbox state has an invalid delivery error.")}function oG(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString()===e}function iG(e,t){if(!aG(e))throw new Oo("A diagnostics report object is required.");let n;try{n=JSON.stringify(e)}catch(o){throw new Oo(`The diagnostics report is not serializable: ${cG(o)}`)}if(n===void 0)throw new Oo("The diagnostics report is not serializable.");let r=Buffer.byteLength(n,"utf8");if(r>t)throw new Oo(`The diagnostics report is ${r} bytes; the outbox limit is ${t} bytes.`,"DIAGNOSTICS_OUTBOX_REPORT_TOO_LARGE")}function ov(e){return{report:e.report,enqueued_at:e.enqueued_at,attempts:Math.max(0,Number(e.attempts)||0),last_attempt_at:e.last_attempt_at??null,last_error:e.last_error??null}}function aG(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function cG(e){return(e instanceof Error?e.message:String(e??"")).trim()||"Diagnostics delivery failed without an error message."}var sG,swe,iwe,Oo,lG=V(()=>{M();Pr();sG=1,swe=256*1024,iwe=500,Oo=class extends Error{constructor(t,n="DIAGNOSTICS_OUTBOX_INVALID"){super(t),this.name="DiagnosticsOutboxError",this.code=n}}});import cwe from"node:path";function sv(e,t=process.env){return e?.quality_baseline===!1?!1:!["off","0","false","no"].includes(String(t.ENGINEEROS_QUALITY_BASELINE??"").trim().toLowerCase())}function pG(e=process.env){let t=Number(e.ENGINEEROS_BASELINE_IDLE_MS);return Number.isFinite(t)&&t>0?Math.floor(t):600*1e3}function hwe(e){let t=String(e?.name??"");return fwe.has(t)?{support:"helper"}:pwe.has(t)?{support:"run"}:uG.has(t)?{support:"skipped",reason:uG.get(t)}:{support:"unsupported",reason:`There is no baseline recipe for ${t||"this runner"}. Schedule its command and upload the JUnit report instead.`}}function gwe(e,t){let n=null;for(let r of t)r.name!==e.framework||!mwe(e.file,r.root)||(!n||r.root.length>n.root.length)&&(n=r);return n}function wwe(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>lwe&&(o.push(i),i=[],a=0),i.push(c),a+=l}return i.length&&o.push(i),o}function fG({runners:e=[],testFiles:t=[],selection:n=null,durations:r={},workerLimit:o=1}={}){let s=n?.test_files?new Set(n.test_files.map(wA)):null,i=[];for(let l of e){let u=hwe(l);u.support!=="helper"&&i.push({index:i.length,name:l.name,root:wA(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:wA(u.file)})))s&&!s.has(l.file)||gwe(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=ywe(l,r);l.shards=u.map(({files:p,packages:d},f)=>({id:`${l.index}-${f}`,index:f,total:u.length,files:p,directory:l.root,packages:d}))}let a=Number(o);return{concurrency:Math.max(1,Math.min(dwe,Number.isInteger(a)&&a>0?a:1)),runners:i.map(({files:l,...u})=>u)}}function ywe(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=cwe.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:[]}]:wwe(e.files,{perShard:uwe[e.name]??40,durations:t}).map(n=>({files:n,packages:[]}))}var dG,lwe,uwe,dwe,pwe,fwe,uG,wA,mwe,yA=V(()=>{M();dG=3,lwe=300*1e3,uwe={pytest:40,"node:test":40,vitest:60,jest:60},dwe=3,pwe=new Set(["pytest","vitest","jest","node:test","go-test","junit"]),fwe=new Set(["pytest-asyncio","pytest-cov","hypothesis","schemathesis","locust","bandit","pip-audit","@testing-library/react","@axe-core/playwright","k6","testify"]),uG=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."]]);wA=e=>String(e??"").replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),mwe=(e,t)=>!t||e.startsWith(`${t}/`)});function iv(e){return String(e??"").replace(/[\x00-\x1f\x7f]/g," ").slice(0,kwe)}function Swe(e){if(!e||typeof e!="object")throw new Error("A capability provider must be an object.");if(typeof e.id!="string"||!bwe.test(e.id))throw new Error(`Capability provider ID ${iv(e.id)} is not a stable lowercase identifier.`);if(!Number.isSafeInteger(e.version??1)||(e.version??1)<1)throw new Error(`Capability provider ${e.id} needs a positive integer protocol version.`);if(typeof e.fields!="function")throw new Error(`Capability provider ${e.id} must supply a fields inspector.`);if(e.readiness!==void 0&&typeof e.readiness!="function")throw new Error(`Capability provider ${e.id} readiness must be a function.`);if(e.dependsOn!==void 0&&!Array.isArray(e.dependsOn))throw new Error(`Capability provider ${e.id} dependsOn must be an array.`)}function xwe(e){let t=new Map(e.map(s=>[s.id,s])),n=new Set,r=new Set,o=(s,i)=>{if(!r.has(s)){if(n.has(s))throw new Error(`Capability dependency cycle: ${[...i,s].join(" -> ")}.`);n.add(s);for(let a of t.get(s).dependsOn??[]){if(!t.has(a))throw new Error(`Capability provider ${s} depends on unknown provider ${iv(a)}.`);o(a,[...i,s])}n.delete(s),r.add(s)}};for(let s of e)o(s.id,[])}function hG(e){let t=new Set,n=e.map(s=>{if(Swe(s),t.has(s.id))throw new Error(`Duplicate capability provider ${s.id}.`);return t.add(s.id),Object.freeze({...s,version:s.version??1,dependsOn:[...s.dependsOn??[]]})});xwe(n);function r(s={}){let i={},a=new Map;for(let c of n){let l=c.fields(s)??{};for(let[u,p]of Object.entries(l)){if(a.has(u))throw new Error(`Capability field ${u} is claimed by both ${a.get(u)} and ${c.id}.`);a.set(u,c.id),i[u]=p}}return i}function o(s={}){let i=new Map,a=c=>{if(i.has(c.id))return i.get(c.id);let l="healthy",u="";if(c.readiness)try{let d=c.readiness(s)??{};if(typeof d.then=="function")throw d.then(()=>{},()=>{}),new Error("readiness must be synchronous");l=vwe.has(d.state)?d.state:"unknown",u=iv(d.detail)}catch(d){l="unknown",u=iv(`Readiness inspection failed: ${d?.message??d}`)}if(l==="healthy"||l==="degraded"){let d=c.dependsOn.map(f=>a(n.find(h=>h.id===f))).find(f=>f.state!=="healthy"&&f.state!=="degraded");d&&(l="blocked",u=`Waiting for ${d.id}.`)}let p=Object.freeze({id:c.id,version:c.version,depends_on:[...c.dependsOn],state:l,...u?{detail:u}:{}});return i.set(c.id,p),p};return n.map(a)}return Object.freeze({ids:()=>n.map(s=>s.id),advertise:r,inspect:o})}var _we,vwe,bwe,kwe,mG=V(()=>{M();_we=Object.freeze(["healthy","degraded","blocked","disabled","unknown"]),vwe=new Set(_we),bwe=/^[a-z][a-z0-9_.]{0,63}$/,kwe=300});import Ewe from"node:path";function mc(e,t,n,{secretNames:r=[]}={}){return gG.advertise({config:e,codingAgent:t,toolInventory:n,secretNames:r})}function wG(e,t,n,{browserRuntime:r=null}={}){return gG.inspect({config:e,codingAgent:t,toolInventory:n,browserRuntime:r})}function _A(e){let t={runtime_quota_groups:e.runtime_quota_groups,multi_runtime_contract:e.multi_runtime_contract,default_runtime_id:e.default_runtime_id,agent_runtimes:e.agent_runtimes?.map(({discovered_at:n,limits:r,...o})=>o),execution_profiles:e.execution_profiles,goal_plan_review:e.goal_plan_review};return JSON.stringify(t,(n,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.keys(r).sort().map(o=>[o,r[o]])):r)}var $we,on,Awe,gG,yG=V(()=>{M();du();yA();Bo();ho();Pl();Zc();Xf();qh();W_();Iw();Qf();mG();os();Nf();$we=4,on=e=>!!e.hunt_host,Awe=[{id:"connection",fields:({config:e,codingAgent:t})=>({agent_protocols:[t.protocol],...t.runtimeCatalog?{multi_runtime_contract:Zj,default_runtime_id:"default",agent_runtimes:t.runtimeCatalog,agent_runtime_refresh:on(e)?0:1,agent_runtime_management:on(e)?0:1}:{},coding_agent:!0,connector_jobs:!0,assessment_worker_limit_contract:1,assessment_quota_contract:1,assessment_runtime_change_contract:1,runtime_limits:e.runtime_limits??{},runtime_quota_groups:e.runtime_quota_groups??{},runtime_quota_controls:on(e)?0:1,http_updates:!0,platform:process.platform,workspace_name:Ewe.basename(e.workspace),agent_name:t.name,agent_version:t.version,...e.agent_id?{agent_id:e.agent_id}:{},codex_cli:t.protocol==="codex"})},{id:"coding_agent",dependsOn:["connection"],readiness:({codingAgent:e})=>{if(Array.isArray(e.runtimeCatalog))return e.runtimeCatalog.some(n=>n.status==="ready")?{state:"healthy",detail:"An enabled runtime has available discovered capabilities. Live session verification and selected-runtime access checks remain separate admission requirements."}:e.runtimeCatalog.some(n=>n.status==="unknown")?{state:"unknown",detail:"Enabled runtime availability is not yet verified; restore a local sign-in or refresh its capabilities."}:{state:"blocked",detail:"No enabled runtime is available. Restore a local provider sign-in or installation, then refresh its capabilities."};let t=e.sessionStatus?.status;return t==="authenticated"?{state:"healthy"}:t==="logged_out"?{state:"blocked",detail:e.sessionStatus.message}:{state:"unknown",detail:e.sessionStatus?.message??"Agent authentication status was not reported."}},fields:({config:e,codingAgent:t})=>{let n=t.executionProfiles||{model_selection:!1,model_profiles:[],reasoning_efforts:[]},r=t.sessionStatus||{status:"unknown",message:"Agent authentication status was not reported.",login_command:null,logout_command:null},o=BM(t.protocol);return{tool_rule_kinds:wf({...e,agent_protocol:t.protocol}),self_contained_prompts:1,model_probe:!0,agent_warm:!on(e),...Yp(e.worker_limit),agent_session:r,provider_login:{supported:o,mode:o?"connector_terminal":null},...oC(),execution_profiles:{...n,models:(n.model_profiles||[]).map(s=>s.id)}}}},{id:"workspace",dependsOn:["connection"],fields:({config:e,toolInventory:t})=>({quality_map:!on(e),workspace_head:!on(e),product_stage_handover:!on(e),local_design_context:!on(e),workspace_opportunities:!on(e),...t?{tool_inventory:t}:{}})},{id:"goals",dependsOn:["coding_agent","workspace"],readiness:({config:e})=>on(e)?{state:"disabled",detail:"A dedicated hunt host does not run Goals."}:{state:"healthy"},fields:({config:e,codingAgent:t})=>({capability_delivery:!on(e),goal_plan_review:!on(e)&&(Array.isArray(t.runtimeCatalog)?t.runtimeCatalog.some(n=>n.status==="ready"&&n.capabilities?.goal_plan_review===!0):yk({...e,agent_protocol:t.protocol})),measured_test_evidence:!on(e),resumable_runs:!on(e),goal_recovery:on(e)?0:2,goal_run_contract:$we,runtime_transition_contract:on(e)?0:eN,proposal_context_contract:on(e)?0:1,factory_run_contract:on(e)?0:1,factory_prompt_contract:on(e)?0:1,release_deployment_contract:on(e)?0:1})},{id:"test_automation",dependsOn:["coding_agent","workspace"],readiness:({config:e})=>on(e)?{state:"disabled",detail:"A dedicated hunt host does not run test automation."}:{state:"healthy"},fields:({config:e})=>({test_automation_task:!on(e),test_automation_policy_contract:on(e)?0:dL,test_checks:!on(e)&&String(process.env.ENGINEEROS_TEST_CHECKS??"").trim().toLowerCase()!=="off",test_automation_workers:!on(e),test_schedules:!on(e),quality_baseline:!on(e)&&sv(e),quality_baseline_contract:dG,test_environments:!0})},{id:"bug_hunter",dependsOn:["connection"],readiness:({toolInventory:e,browserRuntime:t})=>(t?t.profile==="bug-hunter-browser-testing"&&t.state==="ready":Bh(e))?{state:"healthy"}:{state:"degraded",detail:t?.profile==="generic"?"This project's prerequisite profile does not provision a browser; non-browser hunts remain available.":`Browser runtime is ${t?.state??"not provisioned"}; non-browser hunts remain available.`},fields:({config:e,toolInventory:t,secretNames:n=[]})=>({...e.hunt_host?{hunt_host:!0}:{},bug_hunt_development_v1:!0,bug_hunt:!0,bug_hunt_scenarios:hz,bug_hunt_performance:1,bug_hunt_specialists:1,bug_hunt_actions:[...o_],bug_hunt_electron:process.env.ENGINEEROS_HUNT_HOST==="dedicated",bug_hunt_webdriver:!0,bug_hunt_native:!0,bug_hunt_browser:Bh(t),bug_hunt_sign_in:Nl,bug_hunt_flow_recording:tH,bug_hunt_write_only:3,bug_hunt_evidence:1,bug_hunt_inputs:1,bug_hunt_target_briefs:1,bug_hunt_page_turns:1,bug_hunt_checks:[...p$],bug_hunt_secret_names:[...n]})},{id:"delivery",dependsOn:["coding_agent"],fields:({config:e,codingAgent:t})=>({delivery_tasks:{specialist_contract:on(e)?0:1,scope_contract:on(e)?0:1,final_review_contract:on(e)?0:1,protocol_version:1,backend_contract:1,schema_revision:"20261027_000183",connector_version:"1.67.8",runtime:e.agent_id||t.protocol,runtime_version:t.version||null,adapter_version:"1",worker_version:Sy,isolation_hash:on(e)?null:yl(e.delivery_isolation),operations:on(e)?[]:["start","cancel"]}})},{id:"integrations",dependsOn:["connection"],fields:()=>({integrations:!0})}],gG=hG(Awe)});function bG({actions:e={},recoveryExecutor:t=null,onNotify:n=null,onUpdate:r=null,explain:o=null,clock:s=Date.now,interval:i=1e3}={}){let a=[],c=[],l=new Map,u=new Map,p=new Map,d="starting",f=s(),h=0,g=0,v="",y=!1,b,E=!1,w=j=>{j?.message&&(a.push(j),a.length>500&&(a.shift(),h+=1))},m=async()=>{let j=a.splice(0,a.length),P=!1;for(let L of j){c.push(L),c.length>200&&c.shift(),f=L.at;let A=Twe.find(le=>le.match.test(L.message));A&&(d=A.state);let D=Cwe.exec(L.message),B=D?L.message.slice(D[0].length):L.message,F=D&&Iwe.exec(B);if(F){k(D[2],Mwe(F),L);continue}if(L.level==="info"||Rwe.test(L.message))continue;let ee=jwe.find(le=>le.match.test(B));if(!ee&&L.level==="unknown")continue;let W=ee?null:Owe.find(le=>le.match.test(B));(W?S(W.area,L):_(L,{prefix:D,body:B,rule:ee}))&&(P=!0)}T(),await $(),x();let N=[...l.values()].map(L=>`${L.key}/${L.severity}/${L.occurrences}/${L.recoveryStatus}/${L.explanation?"read":"unread"}`).join("|");if(r&&N!==v){v=N;try{await r(I())}catch{}}if(!E&&P&&n&&s()-g>=6e4){g=s();try{await n(I())}catch{}}};function _(j,{prefix:P,body:N,rule:L}){let A=L?.area||(P?P[1]:"connector");return R(`${A}:${Nwe(N)}`,{area:A,recovery:L?.recovery||null,message:j.message,at:j.at,subject:P?.[2],severity:"warning",escalateAfter:L?.escalateAfter??3})}function S(j,P){let N=(u.get(j)||[]).filter(L=>P.at-L<6e5);return N.push(P.at),u.set(j,N),N.length<5?!1:R(`${j}:degradation`,{area:j,recovery:null,message:P.message,at:P.at,degraded:N.length,severity:"warning",escalateAfter:Number.POSITIVE_INFINITY})}function k(j,P,N){let L=p.get(j)||{running:0,samples:[]};if(P<L.running&&(L.samples=[...L.samples,L.running].slice(-5),l.delete(_G(j))),L.running=P,p.set(j,L),L.samples.length<2)return;let A=Dwe(L.samples);A<6e4||P<A*2||R(_G(j),{area:"assessment",recovery:null,message:`${j} has been running ${vG(P)}, about ${(P/A).toFixed(1)}x its usual ${vG(A)}.`,at:N.at,subject:j,severity:"warning",escalateAfter:Number.POSITIVE_INFINITY})}function x(){if(E||!o||y)return;let j=C().find(P=>P.severity==="failed"&&!P.asked&&(!P.recovery||P.recoveryStatus==="failed"||P.attempts>=3));j&&(y=!0,j.asked=!0,Promise.resolve(o({title:Qh[j.area].title,message:j.message,occurrences:j.occurrences,subjects:j.subjects,lines:c.slice(-40).map(P=>P.message)})).then(P=>{P?j.explanation=String(P).trim().slice(0,400):j.asked=!1}).catch(()=>{}).finally(()=>{y=!1}))}function R(j,P){let L=l.get(j)||{key:j,area:P.area,recovery:P.recovery,firstMessage:P.message,firstSeenAt:P.at,occurrences:0,subjects:[],severity:P.severity,attempts:0,lastAttemptAt:0,recoveryStatus:null,recoveryDetail:null,asked:!1,explanation:null};L.occurrences+=1,L.message=P.message,L.lastSeenAt=P.at,L.degraded=P.degraded??L.degraded,P.subject&&!L.subjects.includes(P.subject)&&(L.subjects=[...L.subjects,P.subject].slice(-5));let A=L.severity!=="failed"&&L.occurrences>=P.escalateAfter;if(A&&(L.severity="failed"),l.set(j,L),l.size>20){let D=[...l.values()].sort((B,F)=>B.lastSeenAt-F.lastSeenAt)[0];l.delete(D.key)}return A}function T(){let j=s();for(let[P,N]of l)j-N.lastSeenAt>=9e5&&l.delete(P);for(let[P,N]of u){let L=N.filter(A=>j-A<6e5);L.length?u.set(P,L):u.delete(P)}}async function $(){let j=s();for(let P of l.values()){let N=P.recovery?e[P.recovery]:null;if(!(E||!N||P.severity!=="failed"||P.attempts>=3||j-P.lastAttemptAt<3e5)){P.attempts+=1,P.lastAttemptAt=j;try{if(t?.supports(P.recovery)){let L=await t.execute({action:P.recovery,fingerprint:P.key,context:{area:P.area,message:P.message,occurrences:P.occurrences,subjects:[...P.subjects]}});P.recoveryStatus=L.status,P.recoveryDetail=L.detail||null}else await N(),P.recoveryStatus="ran",P.recoveryDetail=null}catch(L){P.recoveryStatus="failed",P.recoveryDetail=Pwe(L)}}}}function O(j){let N=[...l.values()].filter(L=>L!==j&&Qh[j.area].dependsOn.includes(L.area)&&L.firstSeenAt<=j.lastSeenAt&&j.firstSeenAt-L.firstSeenAt<=12e4).sort((L,A)=>L.firstSeenAt-A.firstSeenAt)[0];return N?`${Qh[N.area].title}: ${N.firstMessage}`:null}function C(){return[...l.values()].sort((j,P)=>(P.severity==="failed")-(j.severity==="failed")||P.occurrences-j.occurrences||P.lastSeenAt-j.lastSeenAt)}function I(){let j=s(),P=c.filter(L=>j-L.at<6e5),N=C().filter(L=>L.severity==="failed");return{generated_at:new Date(j).toISOString(),state:N.length&&!["reconnecting","stopped"].includes(d)?"degraded":d,activity:{window_seconds:6e5/1e3,last_activity_at:new Date(f).toISOString(),logged:P.length,warnings:P.filter(L=>L.level==="warning").length,errors:P.filter(L=>L.level==="error").length,dropped:h},incidents:C().map(L=>({id:L.key,area:L.area,title:Qh[L.area].title,severity:L.severity,message:L.message,occurrences:L.occurrences,subjects:L.subjects,first_seen_at:new Date(L.firstSeenAt).toISOString(),last_seen_at:new Date(L.lastSeenAt).toISOString(),probable_cause:O(L),agent_reading:L.explanation||null,remedy:Qh[L.area].remedy,recovery:L.recovery?{action:L.recovery,status:L.recoveryStatus||"pending",attempts:L.attempts,detail:L.recoveryDetail}:null}))}}return{observe:w,drain:m,health:I,healthChecks:()=>vA(I()),start(){b||(E=!1,b=setInterval(()=>{m()},i),b.unref?.())},stop(){E=!0,clearInterval(b),b=void 0}}}function vA(e){return(e?.incidents||[]).slice(0,5).map(t=>({id:`insight_${t.area}`.slice(0,64),title:`${t.title} (observed)`,status:t.severity,detail:[`${t.message}`,`Seen ${t.occurrences} time(s) since ${t.first_seen_at}${t.subjects.length?` across ${t.subjects.join(", ")}`:""}.`,t.probable_cause?`Probable cause: ${t.probable_cause}`:null,t.agent_reading?`Agent reading: ${t.agent_reading}`:null,t.recovery?`Recovery ${t.recovery.action}: ${t.recovery.status}${t.recovery.detail?` - ${t.recovery.detail}`:""}.`:null].filter(Boolean).join(" ").slice(0,500),remedy:t.remedy})).filter((t,n,r)=>r.findIndex(o=>o.id===t.id)===n)}function Nwe(e){return e.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"<id>").replace(/\b[0-9a-f]{7,40}\b/gi,"<rev>").replace(/\d+(?:\.\d+)?/g,"<n>").replace(/\s+/g," ").trim().toLowerCase().slice(0,200)}function Pwe(e){return(e instanceof Error?e.message:String(e??"")).trim().slice(0,300)||"No detail was reported."}function _G(e){return`assessment:slow:${e}`}function Mwe(e){return(Number(e[1]||0)*60+Number(e[2]))*1e3}function Dwe(e){let t=[...e].sort((r,o)=>r-o),n=Math.floor(t.length/2);return t.length%2?t[n]:(t[n-1]+t[n])/2}function vG(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60);return n?`${n}m ${t%60}s`:`${t}s`}var Qh,Twe,Rwe,Owe,Cwe,Iwe,jwe,kG=V(()=>{M();Qh={backend:{title:"EngineerOS backend",dependsOn:[],remedy:"Check the network between this machine and EngineerOS, and that the backend is running."},coding_agent:{title:"Coding agent",dependsOn:[],remedy:"Run `engineeros-connector doctor` in this workspace; the agent reports what it needs."},assessment:{title:"Workspace assessment",dependsOn:["coding_agent","backend"],remedy:"Open the assessment in EngineerOS for the stage that stopped."},prompt:{title:"Connected prompt",dependsOn:["coding_agent","backend"],remedy:"Ask again in EngineerOS once the reported cause is fixed."},tooling:{title:"Tool registry",dependsOn:[],remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},goal_runner:{title:"Goal runner",dependsOn:["coding_agent"],remedy:"Read .engineeros/runs/<run-id>/activity.log in this workspace for the failing job."},workspace:{title:"Workspace repository",dependsOn:[],remedy:"Resolve the reported Git state in this workspace."},connector:{title:"Connector",dependsOn:["backend"],remedy:"Run `engineeros-connector doctor` in this workspace."}},Twe=[{match:/^Connecting .+ to /,state:"connecting"},{match:/^Connected and waiting for |^Reconnected after .+ offline|^Paired\. Connector .+ is online|^Reconnected existing workspace connector/,state:"connected"},{match:/^Connection unavailable|^WebSocket connection to .+ failed/,state:"reconnecting"},{match:/^This connector was revoked|^Connection rejected/,state:"stopped"}],Rwe=/failed \d+ time\(s\); retrying in \d+s/i,Owe=[{area:"backend",match:/^Connection unavailable|Retrying in \d+s|delivery failed/i},{area:"assessment",match:/is waiting for EngineerOS|Resuming session/i}],Cwe=/^\[(assessment|prompt):([^\]]+)\]\s*/,Iwe=/^(?:(\d+)m )?(\d+)s elapsed\b/,jwe=[{area:"connector",match:/^Connector stopping after an unhandled failure/,escalateAfter:1},{area:"coding_agent",match:/Agent session interrupted|is not authenticated|agent session|could not start the required agent|no output for/i},{area:"backend",match:/EngineerOS did not accept|is unreachable|answered \d{3}|^EngineerOS:|connector update|^Workspace assessment failed/i},{area:"assessment",match:/^Assessment (?:failure delivery|freshness|status)/i},{area:"prompt",match:/^Prompt (?:failure|progress) delivery/i},{area:"tooling",match:/^Tool (?:registry|authentication|inventory)/i,recovery:"refresh_tool_inventory"},{area:"goal_runner",match:/Runner setup failed|^Goal cleanup is pending|Goal Run .+ could not be integrated|^Supervisor cannot|^Goal cleanup will retry/i,recovery:"restart_goal_runner"},{area:"workspace",match:/Local Git|repository|commit/i}]});function AG({inspect:e,current:t,publish:n}={}){for(let[r,o]of Object.entries({inspect:e,current:t,publish:n}))if(typeof o!="function")throw new TypeError(`${r} must be a function.`);return{async run(){return{previous:structuredClone(t()),candidate:await e()}},async verify({result:r}){let o=await e();return xG(r?.candidate)!==xG(o)?{ok:!1,detail:"Tool inventory changed between inspection and verification."}:(await n(o),!0)},async rollback({result:r}){r?.previous!=null&&await n(r.previous)}}}function xG(e){return JSON.stringify(e,(t,n)=>t==="checked_at"?void 0:n)}function TG({restart:e,probe:t,wait:n=i=>new Promise(a=>setTimeout(a,i)),clock:r=Date.now,timeoutMs:o=15e3,pollMs:s=500}={}){for(let[i,a]of Object.entries({restart:e,probe:t,wait:n,clock:r}))if(typeof a!="function")throw new TypeError(`${i} must be a function.`);for(let[i,a]of Object.entries({timeoutMs:o,pollMs:s}))if(!Number.isSafeInteger(a)||a<1)throw new TypeError(`${i} must be a positive integer.`);return{async run(){return await e(),{restart_requested:!0}},async verify(){let i=zd(r())+o,a=null;for(;;){try{a=await t()}catch(l){a={live:!1,code:"RUNNER_PROBE_FAILED",detail:av(l)}}if(a?.live===!0)return!0;let c=zd(r());if(c>=i){let l=typeof a?.code=="string"?a.code:"RUNNER_NOT_LIVE",u=typeof a?.detail=="string"?a.detail:"No liveness detail was reported.";return{ok:!1,detail:`Goal runner did not become live before the verification deadline (${l}): ${u}`}}await n(Math.min(s,i-c))}},async rollback(){}}}function RG({stateFile:e,repairs:t,clock:n=Date.now,random:r=Math.random,maxAttempts:o=Lwe,baseDelayMs:s=Uwe,maxDelayMs:i=qwe,breakerFailures:a=Fwe,breakerResetMs:c=zwe,maxIncidents:l=Bwe,maxHistory:u=Hwe}={}){if(!e||typeof e!="string")throw new TypeError("A recovery state file is required.");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("A fixed recovery registry is required.");for(let[w,m]of Object.entries(t)){kA(w,"Recovery action");for(let _ of["run","verify","rollback"])if(typeof m?.[_]!="function")throw new TypeError(`Recovery ${w} must define ${_}().`)}for(let[w,m]of Object.entries({maxAttempts:o,baseDelayMs:s,maxDelayMs:i,breakerFailures:a,breakerResetMs:c,maxIncidents:l,maxHistory:u}))if(!Number.isSafeInteger(m)||m<(w.includes("Delay")||w.includes("Reset")?0:1))throw new TypeError(`${w} must be a bounded non-negative integer.`);if(s>i)throw new TypeError("baseDelayMs cannot exceed maxDelayMs.");let p,d=Promise.resolve(),f=w=>{let m=d.then(w,w);return d=m.catch(()=>{}),m};async function h(){return p||(p=qe(e).then(w=>Wwe(w))),p}async function g({action:w,fingerprint:m,context:_=null}={}){return f(async()=>{let S=t[w];if(!S)throw new Zh("RECOVERY_ACTION_NOT_APPROVED",`Recovery action ${kA(w,"Recovery action")} is not approved.`);let k=`${w}:${kA(m,"Failure fingerprint")}`,x=await h(),R=zd(n()),T=x.breakers[w]||Kwe();x.breakers[w]=T;let $=x.incidents[k]||Jwe(w,m);if(T.open_until>R)return bA("circuit_open",$,T.open_until,"Recovery circuit is open.");if($.attempts>=o)return bA("budget_exhausted",$,null,"Recovery retry budget is exhausted.");if($.next_attempt_at>R)return bA("cooldown",$,$.next_attempt_at,"Recovery is cooling down.");let O=$.attempts+1,C={...$,action:w,fingerprint:m,attempts:O,status:"running",last_attempt_at:R,next_attempt_at:R+v(O),detail:null};x.incidents[k]=C,y(x),await E(x);let I,j;try{I=await S.run({action:w,fingerprint:m,attempt:O,context:_})}catch(N){j=N}if(!j)try{let N=await S.verify({action:w,fingerprint:m,attempt:O,context:_,result:I});N!==!0&&N?.ok!==!0&&(j=new Error(Xwe(N)||"Independent verification did not pass."))}catch(N){j=N}if(!j)return C.status="verified",C.detail=null,C.verified_at=zd(n()),T.consecutive_failures=0,T.open_until=0,b(x,C),await E(x),SA(C);let P;try{await S.rollback({action:w,fingerprint:m,attempt:O,context:_,result:I,cause:j})}catch(N){P=N}return C.status=P?"rollback_failed":"rolled_back",C.detail=P?`${av(j)} Rollback failed: ${av(P)}`:av(j),T.consecutive_failures+=1,T.consecutive_failures>=a&&(T.open_until=zd(n())+c),b(x,C),await E(x),SA(C,T.open_until||null)})}function v(w){let m=Math.min(i,s*2**Math.max(0,w-1)),_=.75+Math.min(1,Math.max(0,Number(r())))*.5;return Math.min(i,Math.round(m*_))}function y(w){let m=Object.entries(w.incidents);m.length<=l||m.sort(([,_],[,S])=>_.last_attempt_at-S.last_attempt_at).slice(0,m.length-l).forEach(([_])=>delete w.incidents[_])}function b(w,m){w.history.push({action:m.action,fingerprint:m.fingerprint,attempt:m.attempts,status:m.status,at:zd(n()),detail:m.detail}),w.history=w.history.slice(-u)}async function E(w){await Rt(e,w)}return{execute:g,supports:w=>Object.hasOwn(t,w),async snapshot(){return structuredClone(await f(h))}}}function Wwe(e){if(e==null)return Vwe();if(e?.schema_version!==$G||!EG(e.incidents)||!EG(e.breakers)||!Array.isArray(e.history))throw new Zh("RECOVERY_STATE_INVALID","Recovery state is invalid; repair it before automatic recovery resumes.");return e}function Vwe(){return{schema_version:$G,incidents:{},breakers:{},history:[]}}function Jwe(e,t){return{action:e,fingerprint:t,attempts:0,status:"pending",last_attempt_at:0,next_attempt_at:0,verified_at:null,detail:null}}function Kwe(){return{consecutive_failures:0,open_until:0}}function bA(e,t,n,r){return{...SA(t,n),status:e,detail:r}}function SA(e,t=null){return{action:e.action,fingerprint:e.fingerprint,status:e.status,attempts:e.attempts,retry_at:t,detail:e.detail}}function kA(e,t){let n=typeof e=="string"?e.trim():"";if(!n||n.length>SG||/[\u0000-\u001f]/.test(n))throw new Zh("RECOVERY_INPUT_INVALID",`${t} must be between 1 and ${SG} printable characters.`);return n}function Xwe(e){return!e||typeof e!="object"?"":typeof e.detail=="string"?e.detail:""}function av(e){return((e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported.").slice(0,Gwe)}function zd(e){if(!Number.isSafeInteger(e)||e<0)throw new TypeError("clock must return a timestamp.");return e}function EG(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var $G,Lwe,Uwe,qwe,Fwe,zwe,Bwe,Hwe,SG,Gwe,Zh,OG=V(()=>{M();Pr();$G=1,Lwe=3,Uwe=3e5,qwe=36e5,Fwe=3,zwe=18e5,Bwe=100,Hwe=200,SG=200,Gwe=300,Zh=class extends Error{constructor(t,n,r){super(n,r),this.name="RecoveryExecutionError",this.code=t}}});function CG({clock:e=Date.now}={}){let t=e(),n=new Map,r=o=>{let s=n.get(o);return s||(s={kind:o,completed:0,failed:0,total_ms:0,longest_ms:0,last_at:null,input_tokens:0,output_tokens:0,total_tokens:0},n.set(o,s)),s};return{record(o,s,{durationMs:i=0,usage:a=null}={}){let c=r(o);s==="failed"?c.failed+=1:c.completed+=1;let l=Number.isFinite(i)?Math.max(0,i):0;c.total_ms+=l,c.longest_ms=Math.max(c.longest_ms,l),c.last_at=e();for(let u of Ywe(a))c.input_tokens+=u.input_tokens,c.output_tokens+=u.output_tokens,c.total_tokens+=u.total_tokens;return c},snapshot(){return{started_at:t,uptime_ms:e()-t,kinds:[...n.values()].map(o=>({...o}))}}}}function Ywe(e){return(Array.isArray(e)?e:[e]).filter(n=>n&&typeof n=="object").map(n=>{let r=xA(n.input_tokens),o=xA(n.output_tokens);return{input_tokens:r,output_tokens:o,total_tokens:xA(n.total_tokens)||r+o}}).filter(n=>n.total_tokens>0)}function xA(e){return Number.isFinite(e)&&e>0?Math.round(e):0}var IG=V(()=>{M()});import Qwe from"node:readline";function PG(){return jG}function Zwe(e,t,n={}){let[r,...o]=String(e).trim().split(/\s+/),s=NG.find(([i])=>i===r.toLowerCase());return s?s[2](t,o,n):`${r} is not a connector command. ${jG}`}function MG({ui:e,stdin:t=process.stdin,snapshot:n,actions:r,onInterrupt:o=()=>process.kill(process.pid,"SIGINT")}){if(!e.live||!t.isTTY||typeof t.setRawMode!="function")return null;let s="",i=!1,a,c=d=>{if(!a)return;clearTimeout(a.timer);let f=a.resolve;a=null,f(d)},l=()=>e.input(s.length?s:null),u=async d=>{i=!0,e.line("command","info",d);try{e.line("command","info",await Zwe(d,await n(),r))}catch(f){e.line("command","error",`${d} could not be answered: ${f instanceof Error?f.message:String(f)}`)}finally{i=!1}},p=(d,f={})=>{if(f.ctrl&&f.name==="s"){if(a)return;s&&(s="",l()),i||u("/agents");return}if(f.ctrl&&(f.name==="c"||f.name==="d")){if(s){s="",l();return}o();return}if(f.name==="return"||f.name==="enter"){let h=s.trim();if(s="",l(),!h)return;if(a){let g=h.toLowerCase()==="approve";c(g),e.line("command","info",g?"Local operation approved.":"Local operation declined.");return}if(i){e.line("command","info",`${h} was not read: the previous command is still being answered.`);return}u(h);return}if(f.name==="escape"){s="",l();return}if(f.name==="backspace"){s=s.slice(0,-1),l();return}f.ctrl||f.meta||!d||d.length!==1||d.codePointAt(0)<32||d.codePointAt(0)===127||(s+=d,l())};return Qwe.emitKeypressEvents(t),t.setRawMode(!0),t.resume(),t.unref?.(),t.on("keypress",p),{confirm(d){return a||i?Promise.resolve(!1):(s="",l(),e.line("command","warning",`${d}. Type approve to continue, or decline. Approval expires in 60 seconds.`),new Promise(f=>{a={resolve:f,timer:setTimeout(()=>c(!1),6e4)}}))},stop(){c(!1),t.off("keypress",p);try{t.setRawMode(!1)}catch{}s="",e.input(null)}}}function eye(){return["Connector commands. Ctrl+S opens /agents. Only /doctor, /cancel, /verbose, /workers and /update change anything; the rest only read.",...NG.map(([e,t])=>` ${e.padEnd(10)} ${t}`)].join(`
2727
2727
  `)}function tye(e,t,n){return t.length?"Run /doctor without arguments to refresh connector self-diagnostics.":n.selfDiagnostics()}function nye(e,[t],n){let r=e.work.prompts.map(s=>s.id);if(!t)return r.length?`Name the prompt to stop: /cancel <id>. Running: ${r.join(", ")}.`:"No prompt is running here, so there is nothing to cancel.";let o=r.filter(s=>s.startsWith(t));return o.length!==1?o.length?`${t} matches ${o.length} prompts (${o.join(", ")}); give more of the id.`:`No running prompt starts with ${t}.${r.length?` Running: ${r.join(", ")}.`:""}`:n.cancelPrompt(o[0])}function rye(e,[t],n){let r=String(t||"").toLowerCase();return r!=="on"&&r!=="off"?"Say /verbose on to print every agent step here, or /verbose off to show only the latest steps.":n.setVerbose(r==="on")}function DG(e){return e.worker_limit?`Workers: ${e.worker_limit} side by side, set here, for ${em}`:`Workers: automatic, ${e.automatic_worker_limit} side by side for this machine's CPU and memory, for ${em}`}function oye(e,t,n){let{positional:r,flags:o}=ru(["runtime",...t]),s=r[0]??"list";if(s==="list"&&r.length<=1&&!Object.keys(o).length)return["Agent runtimes (saved local selection):",...[{id:"default",agent_protocol:e.config.agent_protocol,agent_id:e.config.agent_id},...e.config.agent_runtimes??[]].map(c=>{let l=e.config.runtime_catalog?.find(u=>u.id===c.id);return` ${c.id}: ${c.enabled===!1?"disabled":"enabled"} - ${c.agent_id??c.agent_protocol??"codex"} - ${l?.status??"not refreshed"}`}),"Use /runtime add ID --agent ACP_ID, /runtime enable ID, /runtime disable ID or /runtime refresh. Use /runtime retry ID for one quota check (may consume provider usage); /runtime quota-group ID --quota-group LABEL marks shared allowance.","Changes are saved when idle; current work keeps its runtime and session."].join(`
2728
2728
  `);if(s==="refresh"&&r.length===1&&!Object.keys(o).length)return n.runtimeSelection({action:s});if(o.workspace||r.length!==2)throw new Error("Use /runtime add|enable|disable|remove ID in this connector's workspace.");if(s==="configure")throw new Error("Use the local runtime configure command with --model-metadata in another terminal.");let i={action:s,id:r[1],flags:o};return _l(i),n.runtimeSelection(i)}function sye(e,[t],n){return t===void 0?[DG(e),"Change it any time with /workers 1-8, or /workers auto."].join(`
2729
2729
  `):n.setWorkers(String(t).toLowerCase())}function iye(e,[t,n],r){return t?r.runtimeUpdate({action:t.toLowerCase(),policy:n?.toLowerCase()??null}):e.runtime_update?iu(e.runtime_update):"The connector update state could not be read; see the connector log."}function aye(e){let t=[...e.work.assessments.map(o=>({name:`assessment ${o.stage}`,phase:o.phase||"working",detail:o.message,startedAt:o.started_at,pid:o.pid,agent:o.agent||e.agent.name})),...e.work.prompts.map(o=>({name:`prompt ${o.id}`,phase:o.phase||"working",detail:o.message||o.purpose,startedAt:o.started_at,pid:o.pid,agent:o.agent||e.agent.name})),...LG(e).map(o=>({name:`goal ${o.runId.slice(0,8)}`,phase:o.activity?.phase||o.status,detail:o.activity?.message,startedAt:pye(o,e.now),pid:o.pid,agent:o.agent||e.agent.name}))],n=[`Coding-agent activity \xB7 ${e.agent.name} through ${e.agent.protocol} (${e.agent.version})`];if(!t.length)n.push("No coding-agent process is active. This connector is waiting for EngineerOS.");else{n.push(`${t.length} active process(es):`);for(let o of t){let s=[o.agent,o.pid?`pid ${o.pid}`:null,`${Qt(e.now-o.startedAt)} elapsed`].filter(Boolean).join(" \xB7 "),i=[o.phase,o.detail].filter(Boolean).join(": ");n.push(` ${o.name} \xB7 ${s}
@@ -2942,8 +2942,8 @@ process.stdout.write(readFileSync(answer, "utf8"));
2942
2942
  `),n}async function Dv(e,t,n,r,{verified:o=!1}={}){let s=XT(n),i=WSe(n,t);if(!s||!i||!await wm(n,t))return zT(e);let a=await zT(e),c=a.find(p=>p.key===s),l=kc(r()),u={key:s,playwright_version:jn(n.playwright_version,64),browser_revision:jn(n.browser_revision,64),directory:i,size_bytes:await _m(ln.join(t,i)),installed_at:c?.installed_at??l,last_verified_at:o?l:c?.last_verified_at??null,last_used_at:l};return B5(e,[u,...a.filter(p=>p.key!==s&&p.directory!==i)])}async function Lv(e,t,n=null){let r=n??await zT(t),o=[];for(let s of r)o.push({...s,size_bytes:await _m(ln.join(e,s.directory))});return{entries:o,consumptionBytes:await _m(e)}}async function I5(e,t,n,r){let o=XT(t);o&&(await P5(ln.dirname(e),{recursive:!0,mode:448}),await He(e,`${JSON.stringify({key:o,pid:process.pid,host:Xo.hostname(),token:r,updated_at:kc(n())})}
2943
2943
  `))}async function VSe(e,t,n,r=F5){let o=new Set,s=(await HT(e).catch(()=>[])).slice(0,VT*4);for(let i of s){if(!i.endsWith(".json"))continue;let a=ln.join(e,i),c,l;try{[c,l]=await Promise.all([Sc(a,"utf8").then(JSON.parse),Uv(a)])}catch{continue}let u=c?.host===Xo.hostname()&&await r(c?.pid),p=Math.max(0,t()-l.mtimeMs)<n;typeof c?.key=="string"&&(u||p)?o.add(c.key):!u&&!p&&await np(a,{force:!0})}return o}async function JSe({cacheRoot:e,registryPath:t,identity:n,now:r,quotaBytes:o,staleMs:s,protectedKeys:i=new Set}){let a=XT(n),c=await Lv(e,t),l=new Set(c.entries.filter(g=>g.key===a||i.has(g.key)).map(g=>g.directory)),u=c.entries.filter(g=>g.key!==a&&!i.has(g.key)&&!l.has(g.directory)).sort((g,v)=>Date.parse(g.last_used_at??0)-Date.parse(v.last_used_at??0)),p=u.at(-1)?.key??null,d=c.consumptionBytes,f=new Set;for(let g of u){if(g.key===p)continue;let v=Math.max(0,r()-Date.parse(g.last_used_at??g.installed_at??0)),y=d>o,b=Number.isFinite(v)&&v>=s;!y&&!b||(await np(ln.join(e,g.directory),{recursive:!0,force:!0}),d=Math.max(0,d-(g.size_bytes??0)),f.add(g.key))}let h=c.entries.filter(g=>!f.has(g.key));return await B5(t,h),{entries:h,consumptionBytes:f.size?await _m(e):d,removed:f.size}}function H5({workspace:e,persistentRoot:t,runtimeIdentity:n=async()=>null,provision:r=async()=>{throw new Error("Runtime provisioning is unavailable.")},verify:o=async()=>{throw new Error("Runtime verification is unavailable.")},onReport:s=()=>{},now:i=Date.now,lockOptions:a={},env:c=process.env,isIdle:l=async()=>!0,cacheQuotaBytes:u=kSe,cacheStaleMs:p=SSe,cacheLeaseStaleMs:d=A5}={}){if(!e)throw new Error("Runtime prerequisite manager requires a workspace.");let f=ISe(e,t),h=NSe(f,c),g=ln.join(f,"playwright-receipt-v1.json"),v=ln.join(f,"playwright-cache-registry-v1.json"),y=ln.join(f,"playwright-cache-leases"),b=N5(),E=ln.join(y,`${process.pid}-${b}.json`),w=ln.join(f,"playwright-reconcile.lock"),m=HSe(h,i),_=null,S=null,k=null,x=null,R=Math.max(1e3,Math.floor(d/3)),T=setInterval(()=>{x&&I5(E,x,i,b).catch(()=>{})},R);T.unref?.();let $=async P=>{P&&(x=P,await I5(E,P,i,b))},O=P=>(m=Object.freeze({...P,updated_at:kc(i())}),s(m),m),C=(P,N)=>P?[{id:"playwright",version:P.playwright_version??null,browser:"chromium",browser_revision:P.browser_revision??N?.browser_revision??null,browser_version:N?.browser_version??null}]:[];async function I(P,N){let L=i(),A;try{A=U5(P)}catch(_e){return O({...m,state:"incompatible",requirements:[],verification:{state:"failed",checks:[],detail:jn(_e.message,300)}})}_=A;let D=await FT({runtimeIdentity:n,now:i,workspace:e,env:c}),B=await n().catch(()=>null);if(A.profile===qv)return O({...m,profile:A.profile,state:A.mode==="disabled"?"disabled":"ready",inventory:D,requirements:[],installed_dependencies:C(B,null),verification:{state:"skipped",checks:[]},cache:{...m.cache,compatible:!1}});if(A.profile===M5){let _e=A.requirements.map(fe=>fe.id).filter(fe=>!_Se.has(fe));if(_e.length)return O({...m,profile:A.profile,state:"incompatible",inventory:D,requirements:Ko(A,!1,_e),installed_dependencies:C5(A,D),verification:{state:"failed",checks:[],detail:`Unsupported requirements: ${_e.map(fe=>jn(fe)).join(", ")}.`},cache:{...m.cache,compatible:!1}});let de=BSe(A,D),Ce=de.filter(fe=>fe.required).every(fe=>fe.state==="ready");return O({...m,profile:A.profile,state:Ce?"ready":"provisioning_required",inventory:D,requirements:de,installed_dependencies:C5(A,D),verification:{state:"skipped",checks:[]},cache:{...m.cache,compatible:!1}})}let F=A.requirements.map(_e=>_e.id).filter(_e=>!vSe.has(_e)),ee=await wm(B,h),W=await O5(g,h,B,A);if(F.length)return O({...m,profile:A.profile,state:"incompatible",inventory:D,requirements:Ko(A,!1,F),installed_dependencies:C(B,W),verification:{state:"failed",checks:[],detail:`Unsupported requirements: ${F.map(_e=>jn(_e)).join(", ")}.`},cache:{...m.cache,compatible:!1}});if(A.mode==="disabled")return O({...m,profile:A.profile,state:"disabled",inventory:D,requirements:Ko(A,!1),installed_dependencies:C(B,W),verification:{state:"skipped",checks:[]},cache:{...m.cache,compatible:!!W}});if(N==="gc"){if(await GSe(f),!await l())return O({...m,profile:A.profile,state:W?"ready":"provisioning_required",inventory:D,requirements:Ko(A,!!W),installed_dependencies:C(B,W),verification:W?.verification??{state:"pending",checks:[]},cache:{...m.cache,compatible:!!W,verified_at:W?.verified_at}});let _e=await R5(w,async()=>{let de=await n().catch(()=>null);de&&(await Dv(v,h,de,i),await $(de));let Ce=await VSe(y,i,Math.max(1e3,Number(d)||A5));return JSe({cacheRoot:h,registryPath:v,identity:de,now:i,quotaBytes:Math.max(0,Number(u)||0),staleMs:Math.max(0,Number(p)||0),protectedKeys:Ce})},a);return O({...m,profile:A.profile,state:W?"ready":"provisioning_required",inventory:D,requirements:Ko(A,!!W),installed_dependencies:C(B,W),verification:W?.verification??{state:"pending",checks:[]},cache:{...m.cache,compatible:!!W,verified_at:W?.verified_at,consumption_bytes:_e.consumptionBytes}})}if(W&&["refresh","provision"].includes(N)){let _e=await Dv(v,h,B,i);await $(B);let de=await Lv(h,v,_e);return O({...m,profile:A.profile,state:"ready",inventory:D,requirements:Ko(A,!0),installed_dependencies:C(B,W),verification:W.verification,cache:{...m.cache,compatible:!0,verified_at:W.verified_at,consumption_bytes:de.consumptionBytes}})}if(N==="refresh"){if(ee){let _e=await Dv(v,h,B,i);await $(B);let de=await Lv(h,v,_e);return O({...m,profile:A.profile,state:"provisioning_required",inventory:D,requirements:Ko(A,!1),installed_dependencies:C(B,W),verification:{state:"pending",checks:[]},cache:{...m.cache,compatible:!1,consumption_bytes:de.consumptionBytes}})}return O({...m,profile:A.profile,state:"provisioning_required",inventory:D,requirements:Ko(A,!1),installed_dependencies:C(B,W),verification:{state:"pending",checks:[]},cache:{...m.cache,compatible:!1}})}if(N==="validate"&&!ee){let _e=A.mode==="approval_required"?"approval_required":A.mode==="managed_image"?"partially_ready":"provisioning_required";return O({...m,profile:A.profile,state:_e,inventory:D,requirements:Ko(A,!1),installed_dependencies:[],verification:{state:"pending",checks:[]},cache:{...m.cache,compatible:!1}})}let z=A.mode==="approved_auto";if((N==="repair"||!ee)&&["provision","repair"].includes(N)&&!z){let _e=A.mode==="approval_required"?"approval_required":A.mode==="managed_image"?"partially_ready":"provisioning_required";return O({...m,profile:A.profile,state:_e,inventory:D,requirements:Ko(A,!1),installed_dependencies:C(B,W),verification:{state:"pending",checks:[]},cache:{...m.cache,compatible:!1}})}O({...m,profile:A.profile,state:"provisioning_in_progress",inventory:D,requirements:Ko(A,!1),installed_dependencies:C(B,W),verification:{state:"running",checks:[]},cache:{...m.cache,compatible:!1}});try{return await R5(w,async()=>{B=await n().catch(()=>null),ee=await wm(B,h),W=await O5(g,h,B,A);let _e,de=W&&Date.parse(W.verified_at)>=L;if(W&&N!=="validate"&&(N!=="repair"||de))_e=W.verification;else{let St={cacheRoot:h,requirements:A.requirements,allowPrivilegedOsDependencies:A.allow_privileged_os_dependencies,repair:N==="repair"};if(_e=ee&&N!=="repair"?await o(St):await r(St),B=await n(),!B||!await wm(B,h))throw new Error("Playwright Chromium did not produce a persistent executable in the connector-managed cache.");let xt=[...new Set(_e?.checks??[])];if(z5(A).some(Ze=>!xt.includes(Ze)))throw new Error("Synthetic browser verification did not cover every required evidence capability.");W={receipt_version:WT,profile:Hl,cache_key:JT(h),playwright_version:B.playwright_version,browser_revision:B.browser_revision,browser_version:_e.browser_version??null,verification:{state:"passed",checks:xt,checked_at:_e.checked_at??kc(i()),duration_ms:Math.max(0,Math.min(6e5,Number(_e.duration_ms)||0))},verified_at:kc(i())},await He(g,`${JSON.stringify(W,null,2)}
2944
2944
  `)}let Ce=await Dv(v,h,B,i,{verified:!0});await $(B);let fe=await Lv(h,v,Ce);return D=await FT({runtimeIdentity:n,now:i,workspace:e,env:c}),O({...m,state:"ready",inventory:D,requirements:Ko(A,!0),installed_dependencies:C(B,W),verification:W.verification,cache:{...m.cache,compatible:!0,verified_at:W.verified_at,consumption_bytes:fe.consumptionBytes}})},a)}catch(_e){let de=_e?.code==="PRIVILEGED_OS_DEPENDENCIES_REQUIRED";return O({...m,profile:A.profile,state:de?"approval_required":"provisioning_failed",inventory:await FT({runtimeIdentity:n,now:i,workspace:e,env:c}),requirements:Ko(A,!1),installed_dependencies:C(await n().catch(()=>null),null),verification:{state:"failed",checks:[],detail:jn(_e?.message??_e,300)},cache:{...m.cache,compatible:!1}})}}function j(P,{action:N="provision"}={}){if(!D5.has(N))return Promise.resolve(O({...m,state:"incompatible",verification:{state:"failed",checks:[],detail:`Unsupported runtime prerequisite action ${jn(N)}.`}}));let L=`${N}:${JSON.stringify(P??null)}`;if(k?.key===L)return k.promise;let D=(S?S.then(()=>I(P,N)):I(P,N)).finally(()=>{S===D&&(S=null),k?.promise===D&&(k=null)});return S=D,k={key:L,promise:D},D}return Object.freeze({cacheRoot:h,reconcile:j,report:()=>m,latestPlan:()=>_,close:async()=>{clearInterval(T),x=null,await np(E,{force:!0})}})}function YT(){return{schema_version:ym,profile:qv,mode:"detect_only",requirements:[],policy:{allow_privileged_os_dependencies:!1}}}var ym,Hl,M5,qv,GT,wSe,D5,ySe,_Se,vSe,WT,L5,VT,bSe,kSe,SSe,A5,xSe,ESe,$Se,ASe,TSe,RSe,OSe,CSe,G5=V(()=>{M();qT();An();ym=1,Hl="bug-hunter-browser-testing",M5="agentic-software-factory",qv="generic",GT="prerequisite.reconcile",wSe=new Set(["detect_only","recommend","approval_required","approved_auto","managed_image","disabled"]),D5=new Set(["refresh","validate","provision","repair","gc"]),ySe=Object.freeze(["playwright","browser.chromium","browser.screenshot","browser.trace","browser.video"]),_Se=new Set(["node","git","python","docker"]),vSe=new Set(ySe),WT=1,L5=1,VT=32,bSe=2e4,kSe=5*1024*1024*1024,SSe=720*60*6e4,A5=5*6e4,xSe=12e4,ESe=15*6e4,$Se=4,ASe=80,TSe=2e3,RSe=gSe(cSe),OSe=Object.freeze([["npm","npm",["--version"]],["pnpm","pnpm",["--version"]],["python",process.platform==="win32"?"python":"python3",["--version"]],["uv","uv",["--version"]],["git","git",["--version"]],["docker","docker",["--version"]],["github-cli","gh",["--version"]],["gitlab-cli","glab",["--version"]]]),CSe=Object.freeze([["apt","apt",["--version"]],["dnf","dnf",["--version"]],["yum","yum",["--version"]],["apk","apk",["--version"]],["homebrew","brew",["--version"]],["winget","winget",["--version"]]])});function KSe(e){return e==null?"unknown":e>=90?"healthy":e>=50?"degraded":"unhealthy"}function XSe(e,{collectionError:t=null}={}){if(t)return Object.freeze({score:0,band:"unhealthy",reasons:Object.freeze([`collection_failed: ${W5(t)}`])});if(!e||typeof e!="object")return Object.freeze({score:null,band:"unknown",reasons:Object.freeze(["no_report"])});let n=typeof e.status=="string"?e.status:"unknown",r=Array.isArray(e.checks)?e.checks:[],o=[],s;if(r.length){let a=0;for(let c of r){let l=typeof c?.status=="string"?c.status:"unknown";a+=QT[l]??0,l!=="ok"&&o.push(`${c?.name??c?.id??"unknown_check"}: ${l}`)}s=Math.round(a/r.length)}else s=QT[n]??0;let i=QT[n]??0;return s=Math.min(s,i),n!=="ok"&&o.push(`report: ${n}`),Object.freeze({score:s,band:KSe(s),reasons:Object.freeze([...new Set(o)])})}function W5(e){return(e instanceof Error?e.message:String(e??"")).trim()||"No detail was reported."}function V5({collect:e,intervalMs:t=3e5,isBusy:n=()=>!1,onError:r=()=>{},setIntervalImpl:o=setInterval,clearIntervalImpl:s=clearInterval}={}){if(typeof e!="function")throw new TypeError("Self-diagnostics collect must be a function.");if(!Number.isFinite(t)||t<=0)throw new TypeError("Self-diagnostics intervalMs must be positive.");let i=null,a=!1,c=null,l=null,u=null,p=null,d=0,f=0,h=[];function g(m,_){l?.status!==m.status&&(h.push({at:m.checked_at??new Date().toISOString(),from:l?.status??"unknown",to:m.status,reason:_}),h.length>20&&h.splice(0,h.length-20))}function v({force:m=!1,reason:_="manual"}={}){if(a)return Promise.resolve(null);if(c)return c;let k=(async()=>{if(!m&&await n())return f+=1,null;try{let x=await e({reason:_});if(!x||typeof x!="object"||typeof x.status!="string")throw new TypeError("Self-diagnostics collect returned no diagnostic report.");return g(x,_),l=x,u=_,p=null,d=0,x}catch(x){throw u=_,p=W5(x),d+=1,r(x,w()),x}})().finally(()=>{c===k&&(c=null)});return c=k,k}function y(m){v({reason:m}).catch(()=>{})}function b({immediate:m=!0}={}){i||(a=!1,m&&y("startup"),i=o(()=>y("scheduled"),t),i?.unref?.())}function E(){a=!0,i&&s(i),i=null}function w(){let m=XSe(l,{collectionError:p});return{state:a?"stopped":c?"checking":l?.status??(p?"failed":"unknown"),running:!!c,last_checked_at:l?.checked_at??null,last_reason:u,last_error:p,consecutive_failures:d,deferred_runs:f,health:m,transitions:h.map(_=>({..._})),report:l}}return Object.freeze({refresh:v,snapshot:w,start:b,stop:E})}var QT,J5=V(()=>{M();QT=Object.freeze({ok:100,warning:50,failed:0})});var Nxe={};import{randomUUID as YSe}from"node:crypto";import QSe from"node:os";import ar from"node:path";function xc(e){return gR+=1,e.finally(()=>{gR-=1})}function dp({exitCode:e=0}={}){if(Wl)return kR.stop({exitCode:e}),Wl;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Wl=oxe({exitCode:e}).finally(()=>clearTimeout(t)),Wl}async function oxe({exitCode:e}){let{exitCode:t,errors:n}=await kR.stop({exitCode:e});for(let{id:r,detail:o}of n)console.error(`Connector runtime ${r} did not stop cleanly: ${o}`);if(t&&t!==Sp){let r;await Promise.race([(async()=>{await xa?.drain(),await hp(U,U.workspace)})().catch(()=>{}),new Promise(o=>{r=setTimeout(o,1e4)})]).finally(()=>clearTimeout(r))}process.exit(t)}async function ixe(){if(U.hunt_host)return;Y5??=bE(U.workspace);let{jobs:e}=await Y5(),t=new Set,n=e.filter(r=>r.status!=="queued"&&Xv.includes(r.status)).length;for(let r of e){if(!Xv.includes(r.status))continue;t.add(r.runId),cR.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;Gn.status(`goal:${r.runId}`,r.activity?.message||o,axe(r),{agent:r.status!=="queued",link:Jl&&`${Jl}/goals`,phase:o}),Gn.step(`goal:${r.runId}`,r.activity?.message)}for(let r of cR)t.has(r)||(cR.delete(r),Gn.clearStatus(`goal:${r}`))}function axe(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function jo({ignoreBugHunt:e=!1}={}){if(sn||va||Zn.size>0||Rr.size>0||Ws>0||(Gl?.active??0)>0||(Em?.active??0)>0||(pp?.activeCount??0)>0||(up?.active??0)>0||!e&&(Yl?.active??0)>0)return!1;try{let{jobs:t}=await ca(U.workspace);return!sn&&!va&&!t.some(n=>Xv.includes(n.status))}catch{return!1}}async function lxe(){if(vm)return vm;if(Date.now()-t3<3e4)return;t3=Date.now();let e=[...Io],t=[...new Set(e.map(n=>n.assessment_id))].slice(0,32);if(t.length)return vm=(async()=>{try{let n=await ws({type:"workspace.assessment.queue_state",assessment_ids:t}),r=NH(Io,e,n?.assessment_states);r&&console.log(`Connector update: retired ${r} queued stage offers for server-closed assessments; saved checkpoints and running work are retained.`)}catch{console.error("Connector update: queued assessment state could not be confirmed; keeping queued work and deferring the switch.")}})().finally(()=>{vm=null}),vm}function Ci(){return up??=k6({getConfig:()=>U,jobStore:lp,canRun:()=>jo()}),Yl??=HW({getConfig:()=>({...U,tool_inventory:nt.tool_inventory}),jobStore:lp,recordedSignIns:fR,isIdle:()=>jo({ignoreBugHunt:!0}),canRun:async e=>{if(!await jo({ignoreBugHunt:!0}))return!1;let t=e.assignment;return t.kind!=="production_check"&&vn?.state!=="ready"?!1:t.surface?.app_surface==="webdriver"||nt.bug_hunt_browser===!0},activity:{status:Gn.status,step:xR,agents:Gn.agents,finish:Gn.finish}}),Em??=N6({getConfig:()=>U,jobStore:lp,canRun:()=>jo()}),{scheduledTests:up,bugHunts:Yl,baselines:Em}}async function dxe(e){let t=Ci(),n=[];for(let r of e.jobs??[])await lp.get(r.kind,r.id)&&n.push(r);await Promise.all([t.bugHunts.sync(n),t.scheduledTests.sync(n),t.baselines.sync(n)]);for(let r of e.assignments??[]){try{UT(r)}catch(s){console.error(`Rejecting unauthorized connector work ${r.type??"unknown"}: ${s.message}`);continue}let o=`${r.type}:${r.grant_id??r.session_id??r.run_id}`;yR.has(o)||Kv.set(o,r)}pxe()}function pxe(){dR||sn||(dR=(async()=>{let e=Ci();for(;Kv.size&&!sn;){let[t,n]=Kv.entries().next().value;Kv.delete(t),yR.add(t);try{if(UT(n),n.type===hv)await e.scheduledTests.configure(n);else if(n.type===OT)await e.bugHunts.handle(n);else if(n.type===fv)await e.scheduledTests.handle(n);else if(n.type===DA)await e.baselines.handle(n);else throw new Error(`Unsupported cached work ${n.type}. Update the connector before accepting it.`)}catch(r){console.error(`Caching connector work: ${r.message}`)}finally{yR.delete(t)}}})().finally(()=>{dR=null}))}async function _3(){if(!(!U.connector_id||!U.token||sn))return km||(km=(async()=>{let e=Ci();await Promise.all([e.bugHunts.start(),e.scheduledTests.start(),e.baselines.start()]),(await lp.list({kind:"bug_hunt",status:["queued","running"]})).some(n=>Date.parse(n.execution_lease.expires_at)>Date.now())&&(ER(),nb()),$xe()})().catch(e=>{throw km=null,e}),km)}async function fxe(){let e=await ca(U.workspace).catch(()=>({service:null,jobs:[]}));return{version:Ss,now:Date.now(),workspace:U.workspace,config_path:_r(U.workspace),config:U,agent:Ct,automatic_worker_limit:Pu(),worker_limit:Qi(U.worker_limit),connection:{state:hxe(),server_url:U.server_url,last_error:Yo||null},work:{assessments:[...Zn.values()].map(t=>({stage:t.stage,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:Ct.name})),prompts:[...Rr.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:Ct.name})),integrations:Ws},runner:e,runtime_update:ba.report(),diagnostics:fp?.snapshot()??null,capability_readiness:wG(U,Ct,nt.tool_inventory,{browserRuntime:Ql.report()}),health:xa?.health()??null,activity:$m.snapshot()}}function hxe(){return sn||Co?"stopped":pn?.readyState===WebSocket.OPEN?"connected":"connecting"}async function v3(){if(sn||Co)return;mR?.(),console.log(`Connecting ${U.name} to ${U.server_url}`),Co=!1,Yo=void 0;let e=new WebSocket(U.server_url),t=!1,n=null,r=y=>JSON.stringify({runtimes:y.agent_runtimes,profiles:y.execution_profiles});pn=e;let o=VM(e,U.server_url,{onTimeout:y=>{pn===e&&(Yo=y,console.error(y),Fv())}});g3=o;let s,i=()=>{s?.stop(),s=JM(e,{onTimeout:y=>{pn!==e||sn||Wl||(Yo=y,console.error(y),Fv())}}),mR=s.stop};e.addEventListener("open",()=>{if(pn!==e){e.close();return}try{if(n=mo.type==="authenticate"&&vn?.state==="ready"&&mo.capabilities?.agent_session?.status==="authenticated"?r(mo.capabilities):null,qM(pn,e,mo))return;throw new Error("The WebSocket was not open when authentication started.")}catch(y){Yo=On(y),console.error(`Could not authenticate the WebSocket connection: ${Yo}`);try{e.close()}catch{}Fv()}});let a=async y=>{Zv||wxe(y)},c=async y=>{if(U.hunt_host)throw new Error("Pair a repository connector before dispatching delivery tasks.");await HU(U.workspace,U.connector_id,y),await la(U.workspace)},l={"connection.pong":async y=>{s?.receive(y)},paired:async y=>{o();let b;try{Mq(gs,y)}catch(w){sn=!0,Co=!0,b=w}let E=Vl?.connector_id===y.connector.id;if(U=TO(b&&E?Vl:U,Vl,y.connector.id,y.token),gs?U.auto_pairing_pending=!!b:delete U.auto_pairing_pending,await bn(U),b){console.error(b.message),e.close();return}if(y.connector?.capabilities?.http_updates!==!0||y.websocket_probe!==1){sn=!0,Co=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates and WebSocket round-trip probes, then start this connector again."),e.close();return}if(gs)try{Ct=await di(U,U.workspace),U={...U,execution_profiles:Ct.executionProfiles,runtime_catalog:Ct.runtimeCatalog},await bn(U);let w=mc(U,Ct,nt.tool_inventory);Object.assign(nt,{runtime_quota_groups:w.runtime_quota_groups,multi_runtime_contract:w.multi_runtime_contract,default_runtime_id:w.default_runtime_id,agent_runtimes:w.agent_runtimes,execution_profiles:w.execution_profiles,goal_plan_review:w.goal_plan_review})}catch(w){sn=!0,Co=!0,console.error(`Pairing saved; no selected runtime completed tool setup: ${w.message}`),e.close();return}if(mo={type:"authenticate",connector_id:U.connector_id,token:U.token,capabilities:nt},console.log(E?`Reconnected existing workspace connector ${U.connector_id}; assessment history is preserved.`:`Paired. Connector ${U.connector_id} is online.`),gs){e.close(1e3,"Auto runtime setup completed");return}i(),i3(y)},authenticated:async y=>{if(y.connector?.capabilities?.http_updates!==!0||y.websocket_probe!==1){sn=!0,Co=!0,o(),console.error("Update the EngineerOS backend to support connector HTTP updates and WebSocket round-trip probes before reconnecting."),e.close();return}o();let b=U.hunt_host?"Bug Hunter sessions":"EngineerOS runs";if(console.log(cp?`Reconnected after ${Qt(Date.now()-cp)} offline; waiting for ${b}.`:`Connected and waiting for ${b}.`),cp=void 0,t=vn?.state==="ready"&&n!==null&&n===r(nt),(gs||Object.hasOwn(U,"auto_pairing_pending"))&&vn?.state==="ready"&&!t){e.close(1e3,"Runtime readiness changed");return}i(),await k3(U).catch(E=>{console.error(`Saved connector diagnostics could not be retried: ${E instanceof Error?E.message:String(E)}`)}),i3(y)},"connector.update":async y=>{gxe(e,y)},"connector.disconnect":async y=>{console.log(y.message),await dp()},"connector.revoked":async y=>{sn=!0,console.error("This connector was revoked in EngineerOS."),e.close()},"run.error":async y=>{console.error(`EngineerOS: ${y.message}`)},"connection.error":async y=>{Co=!0,console.error(`EngineerOS: ${y.message}`)}},u={"agent_runtimes.list":async y=>{let b=_a.list();b.busy=ip||!await jo(),await ws({type:"agent_runtimes.result",command_id:y.command_id,state:b})},"agent_runtimes.change":async y=>{try{let b=_a.request(y.command_id,y.change);await ws({type:"agent_runtimes.result",command_id:y.command_id,state:b})}catch(b){console.error(`Runtime selection rejected: ${redact(b.message)}`),await ws({type:"agent_runtimes.result",command_id:y.command_id,error:"Runtime selection was rejected. Reload the runtime list and check the connector terminal."})}},"agent_runtimes.refresh":async()=>{sp=!0,$R()},"provider.login":a,"provider.logout":a,"workspace.refresh":async y=>{Xl(y.assessment_id??null)},"workers.update":async y=>{try{console.log(`EngineerOS changed the workers. ${await b3(y.worker_limit??"auto")}`)}catch(b){console.error(`Workers were not changed: ${b.message}`)}},"logging.update":async y=>{SR(y.activity_log_enabled===!0)}},p={"tools.update":async y=>{let b=y.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(y.action);b&&(ka=!1,nt.bug_hunt_browser=!1,cr());try{nt.tool_inventory=await Ug(U.workspace,y,void 0,{confirmLocal:E=>Am?.confirm(E)??!1,log:eb}),b&&ER(),nt.bug_hunt_browser=Bh(nt.tool_inventory)&&ka,e.send(JSON.stringify({type:"tools.updated",command_id:y.command_id,inventory:nt.tool_inventory})),cr(),console.log(`Tool registry updated: ${y.action} ${y.provider_id}.`)}catch(E){let w=E instanceof Error?E.message.slice(0,300):"The local connector rejected the tool registry update.";e.send(JSON.stringify({type:"tools.updated",command_id:y.command_id,error:w})),console.error(`Tool registry update rejected: ${w}`)}},"tools.auth":async y=>{try{let b=await Fg(U.workspace,y,{onStatus:async()=>{nt.tool_inventory=await Lr(U.workspace),cr()}});nt.tool_inventory=b.inventory,b.completion&&b.completion.catch(E=>console.error(`Tool authentication status: ${E instanceof Error?E.message.slice(0,300):"Local status update failed."}`)),e.send(JSON.stringify({type:"tools.updated",command_id:y.command_id,inventory:nt.tool_inventory})),cr(),console.log(`Tool authentication updated: ${y.action} ${y.provider_id}.`)}catch(b){let E=b instanceof Error?b.message.slice(0,300):"The local connector rejected the tool authentication request.";e.send(JSON.stringify({type:"tools.updated",command_id:y.command_id,error:E})),console.error(`Tool authentication rejected: ${E}`)}},[GT]:async y=>{let b=E=>e.send(JSON.stringify({type:"prerequisite.reconciled",command_id:y.command_id,execution_id:y.execution_id,...E}));try{let E=await q5(y,{ledger:cxe}),w=E.plan??Ql.latestPlan()??YT(),m=await Ql.reconcile(w,{action:E.action});b({report:m})}catch(E){let w=E instanceof Error?E.message.slice(0,300):"The local connector rejected the prerequisite reconciliation request.";b({error:w}),console.error(`Runtime prerequisite reconciliation rejected: ${w}`)}}},d={"workspace.assessment":async y=>{let b=`${y.assessment_id}:${y.stage}`;Kp(Io,Zn.get(b),y,{activeWorkers:Zn.values()})==="deferred"&&console.log(`Assessment stage ${y.stage} is already running here; EngineerOS will be answered when it finishes.`),Sa()},"prompt.execute":async y=>{let b=Rr.get(y.prompt_id);if(b)A3(y)>b.executionRevision&&await Rxe(b,y);else{let E=await Kl.offer(y,()=>{Rr.has(y.prompt_id)||$3(y)});E?.status==="execution_unknown"&&vR(y.prompt_id,{kind:"status",message:E.reason})}},"prompt.cancel":async y=>{let b=Kl.cancel(y.prompt_id),E=Rr.get(y.prompt_id);E&&await AR(E),await b},"agent.warm":async y=>{kxe(y)}},f={"run.available":async y=>{if(U.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let b=await h3.dispatch(y);b.blocked?console.error(b.message):console.log(`Goal ${y.run_id} queued for the independent runner. Logs: ${ar.join(U.workspace,".engineeros","runs",y.run_id,"activity.log")}`)}catch(b){console.error(`Goal dispatch failed: ${On(b)}`)}},"delivery.task.start":c,"delivery.task.cancel":c,"goal.cleanup":async y=>{try{await dq(U.workspace),await la(U.workspace)}catch(b){console.error(`Goal cleanup is pending: ${b.message}`)}},"run.accepted":async y=>{Ixe(y)},"run.cancelled":async y=>{await vE(U.workspace,y.run_id)}},h={"test_environment.health_check":async y=>{ai(y).then(b=>{e.send(JSON.stringify({type:"test_environment.health_result",command_id:y.command_id,result:b})),console.log(`Test environment health: ${b.status}${b.message?` (${b.message})`:""}.`)}).catch(b=>console.error(`Test environment health was not reported: ${b.message}`))},[uL]:async y=>{Gl??=XS({getConfig:()=>U,onTestsCommitted:()=>Xl()}),xc(Gl.handle(y))},[GS]:async y=>{Gl??=XS({getConfig:()=>U,onTestsCommitted:()=>Xl()}),await Gl.cancel(y)},[OT]:async y=>{xc(Ci().bugHunts.handle(y)).catch(b=>console.error(`Bug Hunter assignment: ${b.message}`))},"bug_hunt.grant":async y=>{xc(Ci().bugHunts.configure(y)).catch(b=>console.error(`Bug Hunter settings: ${b.message}`))},[CT]:async y=>{Yl?.stop(y)},[fv]:async y=>{xc(Ci().scheduledTests.handle(y)).catch(b=>console.error(`Scheduled test assignment: ${b.message}`))},[hv]:async y=>{xc(Ci().scheduledTests.configure(y)).catch(b=>console.error(`Scheduled test settings: ${b.message}`))},[DA]:async y=>{xc(Ci().baselines.handle(y)).catch(b=>console.error(`Baseline assignment: ${b.message}`))},[LA]:async y=>{await Ci().baselines.cancel(y)},[D6]:async y=>{Q5??=L6({getConfig:()=>U,isIdle:()=>jo(),agentTurn:Hx}),xc(Q5.handle(y))}},g={[pH]:async y=>{xc(rxe(y).then(b=>(b.error&&console.error(`${y.provider} ${y.operation} failed: ${b.error}`),hH(U,b))).catch(b=>console.error(`An integration answer was not delivered: ${b.message}`)))}},v=f5({beforeHandle:y=>{if(!gs&&!Object.hasOwn(U,"auto_pairing_pending")||!sn&&!Co&&U.auto_pairing_pending!==!0&&t&&vn?.state==="ready")return;let b=new Set(["connection.pong","paired","authenticated","connector.disconnect","connector.revoked","run.error","connection.error","prompt.cancel","run.cancelled","run.accepted","delivery.task.cancel","goal.cleanup",GS,CT,LA]);if(!(!sn&&!Co&&U.auto_pairing_pending!==!0&&mo.type==="authenticate"&&["provider.login","provider.logout","agent_runtimes.refresh","agent_runtimes.list","agent_runtimes.change"].includes(y))&&!b.has(y))throw new Error("Auto pairing has not completed acknowledgement, runtime setup and session readiness. Work was not started; finish pairing before dispatching assignments.")},handlers:[...Object.entries(l),...Object.entries(u),...Object.entries(p),...Object.entries(d),...Object.entries(f),...Object.entries(h),...Object.entries(g)],onMalformed:()=>console.error("Ignored a malformed EngineerOS message frame (invalid JSON)."),onFailure:(y,b)=>{console.error(`EngineerOS ${y.slice(0,80)} message failed: ${On(b)}`)},onUnknown:y=>{console.warn(`Unknown EngineerOS message type ${y}; connector ${Ss}. Update the connector and backend to compatible versions.`)}});e.addEventListener("message",y=>{pn===e&&v.handleFrame(y.data)}),e.addEventListener("close",y=>{if(o(),s?.stop(),pn!==e||Wl)return;let b=zM(y);if(!b.retry||Co||sn){console.error(b.message),b.retry&&Co&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),dp();return}Yo=Yo?`${b.message} ${Yo}`:b.message,Fv()}),e.addEventListener("error",y=>{pn===e&&(Yo=UM(y),console.error(`WebSocket connection to ${U.server_url} failed: ${Yo}`))})}async function gxe(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=ba.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 ba.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 wxe(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";Zv=!0,console.log(`Starting interactive ${Ct.name} provider ${n}.`);try{await(n==="logout"?WM:GM)(Ct,U.workspace),Ct=await di(U,U.workspace),U={...U,execution_profiles:Ct.executionProfiles??null,runtime_catalog:Ct.runtimeCatalog??null},await bn(U),vn=null,nt={...mc(U,Ct,nt.tool_inventory,{secretNames:await y3()}),runtime_prerequisites:Ql.report(),bug_hunt_browser:ka},mo.capabilities=nt,pn.readyState===WebSocket.OPEN&&(pn.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:nt.agent_session})),pn.close(1e3,`Provider ${n} completed`)),console.log(`${Ct.name} provider ${n} completed.`)}catch(r){let o=On(r).slice(0,500);pn.readyState===WebSocket.OPEN&&pn.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{Zv=!1}}function Fv(){if(sn||Co||Gv)return;let e=FM(Wv),t=Yo?` Last error: ${Yo}`:"",n=cp?` Offline for ${Qt(Date.now()-cp)}.`:"";cp??=Date.now(),console.error(`Connection unavailable.${t}${n} Retrying in ${Math.round(e/1e3)}s.`),Gv=setTimeout(()=>{Gv=void 0,v3()},e),Wv=Math.min(3e4,Wv*2)}async function Xl(e=null){if(U.hunt_host||(Jv=!0,e&&(aR=e),va||sn||pn.readyState!==WebSocket.OPEN))return;Jv=!1,va=!0;let t=aR;aR=null;let n=!1,r=Gf(ws),o=s=>{console.log(s),t&&(r.update({type:"workspace.assessment.progress",assessment_id:t,stage:"inventory",progress_percent:0,message:s}),r.flush().catch(()=>{}).then(()=>r.flush()).catch(()=>{}))};console.log("Inspecting the workspace without executing its code.");try{let s=await KD(U.workspace,{onProgress:o});o("Comparing Git changes with the last reported revision");let i=await JD(U.workspace,U.last_head_reported??U.last_snapshot_head,s.head_revision).catch(()=>null);i&&(s.changed_since=i),o("Uploading sanitized inventory; waiting for EngineerOS to accept it");let a=await fetch(pr(U.server_url,U.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:JSON.stringify(s)});if(!a.ok)throw new Error(await Bu(a,"the workspace"));let c=await a.json();n=!0;let l=c.source_revision;U={...U,onboarding_pending:!1,last_snapshot_head:s.head_revision??U.last_snapshot_head,last_head_reported:s.head_revision??U.last_head_reported,last_head_branch:s.head_revision?s.branch??null:U.last_head_branch},await bn(U),console.log(`Inventoried ${s.total_file_count.toLocaleString()} safe file(s).`),console.log(`Uploaded ${s.evidence_file_count.toLocaleString()} prioritized source file(s).`),console.log("Ignored, sensitive and generated files excluded; total not counted."),s.omitted_evidence_file_count>0&&console.log(`${s.omitted_evidence_file_count.toLocaleString()} additional file(s) remain available to the connected Agent locally.`),console.log(`Workspace inventory registered as ${c.workspace_kind}. Start the baseline assessment in EngineerOS to continue.`);let{encoded:u,stats:p}=await OA({workspace:U.workspace,connectorId:U.connector_id,snapshot:s,refresh:yu,buildMap:(d,f)=>uv(U.workspace,d,{head:f.head_revision,branch:f.branch}),log:d=>console.error(d)});if(u&&l){let d=await fetch(CO(U.server_url,U.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:JSON.stringify({source_revision:l,quality_map_base64:u.base64})});d.ok?await dv(U.workspace,U.connector_id,u.map).catch(()=>{}):console.error(await Bu(d,"the workspace quality map"))}p&&console.log(`Built the local context index: ${p.total_files.toLocaleString()} file(s) ready for assignment context.`)}catch(s){t&&!n&&ws({type:"workspace.assessment.failed",assessment_id:t,stage:"inventory",message:"Workspace inventory could not be refreshed. Check the connector terminal for the failed step, resolve it, then retry the assessment."}).catch(()=>{}),console.error(`Workspace assessment failed: ${On(s)}`)}finally{va=!1,Jv&&!sn&&pn.readyState===WebSocket.OPEN&&Xl()}}async function _xe({current:e,previous:t}){if(va||pn?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=ar.resolve(U.workspace),r=async()=>{U={...U,last_head_reported:e.head,last_head_branch:e.branch??null},await bn(U)},o=await RA(U.workspace,U.connector_id),s=async()=>{if(await Xl(),U.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let i,a=async()=>(i??=yu(U.workspace,U.connector_id),(await i).index),c=null,l=await _6({previous:{head:t.head,branch:t.branch??null},current:e,compare:(f,h)=>DS(U.workspace,f,h),inventoryDelta:async f=>{let h=await a();return HC(n,Object.entries(h.files).map(([g,v])=>({path:g,size:v.size})),f)},mapDelta:async()=>{let f=await a();return c=await uv(U.workspace,f,{head:e.head,branch:e.branch}),TA(o,c)},contentHead:(await hw(n).catch(()=>null))?.content_head_revision??null});if(l.status==="snapshot")return s();let u=JSON.stringify(l.report);if(Buffer.byteLength(u)>yxe)return s();let p=await fetch(IO(U.server_url,U.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:u});if(!p.ok)throw new Error(await Bu(p,"the new commit"));let d=await p.json();if(d.needs_snapshot)return s();if(d.accepted!==!0)throw new Error("EngineerOS did not acknowledge the new commit.");await r(),c&&await dv(U.workspace,U.connector_id,c).catch(()=>{}),console.log(`Reported ${l.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 vxe(){U.hunt_host||U.onboarding_pending||va||pn?.readyState!==WebSocket.OPEN||(r3??=y6({readHead:()=>w6(U.workspace),getLastReported:()=>({head:U.last_head_reported??U.last_snapshot_head,branch:U.last_head_branch}),onChange:_xe,onError:e=>{e.message!==o3&&(o3=e.message,console.error(`The new commit could not be reported yet: ${On(e)}`))}}),r3.poll().catch(()=>{}))}async function kxe(e){if(U.hunt_host)return;let t=lo(U,e.execution_profile??{}),n=typeof e.session_key=="string"?Vc(e.session_key.trim(),t.agent_runtime_id):"",r=n?U.sessions?.[n]:void 0,o=[];Date.now()-s3>bxe&&(s3=Date.now(),o.push(yu(U.workspace,U.connector_id).catch(s=>console.error(`Context index refresh ahead of a conversation failed: ${s.message}`)))),t.agent_protocol==="acp"&&o.push(gN(U.workspace,t,{sessionKey:r?n:null,previousSessionId:r,sandbox:e.sandbox_mode==="workspace-write"?"workspace-write":"read-only",profile:e.execution_profile&&typeof e.execution_profile=="object"?e.execution_profile:{}}).catch(s=>console.error(`${Ct?.name||"The agent"} could not be started ahead of the conversation: ${s.message}`))),await Promise.all(o)}function cr(){sn||!U.connector_id||!U.token||(uR=!0,!lR&&(lR=(async()=>{do uR=!1,await Sxe();while(uR&&!sn)})().then(()=>{bm=0}).catch(e=>{if(e?.status===409&&/synchronize again/i.test(String(e.message))&&bm<uxe){bm+=1,setTimeout(cr,2e3*bm).unref?.();return}bm=0,console.error(`Connector synchronization: ${On(e,{network:!0})}`)}).finally(()=>{lR=null})))}async function Sxe(){let e=eP(Zn),t=await lp.snapshot();n3.update({type:"assessment.workers",assessment_workers:e,tool_inventory:nt.tool_inventory,runtime_update:nt.runtime_update,agent_session:nt.agent_session,runtime_limits:U.runtime_limits??{},bug_hunt_browser:nt.bug_hunt_browser,runtime_prerequisites:nt.runtime_prerequisites,connector_jobs:t.jobs,...Yp(U.worker_limit)}),await n3.flush()}async function b3(e){let t=Qi(e);return t===Qi(U.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(U={...U,worker_limit:t},await bn(U),Sa(),cr(),t===null?`Workers are automatic again: up to ${Pu()} side by side for this machine's CPU and memory, for ${em} (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: ${em}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function SR(e){if(e!==Qv){if(Qv=e,!e)for(let t of Zn.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."),cr()}}function xR(e,t,n=null){Gn.step(e,t,n)&&Qv&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function xxe(){fp.start()}async function k3(e){return Yv??=gA({stateFile:ar.join(yr(),"diagnostics-outbox.json")}),Yv.flush(async t=>{let n=await tG(e,t,pi);return n==null?{acknowledged:!1}:{acknowledged:!0,response:n}})}async function hp(e,t,n=xa?.healthChecks()??[]){let r=await eG({config:e,workspace:t,version:Ss,insights:[...n,...xm?[xm]:[]],agentSession:vn,probes:{inspectAgent:(i,a)=>sn?Ct:di(i,a),inspectTools:i=>sn?nt.tool_inventory:Lr(i),runnerStatus:ca,connectorJobs:()=>Us({getConfig:()=>e}).list({except:{kind:"bug_hunt_grant",status:["superseded","cancelled"]}})}});Yv??=gA({stateFile:ar.join(yr(),"diagnostics-outbox.json")}),await Yv.enqueue(r);let o=await k3(e);return d3=(o.acknowledgement?.response??null)?.autonomy_scan===!0,o.status==="pending"&&console.error(`EngineerOS did not acknowledge the connector self-check; the newest report remains queued for reconnect${o.pending?.last_error?`: ${o.pending.last_error}`:"."}`),r}async function S3(e){if(sn)return Wl;let t=e instanceof Error?e.message:String(e),n=await hp(U,U.workspace).catch(()=>null);n&&console.error(rv(n)),Tr(t)}function i3(e){U.auto_pairing_pending!==!0&&(Kl.flush().catch(t=>console.error(`Saved prompt result delivery: ${t.message}`)),SR(e.connector?.activity_log_enabled===!0),Jl=e.project_url??null,Wv=1e3,ER(KT(e)),nb(),ba.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),_3().catch(t=>console.error(`Saved connector work: ${t.message}`)),(U.onboarding_pending||Jv)&&Xl())}async function ER(e=null){return op||(op=(async()=>{w3&&await Uj(U.workspace,{log:o=>console.log(`[tools] ${o}`)}).catch(o=>console.error(`[tools] Tool updates were skipped: ${o.message}`));let t=Date.now(),n=e??Ql.latestPlan()??YT(),r=await Ql.reconcile(n,{action:"provision"});if(nt.tool_inventory=await Lr(U.workspace),nt.bug_hunt_browser_diagnostics=r.verification,ka=r.profile===Hl&&r.state==="ready",nt.bug_hunt_browser=ka,ka)xm=null,eb(`Bug Hunter's browser is ready (${Qt(Date.now()-t)}).`);else if(["provisioning_failed","incompatible"].includes(r.state)){let o=r.verification?.detail??"The runtime prerequisite plan did not produce a usable browser.";console.error(`[browser] Bug Hunter's browser setup failed after ${Qt(Date.now()-t)}: ${o}`),xm={id:"hunt_browser",title:"Bug Hunter browser",status:"failed",detail:o,remedy:"Resolve the reported prerequisite or submit an approved reconciliation plan."},hp(U,U.workspace).catch(()=>null)}cr()})().finally(()=>{op=null}),op)}function eb(e){console.log(`[browser] ${e}`)}async function nb(){if(U.auto_pairing_pending===!0||["checking","ready"].includes(vn?.state))return;_R=Date.now();let e=_R;nt.agent_session={...nt.agent_session,status:"checking",message:`Checking that ${Ct.name} can answer.`},cr(),vn={state:"checking",detail:`Asking ${Ct.name} one question to confirm its session.`},console.log(`Checking that ${Ct.name} can answer before accepting work.`);try{let t=Ct.runtimeCatalog?await lN(U,Ct.runtimeCatalog,Hf):(await Hf(U,Ct.name),{name:Ct.name,rejected:[]}),n=t.runtime_id??"default",r=Zg(U.runtime_limits?.[n],e);r&&(U={...U,runtime_limits:{...U.runtime_limits,[n]:r}},nt.runtime_limits=U.runtime_limits,await bn(U).catch(()=>console.error("Readiness recovered, but its quota observation could not be saved."))),vn={state:"ready",detail:`${t.name} answered; its session is usable.`},nt.agent_session={...nt.agent_session,status:"authenticated",message:vn.detail},console.log(vn.detail),(gs||Object.hasOwn(U,"auto_pairing_pending")||t.rejected.length||t.changed)&&pn?.readyState===WebSocket.OPEN&&(await bn(U),pn.close(1e3,"Runtime readiness changed"))}catch(t){let n=Ff(t);vn={state:"failed",detail:n.message,remedy:n.status==="logged_out"?U.hunt_host?jq(U.agent_id||U.agent_protocol):Qu(U.agent_id||U.agent_protocol):null},nt.agent_session={...nt.agent_session,...n,message:[vn.detail,vn.remedy].filter(Boolean).join(" ").slice(0,500)},console.error([vn.detail,vn.remedy].filter(Boolean).join(`
2945
- `))}Ct.runtimeCatalog&&(nt.goal_plan_review=mc(U,Ct,nt.tool_inventory).goal_plan_review,mo.capabilities=nt),Ct.runtimeCatalog&&(nt.goal_plan_review=mc(U,Ct,nt.tool_inventory).goal_plan_review,mo.capabilities=nt),cr(),vn.state==="ready"&&(Sa(),Ci().bugHunts.wake().catch(t=>console.error(`Bug Hunter scheduler: ${t.message}`))),await hp(U,U.workspace).catch(()=>null)}function $xe(){clearInterval(hR);let e=!1,t=0,n=0,r=!1,o=()=>{pp.flush().catch(()=>console.error("Deployment evidence delivery remains pending.")),pn?.readyState===WebSocket.OPEN&&Kl.flush().catch(s=>console.error(`Saved prompt result delivery: ${s.message}`)),ba.tick(),$R(),Axe(),vxe(),op&&(vn===null||U.hunt_host&&vn?.state==="failed"&&Date.now()-_R>=Iq(Exe))&&jo().then(s=>{if(s)return nb()}),!U.hunt_host&&!r&&Xh(nR.id)&&(r=!0,h3.flush().then(()=>Bv(nR)).catch(s=>zv(nR,s)).finally(()=>{r=!1})),cr(),!U.hunt_host&&!Ii&&Date.now()-t>=exe&&Xh(ZT.id)&&(t=Date.now(),E3().then(()=>Bv(ZT)).catch(s=>zv(ZT,s))),!U.hunt_host&&d3&&!Hv&&Xh(eR.id)&&Date.now()-m3>=qL&&(Hv=!0,Txe().then(()=>Bv(eR)).catch(s=>zv(eR,s)).finally(()=>{Hv=!1})),!e&&Date.now()-n>=txe&&Xh(tR.id)&&(e=!0,n=Date.now(),Lr(U.workspace).then(async s=>{nt.tool_inventory=s,nt.bug_hunt_browser=ka,nt.bug_hunt_browser&&(xm=null),cr(),Bv(tR)}).catch(s=>zv(tR,s)).finally(()=>{e=!1}))};o(),hR=setInterval(o,1e4),xxe()}function x3(e){if(U.hunt_host)throw new Error("A dedicated hunt host cannot change coding-agent runtimes.");return e.action==="retry"&&!e.command_id&&(e={...e,command_id:YSe()}),e.action!=="refresh"&&(_l(e),rp.push(e)),sp=!0,$R(),"Runtime change queued. It will be saved and applied once active work finishes; no restart or pairing is needed."}async function $R(){if(!(sn||U.hunt_host||ip||Vv||!sp&&Date.now()-K5<3e4)){ip=!0,K5=Date.now();try{if(!await jo())return;let e=await yn(U.workspace);if(!e||e.connector_id!==U.connector_id)return;let t=JSON.stringify([e.agent_runtimes,e.model_metadata,e.retired_runtime_ids,e.runtime_quota_groups]);_a.beginRefresh();let n=[],r=rp.findIndex(d=>d.action==="retry"),o=r===0?1:r>0?r:rp.length;for(let d of rp.splice(0,o)){_a.applying(d);try{if(d.action==="retry"){Ws++;try{let f=await MH({request:d,getConfig:()=>U,needsReadiness:vn?.state!=="ready",persist:async h=>{await bn(h),U=h},inspect:async h=>{let g=await di({...h,agent_runtimes:[],retired_runtime_ids:[]},U.workspace,{readOnly:!0});return g.runtimeLimits??g.runtimeCatalog?.find(v=>v.id==="default")?.limits},verify:Hf,authorize:async(h,g)=>{if((await pi(U,{type:"agent_runtimes.quota_check",recovery_id:h,runtime_id:g})).authorized!==!0)throw new Error("Quota check authority was not confirmed.")}});f.verified&&vn?.state!=="ready"&&(vn={state:"ready",detail:"An explicit runtime quota check confirmed readiness."},nt.agent_session={...nt.agent_session,status:"authenticated",message:vn.detail},mo.capabilities=nt,pn?.readyState===WebSocket.OPEN&&pn.close(1e3,"Runtime readiness recovered")),_a.completed(d,f.state,f.message),console.log(`Runtime '${d.id}': ${f.message}`),nt.runtime_limits=U.runtime_limits??{},cr(),e=await yn(U.workspace)}finally{Ws--}}else e=await My(e,d),n.push(d)}catch(f){_a.failed(d),console.error(`Runtime selection was not changed: ${redact(f.message)}`)}}let s=e.retired_runtime_ids??[],i=JSON.stringify(e.agent_runtimes??[])!==JSON.stringify(U.agent_runtimes??[])||JSON.stringify(e.model_metadata??{})!==JSON.stringify(U.model_metadata??{})||JSON.stringify(s)!==JSON.stringify(U.retired_runtime_ids??[])||JSON.stringify(e.runtime_quota_groups??{})!==JSON.stringify(U.runtime_quota_groups??{});if(!sp&&!i&&Date.now()-X5<u3)return;sp=rp.length>0;let a={...U,runtime_quota_groups:e.runtime_quota_groups,model_metadata:e.model_metadata,agent_runtimes:e.agent_runtimes,retired_runtime_ids:s,sessions:Vg(U.sessions,s)},c=await di(a,U.workspace,{readOnly:!0});if(sn)return;let l=await yn(U.workspace);if(!await jo()||l?.connector_id!==U.connector_id||JSON.stringify([l.agent_runtimes,l.model_metadata,l.retired_runtime_ids,l.runtime_quota_groups])!==t){rp.unshift(...n),_a.defer(),sp=!0;return}U={...U,runtime_quota_groups:a.runtime_quota_groups,model_metadata:a.model_metadata,agent_runtimes:a.agent_runtimes,retired_runtime_ids:s,sessions:Vg(U.sessions,s),execution_profiles:c.executionProfiles,runtime_catalog:c.runtimeCatalog};for(let d of c.runtimeCatalog??[])d.limits?.source==="provider_report"&&(U={...U,runtime_limits:{...U.runtime_limits,[d.id]:d.limits}});await bn(U),cr(),Ct=c,vn?.state==="failed"&&(vn=null),X5=Date.now(),_a.applied();let u=mc(U,Ct,nt.tool_inventory),p=_A(nt)!==_A(u);Object.assign(nt,{runtime_quota_groups:u.runtime_quota_groups,multi_runtime_contract:u.multi_runtime_contract,default_runtime_id:u.default_runtime_id,agent_runtimes:u.agent_runtimes,execution_profiles:u.execution_profiles,goal_plan_review:u.goal_plan_review}),mo.capabilities=nt;for(let d of n)console.log(`Runtime '${d.id}': ${d.action} applied for new work.`);(p||n.length)&&console.log("Agent runtime catalogue refreshed."),await mN(s).catch(d=>console.error(`Retired runtime resource cleanup failed: ${d.message}`)),p&&await jo()&&pn?.close(1e3,"Runtime catalogue refreshed")}catch(e){_a.fail(),console.error(`Agent runtime capability refresh failed: ${e.message}`)}finally{ip=!1,Sa()}}}async function Axe(){if(!(!w3||U.agent_installed_only===!0||U.agent_protocol!=="acp"||!U.agent_id||Vv||ip||vn?.state==="checking"||Date.now()-Z5<nxe)){Vv=!0;try{if(!await jo())return;Z5=Date.now();let e,t=await QL(U,{verify:async r=>{e=await di(r,U.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===U||sn)return;U={...t,execution_profiles:e.executionProfiles??null,runtime_catalog:e.runtimeCatalog??null},await bn(U),Ct=e,vn=null;let n=mc(U,Ct,nt.tool_inventory);if(Object.assign(nt,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles,runtime_quota_groups:n.runtime_quota_groups,multi_runtime_contract:n.multi_runtime_contract,default_runtime_id:n.default_runtime_id,agent_runtimes:n.agent_runtimes,goal_plan_review:n.goal_plan_review}),mo.capabilities=nt,!await jo())return;await Vp(),nb(),pn?.readyState===WebSocket.OPEN&&pn.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{Vv=!1}}}function zv(e,t){let n=JH(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 Bv(e){KH(e.id)&&console.log(`${e.title} recovered.`)}async function Txe(){if(U.hunt_host||!await jo())return;m3=Date.now();let{jobs:e}=await ca(U.workspace).catch(()=>({jobs:[]})),t=await FL(U.workspace,{jobs:e});if(!zL(t))return;let n=`${t.fingerprint}:${iR.join(",")}`,r=sR?.key===n,o=r?sR.candidates:await Xx(U,t,iR);sR={key:n,candidates:o};let s=await ws(GL(t,o,{version:Ss}));Array.isArray(s?.refused)&&(iR=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.`)}async function E3(){if(!U.hunt_host){if(Ii)return Ii;Ii=(async()=>{let e=await IL(U,{knownRevision:Ec?.revision??null});if(e.unchanged||(Ec=e),a3===Ec.revision)return Ec;let{jobs:t}=await ca(U.workspace);return!t.some(r=>Xv.includes(r.status))&&Ws===0&&Zn.size===0&&(await ey(U.workspace,Ec),a3=Ec.revision),Ec})();try{return await Ii}finally{Ii=null,Sa()}}}function vR(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)),Rr.get(e)?.events.push(n)}function Sa(){wR.drain();let e=pn.readyState===WebSocket.OPEN,t=Zn.values().next().value,n=Qi(U.worker_limit)??Math.min(Pu(),Uk(t?.workerLimit??Io[0]?.worker_limit)),r=Math.min(n,...[...Zn.values()].map(i=>Qp(i.admittedWorkerLimit)),...Io.map(i=>Qp(i.admitted_worker_limit))),o=e&&!Ii&&Ws===0?HN(Io,Zn.size,Math.max(0,r-wR.running),i=>!Kc(U,i.execution_profile)):[];for(let i of o){let a=`${i.assessment_id}:${i.stage}`,c={kind:"assessment",key:a,runId:i.assessment_id,stage:i.stage,child:null,controller:null,resumeAssignment:null,phase:"starting",progressPercent:5,lastMessage:`Starting ${i.stage} assessment stage`,startedAt:Date.now(),workerLimit:Uk(i.worker_limit),admittedWorkerLimit:Qp(i.admitted_worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};Zn.set(a,c),Cxe(i,c)}o.length>0&&cr();let s=Io.length&&Io.every(i=>Kc(U,i.execution_profile))?"Assessment work is preserved; waiting for provider quota recovery or a server-authorized runtime fallback.":GN({queued:Io,running:Zn.size,workerLimit:r,connected:e,designSync:!!Ii,integrations:Ws});s&&s!==c3&&console.log(s),c3=s}function tb(e){let t=qk(e);return t?`${Ct.name} on ${t}`:Ct.name}async function $3(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s=`${r} \xB7 ${tb(e)}`,i=oP(e,Ct.name),a,c=new Promise(_=>{a=_}),l=e.factory_prompt?.version===1,u={completed:c,runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:kU(ws),executionRevision:A3(e),sessionKey:Vc(Mu(e),e.execution_profile?.runtime_id??"default"),sessionId:null,phase:"preparing",lastMessage:s,replacement:null};Rr.set(t,u);let p=!1,d,f=bU(ws,{type:"prompt.heartbeat",prompt_id:t,execution_revision:u.executionRevision},{onError:_=>{p&&Ka(_)||console.error(`[${n}] Prompt heartbeat: ${_.message}`)}}),h,g=_=>{let S=_?JSON.stringify(_):null;p||!S||S===h||Rr.get(t)!==u||(h=S,vR(t,_))},v=Number(e.answer_within_seconds),y=v>0?o+v*1e3:void 0;console.log([`[${n}] ${i} for ${r}.`,`${Ct.name} can reason for several minutes without reporting a step.`,...y?[Q0(y,o)]:[]].join(" ")),vR(t,{kind:"status",message:i}),Gn.status(n,s,o,{link:Jl,answerBy:y,phase:u.phase});let b=_=>{if(p)return;let S=zN(_),k=FN(_),x=Yc(_);Rr.get(t)===u&&(k&&(u.phase=k),(x??S?.message)&&(u.lastMessage=x??S?.message),Gn.status(n,u.lastMessage,o,{link:Jl,answerBy:y,phase:u.phase}),xR(n,x??S?.message));let R=_.type==="forge.output"?null:x;g(S??(R?{kind:"status",message:R}:null))},E="failed",w=[r],m;try{m=await wR.acquire({signal:u.cancellation.signal,onWaiting:()=>b({type:"connector.step",message:"Waiting for an available connector worker"})}),Zp(e)||(b({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await DL(E3,{pinned:!!e.local_design_context,last:Ec,onFallback:(R,T)=>b({type:"connector.step",message:`Design context not refreshed (${R.message}); continuing with ${T?"the copy synced earlier":"none"}`})})});let _=await zx(e,U,{onProcess:R=>{Rr.get(t)===u&&(u.child=R)},onController:R=>{Rr.get(t)===u&&(u.controller=R)},onSession:R=>{u.sessionId=R},onEvent:b},{signal:u.cancellation.signal});if(m(),Sa(),u.stoppedHere&&!l)throw new Error(l3);if(u.cancelled&&!l)return;let S={type:"prompt.completed",prompt_id:t,execution_revision:u.executionRevision,content:_.content,...Kn(_),..._.proposal_receipt?{proposal_receipt:_.proposal_receipt}:{},..._.native_cost?{native_cost:_.native_cost}:{},session_id:_.sessionId,usage:_.usage};await Kl.save(S),p=!0,u.events.stop(),d=f.stop(),u.phase="delivering",u.lastMessage="Delivering completed response",Gn.status(n,u.lastMessage,o,{link:Jl,phase:u.phase,agent:!1});let k=_.singleTurn?RO(U.sessions,_.sessionKey):jb(U.sessions,_.sessionKey,_.sessionId);if(JSON.stringify(k)!==JSON.stringify(U.sessions||{})&&(U={...U,sessions:k},await bn(U)),u.cancelled&&!l)return;let x=await Kl.deliver(S);$m.record("prompt","completed",{durationMs:Date.now()-o,usage:_.usage}),E=x.status==="delivered"?"finished":"undelivered",w=[Cg(_.usage),r]}catch(_){let S=u.stoppedHere?l3:On(_);$m.record("prompt","failed",{durationMs:Date.now()-o}),u.stoppedHere&&(E="cancelled");let k=BH(e,_,S);if(l&&!k)E="blocked",console.error(`[${n}] ${S} Process termination is unconfirmed; Factory Stop remains pending.`);else if((!u.cancelled||l)&&!p){try{await Kl.deliver(k)}catch(x){console.error(`[${n}] Prompt failure delivery: ${x.message}`)}console.error(S)}else p&&(E="undelivered",console.error(`[${n}] ${S} The original completed result remains saved for delivery.`))}finally{try{m?.(),Sa(),await(d??f.stop()),u.events.stop();let _=u.replacement;_?(E="replaced",w=[`continuing on ${tb(_)}`,r]):u.cancelled&&E!=="blocked"&&(E="cancelled"),Gn.finish(n,E,w),Rr.get(t)===u&&Rr.delete(t),_&&Oxe(u,_)}finally{a()}}}async function AR(e){e.cancelled=!0,e.cancellation.abort(),await e.completed}function A3(e){return Number(e.execution_revision)||1}async function Rxe(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 ${tb(t)}.`),await AR(e))}function Oxe(e,t){e.sessionId&&(U={...U,sessions:jb(U.sessions,e.sessionKey,e.sessionId)},bn(U).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),$3(t)}async function Cxe(e,t){e.runtime_handoff&&(e={...e,prompt_markdown:`${e.prompt_markdown}
2945
+ `))}Ct.runtimeCatalog&&(nt.goal_plan_review=mc(U,Ct,nt.tool_inventory).goal_plan_review,mo.capabilities=nt),Ct.runtimeCatalog&&(nt.goal_plan_review=mc(U,Ct,nt.tool_inventory).goal_plan_review,mo.capabilities=nt),cr(),vn.state==="ready"&&(Sa(),Ci().bugHunts.wake().catch(t=>console.error(`Bug Hunter scheduler: ${t.message}`))),await hp(U,U.workspace).catch(()=>null)}function $xe(){clearInterval(hR);let e=!1,t=0,n=0,r=!1,o=()=>{pp.flush().catch(()=>console.error("Deployment evidence delivery remains pending.")),pn?.readyState===WebSocket.OPEN&&Kl.flush().catch(s=>console.error(`Saved prompt result delivery: ${s.message}`)),ba.tick(),$R(),Axe(),vxe(),op&&(vn===null||U.hunt_host&&vn?.state==="failed"&&Date.now()-_R>=Iq(Exe))&&jo().then(s=>{if(s)return nb()}),!U.hunt_host&&!r&&Xh(nR.id)&&(r=!0,h3.flush().then(()=>Bv(nR)).catch(s=>zv(nR,s)).finally(()=>{r=!1})),cr(),!U.hunt_host&&!Ii&&Date.now()-t>=exe&&Xh(ZT.id)&&(t=Date.now(),E3().then(()=>Bv(ZT)).catch(s=>zv(ZT,s))),!U.hunt_host&&d3&&!Hv&&Xh(eR.id)&&Date.now()-m3>=qL&&(Hv=!0,Txe().then(()=>Bv(eR)).catch(s=>zv(eR,s)).finally(()=>{Hv=!1})),!e&&Date.now()-n>=txe&&Xh(tR.id)&&(e=!0,n=Date.now(),Lr(U.workspace).then(async s=>{nt.tool_inventory=s,nt.bug_hunt_browser=ka,nt.bug_hunt_browser&&(xm=null),cr(),Bv(tR)}).catch(s=>zv(tR,s)).finally(()=>{e=!1}))};o(),hR=setInterval(o,1e4),xxe()}function x3(e){if(U.hunt_host)throw new Error("A dedicated hunt host cannot change coding-agent runtimes.");return e.action==="retry"&&!e.command_id&&(e={...e,command_id:YSe()}),e.action!=="refresh"&&(_l(e),rp.push(e)),sp=!0,$R(),"Runtime change queued. It will be saved and applied once active work finishes; no restart or pairing is needed."}async function $R(){if(!(sn||U.hunt_host||ip||Vv||!sp&&Date.now()-K5<3e4)){ip=!0,K5=Date.now();try{if(!await jo())return;let e=await yn(U.workspace);if(!e||e.connector_id!==U.connector_id)return;let t=JSON.stringify([e.agent_runtimes,e.model_metadata,e.retired_runtime_ids,e.runtime_quota_groups]);_a.beginRefresh();let n=[],r=rp.findIndex(d=>d.action==="retry"),o=r===0?1:r>0?r:rp.length;for(let d of rp.splice(0,o)){_a.applying(d);try{if(d.action==="retry"){Ws++;try{let f=await MH({request:d,getConfig:()=>U,needsReadiness:vn?.state!=="ready",persist:async h=>{await bn(h),U=h},inspect:async h=>{let g=await di({...h,agent_runtimes:[],retired_runtime_ids:[]},U.workspace,{readOnly:!0});return g.runtimeLimits??g.runtimeCatalog?.find(v=>v.id==="default")?.limits},verify:Hf,authorize:async(h,g)=>{if((await pi(U,{type:"agent_runtimes.quota_check",recovery_id:h,runtime_id:g})).authorized!==!0)throw new Error("Quota check authority was not confirmed.")}});f.verified&&vn?.state!=="ready"&&(vn={state:"ready",detail:"An explicit runtime quota check confirmed readiness."},nt.agent_session={...nt.agent_session,status:"authenticated",message:vn.detail},mo.capabilities=nt,pn?.readyState===WebSocket.OPEN&&pn.close(1e3,"Runtime readiness recovered")),_a.completed(d,f.state,f.message),console.log(`Runtime '${d.id}': ${f.message}`),nt.runtime_limits=U.runtime_limits??{},cr(),e=await yn(U.workspace)}finally{Ws--}}else e=await My(e,d),n.push(d)}catch(f){_a.failed(d),console.error(`Runtime selection was not changed: ${redact(f.message)}`)}}let s=e.retired_runtime_ids??[],i=JSON.stringify(e.agent_runtimes??[])!==JSON.stringify(U.agent_runtimes??[])||JSON.stringify(e.model_metadata??{})!==JSON.stringify(U.model_metadata??{})||JSON.stringify(s)!==JSON.stringify(U.retired_runtime_ids??[])||JSON.stringify(e.runtime_quota_groups??{})!==JSON.stringify(U.runtime_quota_groups??{});if(!sp&&!i&&Date.now()-X5<u3)return;sp=rp.length>0;let a={...U,runtime_quota_groups:e.runtime_quota_groups,model_metadata:e.model_metadata,agent_runtimes:e.agent_runtimes,retired_runtime_ids:s,sessions:Vg(U.sessions,s)},c=await di(a,U.workspace,{readOnly:!0});if(sn)return;let l=await yn(U.workspace);if(!await jo()||l?.connector_id!==U.connector_id||JSON.stringify([l.agent_runtimes,l.model_metadata,l.retired_runtime_ids,l.runtime_quota_groups])!==t){rp.unshift(...n),_a.defer(),sp=!0;return}U={...U,runtime_quota_groups:a.runtime_quota_groups,model_metadata:a.model_metadata,agent_runtimes:a.agent_runtimes,retired_runtime_ids:s,sessions:Vg(U.sessions,s),execution_profiles:c.executionProfiles,runtime_catalog:c.runtimeCatalog};for(let d of c.runtimeCatalog??[])d.limits?.source==="provider_report"&&(U={...U,runtime_limits:{...U.runtime_limits,[d.id]:d.limits}});await bn(U),cr(),Ct=c,vn?.state==="failed"&&(vn=null),X5=Date.now(),_a.applied();let u=mc(U,Ct,nt.tool_inventory),p=_A(nt)!==_A(u);Object.assign(nt,{runtime_quota_groups:u.runtime_quota_groups,multi_runtime_contract:u.multi_runtime_contract,default_runtime_id:u.default_runtime_id,agent_runtimes:u.agent_runtimes,execution_profiles:u.execution_profiles,goal_plan_review:u.goal_plan_review}),mo.capabilities=nt;for(let d of n)console.log(`Runtime '${d.id}': ${d.action} applied for new work.`);(p||n.length)&&console.log("Agent runtime catalogue refreshed."),await mN(s).catch(d=>console.error(`Retired runtime resource cleanup failed: ${d.message}`)),p&&await jo()&&pn?.close(1e3,"Runtime catalogue refreshed")}catch(e){_a.fail(),console.error(`Agent runtime capability refresh failed: ${e.message}`)}finally{ip=!1,Sa()}}}async function Axe(){if(!(!w3||U.agent_installed_only===!0||U.agent_protocol!=="acp"||!U.agent_id||Vv||ip||vn?.state==="checking"||Date.now()-Z5<nxe)){Vv=!0;try{if(!await jo())return;Z5=Date.now();let e,t=await QL(U,{verify:async r=>{e=await di(r,U.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===U||sn)return;U={...t,execution_profiles:e.executionProfiles??null,runtime_catalog:e.runtimeCatalog??null},await bn(U),Ct=e,vn=null;let n=mc(U,Ct,nt.tool_inventory);if(Object.assign(nt,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles,runtime_quota_groups:n.runtime_quota_groups,multi_runtime_contract:n.multi_runtime_contract,default_runtime_id:n.default_runtime_id,agent_runtimes:n.agent_runtimes,goal_plan_review:n.goal_plan_review}),mo.capabilities=nt,!await jo())return;await Vp(),nb(),pn?.readyState===WebSocket.OPEN&&pn.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{Vv=!1}}}function zv(e,t){let n=JH(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 Bv(e){KH(e.id)&&console.log(`${e.title} recovered.`)}async function Txe(){if(U.hunt_host||!await jo())return;m3=Date.now();let{jobs:e}=await ca(U.workspace).catch(()=>({jobs:[]})),t=await FL(U.workspace,{jobs:e});if(!zL(t))return;let n=`${t.fingerprint}:${iR.join(",")}`,r=sR?.key===n,o=r?sR.candidates:await Xx(U,t,iR);sR={key:n,candidates:o};let s=await ws(GL(t,o,{version:Ss}));Array.isArray(s?.refused)&&(iR=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.`)}async function E3(){if(!U.hunt_host){if(Ii)return Ii;Ii=(async()=>{let e=await IL(U,{knownRevision:Ec?.revision??null});if(e.unchanged||(Ec=e),a3===Ec.revision)return Ec;let{jobs:t}=await ca(U.workspace);return!t.some(r=>Xv.includes(r.status))&&Ws===0&&Zn.size===0&&(await ey(U.workspace,Ec),a3=Ec.revision),Ec})();try{return await Ii}finally{Ii=null,Sa()}}}function vR(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)),Rr.get(e)?.events.push(n)}function Sa(){wR.drain();let e=pn.readyState===WebSocket.OPEN,t=Zn.values().next().value,n=Qi(U.worker_limit)??Math.min(Pu(),Uk(t?.workerLimit??Io[0]?.worker_limit)),r=Math.min(n,...[...Zn.values()].map(i=>Qp(i.admittedWorkerLimit)),...Io.map(i=>Qp(i.admitted_worker_limit))),o=e&&!Ii&&Ws===0?HN(Io,Zn.size,Math.max(0,r-wR.running),i=>!Kc(U,i.execution_profile)):[];for(let i of o){let a=`${i.assessment_id}:${i.stage}`,c={kind:"assessment",key:a,runId:i.assessment_id,stage:i.stage,child:null,controller:null,resumeAssignment:null,phase:"starting",progressPercent:5,lastMessage:`Starting ${i.stage} assessment stage`,startedAt:Date.now(),workerLimit:Uk(i.worker_limit),admittedWorkerLimit:Qp(i.admitted_worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};Zn.set(a,c),Cxe(i,c)}o.length>0&&cr();let s=Io.length&&Io.every(i=>Kc(U,i.execution_profile))?"Assessment work is preserved; waiting for provider quota recovery or a server-authorized runtime fallback.":GN({queued:Io,running:Zn.size,workerLimit:r,connected:e,designSync:!!Ii,integrations:Ws});s&&s!==c3&&console.log(s),c3=s}function tb(e){let t=qk(e);return t?`${Ct.name} on ${t}`:Ct.name}async function $3(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s=`${r} \xB7 ${tb(e)}`,i=oP(e,Ct.name),a,c=new Promise(_=>{a=_}),l=e.factory_prompt?.version===1,u={completed:c,runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:kU(ws),executionRevision:A3(e),sessionKey:Vc(Mu(e),e.execution_profile?.runtime_id??"default"),sessionId:null,phase:"preparing",lastMessage:s,replacement:null};Rr.set(t,u);let p=!1,d,f=bU(ws,{type:"prompt.heartbeat",prompt_id:t,execution_revision:u.executionRevision},{onError:_=>{p&&Ka(_)||console.error(`[${n}] Prompt heartbeat: ${_.message}`)}}),h,g=_=>{let S=_?JSON.stringify(_):null;p||!S||S===h||Rr.get(t)!==u||(h=S,vR(t,_))},v=Number(e.answer_within_seconds),y=v>0?o+v*1e3:void 0;console.log([`[${n}] ${i} for ${r}.`,`${Ct.name} can reason for several minutes without reporting a step.`,...y?[Q0(y,o)]:[]].join(" ")),vR(t,{kind:"status",message:i}),Gn.status(n,s,o,{link:Jl,answerBy:y,phase:u.phase});let b=_=>{if(p)return;let S=zN(_),k=FN(_),x=Yc(_);Rr.get(t)===u&&(k&&(u.phase=k),(x??S?.message)&&(u.lastMessage=x??S?.message),Gn.status(n,u.lastMessage,o,{link:Jl,answerBy:y,phase:u.phase}),xR(n,x??S?.message));let R=_.type==="forge.output"?null:x;g(S??(R?{kind:"status",message:R}:null))},E="failed",w=[r],m;try{m=await wR.acquire({signal:u.cancellation.signal,onWaiting:()=>b({type:"connector.step",message:"Waiting for an available connector worker"})}),Zp(e)||(b({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await DL(E3,{pinned:!!e.local_design_context,last:Ec,onFallback:(R,T)=>b({type:"connector.step",message:`Design context not refreshed (${R.message}); continuing with ${T?"the copy synced earlier":"none"}`})})});let _=await zx(e,U,{onProcess:R=>{Rr.get(t)===u&&(u.child=R)},onController:R=>{Rr.get(t)===u&&(u.controller=R)},onSession:R=>{u.sessionId=R},onEvent:b},{signal:u.cancellation.signal});if(m(),Sa(),u.stoppedHere&&!l)throw new Error(l3);if(u.cancelled&&!l)return;let S={type:"prompt.completed",prompt_id:t,execution_revision:u.executionRevision,content:_.content,...Kn(_),..._.proposal_receipt?{proposal_receipt:_.proposal_receipt}:{},..._.native_cost?{native_cost:_.native_cost}:{},session_id:_.sessionId,usage:_.usage};await Kl.save(S),p=!0,u.events.stop(),d=f.stop(),u.phase="delivering",u.lastMessage="Delivering completed response",Gn.status(n,u.lastMessage,o,{link:Jl,phase:u.phase,agent:!1});let k=_.singleTurn?RO(U.sessions,_.sessionKey):jb(U.sessions,_.sessionKey,_.sessionId);if(JSON.stringify(k)!==JSON.stringify(U.sessions||{})&&(U={...U,sessions:k},await bn(U)),u.cancelled&&!l)return;let x=await Kl.deliver(S);$m.record("prompt","completed",{durationMs:Date.now()-o,usage:_.usage}),E=x.status==="delivered"?"finished":"undelivered",w=[Cg(_.usage),r]}catch(_){let S=u.stoppedHere?l3:On(_);$m.record("prompt","failed",{durationMs:Date.now()-o}),u.stoppedHere&&(E="cancelled");let k=BH(e,_,S);if(l&&!k)E="blocked",console.error(`[${n}] ${S} Process termination is unconfirmed; Factory Stop remains pending.`);else if((!u.cancelled||l)&&!p){try{await Kl.deliver(k)}catch(x){console.error(`[${n}] Prompt failure delivery: ${x.message}`)}console.error(S)}else p&&(E="undelivered",console.error(`[${n}] ${S} The original completed result remains saved for delivery.`))}finally{try{m?.(),Sa(),await(d??f.stop()),u.events.stop();let _=u.replacement;_?(E="replaced",w=[`continuing on ${tb(_)}`,r]):u.cancelled&&E!=="blocked"&&(E="cancelled"),Gn.finish(n,E,w),Rr.get(t)===u&&Rr.delete(t),_&&Oxe(u,_)}finally{a()}}}async function AR(e){e.cancelled=!0,e.cancellation.abort(),await e.completed}function A3(e){return Number(e.execution_revision)||1}async function Rxe(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 ${tb(t)}.`),await AR(e))}function Oxe(e,t){e.sessionId&&(U={...U,sessions:jb(U.sessions,e.sessionKey,e.sessionId)},bn(U).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),$3(t)}async function Cxe(e,t){e.runtime_handoff&&(e={...e,session_key:`assessment-${e.assessment_id}-${e.stage}-${e.routing_revision}`,prompt_markdown:`${e.prompt_markdown}
2946
2946
 
2947
2947
  ## Continue retained assessment work
2948
- This is the same approved assessment on a fresh runtime session. Inspect the existing stage draft and retained evidence, preserve completed sections, and continue only unfinished work. Never replay external mutations or use another runtime's native session. Existing correction and execution allowances remain unchanged.`});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 ${tb(e)}.`),!oR.has(n)){oR.add(n);try{let m=await LN(U.workspace);if(!m.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let _=m.accepted_head_revision?m.current_head_revision?m.current_head_revision!==m.accepted_head_revision?`The workspace is now at commit \`${m.current_head_revision}\`; the accepted assessment is from \`${m.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${m.accepted_head_revision}\`; the current commit could not be read.`:"Its accepted commit is unavailable; this run will refresh that provenance.";console.log(`Last accepted assessment covers ${m.stages.length||"no"} section(s). ${_}`)}}catch(m){console.error(`Assessment freshness check failed: ${m.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,p=null,d=null,f=null,h=new Set,g=()=>!sn&&Zn.get(t.key)===t,v=async m=>{try{return await _U(async _=>{let S=await ws(_);for(let k of S?.assessment_assignments??[])k.assessment_id===n&&(k.stage===r?t.authorizedRetry={...e,...k}:Kp(Io,Zn.get(`${k.assessment_id}:${k.stage}`),k));return S},m)||console.warn(`[${s}] ${yU}`),!0}catch(_){return console.error(`Assessment failure delivery: ${_.message}`),!1}},y=(m,{milestone:_=!0}={})=>{if(!g()||_&&f===m)return;_&&(f=m,h.has(m)||(h.add(m),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${m}.`));let S=String(m).slice(0,500);t.progressPercent=c,t.lastMessage=S,Gn.status(s,S,o,{link:Jl,phase:t.phase,agent:!a})};y(`Starting ${r} assessment stage`);let b=setInterval(()=>{let m=Date.now(),_=m-t.lastActivityAt,S=i&&!a?qN(r,_):null;if(!p&&S){p=S,console.error(`[assessment:${r}] ${p}`),Ck(t.controller,t.child);return}p||xa.observe({at:m,level:"info",message:Gn.status(s,`${t.lastMessage} \xB7 last agent activity ${Qt(_)} ago (${t.eventCount.toLocaleString()} events)`,o,{phase:t.phase,agent:!a})})},15e3),E={onSession:async m=>{g()&&(d=String(m),await eI(U.workspace,n,r,m,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision,runtimeId:e.execution_profile?.runtime_id??"default"}))},onController:m=>{g()&&(t.controller=m)},onProcess:m=>{g()&&(t.child=m,i=!0,t.phase!=="correcting"&&(t.phase="running",y("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:m=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let _=UN(m);if(_&&y(_),!g())return;let S=Yc(m);!S||S===t.lastDetail||(t.lastDetail=S,xR(s,S))}},w=(m,_)=>wy(m,_,U,E,{draftPath:ar.relative(U.workspace,ar.join(Uo(U.workspace,n),m.report_file)).split(ar.sep).join("/")});try{if(Kc(U,e.execution_profile))throw new Error("Provider usage limit reached; this runtime is waiting for quota recovery or an authorized fallback.");let m=(rR.get(e.execution_profile?.runtime_id??"default")??0)-Date.now();m>0&&(y(`Waiting ${Math.ceil(m/1e3)}s for the model provider's rate limit to clear`),await new Promise(O=>setTimeout(O,m+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,y("Calculating changed files and affected behavior"));let _=await sI(U.workspace,e),S=await C0(U.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(S)w(S,_),y("Recovered completed stage report from connector storage");else{if(d=await tI(U.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision,expectedRuntimeId:e.execution_profile?.runtime_id??"default"}),d&&y("Restoring interrupted agent session"),S=await Fx(_,U,E,{previousSessionId:d}),p)throw new Error(p);a=!0,await O0(U.workspace,n,_,S)}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(NO(U.server_url,U.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:JSON.stringify(O),signal:AbortSignal.timeout(DN)}),x,T=await rP(S,{submit:O=>nP(O,k,{isActive:()=>g()&&!sn,readAcknowledgement:async C=>{let I=await C.json();if(r==="synthesis"&&I?.status==="completed"&&(typeof I.report_markdown!="string"||!I.report_markdown.trim().startsWith(`# Workspace Assessment
2948
+ This is the same approved assessment on a fresh runtime session. Inspect the existing stage draft and retained evidence, preserve completed sections, and continue only unfinished work. Never replay external mutations or use another runtime's native session. Existing correction and execution allowances remain unchanged.`});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 ${tb(e)}.`),!oR.has(n)){oR.add(n);try{let m=await LN(U.workspace);if(!m.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let _=m.accepted_head_revision?m.current_head_revision?m.current_head_revision!==m.accepted_head_revision?`The workspace is now at commit \`${m.current_head_revision}\`; the accepted assessment is from \`${m.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${m.accepted_head_revision}\`; the current commit could not be read.`:"Its accepted commit is unavailable; this run will refresh that provenance.";console.log(`Last accepted assessment covers ${m.stages.length||"no"} section(s). ${_}`)}}catch(m){console.error(`Assessment freshness check failed: ${m.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,p=null,d=null,f=null,h=new Set,g=()=>!sn&&Zn.get(t.key)===t,v=async m=>{try{return await _U(async _=>{let S=await ws(_);for(let k of S?.assessment_assignments??[])k.assessment_id===n&&(k.stage===r?t.authorizedRetry={...e,...k}:Kp(Io,Zn.get(`${k.assessment_id}:${k.stage}`),k));return S},m)||console.warn(`[${s}] ${yU}`),!0}catch(_){return console.error(`Assessment failure delivery: ${_.message}`),!1}},y=(m,{milestone:_=!0}={})=>{if(!g()||_&&f===m)return;_&&(f=m,h.has(m)||(h.add(m),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${m}.`));let S=String(m).slice(0,500);t.progressPercent=c,t.lastMessage=S,Gn.status(s,S,o,{link:Jl,phase:t.phase,agent:!a})};y(`Starting ${r} assessment stage`);let b=setInterval(()=>{let m=Date.now(),_=m-t.lastActivityAt,S=i&&!a?qN(r,_):null;if(!p&&S){p=S,console.error(`[assessment:${r}] ${p}`),Ck(t.controller,t.child);return}p||xa.observe({at:m,level:"info",message:Gn.status(s,`${t.lastMessage} \xB7 last agent activity ${Qt(_)} ago (${t.eventCount.toLocaleString()} events)`,o,{phase:t.phase,agent:!a})})},15e3),E={onSession:async m=>{g()&&(d=String(m),await eI(U.workspace,n,r,m,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision,runtimeId:e.execution_profile?.runtime_id??"default",routingRevision:e.routing_revision}))},onController:m=>{g()&&(t.controller=m)},onProcess:m=>{g()&&(t.child=m,i=!0,t.phase!=="correcting"&&(t.phase="running",y("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:m=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let _=UN(m);if(_&&y(_),!g())return;let S=Yc(m);!S||S===t.lastDetail||(t.lastDetail=S,xR(s,S))}},w=(m,_)=>wy(m,_,U,E,{draftPath:ar.relative(U.workspace,ar.join(Uo(U.workspace,n),m.report_file)).split(ar.sep).join("/")});try{if(Kc(U,e.execution_profile))throw new Error("Provider usage limit reached; this runtime is waiting for quota recovery or an authorized fallback.");let m=(rR.get(e.execution_profile?.runtime_id??"default")??0)-Date.now();m>0&&(y(`Waiting ${Math.ceil(m/1e3)}s for the model provider's rate limit to clear`),await new Promise(O=>setTimeout(O,m+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,y("Calculating changed files and affected behavior"));let _=await sI(U.workspace,e),S=await C0(U.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(S)w(S,_),y("Recovered completed stage report from connector storage");else{if(d=await tI(U.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision,expectedRuntimeId:e.execution_profile?.runtime_id??"default",expectedRoutingRevision:e.runtime_handoff?e.routing_revision:void 0}),d&&y("Restoring interrupted agent session"),S=await Fx(_,U,E,{previousSessionId:d}),p)throw new Error(p);a=!0,await O0(U.workspace,n,_,S)}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(NO(U.server_url,U.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${U.token}`},body:JSON.stringify(O),signal:AbortSignal.timeout(DN)}),x,T=await rP(S,{submit:O=>nP(O,k,{isActive:()=>g()&&!sn,readAcknowledgement:async C=>{let I=await C.json();if(r==="synthesis"&&I?.status==="completed"&&(typeof I.report_markdown!="string"||!I.report_markdown.trim().startsWith(`# Workspace Assessment
2949
2949
  `)))throw new Error("EngineerOS returned an incomplete assessment acknowledgement without its canonical Workspace Assessment document. The completed report remains saved for delivery.");return x=I,I},onRetry:(C,I)=>{y("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${On(C)} Retrying in ${Math.round(I/1e3)}s without rerunning the agent.`)}}),payloadFor:O=>r==="synthesis"?I0(U.workspace,n,O,{expectedSourceRevision:e.source_revision}):lI(O),rejectionFor:O=>Bu(O,"the assessment"),correct:async(O,C)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!O.correctAfterRejection)throw new Error(`${C} The connector could not start the required agent correction.`);return O.correctAfterRejection(C)},onCorrected:async O=>{if(p)throw new Error(p);a=!0,await rI(U.workspace,n,r);let C=await O0(U.workspace,n,_,O);return w(C,_),t.phase="delivering",t.lastMessage="Delivering corrected stage result",C}});if(p)throw new Error(p);S=T.result;let $=T.response;if(!$.ok)throw new Error(await Bu($,"the assessment"));if(l=!0,$m.record("assessment stage","completed",{durationMs:Date.now()-o,usage:S.usage}),r==="synthesis"){let O=await iI(U.workspace,n,e,S,x.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${ar.relative(U.workspace,O)}.`);try{let C=await Xm(U.workspace);C.committed&&console.log(`Assessment committed to Git as ${C.revision.slice(0,8)}.`)}catch(C){console.error(`The assessment is saved locally but could not be committed to Git: ${C.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(m){let _=XN(e,m),S=ZN(m),k=JN(m);S&&(await nI(U.workspace,n,r).catch($=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${$.message}`)}),d=null);let x=Qg(m);if(x){let $=e.execution_profile?.runtime_id??"default";U={...U,runtime_limits:{...U.runtime_limits,[$]:x}},nt.runtime_limits=U.runtime_limits;try{await bn(U)}catch(O){console.error(`Quota state is retained in memory but could not be saved: ${On(O)}`)}cr()}let R=!x&&!p&&(d||S)&&(S||VN(m))&&_<k,T=p||eC(m)||On(m);if(g()&&R){t.phase="starting",t.lastMessage=S?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=YN(e,m);let $=QN(m,_);if(Xp(m)){let O=e.execution_profile?.runtime_id??"default";rR.set(O,Math.max(rR.get(O)??0,Date.now()+$))}console.warn(`[assessment:${r}] ${S?"Agent session became unusable":"Agent session interrupted"}: ${T} ${S?"Starting a fresh session from the saved draft":`Resuming session ${d}`} in ${Math.round($/1e3)}s (${_+1}/${k}).`),await new Promise(O=>setTimeout(O,$))}else g()&&(u=await v({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:T,...x?{quota:x,execution_profile:e.execution_profile??{},failure_usage:Rs(m)}:{}}));R||($m.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${T}`))}finally{clearInterval(b),Gn.clearStatus(s),r==="synthesis"&&l&&oR.delete(n),g()&&(Zn.delete(t.key),t.authorizedRetry&&Kp(Io,null,t.authorizedRetry,{front:!0}),tP(Io,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),Sa())}}async function Ixe(e){let t=String(e.run_id||"");Ws+=1;try{Ii&&await Ii;let n=await Ux(U.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 Xl();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: ${On(n)}`)}finally{Ws-=1,Sa()}}function jxe(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{Tr('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function Tr(e){console.error(e),process.exit(1)}var u3,Xv,ZSe,ZT,eR,exe,txe,nxe,tR,nR,$c,Sm,tn,xa,sn,vn,ip,K5,X5,sp,rp,_a,xm,d3,p3,bR,Gn,Am,pR,Y5,up,Em,Q5,Gl,Yl,fR,pp,rxe,$m,Yv,ap,U,mo,Vl,f3,gs,h3,Ws,Qv,Jl,Zn,rR,oR,Io,Rr,pn,hR,fp,Ii,Hv,m3,sR,iR,Gv,g3,mR,Wv,cp,Z5,Vv,Co,Yo,va,Jv,aR,Zv,gR,Wl,kR,e3,sxe,cR,w3,Ct,y3,nt,cxe,Ql,vm,t3,ba,lp,ws,n3,Kl,wR,lR,uR,uxe,bm,km,Kv,yR,dR,mxe,yxe,r3,o3,bxe,s3,op,ka,_R,Exe,Ec,a3,c3,l3,T3=V(async()=>{M();Wi();PH();DH();ew();UH();rh();ei();Xu();FH();Ry();au();RE();Pl();nx();Tn();Zc();Za();Xi();os();OE();$f();Su();Jc();Dr();dl();Bo();Wf();GH();VH();Ym();rG();lG();hA();yG();Uy();Cu();Tm();kG();OG();IG();FG();Hc();GG();JG();XG();ri();CA();Zo();v6();nf();ix();tl();S6();BA();P6();U6();vu();Nf();jT();GW();oc();a5();l5();Hh();W_();uA();Nc();d5();_p();Rm();h5();_5();G5();qT();J5();u3=3e5,Xv=["queued","running","reporting"],ZSe=5e3,ZT={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."},eR={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."},exe=6e4,txe=3e4,nxe=60*6e4,tR={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},nR={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:$c,positional:Sm,flags:tn}=ru(process.argv.slice(2)),xa=null,sn=!1,vn=null,ip=!1,K5=0,X5=Date.now(),sp=!1,rp=[],_a=LH({getConfig:()=>U,requestChange:x3,isBusy:()=>ip||va||Zn.size>0||Rr.size>0}),xm=null,d3=!1,p3=null,bR=null,Gn=null,Am=null,fR=G_({getWorkspace:()=>U.workspace,onRecorded:e=>QB(U,e).then(()=>console.log(`Recorded the ${e.role} sign-in for Bug Hunter; it is kept on this machine.`)).catch(t=>console.error(`The recorded ${e.role} sign-in was not reported to EngineerOS: ${t.message}`))}),rxe=fH({getWorkspace:()=>U.workspace,getConfig:()=>U,releaseDeployments:{handle:(...e)=>pp.handle(...e)},huntSignIns:fR,huntFlowRecordings:nH({signIns:fR,getWorkspace:()=>U.workspace})}),$m=CG();if($c==="doctor"){let e=ar.resolve(tn.workspace||process.cwd()),t=await yn(e),n=await HG(e),r=await hp(t||{workspace:e},e,vA(n));console.log(rv(r)),process.exit(r.status==="failed"?1:0)}ap=$c==="hunt-host";if(ap){try{tn.workspace=Oq(Sm,tn)}catch(e){Tr(e.message)}!Sm[0]&&ar.resolve(tn.workspace)!==ar.resolve(process.cwd())&&console.log(`This hunt host still keeps its files in ${tn.workspace}. To keep everything in ${process.cwd()}, pair it again from here with a new pairing command.`)}if(($c==="start"||$c==="pair"||ap)&&process.env[Ra]!=="1"&&Jn(ou))try{process.exit(await u5({root:yr(),bundled:{version:ou,entry:ar.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:ar.resolve(tn.workspace||process.cwd())}))}catch(e){Tr(`The connector process could not be started: ${e.message}`)}if(ap){try{await Cq(tn.workspace,Sm[0]?tn.agent:null)}catch(e){Tr(e.message)}$c=Sm[0]?"pair":"start"}gs=Dy(tn);if($c==="pair"){let e=Sm[0];e||Tr("Usage: engineeros-connector pair CODE --url URL [--auto-agents codex-cli,forge | --agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=tn.url;t||Tr("Pairing requires --url with the EngineerOS backend address."),tn.agent&&tn["agent-command"]&&Tr("Use either --agent or --agent-command, not both.");let n=tn["agent-protocol"]||(tn["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||Tr(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(tn.agent||tn["agent-command"])&&Tr("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{tn.agent&&(await Zu(tn.agent),r=await ul(tn.agent))}catch(o){Tr(o instanceof Error?o.message:String(o))}if(U={server_url:Ib(t),workspace:ar.resolve(tn.workspace||process.cwd()),onboard:tn.onboard===!0,onboarding_pending:tn.onboard===!0,hunt_host:ap,...tn["knowledge-dir"]?{knowledge_dir:ar.resolve(tn["knowledge-dir"])}:{},agent_protocol:n,agent_command:tn["agent-command"]||null,agent_args:jxe(tn["agent-args"]),agent_name:tn["agent-name"]||null,...r,skip_git_repo_check:ap||tn["skip-git-repo-check"]===!0,name:tn.name||`${QSe.hostname()} - ${ar.basename(ar.resolve(tn.workspace||process.cwd()))}`},Vl=await yn(U.workspace).catch(o=>(gs&&Tr(`Auto cannot safely read the existing workspace pairing. Restore its credential store/configuration, then retry; the existing pairing was not changed. ${o.message}`),console.warn(`${o instanceof Error?o.message:String(o)} Pairing as a new connector instead.`),null)),gs)try{let o=await Dq(U,Vl,gs,{inspect:di});U=o.config,f3=o.inspected;for(let s of o.statuses)console.log(`[auto] ${s.id}: ${s.status}${s.message?` - ${s.message}`:""}`)}catch(o){Tr(o.message)}mo={type:"pair",pairing_code:e,name:U.name,capabilities:{},...gs?{routing_mode:"auto"}:{},...AO(Vl,U.server_url)}}else $c==="start"?(U=await yn(tn.workspace||process.cwd()),U||Tr("This connector is not paired. Create a pairing command in EngineerOS first."),U.auto_pairing_pending===!0&&Tr("Auto routing confirmation is pending. Paired credentials and saved sessions are retained. Update the backend or resolve its routing policy, then explicitly pair again before starting this connector."),ap&&!U.hunt_host&&Tr("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),tn["knowledge-dir"]&&(U={...U,knowledge_dir:ar.resolve(tn["knowledge-dir"])},await bn(U)),U.token||Tr("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),mo={type:"authenticate",connector_id:U.connector_id,token:U.token}):Tr("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `history compact`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");h3=qH(()=>U,{reportError:e=>console.error(e)}),Ws=0,Qv=!1,Jl=null,Zn=new Map,rR=new Map,oR=new Set,Io=[],Rr=new Map,Ii=null,Hv=!1,m3=0,sR=null,iR=[],Wv=1e3,Z5=0,Vv=!1,Co=!1,va=!1,Jv=!1,aR=null,Zv=!1,gR=0;kR=y5({runtimes:[{id:"transport",stop:()=>{pn?.close()}},{id:"agent-processes",stop:()=>NI().catch(e=>{throw new Error(`${e.message}. Stop those processes before restarting the connector.`,{cause:e})})},{id:"acp-runtimes",stop:()=>Vp()},{id:"release-deployments",stop:()=>pp?.stop()},{id:"bug-hunts",stop:()=>Yl?.abortAll()},{id:"scheduled-tests",stop:()=>up?.stop()},{id:"quality-baselines",stop:()=>Em?.stop()},{id:"test-automation",stop:()=>Gl?.cancelAll()},{id:"active-work",stop:async()=>{await Promise.all([...Zn.values()].map(e=>Ur(e.child))),await Promise.all([...Rr.values()].map(AR))}},{id:"diagnostics",stop:()=>{fp?.stop()}},{id:"timers",stop:()=>{g3?.(),mR?.(),clearTimeout(Gv),clearInterval(hR),clearInterval(pR)}},{id:"observers",stop:()=>{xa?.stop(),bR?.stop(),p3?.stop()}},{id:"operator-console",stop:()=>{sn=!0,Am?.stop(),Gn?.stop()}}]});await kR.start();for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{dp()});e3=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{e3||(e3=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await dp({exitCode:1}))});Gn=lj();process.on("exit",()=>{Am?.stop(),Gn.stop()});Gn.banner(`EngineerOS connector ${Ss}`,[U.workspace,U.server_url]);fp=V5({collect:()=>hp(U,U.workspace),intervalMs:u3,isBusy:()=>Zn.size>0||Rr.size>0,onError:e=>console.error(`Connector self-diagnostics failed: ${e instanceof Error?e.message:String(e)}`)});sxe=RG({stateFile:ar.join(yr(),"recovery-state.json"),repairs:{refresh_tool_inventory:AG({inspect:()=>Lr(U.workspace),current:()=>nt.tool_inventory,publish:async e=>{nt.tool_inventory=e,cr()}}),restart_goal_runner:TG({restart:()=>la(U.workspace),probe:()=>tq(U.workspace)})}});xa=bG({recoveryExecutor:sxe,actions:{refresh_tool_inventory:async()=>{nt.tool_inventory=await Lr(U.workspace),cr()},restart_goal_runner:()=>la(U.workspace)},onNotify:()=>fp.refresh({force:!0,reason:"incident"}),explain:async e=>{if(!await jo())return null;let{reading:t}=await Kx(U,e);return t},onUpdate:e=>BG(U.workspace,e)});p3=VG({render:(e,t)=>Gn.write(e,t),onRecord:e=>xa.observe(e)});bR=KG({workspace:U.workspace,onRecord:e=>{xa.observe(e),Gn.line(e.channel,e.level,e.message)}});xa.start();U.hunt_host||bR.start();Gn.live&&!U.hunt_host&&(pR=setInterval(()=>{ixe().catch(()=>{})},ZSe),pR.unref?.());cR=new Set;try{let e=U.hunt_host?{}:await Ca(U.workspace);e.committed&&(U.onboarding_pending=!0,U.connector_id&&await bn(U),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await S3(e)}w3=await io(yr()).then(e=>e.policy!=="manual",()=>!1);try{Ct=f3??await di(U,U.workspace)}catch(e){await S3(e)}console.log(`Using ${Ct.name} through ${Ct.protocol} (${Ct.version}).`);console.log(`System time: ${Qo()} (${Intl.DateTimeFormat().resolvedOptions().timeZone}).`);y3=async()=>ih({workspace:U.workspace}).names().catch(()=>[]),nt=mc(U,Ct,await Lr(U.workspace),{secretNames:await y3()}),cxe=x5({stateFile:ar.join(yr(),"approval-grants.json")}),Ql=H5({workspace:U.workspace,runtimeIdentity:async()=>(await Lg(U.workspace))?.identity??null,provision:e=>Cj(U.workspace,{...e,log:eb}),verify:e=>Ij(U.workspace,{...e,log:eb}),isIdle:async()=>(Yl?.active??0)===0&&(up?.active??0)===0,onReport:e=>{nt.runtime_prerequisites=e,ka=e.profile===Hl&&e.state==="ready",nt.bug_hunt_browser=ka,pn?.readyState===WebSocket.OPEN&&cr()}});nt.runtime_prerequisites=Ql.report();vm=null,t3=0;ba=uO({workspace:U.workspace,running:Bm(process.argv[1],ou),supervised:process.env[Ra]==="1",isIdle:async()=>(Io.length&&Zn.size===0&&!sn&&await lxe(),!sn&&Zn.size===0&&Io.length===0&&Rr.size===0&&Ws===0&&gR===0&&!va&&!Zv&&(Gl?.active??0)===0&&(Em?.active??0)===0&&(pp?.activeCount??0)===0&&(Yl?.active??0)===0&&(up?.active??0)===0&&!Hv),restart:()=>dp({exitCode:Sp}),onChange:e=>{nt.runtime_update=e,pn?.readyState===WebSocket.OPEN&&cr()}});try{await ba.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}U={...U,execution_profiles:Ct.executionProfiles??null,runtime_catalog:Ct.runtimeCatalog??null,runtime_limits:{...U.runtime_limits,...Object.fromEntries((Ct.runtimeCatalog??[]).filter(e=>e.limits?.source==="provider_report").map(e=>[e.id,e.limits]))}};$c==="pair"&&(Vl?.connector_id||gs)||await bn(U);nt.agent_session={...nt.agent_session,status:"checking",message:`Checking that ${Ct.name} can answer.`};nt.bug_hunt_browser=!1;nt.runtime_limits=U.runtime_limits??{};mo.capabilities=nt;console.log(Qi(U.worker_limit)===null?`Workers: automatic, ${Pu()} ${Ct.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Qi(U.worker_limit)} ${Ct.name} workers side by side, set with /workers.`);lp=Us({getConfig:()=>U});pp=i5({getConfig:()=>U,onIssue:e=>console.error(e)});ws=async e=>{let t;try{t=await pi(U,e)}catch(n){throw[401,403].includes(n.status)&&(Co=!0,console.error("EngineerOS withdrew this connector's authorization. Local work is stopping; saved reports are retained."),dp()),n}return t?.execution_sync&&await dxe(t.execution_sync),t},n3=Gf(ws,{signature:wU}),Kl=HH({getConfig:()=>U,send:ws,onRetained:({status:e,file:t,reason:n})=>console.error(`Prompt result ${e==="execution_unknown"?"requires process inspection":e==="pending"?"saved for automatic delivery":"rejected; original evidence retained"}: ${t}${n?` (${n})`:""}`)}),wR=WH({capacity:()=>Ws>0?0:Yp(U.worker_limit).worker_limit-Zn.size}),uR=!1,uxe=3,bm=0,Kv=new Map,yR=new Set;mxe={async cancelPrompt(e){let t=[...Rr.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.`},runtimeSelection:e=>x3(e),setWorkers:e=>b3(e),setVerbose(e){return e===Qv?`Detailed agent activity is already ${e?"on":"off"}.`:(SR(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"?(ba.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 ba.command(e),iu(await ba.refresh()))},async selfDiagnostics(){let e=await fp.refresh({force:!0,reason:"operator"});return e?rv(e):"Connector self-diagnostics stopped before a report was available."}};Am=MG({ui:Gn,snapshot:fxe,actions:mxe});Am&&console.log(PG());await v3();yxe=8e6,o3="";bxe=6e4,s3=0;op=null,ka=!1,_R=0,Exe=Date.now();Ec=null,a3=null;c3=null;l3="Cancelled from the connector terminal by the person running it.";_3().catch(e=>console.error(`Saved connector work: ${e.message}`))});M();Tm();Rm();M();su();var RR=$a("undici"),D3=Object.freeze(["localhost","127.0.0.1","::1"]);function sb(e,t){for(let n of t){let r=String(e[n]??"").trim();if(r)return r}return""}function OR(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return"an unparseable proxy address"}}function L3(e=process.env){let t=sb(e,["HTTP_PROXY","http_proxy"]),n=sb(e,["HTTPS_PROXY","https_proxy"])||t;if(!t&&!n)return null;for(let s of[t,n].filter(Boolean)){let i;try{i=new URL(s)}catch{i=null}if(!i||!["http:","https:"].includes(i.protocol))throw new Error(`The proxy ${OR(s)} in HTTPS_PROXY or HTTP_PROXY is not an http:// or https:// URL.`)}let r=sb(e,["NO_PROXY","no_proxy"]).split(",").map(s=>s.trim()).filter(Boolean),o=[...new Set([...r,...D3])].join(",");return{httpProxy:t||n,httpsProxy:n,noProxy:o}}function CR(e=process.env,{install:t=n=>RR().setGlobalDispatcher(n)}={}){let n=L3(e);return n?(t(new(RR()).EnvHttpProxyAgent(n)),`Using proxy ${OR(n.httpsProxy)} for EngineerOS traffic (bypassing ${n.noProxy}).`):null}Nc();var R3;try{R3=ru(process.argv.slice(2))}catch(e){console.error(e.message),process.exit(1)}var{command:TR,positional:Pxe,flags:Mxe}=R3;TR==="version"&&(console.log(Ss),process.exit(0));var rb=null;try{rb=CR()}catch(e){console.error(e.message),process.exit(1)}rb&&["start","pair","hunt-host","doctor"].includes(TR)&&process.env[Ra]!=="1"&&console.error(rb);var{runCommand:Dxe}=await Promise.resolve().then(()=>(jH(),IH));await Dxe(TR,Pxe,Mxe,{proxyNotice:rb});await T3().then(()=>Nxe);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@engineeros/connector",
3
- "version": "1.67.6",
3
+ "version": "1.67.8",
4
4
  "description": "Connect a local coding agent to EngineerOS, using ACP when supported.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",