@engineeros/connector 1.53.2 → 1.53.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.
@@ -991,7 +991,7 @@ It is checked with the provider and stored in this machine's protected vault
991
991
  (Windows Data Protection, the macOS Keychain or the Linux Secret Service).
992
992
  EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function cG(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(`
993
993
  `),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
994
- `)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 oE=Symbol("missing");function lG(e,t){return new Promise(n=>{let r=iG(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?oE:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function rE(e,t){for(let n of Ps){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 sE(e,t,n,{vault:r=kp(),run:o=pc,fetchImpl:s=fetch,secret:i=cG,interactive:a=lG,install:c=dc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(aG),n.help?0:2;if(e==="integrations")return rE(l,(await mc({run:o,vault:r})).providers),0;let d=t[0];if(!Ps.includes(d))return u(`Unknown provider ${d}. Choose one of: ${Ps.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Fr[d];if(e==="disconnect")return l(`${d} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===oE){let m=await bo(f);if(!m){l(`Installing the ${js[f].label} ${js[f].version} for the connector...`);try{m=(await c(f)).path}catch(y){return u(y.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${hc[d]} is how this machine signs in to ${d}.`),1):(rE(l,{[d]:(await mc({run:o,vault:r})).providers[d]}),0)}let p=st[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await xp(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await $p(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}import{spawn as uG}from"node:child_process";async function iE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=uG,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=Zn(await yt(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await dG(o,c.entry,i,t);if(l===Fo){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let d=await yt(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await tl(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${p.version}.`);continue}catch(p){s(`Automatic rollback failed: ${p.message}`)}}return l??1}}function dG(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Hr]:"1",[Kc]:r.entry,[Yc]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,d)=>{l(),o({code:u,signal:d})})})}var gr="1.53.2",Ec="1.53.2",mG=3e5,kc=["queued","running","reporting"],gG=5e3,Ap={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."},Tp={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."},wG=6e4,yG=3e4,Rp={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Cp={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:Le,positional:ct,flags:_e}=lb(process.argv.slice(2));Le==="version"&&(console.log(gr),process.exit(0));var Jn=null,gt=!1,kn=null,yE=!1,_E=null,Up=null,Ze=null,Bs=null,Lp,aE,cE,Fs,xo,vE=ic({getWorkspace:()=>$.workspace,onRecorded:e=>pS($,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}`))}),_G=tE({getWorkspace:()=>$.workspace,huntSignIns:vE}),Us=fb();Le==="results"&&(ct[0]!=="upload"&&(console.log(Qa),process.exit(_e.help||!ct[0]?0:2)),process.exit(await Xb(_e)));(Le==="connect"||Le==="disconnect"||Le==="integrations")&&process.exit(await sE(Le,ct,_e,{fetchImpl:ZS}));if(Le==="runner"){let e=mt.resolve(_e.workspace||process.cwd()),t=ct[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?mt.join(mt.dirname(Fe(e,_e["run-id"])),"worker.log"):mt.join(e,".engineeros","runner","service.log");fG(mt.dirname(n),{recursive:!0});let r=(...s)=>bs(n,`${hG(...s)}
994
+ `)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 oE=Symbol("missing");function lG(e,t){return new Promise(n=>{let r=iG(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?oE:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function rE(e,t){for(let n of Ps){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 sE(e,t,n,{vault:r=kp(),run:o=pc,fetchImpl:s=fetch,secret:i=cG,interactive:a=lG,install:c=dc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(aG),n.help?0:2;if(e==="integrations")return rE(l,(await mc({run:o,vault:r})).providers),0;let d=t[0];if(!Ps.includes(d))return u(`Unknown provider ${d}. Choose one of: ${Ps.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Fr[d];if(e==="disconnect")return l(`${d} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===oE){let m=await bo(f);if(!m){l(`Installing the ${js[f].label} ${js[f].version} for the connector...`);try{m=(await c(f)).path}catch(y){return u(y.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${hc[d]} is how this machine signs in to ${d}.`),1):(rE(l,{[d]:(await mc({run:o,vault:r})).providers[d]}),0)}let p=st[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await xp(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await $p(r,d,{token:f,site:n.site,email:n.email},s);return l(`Connected ${p.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}import{spawn as uG}from"node:child_process";async function iE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=uG,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=Zn(await yt(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await dG(o,c.entry,i,t);if(l===Fo){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let d=await yt(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await tl(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${p.version}.`);continue}catch(p){s(`Automatic rollback failed: ${p.message}`)}}return l??1}}function dG(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[Hr]:"1",[Kc]:r.entry,[Yc]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,d)=>{l(),o({code:u,signal:d})})})}var gr="1.53.3",Ec="1.53.3",mG=3e5,kc=["queued","running","reporting"],gG=5e3,Ap={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."},Tp={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."},wG=6e4,yG=3e4,Rp={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Cp={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:Le,positional:ct,flags:_e}=lb(process.argv.slice(2));Le==="version"&&(console.log(gr),process.exit(0));var Jn=null,gt=!1,kn=null,yE=!1,_E=null,Up=null,Ze=null,Bs=null,Lp,aE,cE,Fs,xo,vE=ic({getWorkspace:()=>$.workspace,onRecorded:e=>pS($,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}`))}),_G=tE({getWorkspace:()=>$.workspace,huntSignIns:vE}),Us=fb();Le==="results"&&(ct[0]!=="upload"&&(console.log(Qa),process.exit(_e.help||!ct[0]?0:2)),process.exit(await Xb(_e)));(Le==="connect"||Le==="disconnect"||Le==="integrations")&&process.exit(await sE(Le,ct,_e,{fetchImpl:ZS}));if(Le==="runner"){let e=mt.resolve(_e.workspace||process.cwd()),t=ct[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?mt.join(mt.dirname(Fe(e,_e["run-id"])),"worker.log"):mt.join(e,".engineeros","runner","service.log");fG(mt.dirname(n),{recursive:!0});let r=(...s)=>bs(n,`${hG(...s)}
995
995
  `),o=(s,i,a)=>(bs(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(_e["keep-awake"]!==void 0){if(!["on","off"].includes(_e["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await tt(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await gn({...n,runner_keep_awake:_e["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await Ha(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 O0(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await yo(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await cr(e),null,2)):t==="serve"?await M0(e):t==="worker"?await P0(e,_e["run-id"]):Pe("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){Pe(Md(n,e).message)}}_e["assessment-workers"]!==void 0&&Pe("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(Le==="tools"){try{let e=z0(_e),t=ct[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=ct[1];r||Pe(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await Ru(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 cs(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:ct[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await $u(e,t,ct[1]);let n=await Dt(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){Pe(e.message)}process.exit(process.exitCode||0)}if(Le==="agents"){let e;try{e=await Wu()}catch(n){Pe(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await ls(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(Le==="agent"){let e=ct[0],t=ct[1]||"check";(!e||!["check","install"].includes(t))&&Pe("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await us(e):await ls(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){Pe(n instanceof Error?n.message:String(n))}process.exit(0)}if(Le==="mcp"){let e=_e.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=_e["run-id"]||ct[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await tt(e);await Ab({config:n,runId:t,version:gr,input:process.stdin,output:process.stdout}),process.exit(0)}if(Le==="context-mcp"){let e=_e["config-workspace"]||_e.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await tt(e);t||Pe("This workspace is not paired with EngineerOS."),await Db({config:t,workspace:_e.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:gr,input:process.stdin,output:process.stdout}),process.exit(0)}if(Le==="status"){let e=await tt(_e.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(Le==="doctor"){let e=mt.resolve(_e.workspace||process.cwd()),t=await tt(e),n=await Sb(e),r=await Oo(t||{workspace:e},e,Zd(n));console.log(Jd(r)),process.exit(r.status==="failed"?1:0)}if(Le==="update"){let e=ct[0]||"status";try{let t=Qc(process.argv[1],Ec),n=await nl(On(),t,{action:e,policy:ct[1]??null});console.log(zo(rl(n,t,{supervised:!0})))}catch(t){Pe(`${t.message}
996
996
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var $o=Le==="hunt-host";if($o)try{_e.workspace=U0(ct,_e)}catch(e){Pe(e.message)}if((Le==="start"||Le==="pair"||$o)&&process.env[Hr]!=="1"&&Ye(Ec))try{process.exit(await iE({root:On(),bundled:{version:Ec,entry:mt.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:mt.resolve(_e.workspace||process.cwd())}))}catch(e){Pe(`The connector process could not be started: ${e.message}`)}if($o){try{await G0(_e.workspace,ct[0]?_e.agent:null)}catch(e){Pe(e.message)}Le=ct[0]?"pair":"start"}var $,Co,zs;if(Le==="pair"){let e=ct[0];e||Pe("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=_e.url;t||Pe("Pairing requires --url with the EngineerOS backend address."),_e.agent&&_e["agent-command"]&&Pe("Use either --agent or --agent-command, not both.");let n=_e["agent-protocol"]||(_e["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||Pe(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(_e.agent||_e["agent-command"])&&Pe("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{_e.agent&&(await ls(_e.agent),r=await qu(_e.agent))}catch(o){Pe(o instanceof Error?o.message:String(o))}$={server_url:ol(t),workspace:mt.resolve(_e.workspace||process.cwd()),onboard:_e.onboard===!0,onboarding_pending:_e.onboard===!0,hunt_host:$o,agent_protocol:n,agent_command:_e["agent-command"]||null,agent_args:FG(_e["agent-args"]),agent_name:_e["agent-name"]||null,...r,skip_git_repo_check:$o||_e["skip-git-repo-check"]===!0,name:_e.name||`${pG.hostname()} - ${mt.basename(mt.resolve(_e.workspace||process.cwd()))}`},zs=await tt($.workspace),Co={type:"pair",pairing_code:e,name:$.name,capabilities:{},...Gf(zs,$.server_url)}}else Le==="start"?($=await tt(_e.workspace||process.cwd()),$||Pe("This connector is not paired. Create a pairing command in EngineerOS first."),$o&&!$.hunt_host&&Pe("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),Co={type:"authenticate",connector_id:$.connector_id,token:$.token}):Pe("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, or `mcp`.");var bE=L0($,{reportError:e=>console.error(e)}),mr=0,xc=!1,Gs=null,lt=new Map,Op=0,Ip=new Set,Ao=[],it=new Map,at,Dp,_c,xn=null,vc=!1,SE=0,jp=null,Np=[],bc,EE,Ls=1e3,To,qn=!1,Yt,Eo=!1,$c=!1,Fp=0;function gc(e){return Fp+=1,e.finally(()=>{Fp-=1})}var ko,Ur=0;function Hs({exitCode:e=0}={}){if(Ur=Math.max(Ur,e),ko)return ko;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),ko=vG().finally(()=>clearTimeout(t)),ko}async function vG(){if(gt=!0,Bs?.stop(),Jn?.stop(),Up?.stop(),_E?.stop(),clearInterval(Lp),Ze?.stop(),EE?.(),clearTimeout(bc),clearInterval(Dp),clearInterval(_c),await Promise.all([...[...lt.values()].map(e=>bt(e.child))]),await Promise.all([...it.values()].map(Hp)),await Fs?.cancelAll(),await xo?.abortAll(),await da(),await Zp().catch(e=>{Ur=Math.max(Ur,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),at?.close(),Ur&&Ur!==Fo){let e;await Promise.race([(async()=>{await Jn?.drain(),await Oo($,$.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Ur)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{Hs()});var lE=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{lE||(lE=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await Hs({exitCode:1}))});Ze=sf();process.on("exit",()=>{Bs?.stop(),Ze.stop()});Ze.banner(`EngineerOS connector ${gr}`,[$.workspace,$.server_url]);Jn=pb({actions:{refresh_tool_inventory:async()=>{Ee.tool_inventory=await Dt($.workspace),Ot()},restart_goal_runner:()=>yo($.workspace)},onNotify:()=>Oo($,$.workspace),explain:async e=>{if(!await Rc())return null;let{reading:t}=await c0($,e);return t},onUpdate:e=>bb($.workspace,e)});_E=kb({render:(e,t)=>Ze.write(e,t),onRecord:e=>Jn.observe(e)});Up=xb({workspace:$.workspace,onRecord:e=>{Jn.observe(e),Ze.line(e.channel,e.level,e.message)}});Jn.start();$.hunt_host||Up.start();Ze.live&&!$.hunt_host&&(Lp=setInterval(()=>{bG().catch(()=>{})},gG),Lp.unref?.());var Mp=new Set;async function bG(){if($.hunt_host)return;aE??=Id($.workspace);let{jobs:e}=await aE(),t=new Set,n=e.filter(r=>r.status!=="queued"&&kc.includes(r.status)).length;for(let r of e){if(!kc.includes(r.status))continue;t.add(r.runId),Mp.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;Ze.status(`goal:${r.runId}`,o,SG(r),{agent:r.status!=="queued",link:Gs&&`${Gs}/goals`}),Ze.step(`goal:${r.runId}`,r.activity?.message)}for(let r of Mp)t.has(r)||(Mp.delete(r),Ze.clearStatus(`goal:${r}`))}function SG(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function Rc({ignoreBugHunt:e=!1}={}){if(gt||lt.size>0||it.size>0||mr>0||(Fs?.active??0)>0||!e&&(xo?.active??0)>0)return!1;try{let{jobs:t}=await cr($.workspace);return!gt&&!t.some(n=>kc.includes(n.status))}catch{return!1}}try{let e=$.hunt_host?{}:await zr($.workspace);e.committed&&($.onboarding_pending=!0,$.connector_id&&await gn($),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await AE(e)}var kE=await yt(On()).then(e=>e.policy!=="manual",()=>!1),je;try{if(Le==="start"&&kE){let e=await Xy($,{verify:t=>_s(t,$.workspace),busy:async()=>!await Rc()});e!==$&&($=e,await gn($))}je=await _s($,$.workspace)}catch(e){await AE(e)}console.log(`Using ${je.name} through ${je.protocol} (${je.version}).`);var Ee=Yd($,je,await Dt($.workspace)),Xn=Uf({running:Qc(process.argv[1],Ec),supervised:process.env[Hr]==="1",isIdle:async()=>!gt&&lt.size===0&&Ao.length===0&&it.size===0&&mr===0&&Fp===0&&!Eo&&!$c&&!vc,restart:()=>Hs({exitCode:Fo}),onChange:e=>{Ee.runtime_update=e,at?.readyState===WebSocket.OPEN&&Ot()}});try{await Xn.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}$={...$,execution_profiles:je.executionProfiles??null};Le==="pair"&&zs?.connector_id||await gn($);Ee.agent_session={...Ee.agent_session,status:"checking",message:`Checking that ${je.name} can answer.`};Ee.bug_hunt_browser=!1;Co.capabilities=Ee;console.log(Un($.worker_limit)===null?`Workers: automatic, ${po()} ${je.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Un($.worker_limit)} ${je.name} workers side by side, set with /workers.`);var Ro=e=>zn($,e),uE=Da(Ro,{signature:w0});async function EG(){let e=await cr($.workspace).catch(()=>({service:null,jobs:[]}));return{version:gr,now:Date.now(),workspace:$.workspace,config_path:zt($.workspace),config:$,agent:je,automatic_worker_limit:po(),worker_limit:Un($.worker_limit),connection:{state:kG(),server_url:$.server_url,last_error:Yt||null},work:{assessments:[...lt.values()].map(t=>({stage:t.stage,message:t.lastMessage,started_at:t.startedAt})),prompts:[...it.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,started_at:t.startedAt})),integrations:mr},runner:e,runtime_update:Xn.report(),health:Jn?.health()??null,activity:Us.snapshot()}}function kG(){return gt||qn?"stopped":at?.readyState===WebSocket.OPEN?"connected":"connecting"}var xG={async cancelPrompt(e){let t=[...it.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=>$E(e),setVerbose(e){return e===xc?`Detailed agent activity is already ${e?"on":"off"}.`:(zp(e),"This lasts until EngineerOS sends its own setting again: when the connector reconnects, or when it is changed there.")},async runtimeUpdate(e){return e.action==="apply"?(Xn.command(e).catch(t=>console.error(`Connector update: ${t.message}`)),"Preparing the latest connector release beside this one; it switches over once this connector is idle."):(await Xn.command(e),zo(await Xn.refresh()))}};Bs=wb({ui:Ze,snapshot:EG,actions:xG});Bs&&console.log(gb());await xE();var dE=new Set;async function xE(){if(gt||qn)return;console.log(`Connecting ${$.name} to ${$.server_url}`),qn=!1,Yt=void 0;let e=new WebSocket($.server_url);at=e;let t=Lg(e,$.server_url,{onTimeout:r=>{at===e&&(Yt=r,console.error(r),Pp())}});EE=t,e.addEventListener("open",()=>{if(at!==e){e.close();return}try{if(Og(at,e,Co))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){Yt=_t(r),console.error(`Could not authenticate the WebSocket connection: ${Yt}`);try{e.close()}catch{}Pp()}}),e.addEventListener("message",r=>{if(at!==e)return;let o;try{o=JSON.parse(String(r.data))}catch{console.error("Ignored a malformed EngineerOS message frame (invalid JSON).");return}n(o).catch(s=>{console.error(`EngineerOS ${String(o?.type||"unknown").slice(0,80)} message failed: ${_t(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){gt=!0,qn=!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=zs?.connector_id===r.connector.id;if($=Hf($,zs,r.connector.id,r.token),await gn($),r.connector?.capabilities?.http_updates!==!0){gt=!0,qn=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}Co={type:"authenticate",connector_id:$.connector_id,token:$.token,capabilities:Ee},console.log(s?`Reconnected existing workspace connector ${$.connector_id}; assessment history is preserved.`:`Paired. Connector ${$.connector_id} is online.`),fE(r);return}if(r.type==="authenticated"){t();let s=$.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(To?`Reconnected after ${Te(Date.now()-To)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),To=void 0,fE(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){$c||AG(r);return}if(r.type==="workspace.refresh"){Ac();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await $E(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){zp(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(Vn=!1,Ee.bug_hunt_browser=!1,Ot());try{Ee.tool_inventory=await cs($.workspace,r,void 0,{confirmLocal:i=>Bs?.confirm(i)??!1,log:Sc}),s&&(Vn=!0),Ee.bug_hunt_browser=Dr(Ee.tool_inventory)&&Vn,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Ee.tool_inventory})),Ot(),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 Ru($.workspace,r,{onStatus:async()=>{Ee.tool_inventory=await Dt($.workspace),Ot()}});Ee.tool_inventory=s.inventory,s.completion&&s.completion.catch(i=>console.error(`Tool authentication status: ${i instanceof Error?i.message.slice(0,300):"Local status update failed."}`)),e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Ee.tool_inventory})),Ot(),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"){Yr(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===eE){gc(_G(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),nE($,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}`;vd(Ao,lt.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Ws();return}if(r.type==="prompt.execute"){let s=it.get(r.prompt_id);s?IE(r)>s.executionRevision&&await MG(s,r):OE(r);return}if(r.type==="prompt.cancel"){let s=it.get(r.prompt_id);s&&await Hp(s);return}if(r.type==="agent.warm"){RG(r);return}if(r.type==="run.available"){if($.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await bE.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${mt.join($.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${_t(s)}`)}return}if(r.type==="goal.cleanup"){try{await N0($.workspace),await yo($.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){DG(r);return}if(r.type==="run.cancelled"){await Od($.workspace,r.run_id);return}if(r.type===nw){Fs??=pw({getConfig:()=>$,onTestsCommitted:()=>Ac()}),gc(Fs.handle(r));return}if(r.type===rw){await Fs?.cancel(r);return}if(r.type===SS){xo??=AS({getConfig:()=>$,isIdle:()=>Rc({ignoreBugHunt:!0}),recordedSignIns:vE,activity:{status:Ze.status,step:Gp,finish:Ze.finish}}),gc(xo.handle(r));return}if(r.type===ES){xo?.stop(r);return}if(r.type===Jb){cE??=Kb({getConfig:()=>$}),gc(cE.handle(r));return}if(r.type==="connector.update"){$G(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await Hs();return}if(r.type==="connector.revoked"){gt=!0,console.error("This connector was revoked in EngineerOS."),e.close();return}if(r.type==="run.error"){console.error(`EngineerOS: ${r.message}`),r.run_id||(Eo=!1);return}if(r.type==="connection.error"){qn=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);dE.has(o)||(dE.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${gr}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),at!==e||ko)return;let o=Ig(r);if(!o.retry||qn||gt){console.error(o.message),o.retry&&qn&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),Hs();return}Yt=Yt?`${o.message} ${Yt}`:o.message,Pp()}),e.addEventListener("error",r=>{at===e&&(Yt=Cg(r),console.error(`WebSocket connection to ${$.server_url} failed: ${Yt}`))})}async function $G(e,t){let n=r=>e.send(JSON.stringify({type:"connector.updated",command_id:t.command_id,...r}));try{let r={action:t.action,policy:t.policy??null},o=Xn.command(r);r.action==="apply"?(o.catch(s=>console.error(`Connector update: ${s.message}`)),await Promise.race([o,new Promise(s=>setTimeout(s,3e3).unref())])):await o,n({report:await Xn.refresh()}),console.log(`EngineerOS asked for connector update ${r.action}.`)}catch(r){let o=(r instanceof Error?r.message:String(r)).slice(0,300)||"The connector rejected the update request.";n({error:o}),console.error(`Connector update ${t.action} rejected: ${o}`)}}async function AG(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";$c=!0,console.log(`Starting interactive ${je.name} provider ${n}.`);try{await(n==="logout"?Pg:Mg)(je,$.workspace),je=await _s($,$.workspace),Ee=Yd($,je,Ee.tool_inventory),Co.capabilities=Ee,at.readyState===WebSocket.OPEN&&(at.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:Ee.agent_session})),at.close(1e3,`Provider ${n} completed`)),console.log(`${je.name} provider ${n} completed.`)}catch(r){let o=_t(r).slice(0,500);at.readyState===WebSocket.OPEN&&at.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{$c=!1}}function Pp(){if(gt||qn||bc)return;let e=Yt?` Last error: ${Yt}`:"",t=To?` Offline for ${Te(Date.now()-To)}.`:"";To??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(Ls/1e3)}s.`),bc=setTimeout(()=>{bc=void 0,xE()},Ls),Ls=Math.min(3e4,Ls*2)}async function Ac(){if(!$.hunt_host&&!(Eo||at.readyState!==WebSocket.OPEN)){Eo=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await d0($.workspace),t=await u0($.workspace,$.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(Br($.server_url,$.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$.token}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(await Pi(n,"the workspace"));let r=await n.json();$={...$,onboarding_pending:!1,last_snapshot_head:e.head_revision??$.last_snapshot_head},await gn($),console.log(`Inventoried ${e.total_file_count.toLocaleString()} safe file(s).`),console.log(`Uploaded ${e.evidence_file_count.toLocaleString()} prioritized source file(s).`),console.log(`Excluded ${e.excluded_file_count.toLocaleString()} sensitive or generated file(s).`),e.omitted_evidence_file_count>0&&console.log(`${e.omitted_evidence_file_count.toLocaleString()} additional file(s) remain available to the connected Agent locally.`),console.log(`Workspace inventory registered as ${r.workspace_kind}. Start the baseline assessment in EngineerOS to continue.`);try{let o=await vi($.workspace,$.connector_id);console.log(`Built the local context index: ${o.total_files.toLocaleString()} file(s) ready for assignment context.`)}catch(o){console.error(`Local context index build failed: ${o.message}`)}Eo=!1}catch(e){Eo=!1,console.error(`Workspace assessment failed: ${_t(e)}`)}}}var TG=6e4,pE=0;async function RG(e){if($.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?$.sessions?.[t]:void 0,r=[];Date.now()-pE>TG&&(pE=Date.now(),r.push(vi($.workspace,$.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),$.agent_protocol==="acp"&&r.push(Uy($.workspace,$,{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(`${je?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Ot(){let e=Zv(lt);uE.update({type:"assessment.workers",assessment_workers:e,tool_inventory:Ee.tool_inventory,runtime_update:Ee.runtime_update,agent_session:Ee.agent_session,bug_hunt_browser:Ee.bug_hunt_browser,...ja($.worker_limit)}),uE.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function $E(e){let t=Un(e);return t===Un($.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:($={...$,worker_limit:t},await gn($),Ws(),Ot(),t===null?`Workers are automatic again: up to ${po()} side by side for this machine's CPU and memory, for assessment stages, generation, test design and Goals (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: assessment stages, generation, test design and Goals. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function zp(e){if(e!==xc){if(xc=e,!e)for(let t of lt.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."),Ot()}}function Gp(e,t){Ze.step(e,t)&&xc&&console.log(`[${e}] ${t}`)}function CG(){clearInterval(_c);let e=!1,t=()=>{e||lt.size>0||it.size>0||(e=!0,Oo($,$.workspace).finally(()=>{e=!1}))};t(),_c=setInterval(t,mG),_c.unref?.()}async function Oo(e,t,n=Jn?.healthChecks()??[]){let r=await ab({config:e,workspace:t,version:gr,insights:n,agentSession:kn,probes:{inspectAgent:(o,s)=>gt?je:_s(o,s),inspectTools:o=>gt?Ee.tool_inventory:Dt(o),runnerStatus:cr}});try{yE=(await cb(e,r,zn))?.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 AE(e){if(gt)return ko;let t=e instanceof Error?e.message:String(e),n=await Oo($,$.workspace).catch(()=>null);n&&console.error(Jd(n)),Pe(t)}function fE(e){zp(e.connector?.activity_log_enabled===!0),Gs=e.project_url??null,Ls=1e3,IG(),RE(),Xn.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),jG(),$.onboarding_pending&&Ac()}var Ds=null,Vn=!1,TE=0,OG=Date.now();async function IG(){return Ds||(Ds=(async()=>{kE&&await Sy($.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Sc("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await H0($.workspace,{log:Sc}),Vn=!0,Ee.tool_inventory=await Dt($.workspace),Ee.bug_hunt_browser=Dr(Ee.tool_inventory)&&Vn,Sc(`Bug Hunter's browser is ready (${Te(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${Te(Date.now()-e)}: ${t.message}`),Ee.bug_hunt_browser=!1}Ot()})(),Ds)}function Sc(e){console.log(`[browser] ${e}`)}async function RE(){if(kn?.state!=="checking"){TE=Date.now(),Ee.agent_session={...Ee.agent_session,status:"checking",message:`Checking that ${je.name} can answer.`},Ot(),kn={state:"checking",detail:`Asking ${je.name} one question to confirm its session.`},console.log(`Checking that ${je.name} can answer before accepting work.`);try{await r0($,je.name),kn={state:"ready",detail:`${je.name} answered; its session is usable.`},Ee.agent_session={...Ee.agent_session,status:"authenticated",message:kn.detail},console.log(kn.detail)}catch(e){kn={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:$.hunt_host?W0($.agent_id||$.agent_protocol):ao($.agent_id||$.agent_protocol)},Ee.agent_session={...Ee.agent_session,status:"logged_out",message:kn.remedy},console.error(`${kn.detail}
997
997
  ${kn.remedy}`)}Ot(),await Oo($,$.workspace).catch(()=>null)}}function jG(){clearInterval(Dp);let e=!1,t=0,n=0,r=!1,o=()=>{Xn.tick(),$.hunt_host&&Ds&&Date.now()-TE>=B0(OG)&&it.size===0&&lt.size===0&&!(xo?.active>0)&&RE(),!$.hunt_host&&!r&&Rs(Cp.id)&&(r=!0,bE.flush().then(()=>yc(Cp)).catch(s=>wc(Cp,s)).finally(()=>{r=!1})),lt.size>0&&Ot(),!$.hunt_host&&!xn&&Date.now()-t>=wG&&Rs(Ap.id)&&(t=Date.now(),CE().then(()=>yc(Ap)).catch(s=>wc(Ap,s))),!$.hunt_host&&yE&&!vc&&Rs(Tp.id)&&Date.now()-SE>=Tw&&(vc=!0,NG().then(()=>yc(Tp)).catch(s=>wc(Tp,s)).finally(()=>{vc=!1})),!e&&Date.now()-n>=yG&&Rs(Rp.id)&&(e=!0,n=Date.now(),Dt($.workspace).then(async s=>{if(Ee.tool_inventory=s,!Vn&&Dr(s))try{await(await wr(await ur($.workspace))).close(),Vn=!0}catch{Vn=!1}Ee.bug_hunt_browser=Dr(s)&&Vn,Ot(),yc(Rp)}).catch(s=>wc(Rp,s)).finally(()=>{e=!1}))};o(),Dp=setInterval(o,1e4),CG()}function wc(e,t){let n=rb(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 yc(e){ob(e.id)&&console.log(`${e.title} recovered.`)}async function NG(){if($.hunt_host||!await Rc())return;SE=Date.now();let{jobs:e}=await cr($.workspace).catch(()=>({jobs:[]})),t=await Rw($.workspace,{jobs:e});if(!Cw(t))return;let n=`${t.fingerprint}:${Np.join(",")}`,r=jp?.key===n,o=r?jp.candidates:await l0($,t,Np);jp={key:n,candidates:o};let s=await Ro(jw(t,o,{version:gr}));Array.isArray(s?.refused)&&(Np=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 hr=null,hE=null;async function CE(){if(!$.hunt_host){if(xn)return xn;xn=(async()=>{let e=await vw($,{knownRevision:hr?.revision??null});if(e.unchanged||(hr=e),hE===hr.revision)return hr;let{jobs:t}=await cr($.workspace);return!t.some(r=>kc.includes(r.status))&&mr===0&&lt.size===0&&(await Ki($.workspace,hr),hE=hr.revision),hr})();try{return await xn}finally{xn=null,Ws()}}}function mE(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)),it.get(e)?.events.push(n)}var gE=null;function Ws(){let e=at.readyState===WebSocket.OPEN,t=lt.values().next().value,n=Un($.worker_limit)??Math.min(po(),Sd(t?.workerLimit??Ao[0]?.worker_limit)),r=e&&!xn&&mr===0?Hv(Ao,lt.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:Sd(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};lt.set(i,a),LG(s,a)}r.length>0&&Ot();let o=Bv({queued:Ao,running:lt.size,workerLimit:n,connected:e,designSync:!!xn,integrations:mr});o&&o!==gE&&console.log(o),gE=o}function Tc(e){let t=Ed(e);return t?`${je.name} on ${t}`:je.name}async function OE(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:v0(Ro),executionRevision:IE(e),sessionKey:Na(e),sessionId:null,replacement:null};it.set(t,s);let i,a=m=>{let y=m?JSON.stringify(m):null;!y||y===i||it.get(t)!==s||(i=y,mE(t,m))},c=`${r} \xB7 ${Tc(e)}`,l=n0(e,je.name);mE(t,{kind:"status",message:l});let u=Number(e.answer_within_seconds),d=u>0?o+u*1e3:void 0;console.log([`[${n}] ${l} for ${r}.`,`${je.name} can reason for several minutes without reporting a step.`,...d?[Mc(d,o)]:[]].join(" ")),Ze.status(n,c,o,{link:Gs,answerBy:d});let p=m=>{let y=Uv(m),_=Or(m);it.get(t)===s&&Gp(n,_??y?.message);let k=m.type==="forge.output"?null:_;a(y??(k?{kind:"status",message:k}:null))},f="failed",h=[r];try{Ma(e)||(p({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await xw(CE,{pinned:!!e.local_design_context,last:hr,onFallback:(k,b)=>p({type:"connector.step",message:`Design context not refreshed (${k.message}); continuing with ${b?"the copy synced earlier":"none"}`})})});let m=await Nv(e,$,{onProcess:k=>{it.get(t)===s&&(s.child=k)},onController:k=>{it.get(t)===s&&(s.controller=k)},onSession:k=>{s.sessionId=k},onEvent:p},{signal:s.cancellation.signal});if(s.stoppedHere)throw new Error(wE);let y=m.singleTurn?Bf($.sessions,m.sessionKey):sl($.sessions,m.sessionKey,m.sessionId);if(JSON.stringify(y)!==JSON.stringify($.sessions||{})&&($={...$,sessions:y},await gn($)),s.cancelled)return;await s.events.close().catch(k=>{console.error(`[${n}] Prompt progress delivery: ${k.message} The agent has finished; submitting its complete response separately.`)});let _=await La(Ro,{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}] ${Ad}`),Us.record("prompt","completed",{durationMs:Date.now()-o,usage:m.usage}),f=_?"finished":"undelivered",h=[Js(m.usage),r]}catch(m){let y=s.stoppedHere?wE:_t(m);if(Us.record("prompt","failed",{durationMs:Date.now()-o}),s.stoppedHere&&(f="cancelled"),!s.cancelled){try{await La(Ro,{type:"prompt.failed",prompt_id:t,execution_revision:s.executionRevision,message:y})||console.error(`[${n}] ${Ad}`)}catch(_){console.error(`[${n}] Prompt failure delivery: ${_.message}`)}console.error(y)}}finally{s.events.stop();let m=s.replacement;m?(f="replaced",h=[`continuing on ${Tc(m)}`,r]):s.cancelled&&(f="cancelled"),Ze.finish(n,f,h),it.get(t)===s&&it.delete(t),m&&PG(s,m)}}var wE="Cancelled from the connector terminal by the person running it.";async function Hp(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function IE(e){return Number(e.execution_revision)||1}async function MG(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 ${Tc(t)}.`),await Hp(e))}function PG(e,t){e.sessionId&&($={...$,sessions:sl($.sessions,e.sessionKey,e.sessionId)},gn($).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),OE(t)}async function LG(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 ${Tc(e)}.`),!Ip.has(n)){Ip.add(n);try{let w=await Lv($.workspace);if(!w.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let v=w.accepted_head_revision?w.current_head_revision?w.current_head_revision!==w.accepted_head_revision?`The workspace is now at commit \`${w.current_head_revision}\`; the accepted assessment is from \`${w.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${w.accepted_head_revision}\`; the current commit could not be read.`:"Its accepted commit is unavailable; this run will refresh that provenance.";console.log(`Last accepted assessment covers ${w.stages.length||"no"} section(s). ${v}`)}}catch(w){console.error(`Assessment freshness check failed: ${w.message}`)}}let o=t.startedAt,s=`assessment:${r}`,i=!1,a=!1,c=5,l=!1,u=!1,d=null,p=null,f=null,h=new Set,m=()=>!gt&&lt.get(t.key)===t,y=async w=>{try{return await La(Ro,w)||console.warn(`[${s}] ${y0}`),!0}catch(v){return console.error(`Assessment failure delivery: ${v.message}`),!1}},_=(w,{milestone:v=!0}={})=>{if(!m()||v&&f===w)return;v&&(f=w,h.has(w)||(h.add(w),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${w}.`));let g=String(w).slice(0,500);t.progressPercent=c,t.lastMessage=g,Ze.status(s,g,o,{link:Gs})};_(`Starting ${r} assessment stage`);let k=setInterval(()=>{let w=Date.now(),v=w-t.lastActivityAt,g=i&&!a?Fv(r,v):null;if(!d&&g){d=g,console.error(`[assessment:${r}] ${d}`),Pa(t.controller,t.child);return}d||Jn.observe({at:w,level:"info",message:Ze.status(s,`${t.lastMessage} \xB7 last agent activity ${Te(v)} ago (${t.eventCount.toLocaleString()} events)`,o)})},15e3),b={onSession:async w=>{m()&&(p=String(w),await Sm($.workspace,n,r,w,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:w=>{m()&&(t.controller=w)},onProcess:w=>{m()&&(t.child=w,i=!0,t.phase!=="correcting"&&(t.phase="running",_("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:w=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let v=Dv(w);if(v&&_(v),!m())return;let g=Or(w);!g||g===t.lastDetail||(t.lastDetail=g,Gp(s,g))}},S=(w,v)=>yd(w,v,$,b,{draftPath:mt.relative($.workspace,mt.join(Nt($.workspace,n),w.report_file)).split(mt.sep).join("/")});try{let w=Op-Date.now();w>0&&(_(`Waiting ${Math.ceil(w/1e3)}s for the model provider's rate limit to clear`),await new Promise(R=>setTimeout(R,w+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,_("Calculating changed files and affected behavior"));let v=await Am($.workspace,e),g=await Cl($.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(g)S(g,v),_("Recovered completed stage report from connector storage");else{if(p=await Em($.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),p&&_("Restoring interrupted agent session"),g=await jv(v,$,b,{previousSessionId:p}),d)throw new Error(d);a=!0,await Rl($.workspace,n,v,g)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let x=R=>fetch(Vf($.server_url,$.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$.token}`},body:JSON.stringify(R),signal:AbortSignal.timeout(yv)}),I=await t0(g,{submit:R=>e0(R,x,{isActive:()=>m()&&!gt,onRetry:(M,j)=>{_("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${_t(M)} Retrying in ${Math.round(j/1e3)}s without rerunning the agent.`)}}),payloadFor:R=>r==="synthesis"?Ol($.workspace,n,R,{expectedSourceRevision:e.source_revision}):Om(R),rejectionFor:R=>Pi(R,"the assessment"),correct:async(R,M)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!R.correctAfterRejection)throw new Error(`${M} The connector could not start the required agent correction.`);return R.correctAfterRejection(M)},onCorrected:async R=>{if(d)throw new Error(d);a=!0,await xm($.workspace,n,r);let M=await Rl($.workspace,n,v,R);return S(M,v),t.phase="delivering",t.lastMessage="Delivering corrected stage result",M}});if(d)throw new Error(d);g=I.result;let A=I.response;if(!A.ok)throw new Error(await Pi(A,"the assessment"));if(l=!0,Us.record("assessment stage","completed",{durationMs:Date.now()-o,usage:g.usage}),r==="synthesis"){let R=await A.json(),M=await Tm($.workspace,n,e,g,R.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${mt.relative($.workspace,M)}.`);try{let j=await ei($.workspace);j.committed&&console.log(`Assessment committed to Git as ${j.revision.slice(0,8)}.`)}catch(j){console.error(`The assessment is saved locally but could not be committed to Git: ${j.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(w){let v=d||_t(w),g=Xv(e,w),x=Yv(w),T=qv(w);x&&(await km($.workspace,n,r).catch(A=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${A.message}`)}),p=null);let I=!d&&(p||x)&&(x||Wv(w))&&g<T;if(m()&&I){t.phase="starting",t.lastMessage=x?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=Jv(e,w);let A=Kv(w,g);vs(w)&&(Op=Math.max(Op,Date.now()+A)),console.warn(`[assessment:${r}] ${x?"Agent session became unusable":"Agent session interrupted"}: ${v} ${x?"Starting a fresh session from the saved draft":`Resuming session ${p}`} in ${Math.round(A/1e3)}s (${g+1}/${T}).`),await new Promise(R=>setTimeout(R,A))}else m()&&(u=await y({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:v}));I||(Us.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${v}`))}finally{clearInterval(k),Ze.clearStatus(s),r==="synthesis"&&l&&Ip.delete(n),m()&&(lt.delete(t.key),Qv(Ao,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),Ws())}}async function DG(e){let t=String(e.run_id||"");mr+=1;try{xn&&await xn;let n=await xv($.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 Ac();return}console.warn(`Accepted Goal Run ${t} remains on its review branch. ${n.reason}`)}catch(n){console.error(`Accepted Goal Run ${t} could not be integrated: ${_t(n)}`)}finally{mr-=1,Ws()}}function FG(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{Pe('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function Pe(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.53.2",
3
+ "version": "1.53.3",
4
4
  "description": "Connect a local coding agent to EngineerOS, using ACP when supported.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",