@engineeros/connector 1.59.2 → 1.59.3

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.
@@ -1102,7 +1102,7 @@ It is checked with the provider and stored in this machine's protected vault
1102
1102
  (Windows Data Protection, the macOS Keychain or the Linux Secret Service).
1103
1103
  EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function SK(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(`
1104
1104
  `),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
1105
- `)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 qR=Symbol("missing");function kK(e,t){return new Promise(n=>{let r=vK(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?qR:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function WR(e,t){for(let n of hc){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 VR(e,t,n,{vault:r=ow(),run:o=Md,fetchImpl:s=fetch,secret:i=SK,interactive:a=kK,install:c=Nd,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(bK),n.help?0:2;if(e==="integrations")return WR(l,(await Dd({run:o,vault:r})).providers),0;let p=t[0];if(!hc.includes(p))return u(`Unknown provider ${p}. Choose one of: ${hc.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=is[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===qR){let m=await pi(f);if(!m){l(`Installing the ${dc[f].label} ${dc[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} ${Ld[p]} is how this machine signs in to ${p}.`),1):(WR(l,{[p]:(await Dd({run:o,vault:r})).providers[p]}),0)}let d=Xt[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await sw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await iw(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 EK}from"node:child_process";async function XR({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=EK,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=so(await cn(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await $K(o,c.entry,i,t);if(l===zi){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 cn(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await kp(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 $K(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[fs]:"1",[yp]:r.entry,[_p]: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 Co="1.59.2",Wd="1.59.2",RK=3e5,qd=["queued","running","reporting"],CK=5e3,aw={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."},cw={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."},OK=6e4,IK=3e4,jK=60*6e4,lw={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},uw={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:gt,positional:jt,flags:Re}=jA(process.argv.slice(2));gt==="version"&&(console.log(Co),process.exit(0));var Qr=null,Yt=!1,dr=null,uC=!1,dC=null,Sw=null,Nt=null,bc=null,_w,JR,KR,dw,YR,mi,wi,pC=_d({getWorkspace:()=>M.workspace,onRecorded:e=>k1(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}`))}),NK=GR({getWorkspace:()=>M.workspace,huntSignIns:pC}),wc=LA();gt==="results"&&(jt[0]!=="upload"&&(console.log(dd),process.exit(Re.help||!jt[0]?0:2)),process.exit(await zT(Re)));(gt==="connect"||gt==="disconnect"||gt==="integrations")&&process.exit(await VR(gt,jt,Re,{fetchImpl:UR}));if(gt==="runner"){let e=Kt.resolve(Re.workspace||process.cwd()),t=jt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?Kt.join(Kt.dirname(yt(e,Re["run-id"])),"worker.log"):Kt.join(e,".engineeros","runner","service.log");AK(Kt.dirname(n),{recursive:!0});let r=(...s)=>Ua(n,`${TK(...s)}
1105
+ `)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 qR=Symbol("missing");function kK(e,t){return new Promise(n=>{let r=vK(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?qR:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function WR(e,t){for(let n of hc){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 VR(e,t,n,{vault:r=ow(),run:o=Md,fetchImpl:s=fetch,secret:i=SK,interactive:a=kK,install:c=Nd,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(bK),n.help?0:2;if(e==="integrations")return WR(l,(await Dd({run:o,vault:r})).providers),0;let p=t[0];if(!hc.includes(p))return u(`Unknown provider ${p}. Choose one of: ${hc.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=is[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===qR){let m=await pi(f);if(!m){l(`Installing the ${dc[f].label} ${dc[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} ${Ld[p]} is how this machine signs in to ${p}.`),1):(WR(l,{[p]:(await Dd({run:o,vault:r})).providers[p]}),0)}let d=Xt[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await sw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await iw(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 EK}from"node:child_process";async function XR({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=EK,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=so(await cn(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await $K(o,c.entry,i,t);if(l===zi){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 cn(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await kp(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 $K(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[fs]:"1",[yp]:r.entry,[_p]: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 Co="1.59.3",Wd="1.59.3",RK=3e5,qd=["queued","running","reporting"],CK=5e3,aw={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."},cw={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."},OK=6e4,IK=3e4,jK=60*6e4,lw={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},uw={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:gt,positional:jt,flags:Re}=jA(process.argv.slice(2));gt==="version"&&(console.log(Co),process.exit(0));var Qr=null,Yt=!1,dr=null,uC=!1,dC=null,Sw=null,Nt=null,bc=null,_w,JR,KR,dw,YR,mi,wi,pC=_d({getWorkspace:()=>M.workspace,onRecorded:e=>k1(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}`))}),NK=GR({getWorkspace:()=>M.workspace,huntSignIns:pC}),wc=LA();gt==="results"&&(jt[0]!=="upload"&&(console.log(dd),process.exit(Re.help||!jt[0]?0:2)),process.exit(await zT(Re)));(gt==="connect"||gt==="disconnect"||gt==="integrations")&&process.exit(await VR(gt,jt,Re,{fetchImpl:UR}));if(gt==="runner"){let e=Kt.resolve(Re.workspace||process.cwd()),t=jt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?Kt.join(Kt.dirname(yt(e,Re["run-id"])),"worker.log"):Kt.join(e,".engineeros","runner","service.log");AK(Kt.dirname(n),{recursive:!0});let r=(...s)=>Ua(n,`${TK(...s)}
1106
1106
  `),o=(s,i,a)=>(Ua(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(Re["keep-awake"]!==void 0){if(!["on","off"].includes(Re["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await Gt(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await Pn({...n,runner_keep_awake:Re["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await Fu(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 hx(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await ei(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await bo(e),null,2)):t==="serve"?await yx(e):t==="worker"?await _x(e,Re["run-id"]):it("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){it(Dm(n,e).message)}}Re["assessment-workers"]!==void 0&&it("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(gt==="secret")try{let e=Um(Re),t=jt[0]||"list",n=await IA({action:t,name:jt[1],workspace:e,readValue:()=>OA({label:`Value for ${jt[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){it(e.message)}if(gt==="tools"){try{let e=Um(Re),t=jt[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=jt[1];r||it(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await Th(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 Ea(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:jt[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await $h(e,t,jt[1]);let n=await jn(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){it(e.message)}process.exit(process.exitCode||0)}if(gt==="agents"){let e;try{e=await Hh()}catch(n){it(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await xa(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(gt==="agent"){let e=jt[0],t=jt[1]||"check";(!e||!["check","install"].includes(t))&&it("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await Aa(e):await xa(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){it(n instanceof Error?n.message:String(n))}process.exit(0)}if(gt==="mcp"){let e=Re.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=Re["run-id"]||jt[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await Gt(e);await YA({config:n,runId:t,version:Co,input:process.stdin,output:process.stdout}),process.exit(0)}if(gt==="context-mcp"){let e=Re["config-workspace"]||Re.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await Gt(e);t||it("This workspace is not paired with EngineerOS."),await OT({config:t,workspace:Re.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:Co,input:process.stdin,output:process.stdout}),process.exit(0)}if(gt==="status"){let e=await Gt(Re.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(gt==="doctor"){let e=Kt.resolve(Re.workspace||process.cwd()),t=await Gt(e),n=await qA(e),r=await Ei(t||{workspace:e},e,pg(n));console.log(ag(r)),process.exit(r.status==="failed"?1:0)}if(gt==="update"){let e=jt[0]||"status";try{let t=bp(process.argv[1],Wd),n=await Ep(Rr(),t,{action:e,policy:jt[1]??null});console.log(Gi($p(n,t,{supervised:!0})))}catch(t){it(`${t.message}
1107
1107
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var yi=gt==="hunt-host";if(yi)try{Re.workspace=kx(jt,Re)}catch(e){it(e.message)}if((gt==="start"||gt==="pair"||yi)&&process.env[fs]!=="1"&&Et(Wd))try{process.exit(await XR({root:Rr(),bundled:{version:Wd,entry:Kt.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:Kt.resolve(Re.workspace||process.cwd())}))}catch(e){it(`The connector process could not be started: ${e.message}`)}if(yi){try{await Ex(Re.workspace,jt[0]?Re.agent:null)}catch(e){it(e.message)}gt=jt[0]?"pair":"start"}var M,cs,yc;if(gt==="pair"){let e=jt[0];e||it("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=Re.url;t||it("Pairing requires --url with the EngineerOS backend address."),Re.agent&&Re["agent-command"]&&it("Use either --agent or --agent-command, not both.");let n=Re["agent-protocol"]||(Re["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||it(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(Re.agent||Re["agent-command"])&&it("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{Re.agent&&(await xa(Re.agent),r=await Wh(Re.agent))}catch(o){it(o instanceof Error?o.message:String(o))}M={server_url:Rp(t),workspace:Kt.resolve(Re.workspace||process.cwd()),onboard:Re.onboard===!0,onboarding_pending:Re.onboard===!0,hunt_host:yi,agent_protocol:n,agent_command:Re["agent-command"]||null,agent_args:oY(Re["agent-args"]),agent_name:Re["agent-name"]||null,...r,skip_git_repo_check:yi||Re["skip-git-repo-check"]===!0,name:Re.name||`${xK.hostname()} - ${Kt.basename(Kt.resolve(Re.workspace||process.cwd()))}`},yc=await Gt(M.workspace),cs={type:"pair",pairing_code:e,name:M.name,capabilities:{},...Ny(yc,M.server_url)}}else gt==="start"?(M=await Gt(Re.workspace||process.cwd()),M||it("This connector is not paired. Create a pairing command in EngineerOS first."),yi&&!M.hunt_host&&it("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),M.token||it("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),cs={type:"authenticate",connector_id:M.connector_id,token:M.token}):it("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var fC=vx(M,{reportError:e=>console.error(e)}),Ro=0,Vd=!1,_c=null,Zt=new Map,pw=0,fw=new Set,_i=[],Jt=new Map,xt,vw,zd,kr=null,Bd=!1,hC=0,hw=null,mw=[],Gd,mC,mc=1e3,vi,ZR=0,gw=!1,Kr=!1,Xn,To=!1,Xd=!1,bw=0;function hi(e){return bw+=1,e.finally(()=>{bw-=1})}var gi,as=0;function vc({exitCode:e=0}={}){if(as=Math.max(as,e),gi)return gi;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),gi=MK().finally(()=>clearTimeout(t)),gi}async function MK(){if(Yt=!0,bc?.stop(),Qr?.stop(),Sw?.stop(),dC?.stop(),clearInterval(_w),Nt?.stop(),mC?.(),clearTimeout(Gd),clearInterval(vw),clearInterval(zd),await Promise.all([...[...Zt.values()].map(e=>un(e.child))]),await Promise.all([...Jt.values()].map($w)),await mi?.cancelAll(),await wi?.abortAll(),await $a(),await Nw().catch(e=>{as=Math.max(as,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),xt?.close(),as&&as!==zi){let e;await Promise.race([(async()=>{await Qr?.drain(),await Ei(M,M.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(as)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{vc()});var QR=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{QR||(QR=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await vc({exitCode:1}))});Nt=zw();process.on("exit",()=>{bc?.stop(),Nt.stop()});Nt.banner(`EngineerOS connector ${Co}`,[M.workspace,M.server_url]);Qr=PA({actions:{refresh_tool_inventory:async()=>{Le.tool_inventory=await jn(M.workspace),kn()},restart_goal_runner:()=>ei(M.workspace)},onNotify:()=>Ei(M,M.workspace),explain:async e=>{if(!await ki())return null;let{reading:t}=await H$(M,e);return t},onUpdate:e=>WA(M.workspace,e)});dC=XA({render:(e,t)=>Nt.write(e,t),onRecord:e=>Qr.observe(e)});Sw=JA({workspace:M.workspace,onRecord:e=>{Qr.observe(e),Nt.line(e.channel,e.level,e.message)}});Qr.start();M.hunt_host||Sw.start();Nt.live&&!M.hunt_host&&(_w=setInterval(()=>{PK().catch(()=>{})},CK),_w.unref?.());var ww=new Set;async function PK(){if(M.hunt_host)return;JR??=Mm(M.workspace);let{jobs:e}=await JR(),t=new Set,n=e.filter(r=>r.status!=="queued"&&qd.includes(r.status)).length;for(let r of e){if(!qd.includes(r.status))continue;t.add(r.runId),ww.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;Nt.status(`goal:${r.runId}`,o,LK(r),{agent:r.status!=="queued",link:_c&&`${_c}/goals`}),Nt.step(`goal:${r.runId}`,r.activity?.message)}for(let r of ww)t.has(r)||(ww.delete(r),Nt.clearStatus(`goal:${r}`))}function LK(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function ki({ignoreBugHunt:e=!1}={}){if(Yt||Zt.size>0||Jt.size>0||Ro>0||(mi?.active??0)>0||!e&&(wi?.active??0)>0)return!1;try{let{jobs:t}=await bo(M.workspace);return!Yt&&!t.some(n=>qd.includes(n.status))}catch{return!1}}try{let e=M.hunt_host?{}:await ds(M.workspace);e.committed&&(M.onboarding_pending=!0,M.connector_id&&await Pn(M),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await vC(e)}var gC=await cn(Rr()).then(e=>e.policy!=="manual",()=>!1),rt;try{rt=await La(M,M.workspace)}catch(e){await vC(e)}console.log(`Using ${rt.name} through ${rt.protocol} (${rt.version}).`);var wC=async()=>Za({workspace:M.workspace}).names().catch(()=>[]),Le=nd(M,rt,await jn(M.workspace),{secretNames:await wC()}),Zr=by({running:bp(process.argv[1],Wd),supervised:process.env[fs]==="1",isIdle:async()=>!Yt&&Zt.size===0&&_i.length===0&&Jt.size===0&&Ro===0&&bw===0&&!To&&!Xd&&!Bd,restart:()=>vc({exitCode:zi}),onChange:e=>{Le.runtime_update=e,xt?.readyState===WebSocket.OPEN&&kn()}});try{await Zr.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}M={...M,execution_profiles:rt.executionProfiles??null};gt==="pair"&&yc?.connector_id||await Pn(M);Le.agent_session={...Le.agent_session,status:"checking",message:`Checking that ${rt.name} can answer.`};Le.bug_hunt_browser=!1;cs.capabilities=Le;console.log(Br(M.worker_limit)===null?`Workers: automatic, ${Vs()} ${rt.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Br(M.worker_limit)} ${rt.name} workers side by side, set with /workers.`);var bi=e=>Gr(M,e),eC=Mu(bi,{signature:Q$});async function DK(){let e=await bo(M.workspace).catch(()=>({service:null,jobs:[]}));return{version:Co,now:Date.now(),workspace:M.workspace,config_path:yn(M.workspace),config:M,agent:rt,automatic_worker_limit:Vs(),worker_limit:Br(M.worker_limit),connection:{state:FK(),server_url:M.server_url,last_error:Xn||null},work:{assessments:[...Zt.values()].map(t=>({stage:t.stage,message:t.lastMessage,started_at:t.startedAt})),prompts:[...Jt.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,started_at:t.startedAt})),integrations:Ro},runner:e,runtime_update:Zr.report(),health:Qr?.health()??null,activity:wc.snapshot()}}function FK(){return Yt||Kr?"stopped":xt?.readyState===WebSocket.OPEN?"connected":"connecting"}var UK={async cancelPrompt(e){let t=[...Jt.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=>_C(e),setVerbose(e){return e===Vd?`Detailed agent activity is already ${e?"on":"off"}.`:(kw(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"?(Zr.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 Zr.command(e),Gi(await Zr.refresh()))}};bc=zA({ui:Nt,snapshot:DK,actions:UK});bc&&console.log(UA());await yC();var tC=new Set;async function yC(){if(Yt||Kr)return;console.log(`Connecting ${M.name} to ${M.server_url}`),Kr=!1,Xn=void 0;let e=new WebSocket(M.server_url);xt=e;let t=Dv(e,M.server_url,{onTimeout:r=>{xt===e&&(Xn=r,console.error(r),yw())}});mC=t,e.addEventListener("open",()=>{if(xt!==e){e.close();return}try{if(Iv(xt,e,cs))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){Xn=en(r),console.error(`Could not authenticate the WebSocket connection: ${Xn}`);try{e.close()}catch{}yw()}}),e.addEventListener("message",r=>{if(xt!==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: ${en(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){Yt=!0,Kr=!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=yc?.connector_id===r.connector.id;if(M=My(M,yc,r.connector.id,r.token),await Pn(M),r.connector?.capabilities?.http_updates!==!0){Yt=!0,Kr=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}cs={type:"authenticate",connector_id:M.connector_id,token:M.token,capabilities:Le},console.log(s?`Reconnected existing workspace connector ${M.connector_id}; assessment history is preserved.`:`Paired. Connector ${M.connector_id} is online.`),sC(r);return}if(r.type==="authenticated"){t();let s=M.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(vi?`Reconnected after ${Ve(Date.now()-vi)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),vi=void 0,sC(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){Xd||BK(r);return}if(r.type==="workspace.refresh"){Si();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await _C(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){kw(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(Yr=!1,Le.bug_hunt_browser=!1,kn());try{Le.tool_inventory=await Ea(M.workspace,r,void 0,{confirmLocal:i=>bc?.confirm(i)??!1,log:Hd}),s&&(Yr=!0),Le.bug_hunt_browser=ss(Le.tool_inventory)&&Yr,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Le.tool_inventory})),kn(),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 Th(M.workspace,r,{onStatus:async()=>{Le.tool_inventory=await jn(M.workspace),kn()}});Le.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:Le.tool_inventory})),kn(),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"){$s(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===BR){hi(NK(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),HR(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}`;km(_i,Zt.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Sc();return}if(r.type==="prompt.execute"){let s=Jt.get(r.prompt_id);s?$C(r)>s.executionRevision&&await eY(s,r):EC(r);return}if(r.type==="prompt.cancel"){let s=Jt.get(r.prompt_id);s&&await $w(s);return}if(r.type==="agent.warm"){VK(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 fC.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${Kt.join(M.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${en(s)}`)}return}if(r.type==="goal.cleanup"){try{await wx(M.workspace),await ei(M.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){rY(r);return}if(r.type==="run.cancelled"){await Nm(M.workspace,r.run_id);return}if(r.type===Pb){mi??=ih({getConfig:()=>M,onTestsCommitted:()=>Si()}),hi(mi.handle(r));return}if(r.type===Lb){mi??=ih({getConfig:()=>M,onTestsCommitted:()=>Si()}),await mi.cancel(r);return}if(r.type===uR){wi??=mR({getConfig:()=>M,isIdle:()=>ki({ignoreBugHunt:!0}),recordedSignIns:pC,activity:{status:Nt.status,step:Ew,agents:Nt.agents,finish:Nt.finish}}),hi(wi.handle(r));return}if(r.type===dR){wi?.stop(r);return}if(r.type===BT){KR??=GT({getConfig:()=>M}),hi(KR.handle(r));return}if(r.type===JT){dw??=o1({getConfig:()=>M}),hi(dw.handle(r));return}if(r.type===KT){await dw?.cancel(r);return}if(r.type===i1){YR??=a1({getConfig:()=>M,isIdle:()=>ki(),agentTurn:g$}),hi(YR.handle(r));return}if(r.type==="connector.update"){zK(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await vc();return}if(r.type==="connector.revoked"){Yt=!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||(To=!1);return}if(r.type==="connection.error"){Kr=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);tC.has(o)||(tC.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${Co}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),xt!==e||gi)return;let o=jv(r);if(!o.retry||Kr||Yt){console.error(o.message),o.retry&&Kr&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),vc();return}Xn=Xn?`${o.message} ${Xn}`:o.message,yw()}),e.addEventListener("error",r=>{xt===e&&(Xn=Ov(r),console.error(`WebSocket connection to ${M.server_url} failed: ${Xn}`))})}async function zK(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=Zr.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 Zr.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 BK(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";Xd=!0,console.log(`Starting interactive ${rt.name} provider ${n}.`);try{await(n==="logout"?Lv:Pv)(rt,M.workspace),rt=await La(M,M.workspace),Le=nd(M,rt,Le.tool_inventory,{secretNames:await wC()}),cs.capabilities=Le,xt.readyState===WebSocket.OPEN&&(xt.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:Le.agent_session})),xt.close(1e3,`Provider ${n} completed`)),console.log(`${rt.name} provider ${n} completed.`)}catch(r){let o=en(r).slice(0,500);xt.readyState===WebSocket.OPEN&&xt.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{Xd=!1}}function yw(){if(Yt||Kr||Gd)return;let e=Xn?` Last error: ${Xn}`:"",t=vi?` Offline for ${Ve(Date.now()-vi)}.`:"";vi??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(mc/1e3)}s.`),Gd=setTimeout(()=>{Gd=void 0,yC()},mc),mc=Math.min(3e4,mc*2)}async function Si(){if(!M.hunt_host&&!(To||xt.readyState!==WebSocket.OPEN)){To=!0,console.log("Inspecting the workspace without executing its code.");try{let{snapshot:e,map:t,stats:n}=await _g({workspace:M.workspace,connectorId:M.connector_id,refresh:vs,takeSnapshot:V$,buildMap:(i,a)=>cd(M.workspace,i,{head:a.head_revision,branch:a.branch}),log:i=>console.error(i)}),r=await q$(M.workspace,M.last_head_reported??M.last_snapshot_head,e.head_revision).catch(()=>null);r&&(e.changed_since=r);let o=await fetch(hs(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 ua(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 Pn(M),t&&await ld(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.`),To=!1}catch(e){To=!1,console.error(`Workspace assessment failed: ${en(e)}`)}}}var GK=8e6,nC,rC="";async function HK({current:e,previous:t}){if(To||xt?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=Kt.resolve(M.workspace),r=async()=>{M={...M,last_head_reported:e.head,last_head_branch:e.branch??null},await Pn(M)},o=await yg(M.workspace,M.connector_id),s=async()=>{if(await Si(),M.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let{index:i}=await vs(M.workspace,M.connector_id),a=null,c=await vT({previous:{head:t.head,branch:t.branch??null},current:e,compare:(d,f)=>Am(M.workspace,d,f),inventoryDelta:d=>w_(n,Object.entries(i.files).map(([f,h])=>({path:f,size:h.size})),d),mapDelta:async()=>(a=await cd(M.workspace,i,{head:e.head,branch:e.branch}),wg(o,a)),contentHead:(await gl(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)>GK)return s();let u=await fetch(Dy(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 ua(u,"the new commit"));let p=await u.json().catch(()=>({}));if(p.needs_snapshot)return s();await r(),a&&await ld(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 WK(){M.hunt_host||M.onboarding_pending||To||xt?.readyState!==WebSocket.OPEN||(nC??=_T({readHead:()=>yT(M.workspace),getLastReported:()=>({head:M.last_head_reported??M.last_snapshot_head,branch:M.last_head_branch}),onChange:HK,onError:e=>{e.message!==rC&&(rC=e.message,console.error(`The new commit could not be reported yet: ${en(e)}`))}}),nC.poll().catch(()=>{}))}var qK=6e4,oC=0;async function VK(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()-oC>qK&&(oC=Date.now(),r.push(vs(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(fk(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(`${rt?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function kn(){let e=N$(Zt);eC.update({type:"assessment.workers",assessment_workers:e,tool_inventory:Le.tool_inventory,runtime_update:Le.runtime_update,agent_session:Le.agent_session,bug_hunt_browser:Le.bug_hunt_browser,...Ou(M.worker_limit)}),eC.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function _C(e){let t=Br(e);return t===Br(M.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(M={...M,worker_limit:t},await Pn(M),Sc(),kn(),t===null?`Workers are automatic again: up to ${Vs()} side by side for this machine's CPU and memory, for ${ec} (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: ${ec}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function kw(e){if(e!==Vd){if(Vd=e,!e)for(let t of Zt.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."),kn()}}function Ew(e,t,n=null){Nt.step(e,t,n)&&Vd&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function XK(){clearInterval(zd);let e=!1,t=()=>{e||Zt.size>0||Jt.size>0||(e=!0,Ei(M,M.workspace).finally(()=>{e=!1}))};t(),zd=setInterval(t,RK),zd.unref?.()}async function Ei(e,t,n=Qr?.healthChecks()??[]){let r=await EA({config:e,workspace:t,version:Co,insights:n,agentSession:dr,probes:{inspectAgent:(o,s)=>Yt?rt:La(o,s),inspectTools:o=>Yt?Le.tool_inventory:jn(o),runnerStatus:bo}});try{uC=(await $A(e,r,Gr))?.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 vC(e){if(Yt)return gi;let t=e instanceof Error?e.message:String(e),n=await Ei(M,M.workspace).catch(()=>null);n&&console.error(ag(n)),it(t)}function sC(e){kw(e.connector?.activity_log_enabled===!0),_c=e.project_url??null,mc=1e3,KK(),SC(),Zr.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),YK(),M.onboarding_pending&&Si()}var gc=null,Yr=!1,bC=0,JK=Date.now();async function KK(){return gc||(gc=(async()=>{gC&&await JS(M.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Hd("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await $x(M.workspace,{log:Hd}),Yr=!0,Le.tool_inventory=await jn(M.workspace),Le.bug_hunt_browser=ss(Le.tool_inventory)&&Yr,Hd(`Bug Hunter's browser is ready (${Ve(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${Ve(Date.now()-e)}: ${t.message}`),Le.bug_hunt_browser=!1}kn()})(),gc)}function Hd(e){console.log(`[browser] ${e}`)}async function SC(){if(dr?.state!=="checking"){bC=Date.now(),Le.agent_session={...Le.agent_session,status:"checking",message:`Checking that ${rt.name} can answer.`},kn(),dr={state:"checking",detail:`Asking ${rt.name} one question to confirm its session.`},console.log(`Checking that ${rt.name} can answer before accepting work.`);try{await F$(M,rt.name),dr={state:"ready",detail:`${rt.name} answered; its session is usable.`},Le.agent_session={...Le.agent_session,status:"authenticated",message:dr.detail},console.log(dr.detail)}catch(e){dr={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:M.hunt_host?Ax(M.agent_id||M.agent_protocol):Bs(M.agent_id||M.agent_protocol)},Le.agent_session={...Le.agent_session,status:"logged_out",message:dr.remedy},console.error(`${dr.detail}
1108
1108
  ${dr.remedy}`)}kn(),await Ei(M,M.workspace).catch(()=>null)}}function YK(){clearInterval(vw);let e=!1,t=0,n=0,r=!1,o=()=>{Zr.tick(),ZK(),WK(),M.hunt_host&&gc&&Date.now()-bC>=xx(JK)&&Jt.size===0&&Zt.size===0&&!(wi?.active>0)&&SC(),!M.hunt_host&&!r&&Ja(uw.id)&&(r=!0,fC.flush().then(()=>Ud(uw)).catch(s=>Fd(uw,s)).finally(()=>{r=!1})),Zt.size>0&&kn(),!M.hunt_host&&!kr&&Date.now()-t>=OK&&Ja(aw.id)&&(t=Date.now(),kC().then(()=>Ud(aw)).catch(s=>Fd(aw,s))),!M.hunt_host&&uC&&!Bd&&Ja(cw.id)&&Date.now()-hC>=aS&&(Bd=!0,QK().then(()=>Ud(cw)).catch(s=>Fd(cw,s)).finally(()=>{Bd=!1})),!e&&Date.now()-n>=IK&&Ja(lw.id)&&(e=!0,n=Date.now(),jn(M.workspace).then(async s=>{if(Le.tool_inventory=s,!Yr&&ss(s))try{await(await Po(await ko(M.workspace))).close(),Yr=!0}catch{Yr=!1}Le.bug_hunt_browser=ss(s)&&Yr,kn(),Ud(lw)}).catch(s=>Fd(lw,s)).finally(()=>{e=!1}))};o(),vw=setInterval(o,1e4),XK()}async function ZK(){if(!(!gC||M.agent_protocol!=="acp"||!M.agent_id||gw||dr?.state==="checking"||Date.now()-ZR<jK)){gw=!0;try{if(!await ki())return;ZR=Date.now();let e,t=await bk(M,{verify:async r=>{e=await La(r,M.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===M||Yt)return;M={...t,execution_profiles:e.executionProfiles??null},await Pn(M),rt=e;let n=nd(M,rt,Le.tool_inventory);if(Object.assign(Le,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),cs.capabilities=Le,!await ki())return;await $a(),xt?.readyState===WebSocket.OPEN&&xt.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{gw=!1}}}function Fd(e,t){let n=yA(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 Ud(e){_A(e.id)&&console.log(`${e.title} recovered.`)}async function QK(){if(M.hunt_host||!await ki())return;hC=Date.now();let{jobs:e}=await bo(M.workspace).catch(()=>({jobs:[]})),t=await cS(M.workspace,{jobs:e});if(!lS(t))return;let n=`${t.fingerprint}:${mw.join(",")}`,r=hw?.key===n,o=r?hw.candidates:await W$(M,t,mw);hw={key:n,candidates:o};let s=await bi(pS(t,o,{version:Co}));Array.isArray(s?.refused)&&(mw=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 Ao=null,iC=null;async function kC(){if(!M.hunt_host){if(kr)return kr;kr=(async()=>{let e=await Qb(M,{knownRevision:Ao?.revision??null});if(e.unchanged||(Ao=e),iC===Ao.revision)return Ao;let{jobs:t}=await bo(M.workspace);return!t.some(r=>qd.includes(r.status))&&Ro===0&&Zt.size===0&&(await Kl(M.workspace,Ao),iC=Ao.revision),Ao})();try{return await kr}finally{kr=null,Sc()}}}function aC(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)),Jt.get(e)?.events.push(n)}var cC=null;function Sc(){let e=xt.readyState===WebSocket.OPEN,t=Zt.values().next().value,n=Br(M.worker_limit)??Math.min(Vs(),Em(t?.workerLimit??_i[0]?.worker_limit)),r=e&&!kr&&Ro===0?$$(_i,Zt.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:Em(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};Zt.set(i,a),nY(s,a)}r.length>0&&kn();let o=x$({queued:_i,running:Zt.size,workerLimit:n,connected:e,designSync:!!kr,integrations:Ro});o&&o!==cC&&console.log(o),cC=o}function Jd(e){let t=$m(e);return t?`${rt.name} on ${t}`:rt.name}async function EC(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:nx(bi),executionRevision:$C(e),sessionKey:Iu(e),sessionId:null,replacement:null};Jt.set(t,s);let i,a=m=>{let g=m?JSON.stringify(m):null;!g||g===i||Jt.get(t)!==s||(i=g,aC(t,m))},c=`${r} \xB7 ${Jd(e)}`,l=D$(e,rt.name);aC(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}.`,`${rt.name} can reason for several minutes without reporting a step.`,...p?[rp(p,o)]:[]].join(" ")),Nt.status(n,c,o,{link:_c,answerBy:p});let d=m=>{let g=S$(m),_=Yo(m);Jt.get(t)===s&&Ew(n,_??g?.message);let S=m.type==="forge.output"?null:_;a(g??(S?{kind:"status",message:S}:null))},f="failed",h=[r];try{ju(e)||(d({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await oS(kC,{pinned:!!e.local_design_context,last:Ao,onFallback:(S,v)=>d({type:"connector.step",message:`Design context not refreshed (${S.message}); continuing with ${v?"the copy synced earlier":"none"}`})})});let m=await m$(e,M,{onProcess:S=>{Jt.get(t)===s&&(s.child=S)},onController:S=>{Jt.get(t)===s&&(s.controller=S)},onSession:S=>{s.sessionId=S},onEvent:d},{signal:s.cancellation.signal});if(s.stoppedHere)throw new Error(lC);let g=m.singleTurn?Py(M.sessions,m.sessionKey):Cp(M.sessions,m.sessionKey,m.sessionId);if(JSON.stringify(g)!==JSON.stringify(M.sessions||{})&&(M={...M,sessions:g},await Pn(M)),s.cancelled)return;await s.events.close().catch(S=>{console.error(`[${n}] Prompt progress delivery: ${S.message} The agent has finished; submitting its complete response separately.`)});let _=await Nu(bi,{type:"prompt.completed",prompt_id:t,execution_revision:s.executionRevision,content:m.content,model:m.model,session_id:m.sessionId,usage:m.usage});_||console.error(`[${n}] ${Cm}`),wc.record("prompt","completed",{durationMs:Date.now()-o,usage:m.usage}),f=_?"finished":"undelivered",h=[Cc(m.usage),r]}catch(m){let g=s.stoppedHere?lC:en(m);if(wc.record("prompt","failed",{durationMs:Date.now()-o}),s.stoppedHere&&(f="cancelled"),!s.cancelled){try{await Nu(bi,{type:"prompt.failed",prompt_id:t,execution_revision:s.executionRevision,message:g})||console.error(`[${n}] ${Cm}`)}catch(_){console.error(`[${n}] Prompt failure delivery: ${_.message}`)}console.error(g)}}finally{s.events.stop();let m=s.replacement;m?(f="replaced",h=[`continuing on ${Jd(m)}`,r]):s.cancelled&&(f="cancelled"),Nt.finish(n,f,h),Jt.get(t)===s&&Jt.delete(t),m&&tY(s,m)}}var lC="Cancelled from the connector terminal by the person running it.";async function $w(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function $C(e){return Number(e.execution_revision)||1}async function eY(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 ${Jd(t)}.`),await $w(e))}function tY(e,t){e.sessionId&&(M={...M,sessions:Cp(M.sessions,e.sessionKey,e.sessionId)},Pn(M).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),EC(t)}async function nY(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 ${Jd(e)}.`),!fw.has(n)){fw.add(n);try{let b=await _$(M.workspace);if(!b.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let $=b.accepted_head_revision?b.current_head_revision?b.current_head_revision!==b.accepted_head_revision?`The workspace is now at commit \`${b.current_head_revision}\`; the accepted assessment is from \`${b.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${b.accepted_head_revision}\`; the current commit could not be read.`:"Its accepted commit is unavailable; this run will refresh that provenance.";console.log(`Last accepted assessment covers ${b.stages.length||"no"} section(s). ${$}`)}}catch(b){console.error(`Assessment freshness check failed: ${b.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,p=null,d=null,f=null,h=new Set,m=()=>!Yt&&Zt.get(t.key)===t,g=async b=>{try{return await Nu(bi,b)||console.warn(`[${s}] ${ex}`),!0}catch($){return console.error(`Assessment failure delivery: ${$.message}`),!1}},_=(b,{milestone:$=!0}={})=>{if(!m()||$&&f===b)return;$&&(f=b,h.has(b)||(h.add(b),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${b}.`));let k=String(b).slice(0,500);t.progressPercent=c,t.lastMessage=k,Nt.status(s,k,o,{link:_c})};_(`Starting ${r} assessment stage`);let S=setInterval(()=>{let b=Date.now(),$=b-t.lastActivityAt,k=i&&!a?b$(r,$):null;if(!p&&k){p=k,console.error(`[assessment:${r}] ${p}`),Fa(t.controller,t.child);return}p||Qr.observe({at:b,level:"info",message:Nt.status(s,`${t.lastMessage} \xB7 last agent activity ${Ve($)} ago (${t.eventCount.toLocaleString()} events)`,o)})},15e3),v={onSession:async b=>{m()&&(d=String(b),await x0(M.workspace,n,r,b,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:b=>{m()&&(t.controller=b)},onProcess:b=>{m()&&(t.child=b,i=!0,t.phase!=="correcting"&&(t.phase="running",_("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:b=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let $=v$(b);if($&&_($),!m())return;let k=Yo(b);!k||k===t.lastDetail||(t.lastDetail=k,Ew(s,k))}},w=(b,$)=>bm(b,$,M,v,{draftPath:Kt.relative(M.workspace,Kt.join(Tn(M.workspace,n),b.report_file)).split(Kt.sep).join("/")});try{let b=pw-Date.now();b>0&&(_(`Waiting ${Math.ceil(b/1e3)}s for the model provider's rate limit to clear`),await new Promise(R=>setTimeout(R,b+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,_("Calculating changed files and affected behavior"));let $=await O0(M.workspace,e),k=await bf(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(k)w(k,$),_("Recovered completed stage report from connector storage");else{if(d=await A0(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),d&&_("Restoring interrupted agent session"),k=await h$($,M,v,{previousSessionId:d}),p)throw new Error(p);a=!0,await vf(M.workspace,n,$,k)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let T=R=>fetch(Uy(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(QE)}),A=await L$(k,{submit:R=>P$(R,T,{isActive:()=>m()&&!Yt,onRetry:(O,C)=>{_("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${en(O)} Retrying in ${Math.round(C/1e3)}s without rerunning the agent.`)}}),payloadFor:R=>r==="synthesis"?Sf(M.workspace,n,R,{expectedSourceRevision:e.source_revision}):M0(R),rejectionFor:R=>ua(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 R0(M.workspace,n,r);let O=await vf(M.workspace,n,$,R);return w(O,$),t.phase="delivering",t.lastMessage="Delivering corrected stage result",O}});if(p)throw new Error(p);k=A.result;let x=A.response;if(!x.ok)throw new Error(await ua(x,"the assessment"));if(l=!0,wc.record("assessment stage","completed",{durationMs:Date.now()-o,usage:k.usage}),r==="synthesis"){let R=await x.json(),O=await I0(M.workspace,n,e,k,R.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${Kt.relative(M.workspace,O)}.`);try{let C=await Nc(M.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(b){let $=p||en(b),k=C$(e,b),T=j$(b),E=T$(b);T&&(await T0(M.workspace,n,r).catch(x=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${x.message}`)}),d=null);let A=!p&&(d||T)&&(T||A$(b))&&k<E;if(m()&&A){t.phase="starting",t.lastMessage=T?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=O$(e,b);let x=I$(b,k);Da(b)&&(pw=Math.max(pw,Date.now()+x)),console.warn(`[assessment:${r}] ${T?"Agent session became unusable":"Agent session interrupted"}: ${$} ${T?"Starting a fresh session from the saved draft":`Resuming session ${d}`} in ${Math.round(x/1e3)}s (${k+1}/${E}).`),await new Promise(R=>setTimeout(R,x))}else m()&&(u=await g({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:$}));A||(wc.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${$}`))}finally{clearInterval(S),Nt.clearStatus(s),r==="synthesis"&&l&&fw.delete(n),m()&&(Zt.delete(t.key),M$(_i,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),Sc())}}async function rY(e){let t=String(e.run_id||"");Ro+=1;try{kr&&await kr;let n=await i$(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 Si();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: ${en(n)}`)}finally{Ro-=1,Sc()}}function oY(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{it('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function it(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.2",
3
+ "version": "1.59.3",
4
4
  "description": "Connect a local coding agent to EngineerOS, using ACP when supported.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",