@engineeros/connector 1.59.7 → 1.59.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.
@@ -1106,7 +1106,7 @@ It is checked with the provider and stored in this machine's protected vault
1106
1106
  (Windows Data Protection, the macOS Keychain or the Linux Secret Service).
1107
1107
  EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function WK(e,{input:t=process.stdin,output:n=process.stdout}={}){return t.isTTY?new Promise((r,o)=>{n.write(e);let s="";t.setRawMode(!0),t.resume(),t.setEncoding("utf8");let i=c=>{t.setRawMode(!1),t.pause(),t.removeListener("data",a),n.write(`
1108
1108
  `),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
1109
- `)return i();if(l==="")return i(new Error("Cancelled."));l==="\x7F"||l==="\b"?s=s.slice(0,-1):s+=l}};t.on("data",a)}):new Promise((r,o)=>{let s="";t.setEncoding("utf8"),t.on("data",i=>s+=i),t.on("end",()=>r(s.trim())),t.on("error",o)})}var uC=Symbol("missing");function qK(e,t){return new Promise(n=>{let r=GK(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?uC:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function lC(e,t){for(let n of Ec){let r=t[n],o=r.connected?`connected${r.account?` as ${r.account}`:""}`:"not connected";e(`${n.padEnd(8)} ${o}`),r.connected||e(` ${r.detail?`${r.detail} `:""}Connect: ${r.connect_command}`)}}async function dC(e,t,n,{vault:r=fw(),run:o=Gd,fetchImpl:s=fetch,secret:i=WK,interactive:a=qK,install:c=Bd,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(HK),n.help?0:2;if(e==="integrations")return lC(l,(await qd({run:o,vault:r})).providers),0;let p=t[0];if(!Ec.includes(p))return u(`Unknown provider ${p}. Choose one of: ${Ec.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=gs[p];if(e==="disconnect")return l(`${p} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===uC){let m=await ki(f);if(!m){l(`Installing the ${bc[f].label} ${bc[f].version} for the connector...`);try{m=(await c(f)).path}catch(g){return u(g.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${Wd[p]} is how this machine signs in to ${p}.`),1):(lC(l,{[p]:(await qd({run:o,vault:r})).providers[p]}),0)}let d=nn[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await hw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await mw(r,p,{token:f,site:n.site,email:n.email},s);return l(`Connected ${d.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}I();import{spawn as VK}from"node:child_process";async function pC({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=VK,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ho(await gn(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await XK(o,c.entry,i,t);if(l===Xi){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let p=await gn(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await Cp(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${d.version}.`);continue}catch(d){s(`Automatic rollback failed: ${d.message}`)}}return l??1}}function XK(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Es]:"1",[$p]:r.entry,[xp]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,p)=>{l(),o({code:u,signal:p})})})}var Fo="1.59.7",Qd="1.59.7",ZK=3e5,ep=["queued","running","reporting"],QK=5e3,gw={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."},ww={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."},eY=6e4,tY=3e4,nY=60*6e4,yw={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},_w={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:St,positional:zt,flags:Le}=HA(process.argv.slice(2));St==="version"&&(console.log(Fo),process.exit(0));var co=null,sn=!1,br=null,TC=!1,RC=null,Ow=null,Bt=null,Oc=null,Tw,fC,hC,vw,mC,xi,Ti,CC=jd({getWorkspace:()=>M.workspace,onRecorded:e=>F1(M,e).then(()=>console.log(`Recorded the ${e.role} sign-in for Bug Hunter; it is kept on this machine.`)).catch(t=>console.error(`The recorded ${e.role} sign-in was not reported to EngineerOS: ${t.message}`))}),rY=aC({getWorkspace:()=>M.workspace,huntSignIns:CC}),Ac=XA();St==="results"&&(zt[0]!=="upload"&&(console.log($d),process.exit(Le.help||!zt[0]?0:2)),process.exit(await ZT(Le)));(St==="connect"||St==="disconnect"||St==="integrations")&&process.exit(await dC(St,zt,Le,{fetchImpl:oC}));if(St==="runner"){let e=on.resolve(Le.workspace||process.cwd()),t=zt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?on.join(on.dirname(Et(e,Le["run-id"])),"worker.log"):on.join(e,".engineeros","runner","service.log");KK(on.dirname(n),{recursive:!0});let r=(...s)=>Va(n,`${YK(...s)}
1109
+ `)return i();if(l==="")return i(new Error("Cancelled."));l==="\x7F"||l==="\b"?s=s.slice(0,-1):s+=l}};t.on("data",a)}):new Promise((r,o)=>{let s="";t.setEncoding("utf8"),t.on("data",i=>s+=i),t.on("end",()=>r(s.trim())),t.on("error",o)})}var uC=Symbol("missing");function qK(e,t){return new Promise(n=>{let r=GK(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?uC:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function lC(e,t){for(let n of Ec){let r=t[n],o=r.connected?`connected${r.account?` as ${r.account}`:""}`:"not connected";e(`${n.padEnd(8)} ${o}`),r.connected||e(` ${r.detail?`${r.detail} `:""}Connect: ${r.connect_command}`)}}async function dC(e,t,n,{vault:r=fw(),run:o=Gd,fetchImpl:s=fetch,secret:i=WK,interactive:a=qK,install:c=Bd,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(HK),n.help?0:2;if(e==="integrations")return lC(l,(await qd({run:o,vault:r})).providers),0;let p=t[0];if(!Ec.includes(p))return u(`Unknown provider ${p}. Choose one of: ${Ec.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=gs[p];if(e==="disconnect")return l(`${p} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===uC){let m=await ki(f);if(!m){l(`Installing the ${bc[f].label} ${bc[f].version} for the connector...`);try{m=(await c(f)).path}catch(g){return u(g.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${Wd[p]} is how this machine signs in to ${p}.`),1):(lC(l,{[p]:(await qd({run:o,vault:r})).providers[p]}),0)}let d=nn[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await hw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await mw(r,p,{token:f,site:n.site,email:n.email},s);return l(`Connected ${d.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}I();import{spawn as VK}from"node:child_process";async function pC({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=VK,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ho(await gn(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await XK(o,c.entry,i,t);if(l===Xi){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let p=await gn(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await Cp(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${d.version}.`);continue}catch(d){s(`Automatic rollback failed: ${d.message}`)}}return l??1}}function XK(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Es]:"1",[$p]:r.entry,[xp]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,p)=>{l(),o({code:u,signal:p})})})}var Fo="1.59.8",Qd="1.59.8",ZK=3e5,ep=["queued","running","reporting"],QK=5e3,gw={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."},ww={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."},eY=6e4,tY=3e4,nY=60*6e4,yw={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},_w={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:St,positional:zt,flags:Le}=HA(process.argv.slice(2));St==="version"&&(console.log(Fo),process.exit(0));var co=null,sn=!1,br=null,TC=!1,RC=null,Ow=null,Bt=null,Oc=null,Tw,fC,hC,vw,mC,xi,Ti,CC=jd({getWorkspace:()=>M.workspace,onRecorded:e=>F1(M,e).then(()=>console.log(`Recorded the ${e.role} sign-in for Bug Hunter; it is kept on this machine.`)).catch(t=>console.error(`The recorded ${e.role} sign-in was not reported to EngineerOS: ${t.message}`))}),rY=aC({getWorkspace:()=>M.workspace,huntSignIns:CC}),Ac=XA();St==="results"&&(zt[0]!=="upload"&&(console.log($d),process.exit(Le.help||!zt[0]?0:2)),process.exit(await ZT(Le)));(St==="connect"||St==="disconnect"||St==="integrations")&&process.exit(await dC(St,zt,Le,{fetchImpl:oC}));if(St==="runner"){let e=on.resolve(Le.workspace||process.cwd()),t=zt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?on.join(on.dirname(Et(e,Le["run-id"])),"worker.log"):on.join(e,".engineeros","runner","service.log");KK(on.dirname(n),{recursive:!0});let r=(...s)=>Va(n,`${YK(...s)}
1110
1110
  `),o=(s,i,a)=>(Va(n,s),(typeof i=="function"?i:a)?.(),!0);process.stdout.write=process.stderr.write=o,console.log=console.error=console.warn=r}if(t==="install"){if(Le["keep-awake"]!==void 0){if(!["on","off"].includes(Le["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await Yt(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await Wn({...n,runner_keep_awake:Le["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await Xu(e)}`),process.platform==="darwin"&&console.log("macOS may show a Background Items Added notice. Manage the runner in System Settings > General > Login Items.")}else t==="uninstall"?(await Ex(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await di(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await Ro(e),null,2)):t==="serve"?await Tx(e):t==="worker"?await Rx(e,Le["run-id"]):dt("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){dt(Hm(n,e).message)}}Le["assessment-workers"]!==void 0&&dt("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(St==="secret")try{let e=qm(Le),t=zt[0]||"list",n=await GA({action:t,name:zt[1],workspace:e,readValue:()=>BA({label:`Value for ${zt[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){dt(e.message)}if(St==="tools"){try{let e=qm(Le),t=zt[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=zt[1];r||dt(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await Nh(e,{type:"tools.auth",command_id:"00000000-0000-4000-8000-000000000001",action:{"sign-in":"sign_in","auth-status":"status","sign-out":"sign_out"}[t],provider_id:r,confirmed:t==="sign-out"});o.completion&&await o.completion}else["setup","upgrade","rollback"].includes(t)?await Oa(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:zt[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await Oh(e,t,zt[1]);let n=await zn(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){dt(e.message)}process.exit(process.exitCode||0)}if(St==="agents"){let e;try{e=await Kh()}catch(n){dt(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await ja(n.id),`${n.id}: ready (${n.name} ${n.version}, ${n.distribution_type})`}catch(r){let o=r instanceof Error?r.message:String(r);return`${n.id}: setup needed (${n.name} ${n.version}, ${n.distribution_type}) - ${o}`}}));for(let n of t)console.log(n);process.exit(0)}if(St==="agent"){let e=zt[0],t=zt[1]||"check";(!e||!["check","install"].includes(t))&&dt("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await Na(e):await ja(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){dt(n instanceof Error?n.message:String(n))}process.exit(0)}if(St==="mcp"){let e=Le.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=Le["run-id"]||zt[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await Yt(e);await cT({config:n,runId:t,version:Fo,input:process.stdin,output:process.stdout}),process.exit(0)}if(St==="context-mcp"){let e=Le["config-workspace"]||Le.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await Yt(e);t||dt("This workspace is not paired with EngineerOS."),await BT({config:t,workspace:Le.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:Fo,input:process.stdin,output:process.stdout}),process.exit(0)}if(St==="status"){let e=await Yt(Le.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(St==="doctor"){let e=on.resolve(Le.workspace||process.cwd()),t=await Yt(e),n=await rT(e),r=await Mi(t||{workspace:e},e,kg(n));console.log(yg(r)),process.exit(r.status==="failed"?1:0)}if(St==="update"){let e=zt[0]||"status";try{let t=Tp(process.argv[1],Qd),n=await Op(Fr(),t,{action:e,policy:zt[1]??null});console.log(Ki(Ip(n,t,{supervised:!0})))}catch(t){dt(`${t.message}
1111
1111
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var Ri=St==="hunt-host";if(Ri)try{Le.workspace=jx(zt,Le)}catch(e){dt(e.message)}if((St==="start"||St==="pair"||Ri)&&process.env[Es]!=="1"&&It(Qd))try{process.exit(await pC({root:Fr(),bundled:{version:Qd,entry:on.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:on.resolve(Le.workspace||process.cwd())}))}catch(e){dt(`The connector process could not be started: ${e.message}`)}if(Ri){try{await Nx(Le.workspace,zt[0]?Le.agent:null)}catch(e){dt(e.message)}St=zt[0]?"pair":"start"}var M,ys,Tc;if(St==="pair"){let e=zt[0];e||dt("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=Le.url;t||dt("Pairing requires --url with the EngineerOS backend address."),Le.agent&&Le["agent-command"]&&dt("Use either --agent or --agent-command, not both.");let n=Le["agent-protocol"]||(Le["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||dt(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(Le.agent||Le["agent-command"])&&dt("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{Le.agent&&(await ja(Le.agent),r=await Yh(Le.agent))}catch(o){dt(o instanceof Error?o.message:String(o))}M={server_url:Mp(t),workspace:on.resolve(Le.workspace||process.cwd()),onboard:Le.onboard===!0,onboarding_pending:Le.onboard===!0,hunt_host:Ri,agent_protocol:n,agent_command:Le["agent-command"]||null,agent_args:AY(Le["agent-args"]),agent_name:Le["agent-name"]||null,...r,skip_git_repo_check:Ri||Le["skip-git-repo-check"]===!0,name:Le.name||`${JK.hostname()} - ${on.basename(on.resolve(Le.workspace||process.cwd()))}`},Tc=await Yt(M.workspace),ys={type:"pair",pairing_code:e,name:M.name,capabilities:{},...Hy(Tc,M.server_url)}}else St==="start"?(M=await Yt(Le.workspace||process.cwd()),M||dt("This connector is not paired. Create a pairing command in EngineerOS first."),Ri&&!M.hunt_host&&dt("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),M.token||dt("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),ys={type:"authenticate",connector_id:M.connector_id,token:M.token}):dt("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var OC=Cx(M,{reportError:e=>console.error(e)}),Uo=0,tp=!1,Rc=null,an=new Map,bw=0,Sw=new Set,Ci=[],rn=new Map,Nt,Rw,Jd,Nr=null,Kd=!1,IC=0,kw=null,Ew=[],Yd,jC,$c=1e3,Oi,gC=0,$w=!1,so=!1,tr,Do=!1,np=!1,Cw=0;function $i(e){return Cw+=1,e.finally(()=>{Cw-=1})}var Ai,ws=0;function Cc({exitCode:e=0}={}){if(ws=Math.max(ws,e),Ai)return Ai;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Ai=oY().finally(()=>clearTimeout(t)),Ai}async function oY(){if(sn=!0,Oc?.stop(),co?.stop(),Ow?.stop(),RC?.stop(),clearInterval(Tw),Bt?.stop(),jC?.(),clearTimeout(Yd),clearInterval(Rw),clearInterval(Jd),await Promise.all([...[...an.values()].map(e=>yn(e.child))]),await Promise.all([...rn.values()].map(Nw)),await xi?.cancelAll(),await Ti?.abortAll(),await Ia(),await Gw().catch(e=>{ws=Math.max(ws,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),Nt?.close(),ws&&ws!==Xi){let e;await Promise.race([(async()=>{await co?.drain(),await Mi(M,M.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(ws)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{Cc()});var wC=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{wC||(wC=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await Cc({exitCode:1}))});Bt=Kw();process.on("exit",()=>{Oc?.stop(),Bt.stop()});Bt.banner(`EngineerOS connector ${Fo}`,[M.workspace,M.server_url]);co=VA({actions:{refresh_tool_inventory:async()=>{Fe.tool_inventory=await zn(M.workspace),Cn()},restart_goal_runner:()=>di(M.workspace)},onNotify:()=>Mi(M,M.workspace),explain:async e=>{if(!await Ni())return null;let{reading:t}=await ex(M,e);return t},onUpdate:e=>nT(M.workspace,e)});RC=sT({render:(e,t)=>Bt.write(e,t),onRecord:e=>co.observe(e)});Ow=iT({workspace:M.workspace,onRecord:e=>{co.observe(e),Bt.line(e.channel,e.level,e.message)}});co.start();M.hunt_host||Ow.start();Bt.live&&!M.hunt_host&&(Tw=setInterval(()=>{sY().catch(()=>{})},QK),Tw.unref?.());var xw=new Set;async function sY(){if(M.hunt_host)return;fC??=zm(M.workspace);let{jobs:e}=await fC(),t=new Set,n=e.filter(r=>r.status!=="queued"&&ep.includes(r.status)).length;for(let r of e){if(!ep.includes(r.status))continue;t.add(r.runId),xw.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;Bt.status(`goal:${r.runId}`,o,iY(r),{agent:r.status!=="queued",link:Rc&&`${Rc}/goals`}),Bt.step(`goal:${r.runId}`,r.activity?.message)}for(let r of xw)t.has(r)||(xw.delete(r),Bt.clearStatus(`goal:${r}`))}function iY(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function Ni({ignoreBugHunt:e=!1}={}){if(sn||an.size>0||rn.size>0||Uo>0||(xi?.active??0)>0||!e&&(Ti?.active??0)>0)return!1;try{let{jobs:t}=await Ro(M.workspace);return!sn&&!t.some(n=>ep.includes(n.status))}catch{return!1}}try{let e=M.hunt_host?{}:await Ss(M.workspace);e.committed&&(M.onboarding_pending=!0,M.connector_id&&await Wn(M),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await DC(e)}var NC=await gn(Fr()).then(e=>e.policy!=="manual",()=>!1),it;try{it=await Ha(M,M.workspace)}catch(e){await DC(e)}console.log(`Using ${it.name} through ${it.protocol} (${it.version}).`);var MC=async()=>lc({workspace:M.workspace}).names().catch(()=>[]),Fe=gd(M,it,await zn(M.workspace),{secretNames:await MC()}),ao=Cy({running:Tp(process.argv[1],Qd),supervised:process.env[Es]==="1",isIdle:async()=>!sn&&an.size===0&&Ci.length===0&&rn.size===0&&Uo===0&&Cw===0&&!Do&&!np&&!Kd,restart:()=>Cc({exitCode:Xi}),onChange:e=>{Fe.runtime_update=e,Nt?.readyState===WebSocket.OPEN&&Cn()}});try{await ao.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}M={...M,execution_profiles:it.executionProfiles??null};St==="pair"&&Tc?.connector_id||await Wn(M);Fe.agent_session={...Fe.agent_session,status:"checking",message:`Checking that ${it.name} can answer.`};Fe.bug_hunt_browser=!1;ys.capabilities=Fe;console.log(Qr(M.worker_limit)===null?`Workers: automatic, ${oi()} ${it.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Qr(M.worker_limit)} ${it.name} workers side by side, set with /workers.`);var Ii=e=>eo(M,e),yC=Hu(Ii,{signature:lx});async function aY(){let e=await Ro(M.workspace).catch(()=>({service:null,jobs:[]}));return{version:Fo,now:Date.now(),workspace:M.workspace,config_path:$n(M.workspace),config:M,agent:it,automatic_worker_limit:oi(),worker_limit:Qr(M.worker_limit),connection:{state:cY(),server_url:M.server_url,last_error:tr||null},work:{assessments:[...an.values()].map(t=>({stage:t.stage,message:t.lastMessage,started_at:t.startedAt})),prompts:[...rn.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,started_at:t.startedAt})),integrations:Uo},runner:e,runtime_update:ao.report(),health:co?.health()??null,activity:Ac.snapshot()}}function cY(){return sn||so?"stopped":Nt?.readyState===WebSocket.OPEN?"connected":"connecting"}var lY={async cancelPrompt(e){let t=[...rn.values()].find(n=>n.runId.startsWith(e));return t?(t.stoppedHere=!0,t.cancellation.abort(),await t.controller?.completed.catch(()=>{}),`Stopping prompt ${e} (${t.purpose}); EngineerOS will be told it was cancelled here.`):`Prompt ${e} finished before it could be stopped.`},setWorkers:e=>LC(e),setVerbose(e){return e===tp?`Detailed agent activity is already ${e?"on":"off"}.`:(Iw(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"?(ao.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 ao.command(e),Ki(await ao.refresh()))}};Oc=ZA({ui:Bt,snapshot:aY,actions:lY});Oc&&console.log(YA());await PC();var _C=new Set;async function PC(){if(sn||so)return;console.log(`Connecting ${M.name} to ${M.server_url}`),so=!1,tr=void 0;let e=new WebSocket(M.server_url);Nt=e;let t=Xv(e,M.server_url,{onTimeout:r=>{Nt===e&&(tr=r,console.error(r),Aw())}});jC=t,e.addEventListener("open",()=>{if(Nt!==e){e.close();return}try{if(Bv(Nt,e,ys))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){tr=un(r),console.error(`Could not authenticate the WebSocket connection: ${tr}`);try{e.close()}catch{}Aw()}}),e.addEventListener("message",r=>{if(Nt!==e)return;let o;try{o=JSON.parse(String(r.data))}catch{console.error("Ignored a malformed EngineerOS message frame (invalid JSON).");return}n(o).catch(s=>{console.error(`EngineerOS ${String(o?.type||"unknown").slice(0,80)} message failed: ${un(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){sn=!0,so=!0,t(),console.error("Update the EngineerOS backend to support connector HTTP updates before reconnecting."),e.close();return}if(r.type==="paired"){t();let s=Tc?.connector_id===r.connector.id;if(M=Wy(M,Tc,r.connector.id,r.token),await Wn(M),r.connector?.capabilities?.http_updates!==!0){sn=!0,so=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}ys={type:"authenticate",connector_id:M.connector_id,token:M.token,capabilities:Fe},console.log(s?`Reconnected existing workspace connector ${M.connector_id}; assessment history is preserved.`:`Paired. Connector ${M.connector_id} is online.`),kC(r);return}if(r.type==="authenticated"){t();let s=M.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(Oi?`Reconnected after ${tt(Date.now()-Oi)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),Oi=void 0,kC(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){np||dY(r);return}if(r.type==="workspace.refresh"){ji();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await LC(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){Iw(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(io=!1,Fe.bug_hunt_browser=!1,Cn());try{Fe.tool_inventory=await Oa(M.workspace,r,void 0,{confirmLocal:i=>Oc?.confirm(i)??!1,log:Zd}),s&&(io=!0),Fe.bug_hunt_browser=hs(Fe.tool_inventory)&&io,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Fe.tool_inventory})),Cn(),console.log(`Tool registry updated: ${r.action} ${r.provider_id}.`)}catch(i){let a=i instanceof Error?i.message.slice(0,300):"The local connector rejected the tool registry update.";e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,error:a})),console.error(`Tool registry update rejected: ${a}`)}return}if(r.type==="tools.auth"){try{let s=await Nh(M.workspace,r,{onStatus:async()=>{Fe.tool_inventory=await zn(M.workspace),Cn()}});Fe.tool_inventory=s.inventory,s.completion&&s.completion.catch(i=>console.error(`Tool authentication status: ${i instanceof Error?i.message.slice(0,300):"Local status update failed."}`)),e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Fe.tool_inventory})),Cn(),console.log(`Tool authentication updated: ${r.action} ${r.provider_id}.`)}catch(s){let i=s instanceof Error?s.message.slice(0,300):"The local connector rejected the tool authentication request.";e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,error:i})),console.error(`Tool authentication rejected: ${i}`)}return}if(r.type==="test_environment.health_check"){Ps(r).then(s=>{e.send(JSON.stringify({type:"test_environment.health_result",command_id:r.command_id,result:s})),console.log(`Test environment health: ${s.status}${s.message?` (${s.message})`:""}.`)}).catch(s=>console.error(`Test environment health was not reported: ${s.message}`));return}if(r.type===iC){$i(rY(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),cC(M,s))).catch(s=>console.error(`An integration answer was not delivered: ${s.message}`)));return}if(r.type==="workspace.assessment"){let s=`${r.assessment_id}:${r.stage}`;Rm(Ci,an.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Ic();return}if(r.type==="prompt.execute"){let s=rn.get(r.prompt_id);s?GC(r)>s.executionRevision&&await kY(s,r):BC(r);return}if(r.type==="prompt.cancel"){let s=rn.get(r.prompt_id);s&&await Nw(s);return}if(r.type==="agent.warm"){gY(r);return}if(r.type==="run.available"){if(M.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await OC.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${on.join(M.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${un(s)}`)}return}if(r.type==="goal.cleanup"){try{await Ax(M.workspace),await di(M.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){xY(r);return}if(r.type==="run.cancelled"){await Fm(M.workspace,r.run_id);return}if(r.type===qb){xi??=ph({getConfig:()=>M,onTestsCommitted:()=>ji()}),$i(xi.handle(r));return}if(r.type===Vb){xi??=ph({getConfig:()=>M,onTestsCommitted:()=>ji()}),await xi.cancel(r);return}if(r.type===TR){Ti??=jR({getConfig:()=>M,isIdle:()=>Ni({ignoreBugHunt:!0}),recordedSignIns:CC,activity:{status:Bt.status,step:jw,agents:Bt.agents,finish:Bt.finish}}),$i(Ti.handle(r));return}if(r.type===RR){Ti?.stop(r);return}if(r.type===QT){hC??=e1({getConfig:()=>M}),$i(hC.handle(r));return}if(r.type===i1){vw??=m1({getConfig:()=>M}),$i(vw.handle(r));return}if(r.type===a1){await vw?.cancel(r);return}if(r.type===w1){mC??=y1({getConfig:()=>M,isIdle:()=>Ni(),agentTurn:x$}),$i(mC.handle(r));return}if(r.type==="connector.update"){uY(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await Cc();return}if(r.type==="connector.revoked"){sn=!0,console.error("This connector was revoked in EngineerOS."),e.close();return}if(r.type==="run.error"){console.error(`EngineerOS: ${r.message}`),r.run_id||(Do=!1);return}if(r.type==="connection.error"){so=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);_C.has(o)||(_C.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${Fo}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),Nt!==e||Ai)return;let o=Gv(r);if(!o.retry||so||sn){console.error(o.message),o.retry&&so&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),Cc();return}tr=tr?`${o.message} ${tr}`:o.message,Aw()}),e.addEventListener("error",r=>{Nt===e&&(tr=zv(r),console.error(`WebSocket connection to ${M.server_url} failed: ${tr}`))})}async function uY(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=ao.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 ao.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 dY(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";np=!0,console.log(`Starting interactive ${it.name} provider ${n}.`);try{await(n==="logout"?Vv:qv)(it,M.workspace),it=await Ha(M,M.workspace),Fe=gd(M,it,Fe.tool_inventory,{secretNames:await MC()}),ys.capabilities=Fe,Nt.readyState===WebSocket.OPEN&&(Nt.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:Fe.agent_session})),Nt.close(1e3,`Provider ${n} completed`)),console.log(`${it.name} provider ${n} completed.`)}catch(r){let o=un(r).slice(0,500);Nt.readyState===WebSocket.OPEN&&Nt.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{np=!1}}function Aw(){if(sn||so||Yd)return;let e=tr?` Last error: ${tr}`:"",t=Oi?` Offline for ${tt(Date.now()-Oi)}.`:"";Oi??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round($c/1e3)}s.`),Yd=setTimeout(()=>{Yd=void 0,PC()},$c),$c=Math.min(3e4,$c*2)}async function ji(){if(!M.hunt_host&&!(Do||Nt.readyState!==WebSocket.OPEN)){Do=!0,console.log("Inspecting the workspace without executing its code.");try{let{snapshot:e,map:t,stats:n}=await Cg({workspace:M.workspace,connectorId:M.connector_id,refresh:Os,takeSnapshot:rx,buildMap:(i,a)=>Sd(M.workspace,i,{head:a.head_revision,branch:a.branch}),log:i=>console.error(i)}),r=await nx(M.workspace,M.last_head_reported??M.last_snapshot_head,e.head_revision).catch(()=>null);r&&(e.changed_since=r);let o=await fetch($s(M.server_url,M.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:JSON.stringify(e)});if(!o.ok)throw new Error(await wa(o,"the workspace"));let s=await o.json();M={...M,onboarding_pending:!1,last_snapshot_head:e.head_revision??M.last_snapshot_head,last_head_reported:e.head_revision??M.last_head_reported,last_head_branch:e.head_revision?e.branch??null:M.last_head_branch},await Wn(M),t&&await kd(M.workspace,M.connector_id,t).catch(()=>{}),console.log(`Inventoried ${e.total_file_count.toLocaleString()} safe file(s).`),console.log(`Uploaded ${e.evidence_file_count.toLocaleString()} prioritized source file(s).`),console.log(`Excluded ${e.excluded_file_count.toLocaleString()} sensitive or generated file(s).`),e.omitted_evidence_file_count>0&&console.log(`${e.omitted_evidence_file_count.toLocaleString()} additional file(s) remain available to the connected Agent locally.`),console.log(`Workspace inventory registered as ${s.workspace_kind}. Start the baseline assessment in EngineerOS to continue.`),n&&console.log(`Built the local context index: ${n.total_files.toLocaleString()} file(s) ready for assignment context.`),Do=!1}catch(e){Do=!1,console.error(`Workspace assessment failed: ${un(e)}`)}}}var pY=8e6,vC,bC="";async function fY({current:e,previous:t}){if(Do||Nt?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=on.resolve(M.workspace),r=async()=>{M={...M,last_head_reported:e.head,last_head_branch:e.branch??null},await Wn(M)},o=await Rg(M.workspace,M.connector_id),s=async()=>{if(await ji(),M.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let{index:i}=await Os(M.workspace,M.connector_id),a=null,c=await OT({previous:{head:t.head,branch:t.branch??null},current:e,compare:(d,f)=>jm(M.workspace,d,f),inventoryDelta:d=>A_(n,Object.entries(i.files).map(([f,h])=>({path:f,size:h.size})),d),mapDelta:async()=>(a=await Sd(M.workspace,i,{head:e.head,branch:e.branch}),Tg(o,a)),contentHead:(await $l(n).catch(()=>null))?.content_head_revision??null});if(c.status==="snapshot")return s();if(c.status==="nothing")return r();let l=JSON.stringify(c.report);if(Buffer.byteLength(l)>pY)return s();let u=await fetch(Xy(M.server_url,M.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:l});if(!u.ok)throw new Error(await wa(u,"the new commit"));let p=await u.json().catch(()=>({}));if(p.needs_snapshot)return s();await r(),a&&await kd(M.workspace,M.connector_id,a).catch(()=>{}),console.log(`Reported ${c.report.reason==="branch_switch"?"the switch to ":"commit "}${e.head.slice(0,7)}${p.flagged_cases?`: ${p.flagged_cases} test case(s) to check again`:""}.`)}function hY(){M.hunt_host||M.onboarding_pending||Do||Nt?.readyState!==WebSocket.OPEN||(vC??=CT({readHead:()=>RT(M.workspace),getLastReported:()=>({head:M.last_head_reported??M.last_snapshot_head,branch:M.last_head_branch}),onChange:fY,onError:e=>{e.message!==bC&&(bC=e.message,console.error(`The new commit could not be reported yet: ${un(e)}`))}}),vC.poll().catch(()=>{}))}var mY=6e4,SC=0;async function gY(e){if(M.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?M.sessions?.[t]:void 0,r=[];Date.now()-SC>mY&&(SC=Date.now(),r.push(Os(M.workspace,M.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),M.agent_protocol==="acp"&&r.push(kk(M.workspace,M,{sessionKey:n?t:null,previousSessionId:n,sandbox:e.sandbox_mode==="workspace-write"?"workspace-write":"read-only",profile:e.execution_profile&&typeof e.execution_profile=="object"?e.execution_profile:{}}).catch(o=>console.error(`${it?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Cn(){let e=H$(an);yC.update({type:"assessment.workers",assessment_workers:e,tool_inventory:Fe.tool_inventory,runtime_update:Fe.runtime_update,agent_session:Fe.agent_session,bug_hunt_browser:Fe.bug_hunt_browser,...Fu(M.worker_limit)}),yC.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function LC(e){let t=Qr(e);return t===Qr(M.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(M={...M,worker_limit:t},await Wn(M),Ic(),Cn(),t===null?`Workers are automatic again: up to ${oi()} side by side for this machine's CPU and memory, for ${dc} (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: ${dc}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function Iw(e){if(e!==tp){if(tp=e,!e)for(let t of an.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."),Cn()}}function jw(e,t,n=null){Bt.step(e,t,n)&&tp&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function wY(){clearInterval(Jd);let e=!1,t=()=>{e||an.size>0||rn.size>0||(e=!0,Mi(M,M.workspace).finally(()=>{e=!1}))};t(),Jd=setInterval(t,ZK),Jd.unref?.()}async function Mi(e,t,n=co?.healthChecks()??[]){let r=await MA({config:e,workspace:t,version:Fo,insights:n,agentSession:br,probes:{inspectAgent:(o,s)=>sn?it:Ha(o,s),inspectTools:o=>sn?Fe.tool_inventory:zn(o),runnerStatus:Ro}});try{TC=(await PA(e,r,eo))?.autonomy_scan===!0}catch(o){console.error(`EngineerOS did not accept the connector self-check: ${o instanceof Error?o.message:String(o)}`)}return r}async function DC(e){if(sn)return Ai;let t=e instanceof Error?e.message:String(e),n=await Mi(M,M.workspace).catch(()=>null);n&&console.error(yg(n)),dt(t)}function kC(e){Iw(e.connector?.activity_log_enabled===!0),Rc=e.project_url??null,$c=1e3,_Y(),FC(),ao.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),vY(),M.onboarding_pending&&ji()}var xc=null,io=!1,UC=0,yY=Date.now();async function _Y(){return xc||(xc=(async()=>{NC&&await sk(M.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Zd("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await Mx(M.workspace,{log:Zd}),io=!0,Fe.tool_inventory=await zn(M.workspace),Fe.bug_hunt_browser=hs(Fe.tool_inventory)&&io,Zd(`Bug Hunter's browser is ready (${tt(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${tt(Date.now()-e)}: ${t.message}`),Fe.bug_hunt_browser=!1}Cn()})(),xc)}function Zd(e){console.log(`[browser] ${e}`)}async function FC(){if(br?.state!=="checking"){UC=Date.now(),Fe.agent_session={...Fe.agent_session,status:"checking",message:`Checking that ${it.name} can answer.`},Cn(),br={state:"checking",detail:`Asking ${it.name} one question to confirm its session.`},console.log(`Checking that ${it.name} can answer before accepting work.`);try{await J$(M,it.name),br={state:"ready",detail:`${it.name} answered; its session is usable.`},Fe.agent_session={...Fe.agent_session,status:"authenticated",message:br.detail},console.log(br.detail)}catch(e){br={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:M.hunt_host?Lx(M.agent_id||M.agent_protocol):Qs(M.agent_id||M.agent_protocol)},Fe.agent_session={...Fe.agent_session,status:"logged_out",message:br.remedy},console.error(`${br.detail}
1112
1112
  ${br.remedy}`)}Cn(),await Mi(M,M.workspace).catch(()=>null)}}function vY(){clearInterval(Rw);let e=!1,t=0,n=0,r=!1,o=()=>{ao.tick(),bY(),hY(),M.hunt_host&&xc&&Date.now()-UC>=Px(yY)&&rn.size===0&&an.size===0&&!(Ti?.active>0)&&FC(),!M.hunt_host&&!r&&ic(_w.id)&&(r=!0,OC.flush().then(()=>Xd(_w)).catch(s=>Vd(_w,s)).finally(()=>{r=!1})),an.size>0&&Cn(),!M.hunt_host&&!Nr&&Date.now()-t>=eY&&ic(gw.id)&&(t=Date.now(),zC().then(()=>Xd(gw)).catch(s=>Vd(gw,s))),!M.hunt_host&&TC&&!Kd&&ic(ww.id)&&Date.now()-IC>=wS&&(Kd=!0,SY().then(()=>Xd(ww)).catch(s=>Vd(ww,s)).finally(()=>{Kd=!1})),!e&&Date.now()-n>=tY&&ic(yw.id)&&(e=!0,n=Date.now(),zn(M.workspace).then(async s=>{if(Fe.tool_inventory=s,!io&&hs(s))try{await(await Vo(await jo(M.workspace))).close(),io=!0}catch{io=!1}Fe.bug_hunt_browser=hs(s)&&io,Cn(),Xd(yw)}).catch(s=>Vd(yw,s)).finally(()=>{e=!1}))};o(),Rw=setInterval(o,1e4),wY()}async function bY(){if(!(!NC||M.agent_protocol!=="acp"||!M.agent_id||$w||br?.state==="checking"||Date.now()-gC<nY)){$w=!0;try{if(!await Ni())return;gC=Date.now();let e,t=await Ok(M,{verify:async r=>{e=await Ha(r,M.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===M||sn)return;M={...t,execution_profiles:e.executionProfiles??null},await Wn(M),it=e;let n=gd(M,it,Fe.tool_inventory);if(Object.assign(Fe,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),ys.capabilities=Fe,!await Ni())return;await Ia(),Nt?.readyState===WebSocket.OPEN&&Nt.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{$w=!1}}}function Vd(e,t){let n=RA(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 Xd(e){CA(e.id)&&console.log(`${e.title} recovered.`)}async function SY(){if(M.hunt_host||!await Ni())return;IC=Date.now();let{jobs:e}=await Ro(M.workspace).catch(()=>({jobs:[]})),t=await yS(M.workspace,{jobs:e});if(!_S(t))return;let n=`${t.fingerprint}:${Ew.join(",")}`,r=kw?.key===n,o=r?kw.candidates:await tx(M,t,Ew);kw={key:n,candidates:o};let s=await Ii(SS(t,o,{version:Fo}));Array.isArray(s?.refused)&&(Ew=s.refused.map(String));let i=r?"unchanged since the last scan":"scanned";console.log(o.length?`Workspace ${i}; reported ${o.length} delivery candidate(s) to EngineerOS: ${o.map(a=>a.capability_name).join(", ")}.`:`Workspace ${i}; nothing worth starting.`)}var Lo=null,EC=null;async function zC(){if(!M.hunt_host){if(Nr)return Nr;Nr=(async()=>{let e=await lS(M,{knownRevision:Lo?.revision??null});if(e.unchanged||(Lo=e),EC===Lo.revision)return Lo;let{jobs:t}=await Ro(M.workspace);return!t.some(r=>ep.includes(r.status))&&Uo===0&&an.size===0&&(await su(M.workspace,Lo),EC=Lo.revision),Lo})();try{return await Nr}finally{Nr=null,Ic()}}}function $C(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)),rn.get(e)?.events.push(n)}var xC=null;function Ic(){let e=Nt.readyState===WebSocket.OPEN,t=an.values().next().value,n=Qr(M.worker_limit)??Math.min(oi(),Cm(t?.workerLimit??Ci[0]?.worker_limit)),r=e&&!Nr&&Uo===0?M$(Ci,an.size,n):[];for(let s of r){let i=`${s.assessment_id}:${s.stage}`,a={kind:"assessment",key:i,runId:s.assessment_id,stage:s.stage,child:null,controller:null,resumeAssignment:null,phase:"starting",progressPercent:5,lastMessage:`Starting ${s.stage} assessment stage`,startedAt:Date.now(),workerLimit:Cm(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};an.set(i,a),$Y(s,a)}r.length>0&&Cn();let o=P$({queued:Ci,running:an.size,workerLimit:n,connected:e,designSync:!!Nr,integrations:Uo});o&&o!==xC&&console.log(o),xC=o}function rp(e){let t=Om(e);return t?`${it.name} on ${t}`:it.name}async function BC(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s={runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:px(Ii),executionRevision:GC(e),sessionKey:zu(e),sessionId:null,replacement:null};rn.set(t,s);let i,a=m=>{let g=m?JSON.stringify(m):null;!g||g===i||rn.get(t)!==s||(i=g,$C(t,m))},c=`${r} \xB7 ${rp(e)}`,l=X$(e,it.name);$C(t,{kind:"status",message:l});let u=Number(e.answer_within_seconds),p=u>0?o+u*1e3:void 0;console.log([`[${n}] ${l} for ${r}.`,`${it.name} can reason for several minutes without reporting a step.`,...p?[up(p,o)]:[]].join(" ")),Bt.status(n,c,o,{link:Rc,answerBy:p});let d=m=>{let g=I$(m),w=cs(m);rn.get(t)===s&&jw(n,w??g?.message);let b=m.type==="forge.output"?null:w;a(g??(b?{kind:"status",message:b}:null))},f="failed",h=[r];try{Bu(e)||(d({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await hS(zC,{pinned:!!e.local_design_context,last:Lo,onFallback:(b,_)=>d({type:"connector.step",message:`Design context not refreshed (${b.message}); continuing with ${_?"the copy synced earlier":"none"}`})})});let m=await $$(e,M,{onProcess:b=>{rn.get(t)===s&&(s.child=b)},onController:b=>{rn.get(t)===s&&(s.controller=b)},onSession:b=>{s.sessionId=b},onEvent:d},{signal:s.cancellation.signal});if(s.stoppedHere)throw new Error(AC);let g=m.singleTurn?qy(M.sessions,m.sessionKey):Pp(M.sessions,m.sessionKey,m.sessionId);if(JSON.stringify(g)!==JSON.stringify(M.sessions||{})&&(M={...M,sessions:g},await Wn(M)),s.cancelled)return;await s.events.close().catch(b=>{console.error(`[${n}] Prompt progress delivery: ${b.message} The agent has finished; submitting its complete response separately.`)});let w=await Gu(Ii,{type:"prompt.completed",prompt_id:t,execution_revision:s.executionRevision,content:m.content,model:m.model,session_id:m.sessionId,usage:m.usage});w||console.error(`[${n}] ${Pm}`),Ac.record("prompt","completed",{durationMs:Date.now()-o,usage:m.usage}),f=w?"finished":"undelivered",h=[zc(m.usage),r]}catch(m){let g=s.stoppedHere?AC:un(m);if(Ac.record("prompt","failed",{durationMs:Date.now()-o}),s.stoppedHere&&(f="cancelled"),!s.cancelled){try{await Gu(Ii,{type:"prompt.failed",prompt_id:t,execution_revision:s.executionRevision,message:g})||console.error(`[${n}] ${Pm}`)}catch(w){console.error(`[${n}] Prompt failure delivery: ${w.message}`)}console.error(g)}}finally{s.events.stop();let m=s.replacement;m?(f="replaced",h=[`continuing on ${rp(m)}`,r]):s.cancelled&&(f="cancelled"),Bt.finish(n,f,h),rn.get(t)===s&&rn.delete(t),m&&EY(s,m)}}var AC="Cancelled from the connector terminal by the person running it.";async function Nw(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function GC(e){return Number(e.execution_revision)||1}async function kY(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 ${rp(t)}.`),await Nw(e))}function EY(e,t){e.sessionId&&(M={...M,sessions:Pp(M.sessions,e.sessionKey,e.sessionId)},Wn(M).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),BC(t)}async function $Y(e,t){let n=e.assessment_id,r=e.stage;if(console.log(`Running assessment stage ${r}${e.stage_label&&e.stage_label!==r?` "${e.stage_label}"`:""} (${n}) with ${rp(e)}.`),!Sw.has(n)){Sw.add(n);try{let k=await R$(M.workspace);if(!k.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let x=k.accepted_head_revision?k.current_head_revision?k.current_head_revision!==k.accepted_head_revision?`The workspace is now at commit \`${k.current_head_revision}\`; the accepted assessment is from \`${k.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${k.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 ${k.stages.length||"no"} section(s). ${x}`)}}catch(k){console.error(`Assessment freshness check failed: ${k.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,p=null,d=null,f=null,h=new Set,m=()=>!sn&&an.get(t.key)===t,g=async k=>{try{return await Gu(Ii,k)||console.warn(`[${s}] ${ux}`),!0}catch(x){return console.error(`Assessment failure delivery: ${x.message}`),!1}},w=(k,{milestone:x=!0}={})=>{if(!m()||x&&f===k)return;x&&(f=k,h.has(k)||(h.add(k),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${k}.`));let S=String(k).slice(0,500);t.progressPercent=c,t.lastMessage=S,Bt.status(s,S,o,{link:Rc})};w(`Starting ${r} assessment stage`);let b=setInterval(()=>{let k=Date.now(),x=k-t.lastActivityAt,S=i&&!a?O$(r,x):null;if(!p&&S){p=S,console.error(`[assessment:${r}] ${p}`),qa(t.controller,t.child);return}p||co.observe({at:k,level:"info",message:Bt.status(s,`${t.lastMessage} \xB7 last agent activity ${tt(x)} ago (${t.eventCount.toLocaleString()} events)`,o)})},15e3),_={onSession:async k=>{m()&&(d=String(k),await P0(M.workspace,n,r,k,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:k=>{m()&&(t.controller=k)},onProcess:k=>{m()&&(t.child=k,i=!0,t.phase!=="correcting"&&(t.phase="running",w("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:k=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let x=C$(k);if(x&&w(x),!m())return;let S=cs(k);!S||S===t.lastDetail||(t.lastDetail=S,jw(s,S))}},v=(k,x)=>Am(k,x,M,_,{draftPath:on.relative(M.workspace,on.join(Pn(M.workspace,n),k.report_file)).split(on.sep).join("/")});try{let k=bw-Date.now();k>0&&(w(`Waiting ${Math.ceil(k/1e3)}s for the model provider's rate limit to clear`),await new Promise(R=>setTimeout(R,k+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,w("Calculating changed files and affected behavior"));let x=await z0(M.workspace,e),S=await Af(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(S)v(S,x),w("Recovered completed stage report from connector storage");else{if(d=await L0(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),d&&w("Restoring interrupted agent session"),S=await E$(x,M,_,{previousSessionId:d}),p)throw new Error(p);a=!0,await xf(M.workspace,n,x,S)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let C=R=>fetch(Ky(M.server_url,M.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:JSON.stringify(R),signal:AbortSignal.timeout(l$)}),A=await V$(S,{submit:R=>q$(R,C,{isActive:()=>m()&&!sn,onRetry:(O,T)=>{w("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${un(O)} Retrying in ${Math.round(T/1e3)}s without rerunning the agent.`)}}),payloadFor:R=>r==="synthesis"?Tf(M.workspace,n,R,{expectedSourceRevision:e.source_revision}):W0(R),rejectionFor:R=>wa(R,"the assessment"),correct:async(R,O)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!R.correctAfterRejection)throw new Error(`${O} The connector could not start the required agent correction.`);return R.correctAfterRejection(O)},onCorrected:async R=>{if(p)throw new Error(p);a=!0,await U0(M.workspace,n,r);let O=await xf(M.workspace,n,x,R);return v(O,x),t.phase="delivering",t.lastMessage="Delivering corrected stage result",O}});if(p)throw new Error(p);S=A.result;let $=A.response;if(!$.ok)throw new Error(await wa($,"the assessment"));if(l=!0,Ac.record("assessment stage","completed",{durationMs:Date.now()-o,usage:S.usage}),r==="synthesis"){let R=await $.json(),O=await B0(M.workspace,n,e,S,R.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${on.relative(M.workspace,O)}.`);try{let T=await Wc(M.workspace);T.committed&&console.log(`Assessment committed to Git as ${T.revision.slice(0,8)}.`)}catch(T){console.error(`The assessment is saved locally but could not be committed to Git: ${T.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(k){let x=p||un(k),S=F$(e,k),C=G$(k),E=D$(k);C&&(await D0(M.workspace,n,r).catch($=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${$.message}`)}),d=null);let A=!p&&(d||C)&&(C||L$(k))&&S<E;if(m()&&A){t.phase="starting",t.lastMessage=C?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=z$(e,k);let $=B$(k,S);Wa(k)&&(bw=Math.max(bw,Date.now()+$)),console.warn(`[assessment:${r}] ${C?"Agent session became unusable":"Agent session interrupted"}: ${x} ${C?"Starting a fresh session from the saved draft":`Resuming session ${d}`} in ${Math.round($/1e3)}s (${S+1}/${E}).`),await new Promise(R=>setTimeout(R,$))}else m()&&(u=await g({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:x}));A||(Ac.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${x}`))}finally{clearInterval(b),Bt.clearStatus(s),r==="synthesis"&&l&&Sw.delete(n),m()&&(an.delete(t.key),W$(Ci,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),Ic())}}async function xY(e){let t=String(e.run_id||"");Uo+=1;try{Nr&&await Nr;let n=await g$(M.workspace,String(e.base_revision||""),String(e.head_revision||""),String(e.integration_branch||"")||null);if(n.applied){console.log(`Accepted Goal Run ${t} applied to the connected repository at ${n.revision} (${n.method}).`),await ji();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: ${un(n)}`)}finally{Uo-=1,Ic()}}function AY(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{dt('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function dt(e){console.error(e),process.exit(1)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@engineeros/connector",
3
- "version": "1.59.7",
3
+ "version": "1.59.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",