@engineeros/connector 1.56.2 → 1.56.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.
@@ -999,7 +999,7 @@ It is checked with the provider and stored in this machine's protected vault
999
999
  (Windows Data Protection, the macOS Keychain or the Linux Secret Service).
1000
1000
  EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function cB(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(`
1001
1001
  `),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
1002
- `)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 ME=Symbol("missing");function lB(e,t){return new Promise(n=>{let r=iB(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?ME:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function NE(e,t){for(let n of ei){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 PE(e,t,n,{vault:r=qp(),run:o=Nc,fetchImpl:s=fetch,secret:i=cB,interactive:a=lB,install:c=jc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(aB),n.help?0:2;if(e==="integrations")return NE(l,(await Lc({run:o,vault:r})).providers),0;let d=t[0];if(!ei.includes(d))return u(`Unknown provider ${d}. Choose one of: ${ei.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Jr[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===ME){let m=await jo(f);if(!m){l(`Installing the ${Ys[f].label} ${Ys[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} ${Pc[d]} is how this machine signs in to ${d}.`),1):(NE(l,{[d]:(await Lc({run:o,vault:r})).providers[d]}),0)}let p=yt[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Vp(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await Xp(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 uB}from"node:child_process";async function LE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=uB,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ir(await At(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await dB(o,c.entry,i,t);if(l===Ko){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 At(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await Sl(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 dB(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[eo]:"1",[wl]:r.entry,[yl]: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 xr="1.56.2",Wc="1.56.2",mB=3e5,qc=["queued","running","reporting"],gB=5e3,Jp={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."},Kp={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."},wB=6e4,yB=3e4,_B=60*6e4,Yp={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Zp={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:et,positional:bt,flags:_e}=zb(process.argv.slice(2));et==="version"&&(console.log(xr),process.exit(0));var rr=null,vt=!1,$n=null,KE=!1,YE=null,uf=null,lt=null,li=null,af,DE,FE,ri,Lo,ZE=Tc({getWorkspace:()=>C.workspace,onRecorded:e=>HS(C,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}`))}),vB=IE({getWorkspace:()=>C.workspace,huntSignIns:ZE}),oi=Wb();et==="results"&&(bt[0]!=="upload"&&(console.log(Sc),process.exit(_e.help||!bt[0]?0:2)),process.exit(await xS(_e)));(et==="connect"||et==="disconnect"||et==="integrations")&&process.exit(await PE(et,bt,_e,{fetchImpl:RE}));if(et==="runner"){let e=$t.resolve(_e.workspace||process.cwd()),t=bt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?$t.join($t.dirname(Je(e,_e["run-id"])),"worker.log"):$t.join(e,".engineeros","runner","service.log");fB($t.dirname(n),{recursive:!0});let r=(...s)=>Ps(n,`${hB(...s)}
1002
+ `)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 ME=Symbol("missing");function lB(e,t){return new Promise(n=>{let r=iB(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?ME:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function NE(e,t){for(let n of ei){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 PE(e,t,n,{vault:r=qp(),run:o=Nc,fetchImpl:s=fetch,secret:i=cB,interactive:a=lB,install:c=jc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(aB),n.help?0:2;if(e==="integrations")return NE(l,(await Lc({run:o,vault:r})).providers),0;let d=t[0];if(!ei.includes(d))return u(`Unknown provider ${d}. Choose one of: ${ei.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Jr[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===ME){let m=await jo(f);if(!m){l(`Installing the ${Ys[f].label} ${Ys[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} ${Pc[d]} is how this machine signs in to ${d}.`),1):(NE(l,{[d]:(await Lc({run:o,vault:r})).providers[d]}),0)}let p=yt[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Vp(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await Xp(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 uB}from"node:child_process";async function LE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=uB,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=ir(await At(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await dB(o,c.entry,i,t);if(l===Ko){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 At(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await Sl(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 dB(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[eo]:"1",[wl]:r.entry,[yl]: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 xr="1.56.3",Wc="1.56.3",mB=3e5,qc=["queued","running","reporting"],gB=5e3,Jp={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."},Kp={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."},wB=6e4,yB=3e4,_B=60*6e4,Yp={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},Zp={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:et,positional:bt,flags:_e}=zb(process.argv.slice(2));et==="version"&&(console.log(xr),process.exit(0));var rr=null,vt=!1,$n=null,KE=!1,YE=null,uf=null,lt=null,li=null,af,DE,FE,ri,Lo,ZE=Tc({getWorkspace:()=>C.workspace,onRecorded:e=>HS(C,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}`))}),vB=IE({getWorkspace:()=>C.workspace,huntSignIns:ZE}),oi=Wb();et==="results"&&(bt[0]!=="upload"&&(console.log(Sc),process.exit(_e.help||!bt[0]?0:2)),process.exit(await xS(_e)));(et==="connect"||et==="disconnect"||et==="integrations")&&process.exit(await PE(et,bt,_e,{fetchImpl:RE}));if(et==="runner"){let e=$t.resolve(_e.workspace||process.cwd()),t=bt[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?$t.join($t.dirname(Je(e,_e["run-id"])),"worker.log"):$t.join(e,".engineeros","runner","service.log");fB($t.dirname(n),{recursive:!0});let r=(...s)=>Ps(n,`${hB(...s)}
1003
1003
  `),o=(s,i,a)=>(Ps(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 ht(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await mn({...n,runner_keep_awake:_e["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await dc(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 ab(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await Co(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await wr(e),null,2)):t==="serve"?await db(e):t==="worker"?await pb(e,_e["run-id"]):Be("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){Be(op(n,e).message)}}_e["assessment-workers"]!==void 0&&Be("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(et==="tools"){try{let e=wb(_e),t=bt[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=bt[1];r||Be(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await Qu(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 bs(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:bt[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await Ku(e,t,bt[1]);let n=await Vt(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){Be(e.message)}process.exit(process.exitCode||0)}if(et==="agents"){let e;try{e=await md()}catch(n){Be(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await Es(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(et==="agent"){let e=bt[0],t=bt[1]||"check";(!e||!["check","install"].includes(t))&&Be("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await ks(e):await Es(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){Be(n instanceof Error?n.message:String(n))}process.exit(0)}if(et==="mcp"){let e=_e.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=_e["run-id"]||bt[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await ht(e);await sS({config:n,runId:t,version:xr,input:process.stdin,output:process.stdout}),process.exit(0)}if(et==="context-mcp"){let e=_e["config-workspace"]||_e.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await ht(e);t||Be("This workspace is not paired with EngineerOS."),await gS({config:t,workspace:_e.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:xr,input:process.stdin,output:process.stdout}),process.exit(0)}if(et==="status"){let e=await ht(_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(et==="doctor"){let e=$t.resolve(_e.workspace||process.cwd()),t=await ht(e),n=await eS(e),r=await Go(t||{workspace:e},e,vp(n));console.log(yp(r)),process.exit(r.status==="failed"?1:0)}if(et==="update"){let e=bt[0]||"status";try{let t=vl(process.argv[1],Wc),n=await El(Dn(),t,{action:e,policy:bt[1]??null});console.log(Zo(kl(n,t,{supervised:!0})))}catch(t){Be(`${t.message}
1004
1004
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var Do=et==="hunt-host";if(Do)try{_e.workspace=gb(bt,_e)}catch(e){Be(e.message)}if((et==="start"||et==="pair"||Do)&&process.env[eo]!=="1"&&tt(Wc))try{process.exit(await LE({root:Dn(),bundled:{version:Wc,entry:$t.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:$t.resolve(_e.workspace||process.cwd())}))}catch(e){Be(`The connector process could not be started: ${e.message}`)}if(Do){try{await yb(_e.workspace,bt[0]?_e.agent:null)}catch(e){Be(e.message)}et=bt[0]?"pair":"start"}var C,Yr,si;if(et==="pair"){let e=bt[0];e||Be("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||Be("Pairing requires --url with the EngineerOS backend address."),_e.agent&&_e["agent-command"]&&Be("Use either --agent or --agent-command, not both.");let n=_e["agent-protocol"]||(_e["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||Be(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(_e.agent||_e["agent-command"])&&Be("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{_e.agent&&(await Es(_e.agent),r=await gd(_e.agent))}catch(o){Be(o instanceof Error?o.message:String(o))}C={server_url:Tl(t),workspace:$t.resolve(_e.workspace||process.cwd()),onboard:_e.onboard===!0,onboarding_pending:_e.onboard===!0,hunt_host:Do,agent_protocol:n,agent_command:_e["agent-command"]||null,agent_args:zB(_e["agent-args"]),agent_name:_e["agent-name"]||null,...r,skip_git_repo_check:Do||_e["skip-git-repo-check"]===!0,name:_e.name||`${pB.hostname()} - ${$t.basename($t.resolve(_e.workspace||process.cwd()))}`},si=await ht(C.workspace),Yr={type:"pair",pairing_code:e,name:C.name,capabilities:{},...bh(si,C.server_url)}}else et==="start"?(C=await ht(_e.workspace||process.cwd()),C||Be("This connector is not paired. Create a pairing command in EngineerOS first."),Do&&!C.hunt_host&&Be("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),C.token||Be("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),Yr={type:"authenticate",connector_id:C.connector_id,token:C.token}):Be("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, or `mcp`.");var QE=fb(C,{reportError:e=>console.error(e)}),$r=0,Vc=!1,ii=null,St=new Map,Qp=0,ef=new Set,Fo=[],_t=new Map,ct,cf,zc,Nn=null,Gc=!1,ek=0,tf=null,nf=[],Bc,tk,ti=1e3,Uo,UE=0,rf=!1,er=!1,an,Mo=!1,Xc=!1,lf=0;function Dc(e){return lf+=1,e.finally(()=>{lf-=1})}var Po,Kr=0;function ai({exitCode:e=0}={}){if(Kr=Math.max(Kr,e),Po)return Po;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Po=bB().finally(()=>clearTimeout(t)),Po}async function bB(){if(vt=!0,li?.stop(),rr?.stop(),uf?.stop(),YE?.stop(),clearInterval(af),lt?.stop(),tk?.(),clearTimeout(Bc),clearInterval(cf),clearInterval(zc),await Promise.all([...[...St.values()].map(e=>Ct(e.child))]),await Promise.all([..._t.values()].map(ff)),await ri?.cancelAll(),await Lo?.abortAll(),await Ss(),await vf().catch(e=>{Kr=Math.max(Kr,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),ct?.close(),Kr&&Kr!==Ko){let e;await Promise.race([(async()=>{await rr?.drain(),await Go(C,C.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Kr)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{ai()});var zE=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{zE||(zE=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await ai({exitCode:1}))});lt=Af();process.on("exit",()=>{li?.stop(),lt.stop()});lt.banner(`EngineerOS connector ${xr}`,[C.workspace,C.server_url]);rr=Hb({actions:{refresh_tool_inventory:async()=>{Se.tool_inventory=await Vt(C.workspace),Ft()},restart_goal_runner:()=>Co(C.workspace)},onNotify:()=>Go(C,C.workspace),explain:async e=>{if(!await ci())return null;let{reading:t}=await L0(C,e);return t},onUpdate:e=>Qb(C.workspace,e)});YE=nS({render:(e,t)=>lt.write(e,t),onRecord:e=>rr.observe(e)});uf=rS({workspace:C.workspace,onRecord:e=>{rr.observe(e),lt.line(e.channel,e.level,e.message)}});rr.start();C.hunt_host||uf.start();lt.live&&!C.hunt_host&&(af=setInterval(()=>{SB().catch(()=>{})},gB),af.unref?.());var of=new Set;async function SB(){if(C.hunt_host)return;DE??=tp(C.workspace);let{jobs:e}=await DE(),t=new Set,n=e.filter(r=>r.status!=="queued"&&qc.includes(r.status)).length;for(let r of e){if(!qc.includes(r.status))continue;t.add(r.runId),of.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;lt.status(`goal:${r.runId}`,o,EB(r),{agent:r.status!=="queued",link:ii&&`${ii}/goals`}),lt.step(`goal:${r.runId}`,r.activity?.message)}for(let r of of)t.has(r)||(of.delete(r),lt.clearStatus(`goal:${r}`))}function EB(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function ci({ignoreBugHunt:e=!1}={}){if(vt||St.size>0||_t.size>0||$r>0||(ri?.active??0)>0||!e&&(Lo?.active??0)>0)return!1;try{let{jobs:t}=await wr(C.workspace);return!vt&&!t.some(n=>qc.includes(n.status))}catch{return!1}}try{let e=C.hunt_host?{}:await Zr(C.workspace);e.committed&&(C.onboarding_pending=!0,C.connector_id&&await mn(C),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await sk(e)}var nk=await At(Dn()).then(e=>e.policy!=="manual",()=>!1),Ue;try{Ue=await js(C,C.workspace)}catch(e){await sk(e)}console.log(`Using ${Ue.name} through ${Ue.protocol} (${Ue.version}).`);var Se=yc(C,Ue,await Vt(C.workspace)),nr=ch({running:vl(process.argv[1],Wc),supervised:process.env[eo]==="1",isIdle:async()=>!vt&&St.size===0&&Fo.length===0&&_t.size===0&&$r===0&&lf===0&&!Mo&&!Xc&&!Gc,restart:()=>ai({exitCode:Ko}),onChange:e=>{Se.runtime_update=e,ct?.readyState===WebSocket.OPEN&&Ft()}});try{await nr.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}C={...C,execution_profiles:Ue.executionProfiles??null};et==="pair"&&si?.connector_id||await mn(C);Se.agent_session={...Se.agent_session,status:"checking",message:`Checking that ${Ue.name} can answer.`};Se.bug_hunt_browser=!1;Yr.capabilities=Se;console.log(Xn(C.worker_limit)===null?`Workers: automatic, ${Eo()} ${Ue.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Xn(C.worker_limit)} ${Ue.name} workers side by side, set with /workers.`);var zo=e=>Jn(C,e),GE=ac(zo,{signature:q0});async function kB(){let e=await wr(C.workspace).catch(()=>({service:null,jobs:[]}));return{version:xr,now:Date.now(),workspace:C.workspace,config_path:Kt(C.workspace),config:C,agent:Ue,automatic_worker_limit:Eo(),worker_limit:Xn(C.worker_limit),connection:{state:$B(),server_url:C.server_url,last_error:an||null},work:{assessments:[...St.values()].map(t=>({stage:t.stage,message:t.lastMessage,started_at:t.startedAt})),prompts:[..._t.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,started_at:t.startedAt})),integrations:$r},runner:e,runtime_update:nr.report(),health:rr?.health()??null,activity:oi.snapshot()}}function $B(){return vt||er?"stopped":ct?.readyState===WebSocket.OPEN?"connected":"connecting"}var xB={async cancelPrompt(e){let t=[..._t.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=>ok(e),setVerbose(e){return e===Vc?`Detailed agent activity is already ${e?"on":"off"}.`:(df(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"?(nr.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 nr.command(e),Zo(await nr.refresh()))}};li=Jb({ui:lt,snapshot:kB,actions:xB});li&&console.log(Xb());await rk();var BE=new Set;async function rk(){if(vt||er)return;console.log(`Connecting ${C.name} to ${C.server_url}`),er=!1,an=void 0;let e=new WebSocket(C.server_url);ct=e;let t=hw(e,C.server_url,{onTimeout:r=>{ct===e&&(an=r,console.error(r),sf())}});tk=t,e.addEventListener("open",()=>{if(ct!==e){e.close();return}try{if(cw(ct,e,Yr))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){an=Tt(r),console.error(`Could not authenticate the WebSocket connection: ${an}`);try{e.close()}catch{}sf()}}),e.addEventListener("message",r=>{if(ct!==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: ${Tt(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){vt=!0,er=!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=si?.connector_id===r.connector.id;if(C=Sh(C,si,r.connector.id,r.token),await mn(C),r.connector?.capabilities?.http_updates!==!0){vt=!0,er=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}Yr={type:"authenticate",connector_id:C.connector_id,token:C.token,capabilities:Se},console.log(s?`Reconnected existing workspace connector ${C.connector_id}; assessment history is preserved.`:`Paired. Connector ${C.connector_id} is online.`),WE(r);return}if(r.type==="authenticated"){t();let s=C.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(Uo?`Reconnected after ${Ne(Date.now()-Uo)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),Uo=void 0,WE(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){Xc||TB(r);return}if(r.type==="workspace.refresh"){Jc();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await ok(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){df(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(tr=!1,Se.bug_hunt_browser=!1,Ft());try{Se.tool_inventory=await bs(C.workspace,r,void 0,{confirmLocal:i=>li?.confirm(i)??!1,log:Hc}),s&&(tr=!0),Se.bug_hunt_browser=Xr(Se.tool_inventory)&&tr,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Se.tool_inventory})),Ft(),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 Qu(C.workspace,r,{onStatus:async()=>{Se.tool_inventory=await Vt(C.workspace),Ft()}});Se.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:Se.tool_inventory})),Ft(),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"){co(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===OE){Dc(vB(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),jE(C,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}`;Hd(Fo,St.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),ui();return}if(r.type==="prompt.execute"){let s=_t.get(r.prompt_id);s?uk(r)>s.executionRevision&&await LB(s,r):lk(r);return}if(r.type==="prompt.cancel"){let s=_t.get(r.prompt_id);s&&await ff(s);return}if(r.type==="agent.warm"){CB(r);return}if(r.type==="run.available"){if(C.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await QE.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${$t.join(C.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${Tt(s)}`)}return}if(r.type==="goal.cleanup"){try{await ub(C.workspace),await Co(C.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){UB(r);return}if(r.type==="run.cancelled"){await ep(C.workspace,r.run_id);return}if(r.type===Pw){ri??=Vw({getConfig:()=>C,onTestsCommitted:()=>Jc()}),Dc(ri.handle(r));return}if(r.type===Lw){await ri?.cancel(r);return}if(r.type===QS){Lo??=oE({getConfig:()=>C,isIdle:()=>ci({ignoreBugHunt:!0}),recordedSignIns:ZE,activity:{status:lt.status,step:pf,finish:lt.finish}}),Dc(Lo.handle(r));return}if(r.type===eE){Lo?.stop(r);return}if(r.type===AS){FE??=TS({getConfig:()=>C}),Dc(FE.handle(r));return}if(r.type==="connector.update"){AB(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await ai();return}if(r.type==="connector.revoked"){vt=!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||(Mo=!1);return}if(r.type==="connection.error"){er=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);BE.has(o)||(BE.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${xr}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),ct!==e||Po)return;let o=lw(r);if(!o.retry||er||vt){console.error(o.message),o.retry&&er&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),ai();return}an=an?`${o.message} ${an}`:o.message,sf()}),e.addEventListener("error",r=>{ct===e&&(an=aw(r),console.error(`WebSocket connection to ${C.server_url} failed: ${an}`))})}async function AB(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=nr.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 nr.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 TB(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";Xc=!0,console.log(`Starting interactive ${Ue.name} provider ${n}.`);try{await(n==="logout"?fw:pw)(Ue,C.workspace),Ue=await js(C,C.workspace),Se=yc(C,Ue,Se.tool_inventory),Yr.capabilities=Se,ct.readyState===WebSocket.OPEN&&(ct.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:Se.agent_session})),ct.close(1e3,`Provider ${n} completed`)),console.log(`${Ue.name} provider ${n} completed.`)}catch(r){let o=Tt(r).slice(0,500);ct.readyState===WebSocket.OPEN&&ct.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{Xc=!1}}function sf(){if(vt||er||Bc)return;let e=an?` Last error: ${an}`:"",t=Uo?` Offline for ${Ne(Date.now()-Uo)}.`:"";Uo??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(ti/1e3)}s.`),Bc=setTimeout(()=>{Bc=void 0,rk()},ti),ti=Math.min(3e4,ti*2)}async function Jc(){if(!C.hunt_host&&!(Mo||ct.readyState!==WebSocket.OPEN)){Mo=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await U0(C.workspace),t=await F0(C.workspace,C.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(to(C.server_url,C.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.token}`},body:JSON.stringify(e)});if(!n.ok)throw new Error(await la(n,"the workspace"));let r=await n.json();C={...C,onboarding_pending:!1,last_snapshot_head:e.head_revision??C.last_snapshot_head},await mn(C),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 Hi(C.workspace,C.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}`)}Mo=!1}catch(e){Mo=!1,console.error(`Workspace assessment failed: ${Tt(e)}`)}}}var RB=6e4,HE=0;async function CB(e){if(C.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?C.sessions?.[t]:void 0,r=[];Date.now()-HE>RB&&(HE=Date.now(),r.push(Hi(C.workspace,C.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),C.agent_protocol==="acp"&&r.push(m_(C.workspace,C,{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(`${Ue?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Ft(){let e=A0(St);GE.update({type:"assessment.workers",assessment_workers:e,tool_inventory:Se.tool_inventory,runtime_update:Se.runtime_update,agent_session:Se.agent_session,bug_hunt_browser:Se.bug_hunt_browser,...nc(C.worker_limit)}),GE.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function ok(e){let t=Xn(e);return t===Xn(C.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(C={...C,worker_limit:t},await mn(C),ui(),Ft(),t===null?`Workers are automatic again: up to ${Eo()} side by side for this machine's CPU and memory, for ${qs} (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: ${qs}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function df(e){if(e!==Vc){if(Vc=e,!e)for(let t of St.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."),Ft()}}function pf(e,t){lt.step(e,t)&&Vc&&console.log(`[${e}] ${t}`)}function OB(){clearInterval(zc);let e=!1,t=()=>{e||St.size>0||_t.size>0||(e=!0,Go(C,C.workspace).finally(()=>{e=!1}))};t(),zc=setInterval(t,mB),zc.unref?.()}async function Go(e,t,n=rr?.healthChecks()??[]){let r=await Fb({config:e,workspace:t,version:xr,insights:n,agentSession:$n,probes:{inspectAgent:(o,s)=>vt?Ue:js(o,s),inspectTools:o=>vt?Se.tool_inventory:Vt(o),runnerStatus:wr}});try{KE=(await Ub(e,r,Jn))?.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 sk(e){if(vt)return Po;let t=e instanceof Error?e.message:String(e),n=await Go(C,C.workspace).catch(()=>null);n&&console.error(yp(n)),Be(t)}function WE(e){df(e.connector?.activity_log_enabled===!0),ii=e.project_url??null,ti=1e3,jB(),ak(),nr.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),NB(),C.onboarding_pending&&Jc()}var ni=null,tr=!1,ik=0,IB=Date.now();async function jB(){return ni||(ni=(async()=>{nk&&await Yy(C.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Hc("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await _b(C.workspace,{log:Hc}),tr=!0,Se.tool_inventory=await Vt(C.workspace),Se.bug_hunt_browser=Xr(Se.tool_inventory)&&tr,Hc(`Bug Hunter's browser is ready (${Ne(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${Ne(Date.now()-e)}: ${t.message}`),Se.bug_hunt_browser=!1}Ft()})(),ni)}function Hc(e){console.log(`[browser] ${e}`)}async function ak(){if($n?.state!=="checking"){ik=Date.now(),Se.agent_session={...Se.agent_session,status:"checking",message:`Checking that ${Ue.name} can answer.`},Ft(),$n={state:"checking",detail:`Asking ${Ue.name} one question to confirm its session.`},console.log(`Checking that ${Ue.name} can answer before accepting work.`);try{await I0(C,Ue.name),$n={state:"ready",detail:`${Ue.name} answered; its session is usable.`},Se.agent_session={...Se.agent_session,status:"authenticated",message:$n.detail},console.log($n.detail)}catch(e){$n={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:C.hunt_host?bb(C.agent_id||C.agent_protocol):_o(C.agent_id||C.agent_protocol)},Se.agent_session={...Se.agent_session,status:"logged_out",message:$n.remedy},console.error(`${$n.detail}
1005
1005
  ${$n.remedy}`)}Ft(),await Go(C,C.workspace).catch(()=>null)}}function NB(){clearInterval(cf);let e=!1,t=0,n=0,r=!1,o=()=>{nr.tick(),MB(),C.hunt_host&&ni&&Date.now()-ik>=vb(IB)&&_t.size===0&&St.size===0&&!(Lo?.active>0)&&ak(),!C.hunt_host&&!r&&Hs(Zp.id)&&(r=!0,QE.flush().then(()=>Uc(Zp)).catch(s=>Fc(Zp,s)).finally(()=>{r=!1})),St.size>0&&Ft(),!C.hunt_host&&!Nn&&Date.now()-t>=wB&&Hs(Jp.id)&&(t=Date.now(),ck().then(()=>Uc(Jp)).catch(s=>Fc(Jp,s))),!C.hunt_host&&KE&&!Gc&&Hs(Kp.id)&&Date.now()-ek>=ly&&(Gc=!0,PB().then(()=>Uc(Kp)).catch(s=>Fc(Kp,s)).finally(()=>{Gc=!1})),!e&&Date.now()-n>=yB&&Hs(Yp.id)&&(e=!0,n=Date.now(),Vt(C.workspace).then(async s=>{if(Se.tool_inventory=s,!tr&&Xr(s))try{await(await Ar(await _r(C.workspace))).close(),tr=!0}catch{tr=!1}Se.bug_hunt_browser=Xr(s)&&tr,Ft(),Uc(Yp)}).catch(s=>Fc(Yp,s)).finally(()=>{e=!1}))};o(),cf=setInterval(o,1e4),OB()}async function MB(){if(!(!nk||C.agent_protocol!=="acp"||!C.agent_id||rf||$n?.state==="checking"||Date.now()-UE<_B)){rf=!0;try{if(!await ci())return;UE=Date.now();let e,t=await E_(C,{verify:async r=>{e=await js(r,C.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===C||vt)return;C={...t,execution_profiles:e.executionProfiles??null},await mn(C),Ue=e;let n=yc(C,Ue,Se.tool_inventory);if(Object.assign(Se,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),Yr.capabilities=Se,!await ci())return;await Ss(),ct?.readyState===WebSocket.OPEN&&ct.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{rf=!1}}}function Fc(e,t){let n=jb(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 Uc(e){Nb(e.id)&&console.log(`${e.title} recovered.`)}async function PB(){if(C.hunt_host||!await ci())return;ek=Date.now();let{jobs:e}=await wr(C.workspace).catch(()=>({jobs:[]})),t=await uy(C.workspace,{jobs:e});if(!dy(t))return;let n=`${t.fingerprint}:${nf.join(",")}`,r=tf?.key===n,o=r?tf.candidates:await D0(C,t,nf);tf={key:n,candidates:o};let s=await zo(hy(t,o,{version:xr}));Array.isArray(s?.refused)&&(nf=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 kr=null,qE=null;async function ck(){if(!C.hunt_host){if(Nn)return Nn;Nn=(async()=>{let e=await ty(C,{knownRevision:kr?.revision??null});if(e.unchanged||(kr=e),qE===kr.revision)return kr;let{jobs:t}=await wr(C.workspace);return!t.some(r=>qc.includes(r.status))&&$r===0&&St.size===0&&(await ka(C.workspace,kr),qE=kr.revision),kr})();try{return await Nn}finally{Nn=null,ui()}}}function VE(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)),_t.get(e)?.events.push(n)}var XE=null;function ui(){let e=ct.readyState===WebSocket.OPEN,t=St.values().next().value,n=Xn(C.worker_limit)??Math.min(Eo(),Wd(t?.workerLimit??Fo[0]?.worker_limit)),r=e&&!Nn&&$r===0?y0(Fo,St.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:Wd(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};St.set(i,a),FB(s,a)}r.length>0&&Ft();let o=_0({queued:Fo,running:St.size,workerLimit:n,connected:e,designSync:!!Nn,integrations:$r});o&&o!==XE&&console.log(o),XE=o}function Kc(e){let t=qd(e);return t?`${Ue.name} on ${t}`:Ue.name}async function lk(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:J0(zo),executionRevision:uk(e),sessionKey:rc(e),sessionId:null,replacement:null};_t.set(t,s);let i,a=m=>{let y=m?JSON.stringify(m):null;!y||y===i||_t.get(t)!==s||(i=y,VE(t,m))},c=`${r} \xB7 ${Kc(e)}`,l=O0(e,Ue.name);VE(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}.`,`${Ue.name} can reason for several minutes without reporting a step.`,...d?[nl(d,o)]:[]].join(" ")),lt.status(n,c,o,{link:ii,answerBy:d});let p=m=>{let y=m0(m),w=Gr(m);_t.get(t)===s&&pf(n,w??y?.message);let S=m.type==="forge.output"?null:w;a(y??(S?{kind:"status",message:S}:null))},f="failed",h=[r];try{oc(e)||(p({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await iy(ck,{pinned:!!e.local_design_context,last:kr,onFallback:(S,v)=>p({type:"connector.step",message:`Design context not refreshed (${S.message}); continuing with ${v?"the copy synced earlier":"none"}`})})});let m=await l0(e,C,{onProcess:S=>{_t.get(t)===s&&(s.child=S)},onController:S=>{_t.get(t)===s&&(s.controller=S)},onSession:S=>{s.sessionId=S},onEvent:p},{signal:s.cancellation.signal});if(s.stoppedHere)throw new Error(JE);let y=m.singleTurn?Eh(C.sessions,m.sessionKey):Rl(C.sessions,m.sessionKey,m.sessionId);if(JSON.stringify(y)!==JSON.stringify(C.sessions||{})&&(C={...C,sessions:y},await mn(C)),s.cancelled)return;await s.events.close().catch(S=>{console.error(`[${n}] Prompt progress delivery: ${S.message} The agent has finished; submitting its complete response separately.`)});let w=await ic(zo,{type:"prompt.completed",prompt_id:t,execution_revision:s.executionRevision,content:m.content,model:m.model,session_id:m.sessionId,usage:m.usage});w||console.error(`[${n}] ${Kd}`),oi.record("prompt","completed",{durationMs:Date.now()-o,usage:m.usage}),f=w?"finished":"undelivered",h=[hi(m.usage),r]}catch(m){let y=s.stoppedHere?JE:Tt(m);if(oi.record("prompt","failed",{durationMs:Date.now()-o}),s.stoppedHere&&(f="cancelled"),!s.cancelled){try{await ic(zo,{type:"prompt.failed",prompt_id:t,execution_revision:s.executionRevision,message:y})||console.error(`[${n}] ${Kd}`)}catch(w){console.error(`[${n}] Prompt failure delivery: ${w.message}`)}console.error(y)}}finally{s.events.stop();let m=s.replacement;m?(f="replaced",h=[`continuing on ${Kc(m)}`,r]):s.cancelled&&(f="cancelled"),lt.finish(n,f,h),_t.get(t)===s&&_t.delete(t),m&&DB(s,m)}}var JE="Cancelled from the connector terminal by the person running it.";async function ff(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function uk(e){return Number(e.execution_revision)||1}async function LB(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 ${Kc(t)}.`),await ff(e))}function DB(e,t){e.sessionId&&(C={...C,sessions:Rl(C.sessions,e.sessionKey,e.sessionId)},mn(C).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),lk(t)}async function FB(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 ${Kc(e)}.`),!ef.has(n)){ef.add(n);try{let _=await p0(C.workspace);if(!_.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let k=_.accepted_head_revision?_.current_head_revision?_.current_head_revision!==_.accepted_head_revision?`The workspace is now at commit \`${_.current_head_revision}\`; the accepted assessment is from \`${_.accepted_head_revision}\`.`:"The accepted assessment is already at the current commit.":`The accepted assessment is from \`${_.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 ${_.stages.length||"no"} section(s). ${k}`)}}catch(_){console.error(`Assessment freshness check failed: ${_.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=()=>!vt&&St.get(t.key)===t,y=async _=>{try{return await ic(zo,_)||console.warn(`[${s}] ${V0}`),!0}catch(k){return console.error(`Assessment failure delivery: ${k.message}`),!1}},w=(_,{milestone:k=!0}={})=>{if(!m()||k&&f===_)return;k&&(f=_,h.has(_)||(h.add(_),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${_}.`));let g=String(_).slice(0,500);t.progressPercent=c,t.lastMessage=g,lt.status(s,g,o,{link:ii})};w(`Starting ${r} assessment stage`);let S=setInterval(()=>{let _=Date.now(),k=_-t.lastActivityAt,g=i&&!a?h0(r,k):null;if(!d&&g){d=g,console.error(`[assessment:${r}] ${d}`),sc(t.controller,t.child);return}d||rr.observe({at:_,level:"info",message:lt.status(s,`${t.lastMessage} \xB7 last agent activity ${Ne(k)} ago (${t.eventCount.toLocaleString()} events)`,o)})},15e3),v={onSession:async _=>{m()&&(p=String(_),await tg(C.workspace,n,r,_,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:_=>{m()&&(t.controller=_)},onProcess:_=>{m()&&(t.child=_,i=!0,t.phase!=="correcting"&&(t.phase="running",w("Connected agent process started")),t.lastActivityAt=Date.now())},onEvent:_=>{t.lastActivityAt=Date.now(),t.eventCount+=1;let k=f0(_);if(k&&w(k),!m())return;let g=Gr(_);!g||g===t.lastDetail||(t.lastDetail=g,pf(s,g))}},b=(_,k)=>Gd(_,k,C,v,{draftPath:$t.relative(C.workspace,$t.join(Bt(C.workspace,n),_.report_file)).split($t.sep).join("/")});try{let _=Qp-Date.now();_>0&&(w(`Waiting ${Math.ceil(_/1e3)}s for the model provider's rate limit to clear`),await new Promise(T=>setTimeout(T,_+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,w("Calculating changed files and affected behavior"));let k=await ig(C.workspace,e),g=await eu(C.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(g)b(g,k),w("Recovered completed stage report from connector storage");else{if(p=await ng(C.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),p&&w("Restoring interrupted agent session"),g=await c0(k,C,v,{previousSessionId:p}),d)throw new Error(d);a=!0,await Ql(C.workspace,n,k,g)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let $=T=>fetch(xh(C.server_url,C.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C.token}`},body:JSON.stringify(T),signal:AbortSignal.timeout(Vv)}),A=await C0(g,{submit:T=>R0(T,$,{isActive:()=>m()&&!vt,onRetry:(M,N)=>{w("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${Tt(M)} Retrying in ${Math.round(N/1e3)}s without rerunning the agent.`)}}),payloadFor:T=>r==="synthesis"?tu(C.workspace,n,T,{expectedSourceRevision:e.source_revision}):ug(T),rejectionFor:T=>la(T,"the assessment"),correct:async(T,M)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!T.correctAfterRejection)throw new Error(`${M} The connector could not start the required agent correction.`);return T.correctAfterRejection(M)},onCorrected:async T=>{if(d)throw new Error(d);a=!0,await og(C.workspace,n,r);let M=await Ql(C.workspace,n,k,T);return b(M,k),t.phase="delivering",t.lastMessage="Delivering corrected stage result",M}});if(d)throw new Error(d);g=A.result;let R=A.response;if(!R.ok)throw new Error(await la(R,"the assessment"));if(l=!0,oi.record("assessment stage","completed",{durationMs:Date.now()-o,usage:g.usage}),r==="synthesis"){let T=await R.json(),M=await ag(C.workspace,n,e,g,T.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${$t.relative(C.workspace,M)}.`);try{let N=await _i(C.workspace);N.committed&&console.log(`Assessment committed to Git as ${N.revision.slice(0,8)}.`)}catch(N){console.error(`The assessment is saved locally but could not be committed to Git: ${N.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(_){let k=d||Tt(_),g=E0(e,_),$=x0(_),x=b0(_);$&&(await rg(C.workspace,n,r).catch(R=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${R.message}`)}),p=null);let A=!d&&(p||$)&&($||v0(_))&&g<x;if(m()&&A){t.phase="starting",t.lastMessage=$?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=k0(e,_);let R=$0(_,g);Ns(_)&&(Qp=Math.max(Qp,Date.now()+R)),console.warn(`[assessment:${r}] ${$?"Agent session became unusable":"Agent session interrupted"}: ${k} ${$?"Starting a fresh session from the saved draft":`Resuming session ${p}`} in ${Math.round(R/1e3)}s (${g+1}/${x}).`),await new Promise(T=>setTimeout(T,R))}else m()&&(u=await y({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:k}));A||(oi.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${k}`))}finally{clearInterval(S),lt.clearStatus(s),r==="synthesis"&&l&&ef.delete(n),m()&&(St.delete(t.key),T0(Fo,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),ui())}}async function UB(e){let t=String(e.run_id||"");$r+=1;try{Nn&&await Nn;let n=await e0(C.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 Jc();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: ${Tt(n)}`)}finally{$r-=1,ui()}}function zB(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{Be('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function Be(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.56.2",
3
+ "version": "1.56.3",
4
4
  "description": "Connect a local coding agent to EngineerOS, using ACP when supported.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",