@engineeros/connector 1.59.18 → 1.59.19

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.
@@ -1118,7 +1118,7 @@ It is checked with the provider and stored in this machine's protected vault
1118
1118
  (Windows Data Protection, the macOS Keychain or the Linux Secret Service).
1119
1119
  EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function FY(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(`
1120
1120
  `),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
1121
- `)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 GO=Symbol("missing");function BY(e,t){return new Promise(n=>{let r=DY(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?GO:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function zO(e,t){for(let n of Lc){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 HO(e,t,n,{vault:r=Lw(),run:o=cp,fetchImpl:s=fetch,secret:i=FY,interactive:a=BY,install:c=ap,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(UY),n.help?0:2;if(e==="integrations")return zO(l,(await dp({run:o,vault:r})).providers),0;let p=t[0];if(!Lc.includes(p))return u(`Unknown provider ${p}. Choose one of: ${Lc.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=$s[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===GO){let m=await Ni(f);if(!m){l(`Installing the ${Nc[f].label} ${Nc[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} ${up[p]} is how this machine signs in to ${p}.`),1):(zO(l,{[p]:(await dp({run:o,vault:r})).providers[p]}),0)}let d=rn[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await Dw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await Uw(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}}j();import{spawn as zY}from"node:child_process";async function qO({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=zY,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ko(await _n(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await GY(o,c.entry,i,t);if(l===aa){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 _n(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await Yp(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 GY(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Ps]:"1",[Wp]:r.entry,[Vp]: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 Jo="1.59.18",yp="1.59.18",VY=3e5,_p=["queued","running","reporting"],XY=5e3,Fw={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."},Bw={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."},JY=6e4,KY=3e4,YY=60*6e4,zw={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Gw={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:vt,positional:zt,flags:Ue}=vT(process.argv.slice(2));vt==="version"&&(console.log(Jo),process.exit(0));var wo=null,an=!1,Tr=null,aC=!1,cC=null,ty=null,Mt=null,Gc=null,Zw,WO,VO,Hw,XO,Li,Ui,lC=Yd({getWorkspace:()=>P.workspace,onRecorded:e=>_R(P,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}`))}),ZY=FO({getWorkspace:()=>P.workspace,huntSignIns:lC}),Fc=ET();vt==="results"&&(zt[0]!=="upload"&&(console.log(zd),process.exit(Ue.help||!zt[0]?0:2)),process.exit(await C1(Ue)));(vt==="connect"||vt==="disconnect"||vt==="integrations")&&process.exit(await HO(vt,zt,Ue,{fetchImpl:LO}));if(vt==="runner"){let e=sn.resolve(Ue.workspace||process.cwd()),t=zt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?sn.join(sn.dirname(Et(e,Ue["run-id"])),"worker.log"):sn.join(e,".engineeros","runner","service.log");qY(sn.dirname(n),{recursive:!0});let r=(...s)=>ic(n,`${WY(...s)}
1121
+ `)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 GO=Symbol("missing");function BY(e,t){return new Promise(n=>{let r=DY(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?GO:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function zO(e,t){for(let n of Lc){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 HO(e,t,n,{vault:r=Lw(),run:o=cp,fetchImpl:s=fetch,secret:i=FY,interactive:a=BY,install:c=ap,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(UY),n.help?0:2;if(e==="integrations")return zO(l,(await dp({run:o,vault:r})).providers),0;let p=t[0];if(!Lc.includes(p))return u(`Unknown provider ${p}. Choose one of: ${Lc.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=$s[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===GO){let m=await Ni(f);if(!m){l(`Installing the ${Nc[f].label} ${Nc[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} ${up[p]} is how this machine signs in to ${p}.`),1):(zO(l,{[p]:(await dp({run:o,vault:r})).providers[p]}),0)}let d=rn[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await Dw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await Uw(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}}j();import{spawn as zY}from"node:child_process";async function qO({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=zY,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ko(await _n(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await GY(o,c.entry,i,t);if(l===aa){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 _n(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await Yp(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 GY(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Ps]:"1",[Wp]:r.entry,[Vp]: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 Jo="1.59.19",yp="1.59.19",VY=3e5,_p=["queued","running","reporting"],XY=5e3,Fw={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."},Bw={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."},JY=6e4,KY=3e4,YY=60*6e4,zw={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Gw={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:vt,positional:zt,flags:Ue}=vT(process.argv.slice(2));vt==="version"&&(console.log(Jo),process.exit(0));var wo=null,an=!1,Tr=null,aC=!1,cC=null,ty=null,Mt=null,Gc=null,Zw,WO,VO,Hw,XO,Li,Ui,lC=Yd({getWorkspace:()=>P.workspace,onRecorded:e=>_R(P,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}`))}),ZY=FO({getWorkspace:()=>P.workspace,huntSignIns:lC}),Fc=ET();vt==="results"&&(zt[0]!=="upload"&&(console.log(zd),process.exit(Ue.help||!zt[0]?0:2)),process.exit(await C1(Ue)));(vt==="connect"||vt==="disconnect"||vt==="integrations")&&process.exit(await HO(vt,zt,Ue,{fetchImpl:LO}));if(vt==="runner"){let e=sn.resolve(Ue.workspace||process.cwd()),t=zt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?sn.join(sn.dirname(Et(e,Ue["run-id"])),"worker.log"):sn.join(e,".engineeros","runner","service.log");qY(sn.dirname(n),{recursive:!0});let r=(...s)=>ic(n,`${WY(...s)}
1122
1122
  `),o=(s,i,a)=>(ic(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(Ue["keep-awake"]!==void 0){if(!["on","off"].includes(Ue["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await Zt(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await Kn({...n,runner_keep_awake:Ue["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await cd(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 Kx(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await ki(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await Do(e),null,2)):t==="serve"?await eA(e):t==="worker"?await tA(e,Ue["run-id"]):pt("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){pt(dg(n,e).message)}}Ue["assessment-workers"]!==void 0&&pt("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(vt==="secret")try{let e=fg(Ue),t=zt[0]||"list",n=await bT({action:t,name:zt[1],workspace:e,readValue:()=>_T({label:`Value for ${zt[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){pt(e.message)}if(vt==="tools"){try{let e=fg(Ue),t=zt[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=zt[1];r||pt(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await tm(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 Ha(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 Zh(e,t,zt[1]);let n=await qn(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){pt(e.message)}process.exit(process.exitCode||0)}if(vt==="agents"){let e;try{e=await wm()}catch(n){pt(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await Wa(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(vt==="agent"){let e=zt[0],t=zt[1]||"check";(!e||!["check","install"].includes(t))&&pt("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await Va(e):await Wa(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){pt(n instanceof Error?n.message:String(n))}process.exit(0)}if(vt==="mcp"){let e=Ue.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=Ue["run-id"]||zt[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await Zt(e);await BT({config:n,runId:t,version:Jo,input:process.stdin,output:process.stdout}),process.exit(0)}if(vt==="context-mcp"){let e=Ue["config-workspace"]||Ue.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await Zt(e);t||pt("This workspace is not paired with EngineerOS."),await v1({config:t,workspace:Ue.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:Jo,input:process.stdin,output:process.stdout}),process.exit(0)}if(vt==="status"){let e=await Zt(Ue.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(vt==="doctor"){let e=sn.resolve(Ue.workspace||process.cwd()),t=await Zt(e),n=await PT(e),r=await Wi(t||{workspace:e},e,Wg(n));console.log(Bg(r)),process.exit(r.status==="failed"?1:0)}if(vt==="update"){let e=zt[0]||"status";try{let t=Jp(process.argv[1],yp),n=await Zp(Xr(),t,{action:e,policy:zt[1]??null});console.log(la(Qp(n,t,{supervised:!0})))}catch(t){pt(`${t.message}
1123
1123
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var Fi=vt==="hunt-host";if(Fi)try{Ue.workspace=sA(zt,Ue)}catch(e){pt(e.message)}if((vt==="start"||vt==="pair"||Fi)&&process.env[Ps]!=="1"&&It(yp))try{process.exit(await qO({root:Xr(),bundled:{version:yp,entry:sn.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:sn.resolve(Ue.workspace||process.cwd())}))}catch(e){pt(`The connector process could not be started: ${e.message}`)}if(Fi){try{await iA(Ue.workspace,zt[0]?Ue.agent:null)}catch(e){pt(e.message)}vt=zt[0]?"pair":"start"}var P,As,Bc;if(vt==="pair"){let e=zt[0];e||pt("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=Ue.url;t||pt("Pairing requires --url with the EngineerOS backend address."),Ue.agent&&Ue["agent-command"]&&pt("Use either --agent or --agent-command, not both.");let n=Ue["agent-protocol"]||(Ue["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||pt(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(Ue.agent||Ue["agent-command"])&&pt("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{Ue.agent&&(await Wa(Ue.agent),r=await ym(Ue.agent))}catch(o){pt(o instanceof Error?o.message:String(o))}P={server_url:nf(t),workspace:sn.resolve(Ue.workspace||process.cwd()),onboard:Ue.onboard===!0,onboarding_pending:Ue.onboard===!0,hunt_host:Fi,agent_protocol:n,agent_command:Ue["agent-command"]||null,agent_args:S7(Ue["agent-args"]),agent_name:Ue["agent-name"]||null,...r,skip_git_repo_check:Fi||Ue["skip-git-repo-check"]===!0,name:Ue.name||`${HY.hostname()} - ${sn.basename(sn.resolve(Ue.workspace||process.cwd()))}`},Bc=await Zt(P.workspace),As={type:"pair",pairing_code:e,name:P.name,capabilities:{},...h_(Bc,P.server_url)}}else vt==="start"?(P=await Zt(Ue.workspace||process.cwd()),P||pt("This connector is not paired. Create a pairing command in EngineerOS first."),Fi&&!P.hunt_host&&pt("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),P.token||pt("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),As={type:"authenticate",connector_id:P.connector_id,token:P.token}):pt("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var uC=nA(P,{reportError:e=>console.error(e)}),Xo=0,bp=!1,Hi=null,cn=new Map,qw=0,Ww=new Set,Bi=[],on=new Map,Nt,Qw,hp,Gr=null,mp=!1,dC=0,Vw=null,Xw=[],gp,pC,Dc=1e3,zi,JO=0,Jw=!1,ho=!1,ir,Vo=!1,vp=!1,ey=0;function Pi(e){return ey+=1,e.finally(()=>{ey-=1})}var Di,Es=0;function zc({exitCode:e=0}={}){if(Es=Math.max(Es,e),Di)return Di;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Di=QY().finally(()=>clearTimeout(t)),Di}async function QY(){if(an=!0,Gc?.stop(),wo?.stop(),ty?.stop(),cC?.stop(),clearInterval(Zw),Mt?.stop(),pC?.(),clearTimeout(gp),clearInterval(Qw),clearInterval(hp),await Promise.all([...[...cn.values()].map(e=>vn(e.child))]),await Promise.all([...on.values()].map(oy)),await Li?.cancelAll(),await Ui?.abortAll(),await qa(),await py().catch(e=>{Es=Math.max(Es,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),Nt?.close(),Es&&Es!==aa){let e;await Promise.race([(async()=>{await wo?.drain(),await Wi(P,P.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Es)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{zc()});var KO=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{KO||(KO=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await zc({exitCode:1}))});Mt=_y();process.on("exit",()=>{Gc?.stop(),Mt.stop()});Mt.banner(`EngineerOS connector ${Jo}`,[P.workspace,P.server_url]);wo=$T({actions:{refresh_tool_inventory:async()=>{He.tool_inventory=await qn(P.workspace),Mn()},restart_goal_runner:()=>ki(P.workspace)},onNotify:()=>Wi(P,P.workspace),explain:async e=>{if(!await qi())return null;let{reading:t}=await Ex(P,e);return t},onUpdate:e=>MT(P.workspace,e)});cC=DT({render:(e,t)=>Mt.write(e,t),onRecord:e=>wo.observe(e)});ty=UT({workspace:P.workspace,onRecord:e=>{wo.observe(e),Mt.line(e.channel,e.level,e.message)}});wo.start();P.hunt_host||ty.start();Mt.live&&!P.hunt_host&&(Zw=setInterval(()=>{e7().catch(()=>{})},XY),Zw.unref?.());var Kw=new Set;async function e7(){if(P.hunt_host)return;WO??=cg(P.workspace);let{jobs:e}=await WO(),t=new Set,n=e.filter(r=>r.status!=="queued"&&_p.includes(r.status)).length;for(let r of e){if(!_p.includes(r.status))continue;t.add(r.runId),Kw.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;Mt.status(`goal:${r.runId}`,r.activity?.message||o,t7(r),{agent:r.status!=="queued",link:Hi&&`${Hi}/goals`,phase:o}),Mt.step(`goal:${r.runId}`,r.activity?.message)}for(let r of Kw)t.has(r)||(Kw.delete(r),Mt.clearStatus(`goal:${r}`))}function t7(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function qi({ignoreBugHunt:e=!1}={}){if(an||cn.size>0||on.size>0||Xo>0||(Li?.active??0)>0||!e&&(Ui?.active??0)>0)return!1;try{let{jobs:t}=await Do(P.workspace);return!an&&!t.some(n=>_p.includes(n.status))}catch{return!1}}try{let e=P.hunt_host?{}:await Ns(P.workspace);e.committed&&(P.onboarding_pending=!0,P.connector_id&&await Kn(P),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await wC(e)}var fC=await _n(Xr()).then(e=>e.policy!=="manual",()=>!1),st;try{st=await rc(P,P.workspace)}catch(e){await wC(e)}console.log(`Using ${st.name} through ${st.protocol} (${st.version}).`);var hC=async()=>Sc({workspace:P.workspace}).names().catch(()=>[]),He=jd(P,st,await qn(P.workspace),{secretNames:await hC()}),go=e_({running:Jp(process.argv[1],yp),supervised:process.env[Ps]==="1",isIdle:async()=>!an&&cn.size===0&&Bi.length===0&&on.size===0&&Xo===0&&ey===0&&!Vo&&!vp&&!mp,restart:()=>zc({exitCode:aa}),onChange:e=>{He.runtime_update=e,Nt?.readyState===WebSocket.OPEN&&Mn()}});try{await go.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}P={...P,execution_profiles:st.executionProfiles??null};vt==="pair"&&Bc?.connector_id||await Kn(P);He.agent_session={...He.agent_session,status:"checking",message:`Checking that ${st.name} can answer.`};He.bug_hunt_browser=!1;As.capabilities=He;console.log(ao(P.worker_limit)===null?`Workers: automatic, ${gi()} ${st.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${ao(P.worker_limit)} ${st.name} workers side by side, set with /workers.`);var xs=e=>co(P,e),YO=od(xs,{signature:Nx});async function n7(){let e=await Do(P.workspace).catch(()=>({service:null,jobs:[]}));return{version:Jo,now:Date.now(),workspace:P.workspace,config_path:Rn(P.workspace),config:P,agent:st,automatic_worker_limit:gi(),worker_limit:ao(P.worker_limit),connection:{state:r7(),server_url:P.server_url,last_error:ir||null},work:{assessments:[...cn.values()].map(t=>({stage:t.stage,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:st.name})),prompts:[...on.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,phase:t.phase,message:t.lastMessage,started_at:t.startedAt,pid:t.child?.pid??null,agent:st.name})),integrations:Xo},runner:e,runtime_update:go.report(),health:wo?.health()??null,activity:Fc.snapshot()}}function r7(){return an||ho?"stopped":Nt?.readyState===WebSocket.OPEN?"connected":"connecting"}var o7={async cancelPrompt(e){let t=[...on.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=>gC(e),setVerbose(e){return e===bp?`Detailed agent activity is already ${e?"on":"off"}.`:(ny(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"?(go.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 go.command(e),la(await go.refresh()))}};Gc=RT({ui:Mt,snapshot:n7,actions:o7});Gc&&console.log(TT());await mC();var ZO=new Set;async function mC(){if(an||ho)return;console.log(`Connecting ${P.name} to ${P.server_url}`),ho=!1,ir=void 0;let e=new WebSocket(P.server_url);Nt=e;let t=yv(e,P.server_url,{onTimeout:r=>{Nt===e&&(ir=r,console.error(r),Yw())}});pC=t,e.addEventListener("open",()=>{if(Nt!==e){e.close();return}try{if(pv(Nt,e,As))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){ir=pn(r),console.error(`Could not authenticate the WebSocket connection: ${ir}`);try{e.close()}catch{}Yw()}}),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: ${pn(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){an=!0,ho=!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=Bc?.connector_id===r.connector.id;if(P=m_(P,Bc,r.connector.id,r.token),await Kn(P),r.connector?.capabilities?.http_updates!==!0){an=!0,ho=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}As={type:"authenticate",connector_id:P.connector_id,token:P.token,capabilities:He},console.log(s?`Reconnected existing workspace connector ${P.connector_id}; assessment history is preserved.`:`Paired. Connector ${P.connector_id} is online.`),nC(r);return}if(r.type==="authenticated"){t();let s=P.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(zi?`Reconnected after ${et(Date.now()-zi)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),zi=void 0,nC(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){vp||i7(r);return}if(r.type==="workspace.refresh"){Gi();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await gC(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){ny(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(mo=!1,He.bug_hunt_browser=!1,Mn());try{He.tool_inventory=await Ha(P.workspace,r,void 0,{confirmLocal:i=>Gc?.confirm(i)??!1,log:wp}),s&&(mo=!0),He.bug_hunt_browser=Ss(He.tool_inventory)&&mo,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:He.tool_inventory})),Mn(),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 tm(P.workspace,r,{onStatus:async()=>{He.tool_inventory=await qn(P.workspace),Mn()}});He.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:He.tool_inventory})),Mn(),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"){Xs(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===UO){Pi(ZY(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),BO(P,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(Bi,cn.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Hc();return}if(r.type==="prompt.execute"){let s=on.get(r.prompt_id);s?SC(r)>s.executionRevision&&await y7(s,r):vC(r);return}if(r.type==="prompt.cancel"){let s=on.get(r.prompt_id);s&&await oy(s);return}if(r.type==="agent.warm"){d7(r);return}if(r.type==="run.available"){if(P.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await uC.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${sn.join(P.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${pn(s)}`)}return}if(r.type==="goal.cleanup"){try{await Qx(P.workspace),await ki(P.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){v7(r);return}if(r.type==="run.cancelled"){await ag(P.workspace,r.run_id);return}if(r.type===gS){Li??=jh({getConfig:()=>P,onTestsCommitted:()=>Gi()}),Pi(Li.handle(r));return}if(r.type===wS){Li??=jh({getConfig:()=>P,onTestsCommitted:()=>Gi()}),await Li.cancel(r);return}if(r.type===iO){Ui??=pO({getConfig:()=>P,isIdle:()=>qi({ignoreBugHunt:!0}),recordedSignIns:lC,activity:{status:Mt.status,step:ry,agents:Mt.agents,finish:Mt.finish}}),Pi(Ui.handle(r));return}if(r.type===aO){Ui?.stop(r);return}if(r.type===I1){VO??=j1({getConfig:()=>P}),Pi(VO.handle(r));return}if(r.type===U1){Hw??=X1({getConfig:()=>P}),Pi(Hw.handle(r));return}if(r.type===F1){await Hw?.cancel(r);return}if(r.type===K1){XO??=Y1({getConfig:()=>P,isIdle:()=>qi(),agentTurn:KE}),Pi(XO.handle(r));return}if(r.type==="connector.update"){s7(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await zc();return}if(r.type==="connector.revoked"){an=!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||(Vo=!1);return}if(r.type==="connection.error"){ho=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);ZO.has(o)||(ZO.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${Jo}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),Nt!==e||Di)return;let o=fv(r);if(!o.retry||ho||an){console.error(o.message),o.retry&&ho&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),zc();return}ir=ir?`${o.message} ${ir}`:o.message,Yw()}),e.addEventListener("error",r=>{Nt===e&&(ir=dv(r),console.error(`WebSocket connection to ${P.server_url} failed: ${ir}`))})}async function s7(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=go.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 go.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 i7(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";vp=!0,console.log(`Starting interactive ${st.name} provider ${n}.`);try{await(n==="logout"?wv:gv)(st,P.workspace),st=await rc(P,P.workspace),He=jd(P,st,He.tool_inventory,{secretNames:await hC()}),As.capabilities=He,Nt.readyState===WebSocket.OPEN&&(Nt.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:He.agent_session})),Nt.close(1e3,`Provider ${n} completed`)),console.log(`${st.name} provider ${n} completed.`)}catch(r){let o=pn(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{vp=!1}}function Yw(){if(an||ho||gp)return;let e=ir?` Last error: ${ir}`:"",t=zi?` Offline for ${et(Date.now()-zi)}.`:"";zi??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(Dc/1e3)}s.`),gp=setTimeout(()=>{gp=void 0,mC()},Dc),Dc=Math.min(3e4,Dc*2)}async function Gi(){if(!P.hunt_host&&!(Vo||Nt.readyState!==WebSocket.OPEN)){Vo=!0,console.log("Inspecting the workspace without executing its code.");try{let{snapshot:e,map:t,stats:n}=await Qg({workspace:P.workspace,connectorId:P.connector_id,refresh:Gs,takeSnapshot:Tx,buildMap:(i,a)=>Ud(P.workspace,i,{head:a.head_revision,branch:a.branch}),log:i=>console.error(i)}),r=await Ax(P.workspace,P.last_head_reported??P.last_snapshot_head,e.head_revision).catch(()=>null);r&&(e.changed_since=r);let o=await fetch(Ls(P.server_url,P.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.token}`},body:JSON.stringify(e)});if(!o.ok)throw new Error(await Oa(o,"the workspace"));let s=await o.json();P={...P,onboarding_pending:!1,last_snapshot_head:e.head_revision??P.last_snapshot_head,last_head_reported:e.head_revision??P.last_head_reported,last_head_branch:e.head_revision?e.branch??null:P.last_head_branch},await Kn(P),t&&await Fd(P.workspace,P.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.`),Vo=!1}catch(e){Vo=!1,console.error(`Workspace assessment failed: ${pn(e)}`)}}}var a7=8e6,QO,eC="";async function c7({current:e,previous:t}){if(Vo||Nt?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=sn.resolve(P.workspace),r=async()=>{P={...P,last_head_reported:e.head,last_head_branch:e.branch??null},await Kn(P)},o=await Zg(P.workspace,P.connector_id),s=async()=>{if(await Gi(),P.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let{index:i}=await Gs(P.workspace,P.connector_id),a=null,c=await u1({previous:{head:t.head,branch:t.branch??null},current:e,compare:(d,f)=>eg(P.workspace,d,f),inventoryDelta:d=>Y_(n,Object.entries(i.files).map(([f,h])=>({path:f,size:h.size})),d),mapDelta:async()=>(a=await Ud(P.workspace,i,{head:e.head,branch:e.branch}),Yg(o,a)),contentHead:(await Dl(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)>a7)return s();let u=await fetch(y_(P.server_url,P.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.token}`},body:l});if(!u.ok)throw new Error(await Oa(u,"the new commit"));let p=await u.json().catch(()=>({}));if(p.needs_snapshot)return s();await r(),a&&await Fd(P.workspace,P.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 l7(){P.hunt_host||P.onboarding_pending||Vo||Nt?.readyState!==WebSocket.OPEN||(QO??=l1({readHead:()=>c1(P.workspace),getLastReported:()=>({head:P.last_head_reported??P.last_snapshot_head,branch:P.last_head_branch}),onChange:c7,onError:e=>{e.message!==eC&&(eC=e.message,console.error(`The new commit could not be reported yet: ${pn(e)}`))}}),QO.poll().catch(()=>{}))}var u7=6e4,tC=0;async function d7(e){if(P.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?P.sessions?.[t]:void 0,r=[];Date.now()-tC>u7&&(tC=Date.now(),r.push(Gs(P.workspace,P.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),P.agent_protocol==="acp"&&r.push(Vk(P.workspace,P,{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(`${st?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Mn(){let e=mx(cn);YO.update({type:"assessment.workers",assessment_workers:e,tool_inventory:He.tool_inventory,runtime_update:He.runtime_update,agent_session:He.agent_session,bug_hunt_browser:He.bug_hunt_browser,...ed(P.worker_limit)}),YO.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function gC(e){let t=ao(e);return t===ao(P.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(P={...P,worker_limit:t},await Kn(P),Hc(),Mn(),t===null?`Workers are automatic again: up to ${gi()} side by side for this machine's CPU and memory, for ${$c} (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: ${$c}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function ny(e){if(e!==bp){if(bp=e,!e)for(let t of cn.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."),Mn()}}function ry(e,t,n=null){Mt.step(e,t,n)&&bp&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function p7(){clearInterval(hp);let e=!1,t=()=>{e||cn.size>0||on.size>0||(e=!0,Wi(P,P.workspace).finally(()=>{e=!1}))};t(),hp=setInterval(t,VY),hp.unref?.()}async function Wi(e,t,n=wo?.healthChecks()??[]){let r=await pT({config:e,workspace:t,version:Jo,insights:n,agentSession:Tr,probes:{inspectAgent:(o,s)=>an?st:rc(o,s),inspectTools:o=>an?He.tool_inventory:qn(o),runnerStatus:Do}});try{aC=(await fT(e,r,co))?.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 wC(e){if(an)return Di;let t=e instanceof Error?e.message:String(e),n=await Wi(P,P.workspace).catch(()=>null);n&&console.error(Bg(n)),pt(t)}function nC(e){ny(e.connector?.activity_log_enabled===!0),Hi=e.project_url??null,Dc=1e3,h7(),_C(),go.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),m7(),P.onboarding_pending&&Gi()}var Uc=null,mo=!1,yC=0,f7=Date.now();async function h7(){return Uc||(Uc=(async()=>{fC&&await Rk(P.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{wp("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await aA(P.workspace,{log:wp}),mo=!0,He.tool_inventory=await qn(P.workspace),He.bug_hunt_browser=Ss(He.tool_inventory)&&mo,wp(`Bug Hunter's browser is ready (${et(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${et(Date.now()-e)}: ${t.message}`),He.bug_hunt_browser=!1}Mn()})(),Uc)}function wp(e){console.log(`[browser] ${e}`)}async function _C(){if(Tr?.state!=="checking"){yC=Date.now(),He.agent_session={...He.agent_session,status:"checking",message:`Checking that ${st.name} can answer.`},Mn(),Tr={state:"checking",detail:`Asking ${st.name} one question to confirm its session.`},console.log(`Checking that ${st.name} can answer before accepting work.`);try{await bx(P,st.name),Tr={state:"ready",detail:`${st.name} answered; its session is usable.`},He.agent_session={...He.agent_session,status:"authenticated",message:Tr.detail},console.log(Tr.detail)}catch(e){Tr={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:P.hunt_host?lA(P.agent_id||P.agent_protocol):di(P.agent_id||P.agent_protocol)},He.agent_session={...He.agent_session,status:"logged_out",message:Tr.remedy},console.error(`${Tr.detail}
1124
1124
  ${Tr.remedy}`)}Mn(),await Wi(P,P.workspace).catch(()=>null)}}function m7(){clearInterval(Qw);let e=!1,t=0,n=0,r=!1,o=()=>{go.tick(),g7(),l7(),P.hunt_host&&Uc&&Date.now()-yC>=cA(f7)&&on.size===0&&cn.size===0&&!(Ui?.active>0)&&_C(),!P.hunt_host&&!r&&_c(Gw.id)&&(r=!0,uC.flush().then(()=>fp(Gw)).catch(s=>pp(Gw,s)).finally(()=>{r=!1})),cn.size>0&&Mn(),!P.hunt_host&&!Gr&&Date.now()-t>=JY&&_c(Fw.id)&&(t=Date.now(),bC().then(()=>fp(Fw)).catch(s=>pp(Fw,s))),!P.hunt_host&&aC&&!mp&&_c(Bw.id)&&Date.now()-dC>=BS&&(mp=!0,w7().then(()=>fp(Bw)).catch(s=>pp(Bw,s)).finally(()=>{mp=!1})),!e&&Date.now()-n>=KY&&_c(zw.id)&&(e=!0,n=Date.now(),qn(P.workspace).then(async s=>{if(He.tool_inventory=s,!mo&&Ss(s))try{await(await Qo(await zo(P.workspace))).close(),mo=!0}catch{mo=!1}He.bug_hunt_browser=Ss(s)&&mo,Mn(),fp(zw)}).catch(s=>pp(zw,s)).finally(()=>{e=!1}))};o(),Qw=setInterval(o,1e4),p7()}async function g7(){if(!(!fC||P.agent_protocol!=="acp"||!P.agent_id||Jw||Tr?.state==="checking"||Date.now()-JO<YY)){Jw=!0;try{if(!await qi())return;JO=Date.now();let e,t=await t$(P,{verify:async r=>{e=await rc(r,P.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===P||an)return;P={...t,execution_profiles:e.executionProfiles??null},await Kn(P),st=e;let n=jd(P,st,He.tool_inventory);if(Object.assign(He,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),As.capabilities=He,!await qi())return;await qa(),Nt?.readyState===WebSocket.OPEN&&Nt.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{Jw=!1}}}function pp(e,t){let n=iT(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 fp(e){aT(e.id)&&console.log(`${e.title} recovered.`)}async function w7(){if(P.hunt_host||!await qi())return;dC=Date.now();let{jobs:e}=await Do(P.workspace).catch(()=>({jobs:[]})),t=await zS(P.workspace,{jobs:e});if(!GS(t))return;let n=`${t.fingerprint}:${Xw.join(",")}`,r=Vw?.key===n,o=r?Vw.candidates:await xx(P,t,Xw);Vw={key:n,candidates:o};let s=await xs(WS(t,o,{version:Jo}));Array.isArray(s?.refused)&&(Xw=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 Wo=null,rC=null;async function bC(){if(!P.hunt_host){if(Gr)return Gr;Gr=(async()=>{let e=await jS(P,{knownRevision:Wo?.revision??null});if(e.unchanged||(Wo=e),rC===Wo.revision)return Wo;let{jobs:t}=await Do(P.workspace);return!t.some(r=>_p.includes(r.status))&&Xo===0&&cn.size===0&&(await yu(P.workspace,Wo),rC=Wo.revision),Wo})();try{return await Gr}finally{Gr=null,Hc()}}}function oC(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)),on.get(e)?.events.push(n)}var sC=null;function Hc(){let e=Nt.readyState===WebSocket.OPEN,t=cn.values().next().value,n=ao(P.worker_limit)??Math.min(gi(),Ym(t?.workerLimit??Bi[0]?.worker_limit)),r=e&&!Gr&&Xo===0?ix(Bi,cn.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:Ym(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};cn.set(i,a),b7(s,a)}r.length>0&&Mn();let o=ax({queued:Bi,running:cn.size,workerLimit:n,connected:e,designSync:!!Gr,integrations:Xo});o&&o!==sC&&console.log(o),sC=o}function Sp(e){let t=Zm(e);return t?`${st.name} on ${t}`:st.name}async function vC(e){let t=e.prompt_id,n=`prompt:${String(t).slice(0,8)}`,r=e.purpose||"project",o=Date.now(),s=`${r} \xB7 ${Sp(e)}`,i=_x(e,st.name),a={runId:t,purpose:r,startedAt:o,child:null,controller:null,cancelled:!1,stoppedHere:!1,cancellation:new AbortController,events:Dx(xs),executionRevision:SC(e),sessionKey:td(e),sessionId:null,phase:"preparing",lastMessage:s,replacement:null};on.set(t,a);let c=Lx(xs,{type:"prompt.heartbeat",prompt_id:t,execution_revision:a.executionRevision},{onError:g=>console.error(`[${n}] Prompt heartbeat: ${g.message}`)}),l,u=g=>{let w=g?JSON.stringify(g):null;!w||w===l||on.get(t)!==a||(l=w,oC(t,g))},p=Number(e.answer_within_seconds),d=p>0?o+p*1e3:void 0;console.log([`[${n}] ${i} for ${r}.`,`${st.name} can reason for several minutes without reporting a step.`,...d?[Ip(d,o)]:[]].join(" ")),oC(t,{kind:"status",message:i}),Mt.status(n,s,o,{link:Hi,answerBy:d,phase:a.phase});let f=g=>{let w=rx(g),$=nx(g),y=hs(g);on.get(t)===a&&($&&(a.phase=$),(y??w?.message)&&(a.lastMessage=y??w?.message),Mt.status(n,a.lastMessage,o,{link:Hi,answerBy:d,phase:a.phase}),ry(n,y??w?.message));let _=g.type==="forge.output"?null:y;u(w??(_?{kind:"status",message:_}:null))},h="failed",m=[r];try{nd(e)||(f({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await DS(bC,{pinned:!!e.local_design_context,last:Wo,onFallback:(y,_)=>f({type:"connector.step",message:`Design context not refreshed (${y.message}); continuing with ${_?"the copy synced earlier":"none"}`})})});let g=await JE(e,P,{onProcess:y=>{on.get(t)===a&&(a.child=y)},onController:y=>{on.get(t)===a&&(a.controller=y)},onSession:y=>{a.sessionId=y},onEvent:f},{signal:a.cancellation.signal});if(a.stoppedHere)throw new Error(iC);let w=g.singleTurn?g_(P.sessions,g.sessionKey):rf(P.sessions,g.sessionKey,g.sessionId);if(JSON.stringify(w)!==JSON.stringify(P.sessions||{})&&(P={...P,sessions:w},await Kn(P)),a.cancelled)return;await a.events.close().catch(y=>{console.error(`[${n}] Prompt progress delivery: ${y.message} The agent has finished; submitting its complete response separately.`)});let $=await rd(xs,{type:"prompt.completed",prompt_id:t,execution_revision:a.executionRevision,content:g.content,model:g.model,session_id:g.sessionId,usage:g.usage});$||console.error(`[${n}] ${rg}`),Fc.record("prompt","completed",{durationMs:Date.now()-o,usage:g.usage}),h=$?"finished":"undelivered",m=[Qc(g.usage),r]}catch(g){let w=a.stoppedHere?iC:pn(g);if(Fc.record("prompt","failed",{durationMs:Date.now()-o}),a.stoppedHere&&(h="cancelled"),!a.cancelled){try{await rd(xs,{type:"prompt.failed",prompt_id:t,execution_revision:a.executionRevision,message:w})||console.error(`[${n}] ${rg}`)}catch($){console.error(`[${n}] Prompt failure delivery: ${$.message}`)}console.error(w)}}finally{await c.stop(),a.events.stop();let g=a.replacement;g?(h="replaced",m=[`continuing on ${Sp(g)}`,r]):a.cancelled&&(h="cancelled"),Mt.finish(n,h,m),on.get(t)===a&&on.delete(t),g&&_7(a,g)}}var iC="Cancelled from the connector terminal by the person running it.";async function oy(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function SC(e){return Number(e.execution_revision)||1}async function y7(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 ${Sp(t)}.`),await oy(e))}function _7(e,t){e.sessionId&&(P={...P,sessions:rf(P.sessions,e.sessionKey,e.sessionId)},Kn(P).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),vC(t)}async function b7(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 ${Sp(e)}.`),!Ww.has(n)){Ww.add(n);try{let S=await QE(P.workspace);if(!S.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let E=S.accepted_head_revision?S.current_head_revision?S.current_head_revision!==S.accepted_head_revision?`The workspace is now at commit \`${S.current_head_revision}\`; the accepted assessment is from \`${S.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${S.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 ${S.stages.length||"no"} section(s). ${E}`)}}catch(S){console.error(`Assessment freshness check failed: ${S.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=()=>!an&&cn.get(t.key)===t,g=async S=>{try{return await rd(xs,S)||console.warn(`[${s}] ${Mx}`),!0}catch(E){return console.error(`Assessment failure delivery: ${E.message}`),!1}},w=(S,{milestone:E=!0}={})=>{if(!m()||E&&f===S)return;E&&(f=S,h.has(S)||(h.add(S),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${S}.`));let b=String(S).slice(0,500);t.progressPercent=c,t.lastMessage=b,Mt.status(s,b,o,{link:Hi,phase:t.phase})};w(`Starting ${r} assessment stage`);let $=setInterval(()=>{let S=Date.now(),E=S-t.lastActivityAt,b=i&&!a?tx(r,E):null;if(!p&&b){p=b,console.error(`[assessment:${r}] ${p}`),sc(t.controller,t.child);return}p||wo.observe({at:S,level:"info",message:Mt.status(s,`${t.lastMessage} \xB7 last agent activity ${et(E)} ago (${t.eventCount.toLocaleString()} events)`,o,{phase:t.phase})})},15e3),y={onSession:async S=>{m()&&(d=String(S),await ib(P.workspace,n,r,S,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:S=>{m()&&(t.controller=S)},onProcess:S=>{m()&&(t.child=S,i=!0,t.phase!=="correcting"&&(t.phase="running",w("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:S=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let E=ex(S);if(E&&w(E),!m())return;let b=hs(S);!b||b===t.lastDetail||(t.lastDetail=b,ry(s,b))}},_=(S,E)=>Xm(S,E,P,y,{draftPath:sn.relative(P.workspace,sn.join(Fn(P.workspace,n),S.report_file)).split(sn.sep).join("/")});try{let S=qw-Date.now();S>0&&(w(`Waiting ${Math.ceil(S/1e3)}s for the model provider's rate limit to clear`),await new Promise(T=>setTimeout(T,S+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,w("Calculating changed files and affected behavior"));let E=await db(P.workspace,e),b=await Xf(P.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(b)_(b,E),w("Recovered completed stage report from connector storage");else{if(d=await ab(P.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),d&&w("Restoring interrupted agent session"),b=await XE(E,P,y,{previousSessionId:d}),p)throw new Error(p);a=!0,await Vf(P.workspace,n,E,b)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let O=T=>fetch(b_(P.server_url,P.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.token}`},body:JSON.stringify(T),signal:AbortSignal.timeout(jE)}),A=await yx(b,{submit:T=>wx(T,O,{isActive:()=>m()&&!an,onRetry:(C,R)=>{w("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${pn(C)} Retrying in ${Math.round(R/1e3)}s without rerunning the agent.`)}}),payloadFor:T=>r==="synthesis"?Jf(P.workspace,n,T,{expectedSourceRevision:e.source_revision}):mb(T),rejectionFor:T=>Oa(T,"the assessment"),correct:async(T,C)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!T.correctAfterRejection)throw new Error(`${C} The connector could not start the required agent correction.`);return T.correctAfterRejection(C)},onCorrected:async T=>{if(p)throw new Error(p);a=!0,await lb(P.workspace,n,r);let C=await Vf(P.workspace,n,E,T);return _(C,E),t.phase="delivering",t.lastMessage="Delivering corrected stage result",C}});if(p)throw new Error(p);b=A.result;let x=A.response;if(!x.ok)throw new Error(await Oa(x,"the assessment"));if(l=!0,Fc.record("assessment stage","completed",{durationMs:Date.now()-o,usage:b.usage}),r==="synthesis"){let T=await x.json(),C=await pb(P.workspace,n,e,b,T.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${sn.relative(P.workspace,C)}.`);try{let R=await rl(P.workspace);R.committed&&console.log(`Assessment committed to Git as ${R.revision.slice(0,8)}.`)}catch(R){console.error(`The assessment is saved locally but could not be committed to Git: ${R.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(S){let E=p||pn(S),b=dx(e,S),O=hx(S),k=lx(S);O&&(await cb(P.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||O)&&(O||cx(S))&&b<k;if(m()&&A){t.phase="starting",t.lastMessage=O?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=px(e,S);let x=fx(S,b);oc(S)&&(qw=Math.max(qw,Date.now()+x)),console.warn(`[assessment:${r}] ${O?"Agent session became unusable":"Agent session interrupted"}: ${E} ${O?"Starting a fresh session from the saved draft":`Resuming session ${d}`} in ${Math.round(x/1e3)}s (${b+1}/${k}).`),await new Promise(T=>setTimeout(T,x))}else m()&&(u=await g({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:E}));A||(Fc.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${E}`))}finally{clearInterval($),Mt.clearStatus(s),r==="synthesis"&&l&&Ww.delete(n),m()&&(cn.delete(t.key),gx(Bi,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),Hc())}}async function v7(e){let t=String(e.run_id||"");Xo+=1;try{Gr&&await Gr;let n=await FE(P.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 Gi();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: ${pn(n)}`)}finally{Xo-=1,Hc()}}function S7(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{pt('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function pt(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.18",
3
+ "version": "1.59.19",
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",