@engineeros/connector 1.56.6 → 1.56.7

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.
@@ -1003,7 +1003,7 @@ It is checked with the provider and stored in this machine's protected vault
1003
1003
  (Windows Data Protection, the macOS Keychain or the Linux Secret Service).
1004
1004
  EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function PB(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(`
1005
1005
  `),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
1006
- `)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 VE=Symbol("missing");function LB(e,t){return new Promise(n=>{let r=NB(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?VE:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function qE(e,t){for(let n of oi){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 XE(e,t,n,{vault:r=Yp(),run:o=Fc,fetchImpl:s=fetch,secret:i=PB,interactive:a=LB,install:c=Dc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(MB),n.help?0:2;if(e==="integrations")return qE(l,(await Gc({run:o,vault:r})).providers),0;let d=t[0];if(!oi.includes(d))return u(`Unknown provider ${d}. Choose one of: ${oi.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Zr[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===VE){let g=await Po(f);if(!g){l(`Installing the ${ti[f].label} ${ti[f].version} for the connector...`);try{g=(await c(f)).path}catch(y){return u(y.message),1}}h=await a(g,["auth","login"])}return h?(u(`${h} ${zc[d]} is how this machine signs in to ${d}.`),1):(qE(l,{[d]:(await Gc({run:o,vault:r})).providers[d]}),0)}let p=vt[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Zp(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await Qp(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 DB}from"node:child_process";async function JE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=DB,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=cr(await Tt(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await FB(o,c.entry,i,t);if(l===Qo){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 Tt(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await Al(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 FB(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[ro]:"1",[Sl]:r.entry,[El]: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 Tr="1.56.6",Kc="1.56.6",BB=3e5,Yc=["queued","running","reporting"],HB=5e3,ef={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."},tf={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,qB=3e4,VB=60*6e4,nf={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},rf={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:et,positional:Et,flags:ve}=Qb(process.argv.slice(2));et==="version"&&(console.log(Tr),process.exit(0));var sr=null,St=!1,xn=null,ck=!1,lk=null,mf=null,ut=null,fi=null,pf,KE,YE,ai,Uo,uk=jc({getWorkspace:()=>C.workspace,onRecorded:e=>nE(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}`))}),XB=HE({getWorkspace:()=>C.workspace,huntSignIns:uk}),ci=rS();et==="results"&&(Et[0]!=="upload"&&(console.log(Ac),process.exit(ve.help||!Et[0]?0:2)),process.exit(await DS(ve)));(et==="connect"||et==="disconnect"||et==="integrations")&&process.exit(await XE(et,Et,ve,{fetchImpl:zE}));if(et==="runner"){let e=xt.resolve(ve.workspace||process.cwd()),t=Et[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?xt.join(xt.dirname(Je(e,ve["run-id"])),"worker.log"):xt.join(e,".engineeros","runner","service.log");zB(xt.dirname(n),{recursive:!0});let r=(...s)=>Us(n,`${GB(...s)}
1006
+ `)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 VE=Symbol("missing");function LB(e,t){return new Promise(n=>{let r=NB(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?VE:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function qE(e,t){for(let n of oi){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 XE(e,t,n,{vault:r=Yp(),run:o=Fc,fetchImpl:s=fetch,secret:i=PB,interactive:a=LB,install:c=Dc,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(MB),n.help?0:2;if(e==="integrations")return qE(l,(await Gc({run:o,vault:r})).providers),0;let d=t[0];if(!oi.includes(d))return u(`Unknown provider ${d}. Choose one of: ${oi.join(", ")}.`),2;if(d==="github"||d==="gitlab"){let f=Zr[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===VE){let g=await Po(f);if(!g){l(`Installing the ${ti[f].label} ${ti[f].version} for the connector...`);try{g=(await c(f)).path}catch(y){return u(y.message),1}}h=await a(g,["auth","login"])}return h?(u(`${h} ${zc[d]} is how this machine signs in to ${d}.`),1):(qE(l,{[d]:(await Gc({run:o,vault:r})).providers[d]}),0)}let p=vt[d];if(e==="disconnect")return await r.delete("",d),l(`Removed the ${p.label} ${p.tokenName} from this machine.`),0;try{await Zp(r);let f=await i(`${p.label} ${p.tokenName} (create one at ${p.tokenUrl}): `),h=await Qp(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 DB}from"node:child_process";async function JE({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=DB,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=cr(await Tt(e),t)}catch(d){s(`${d.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await FB(o,c.entry,i,t);if(l===Qo){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 Tt(e).catch(()=>null);if(d&&!d.confirmed&&d.active?.version===c.version)try{let p=await Al(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 FB(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[ro]:"1",[Sl]:r.entry,[El]: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 Tr="1.56.7",Kc="1.56.7",BB=3e5,Yc=["queued","running","reporting"],HB=5e3,ef={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."},tf={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,qB=3e4,VB=60*6e4,nf={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},rf={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:et,positional:Et,flags:ve}=Qb(process.argv.slice(2));et==="version"&&(console.log(Tr),process.exit(0));var sr=null,St=!1,xn=null,ck=!1,lk=null,mf=null,ut=null,fi=null,pf,KE,YE,ai,Uo,uk=jc({getWorkspace:()=>C.workspace,onRecorded:e=>nE(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}`))}),XB=HE({getWorkspace:()=>C.workspace,huntSignIns:uk}),ci=rS();et==="results"&&(Et[0]!=="upload"&&(console.log(Ac),process.exit(ve.help||!Et[0]?0:2)),process.exit(await DS(ve)));(et==="connect"||et==="disconnect"||et==="integrations")&&process.exit(await XE(et,Et,ve,{fetchImpl:zE}));if(et==="runner"){let e=xt.resolve(ve.workspace||process.cwd()),t=Et[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?xt.join(xt.dirname(Je(e,ve["run-id"])),"worker.log"):xt.join(e,".engineeros","runner","service.log");zB(xt.dirname(n),{recursive:!0});let r=(...s)=>Us(n,`${GB(...s)}
1007
1007
  `),o=(s,i,a)=>(Us(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(ve["keep-awake"]!==void 0){if(!["on","off"].includes(ve["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await gt(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await gn({...n,runner_keep_awake:ve["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await gc(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 _b(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await jo(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await _r(e),null,2)):t==="serve"?await Eb(e):t==="worker"?await kb(e,ve["run-id"]):Be("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){Be(lp(n,e).message)}}ve["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=Rb(ve),t=Et[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=Et[1];r||Be(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await od(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 xs(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:Et[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await td(e,t,Et[1]);let n=await Xt(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 vd()}catch(n){Be(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await Ts(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=Et[0],t=Et[1]||"check";(!e||!["check","install"].includes(t))&&Be("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await Rs(e):await Ts(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=ve.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=ve["run-id"]||Et[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await gt(e);await wS({config:n,runId:t,version:Tr,input:process.stdin,output:process.stdout}),process.exit(0)}if(et==="context-mcp"){let e=ve["config-workspace"]||ve.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await gt(e);t||Be("This workspace is not paired with EngineerOS."),await TS({config:t,workspace:ve.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:Tr,input:process.stdin,output:process.stdout}),process.exit(0)}if(et==="status"){let e=await gt(ve.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=xt.resolve(ve.workspace||process.cwd()),t=await gt(e),n=await pS(e),r=await Wo(t||{workspace:e},e,$p(n));console.log(Ep(r)),process.exit(r.status==="failed"?1:0)}if(et==="update"){let e=Et[0]||"status";try{let t=$l(process.argv[1],Kc),n=await Tl(Un(),t,{action:e,policy:Et[1]??null});console.log(ts(Rl(n,t,{supervised:!0})))}catch(t){Be(`${t.message}
1008
1008
  Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var zo=et==="hunt-host";if(zo)try{ve.workspace=Tb(Et,ve)}catch(e){Be(e.message)}if((et==="start"||et==="pair"||zo)&&process.env[ro]!=="1"&&tt(Kc))try{process.exit(await JE({root:Un(),bundled:{version:Kc,entry:xt.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:xt.resolve(ve.workspace||process.cwd())}))}catch(e){Be(`The connector process could not be started: ${e.message}`)}if(zo){try{await Cb(ve.workspace,Et[0]?ve.agent:null)}catch(e){Be(e.message)}et=Et[0]?"pair":"start"}var C,eo,li;if(et==="pair"){let e=Et[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=ve.url;t||Be("Pairing requires --url with the EngineerOS backend address."),ve.agent&&ve["agent-command"]&&Be("Use either --agent or --agent-command, not both.");let n=ve["agent-protocol"]||(ve["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||Be(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(ve.agent||ve["agent-command"])&&Be("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{ve.agent&&(await Ts(ve.agent),r=await bd(ve.agent))}catch(o){Be(o instanceof Error?o.message:String(o))}C={server_url:jl(t),workspace:xt.resolve(ve.workspace||process.cwd()),onboard:ve.onboard===!0,onboarding_pending:ve.onboard===!0,hunt_host:zo,agent_protocol:n,agent_command:ve["agent-command"]||null,agent_args:mH(ve["agent-args"]),agent_name:ve["agent-name"]||null,...r,skip_git_repo_check:zo||ve["skip-git-repo-check"]===!0,name:ve.name||`${UB.hostname()} - ${xt.basename(xt.resolve(ve.workspace||process.cwd()))}`},li=await gt(C.workspace),eo={type:"pair",pairing_code:e,name:C.name,capabilities:{},...xh(li,C.server_url)}}else et==="start"?(C=await gt(ve.workspace||process.cwd()),C||Be("This connector is not paired. Create a pairing command in EngineerOS first."),zo&&!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."),eo={type:"authenticate",connector_id:C.connector_id,token:C.token}):Be("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, or `mcp`.");var dk=$b(C,{reportError:e=>console.error(e)}),Ar=0,Zc=!1,ui=null,kt=new Map,of=0,sf=new Set,Go=[],bt=new Map,lt,ff,qc,Pn=null,Vc=!1,pk=0,af=null,cf=[],Xc,fk,si=1e3,Bo,ZE=0,lf=!1,nr=!1,cn,Do=!1,Qc=!1,hf=0;function Bc(e){return hf+=1,e.finally(()=>{hf-=1})}var Fo,Qr=0;function di({exitCode:e=0}={}){if(Qr=Math.max(Qr,e),Fo)return Fo;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Fo=JB().finally(()=>clearTimeout(t)),Fo}async function JB(){if(St=!0,fi?.stop(),sr?.stop(),mf?.stop(),lk?.stop(),clearInterval(pf),ut?.stop(),fk?.(),clearTimeout(Xc),clearInterval(ff),clearInterval(qc),await Promise.all([...[...kt.values()].map(e=>Ot(e.child))]),await Promise.all([...bt.values()].map(yf)),await ai?.cancelAll(),await Uo?.abortAll(),await As(),await $f().catch(e=>{Qr=Math.max(Qr,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),lt?.close(),Qr&&Qr!==Qo){let e;await Promise.race([(async()=>{await sr?.drain(),await Wo(C,C.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(Qr)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{di()});var QE=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{QE||(QE=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await di({exitCode:1}))});ut=If();process.on("exit",()=>{fi?.stop(),ut.stop()});ut.banner(`EngineerOS connector ${Tr}`,[C.workspace,C.server_url]);sr=nS({actions:{refresh_tool_inventory:async()=>{Ee.tool_inventory=await Xt(C.workspace),Ut()},restart_goal_runner:()=>jo(C.workspace)},onNotify:()=>Wo(C,C.workspace),explain:async e=>{if(!await pi())return null;let{reading:t}=await J0(C,e);return t},onUpdate:e=>dS(C.workspace,e)});lk=hS({render:(e,t)=>ut.write(e,t),onRecord:e=>sr.observe(e)});mf=mS({workspace:C.workspace,onRecord:e=>{sr.observe(e),ut.line(e.channel,e.level,e.message)}});sr.start();C.hunt_host||mf.start();ut.live&&!C.hunt_host&&(pf=setInterval(()=>{KB().catch(()=>{})},HB),pf.unref?.());var uf=new Set;async function KB(){if(C.hunt_host)return;KE??=ip(C.workspace);let{jobs:e}=await KE(),t=new Set,n=e.filter(r=>r.status!=="queued"&&Yc.includes(r.status)).length;for(let r of e){if(!Yc.includes(r.status))continue;t.add(r.runId),uf.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;ut.status(`goal:${r.runId}`,o,YB(r),{agent:r.status!=="queued",link:ui&&`${ui}/goals`}),ut.step(`goal:${r.runId}`,r.activity?.message)}for(let r of uf)t.has(r)||(uf.delete(r),ut.clearStatus(`goal:${r}`))}function YB(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function pi({ignoreBugHunt:e=!1}={}){if(St||kt.size>0||bt.size>0||Ar>0||(ai?.active??0)>0||!e&&(Uo?.active??0)>0)return!1;try{let{jobs:t}=await _r(C.workspace);return!St&&!t.some(n=>Yc.includes(n.status))}catch{return!1}}try{let e=C.hunt_host?{}:await to(C.workspace);e.committed&&(C.onboarding_pending=!0,C.connector_id&&await gn(C),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await wk(e)}var hk=await Tt(Un()).then(e=>e.policy!=="manual",()=>!1),Ue;try{Ue=await Ds(C,C.workspace)}catch(e){await wk(e)}console.log(`Using ${Ue.name} through ${Ue.protocol} (${Ue.version}).`);var Ee=Ec(C,Ue,await Xt(C.workspace)),or=fh({running:$l(process.argv[1],Kc),supervised:process.env[ro]==="1",isIdle:async()=>!St&&kt.size===0&&Go.length===0&&bt.size===0&&Ar===0&&hf===0&&!Do&&!Qc&&!Vc,restart:()=>di({exitCode:Qo}),onChange:e=>{Ee.runtime_update=e,lt?.readyState===WebSocket.OPEN&&Ut()}});try{await or.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}C={...C,execution_profiles:Ue.executionProfiles??null};et==="pair"&&li?.connector_id||await gn(C);Ee.agent_session={...Ee.agent_session,status:"checking",message:`Checking that ${Ue.name} can answer.`};Ee.bug_hunt_browser=!1;eo.capabilities=Ee;console.log(Kn(C.worker_limit)===null?`Workers: automatic, ${xo()} ${Ue.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Kn(C.worker_limit)} ${Ue.name} workers side by side, set with /workers.`);var Ho=e=>Yn(C,e),ek=pc(Ho,{signature:ob});async function ZB(){let e=await _r(C.workspace).catch(()=>({service:null,jobs:[]}));return{version:Tr,now:Date.now(),workspace:C.workspace,config_path:Yt(C.workspace),config:C,agent:Ue,automatic_worker_limit:xo(),worker_limit:Kn(C.worker_limit),connection:{state:QB(),server_url:C.server_url,last_error:cn||null},work:{assessments:[...kt.values()].map(t=>({stage:t.stage,message:t.lastMessage,started_at:t.startedAt})),prompts:[...bt.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,started_at:t.startedAt})),integrations:Ar},runner:e,runtime_update:or.report(),health:sr?.health()??null,activity:ci.snapshot()}}function QB(){return St||nr?"stopped":lt?.readyState===WebSocket.OPEN?"connected":"connecting"}var eH={async cancelPrompt(e){let t=[...bt.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=>gk(e),setVerbose(e){return e===Zc?`Detailed agent activity is already ${e?"on":"off"}.`:(gf(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"?(or.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 or.command(e),ts(await or.refresh()))}};fi=aS({ui:ut,snapshot:ZB,actions:eH});fi&&console.log(iS());await mk();var tk=new Set;async function mk(){if(St||nr)return;console.log(`Connecting ${C.name} to ${C.server_url}`),nr=!1,cn=void 0;let e=new WebSocket(C.server_url);lt=e;let t=_w(e,C.server_url,{onTimeout:r=>{lt===e&&(cn=r,console.error(r),df())}});fk=t,e.addEventListener("open",()=>{if(lt!==e){e.close();return}try{if(fw(lt,e,eo))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){cn=Rt(r),console.error(`Could not authenticate the WebSocket connection: ${cn}`);try{e.close()}catch{}df()}}),e.addEventListener("message",r=>{if(lt!==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: ${Rt(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){St=!0,nr=!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=li?.connector_id===r.connector.id;if(C=Ah(C,li,r.connector.id,r.token),await gn(C),r.connector?.capabilities?.http_updates!==!0){St=!0,nr=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}eo={type:"authenticate",connector_id:C.connector_id,token:C.token,capabilities:Ee},console.log(s?`Reconnected existing workspace connector ${C.connector_id}; assessment history is preserved.`:`Paired. Connector ${C.connector_id} is online.`),rk(r);return}if(r.type==="authenticated"){t();let s=C.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(Bo?`Reconnected after ${je(Date.now()-Bo)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),Bo=void 0,rk(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){Qc||nH(r);return}if(r.type==="workspace.refresh"){el();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await gk(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){gf(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(rr=!1,Ee.bug_hunt_browser=!1,Ut());try{Ee.tool_inventory=await xs(C.workspace,r,void 0,{confirmLocal:i=>fi?.confirm(i)??!1,log:Jc}),s&&(rr=!0),Ee.bug_hunt_browser=Yr(Ee.tool_inventory)&&rr,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:Ee.tool_inventory})),Ut(),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 od(C.workspace,r,{onStatus:async()=>{Ee.tool_inventory=await Xt(C.workspace),Ut()}});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})),Ut(),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"){po(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===BE){Bc(XB(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),WE(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}`;Jd(Go,kt.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),hi();return}if(r.type==="prompt.execute"){let s=bt.get(r.prompt_id);s?Sk(r)>s.executionRevision&&await dH(s,r):bk(r);return}if(r.type==="prompt.cancel"){let s=bt.get(r.prompt_id);s&&await yf(s);return}if(r.type==="agent.warm"){oH(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 dk.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${xt.join(C.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${Rt(s)}`)}return}if(r.type==="goal.cleanup"){try{await Sb(C.workspace),await jo(C.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){hH(r);return}if(r.type==="run.cancelled"){await sp(C.workspace,r.run_id);return}if(r.type===Vw){ai??=sy({getConfig:()=>C,onTestsCommitted:()=>el()}),Bc(ai.handle(r));return}if(r.type===Xw){await ai?.cancel(r);return}if(r.type===dE){Uo??=gE({getConfig:()=>C,isIdle:()=>pi({ignoreBugHunt:!0}),recordedSignIns:uk,activity:{status:ut.status,step:wf,finish:ut.finish}}),Bc(Uo.handle(r));return}if(r.type===pE){Uo?.stop(r);return}if(r.type===FS){YE??=US({getConfig:()=>C}),Bc(YE.handle(r));return}if(r.type==="connector.update"){tH(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await di();return}if(r.type==="connector.revoked"){St=!0,console.error("This connector was revoked in EngineerOS."),e.close();return}if(r.type==="run.error"){console.error(`EngineerOS: ${r.message}`),r.run_id||(Do=!1);return}if(r.type==="connection.error"){nr=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);tk.has(o)||(tk.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${Tr}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),lt!==e||Fo)return;let o=hw(r);if(!o.retry||nr||St){console.error(o.message),o.retry&&nr&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),di();return}cn=cn?`${o.message} ${cn}`:o.message,df()}),e.addEventListener("error",r=>{lt===e&&(cn=pw(r),console.error(`WebSocket connection to ${C.server_url} failed: ${cn}`))})}async function tH(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=or.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 or.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 nH(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";Qc=!0,console.log(`Starting interactive ${Ue.name} provider ${n}.`);try{await(n==="logout"?yw:ww)(Ue,C.workspace),Ue=await Ds(C,C.workspace),Ee=Ec(C,Ue,Ee.tool_inventory),eo.capabilities=Ee,lt.readyState===WebSocket.OPEN&&(lt.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:Ee.agent_session})),lt.close(1e3,`Provider ${n} completed`)),console.log(`${Ue.name} provider ${n} completed.`)}catch(r){let o=Rt(r).slice(0,500);lt.readyState===WebSocket.OPEN&&lt.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{Qc=!1}}function df(){if(St||nr||Xc)return;let e=cn?` Last error: ${cn}`:"",t=Bo?` Offline for ${je(Date.now()-Bo)}.`:"";Bo??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(si/1e3)}s.`),Xc=setTimeout(()=>{Xc=void 0,mk()},si),si=Math.min(3e4,si*2)}async function el(){if(!C.hunt_host&&!(Do||lt.readyState!==WebSocket.OPEN)){Do=!0,console.log("Inspecting the workspace without executing its code.");try{let e=await Z0(C.workspace),t=await Y0(C.workspace,C.last_snapshot_head,e.head_revision).catch(()=>null);t&&(e.changed_since=t);let n=await fetch(oo(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 fa(n,"the workspace"));let r=await n.json();C={...C,onboarding_pending:!1,last_snapshot_head:e.head_revision??C.last_snapshot_head},await gn(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 Xi(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}`)}Do=!1}catch(e){Do=!1,console.error(`Workspace assessment failed: ${Rt(e)}`)}}}var rH=6e4,nk=0;async function oH(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()-nk>rH&&(nk=Date.now(),r.push(Xi(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(A_(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 Ut(){let e=F0(kt);ek.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,...ac(C.worker_limit)}),ek.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function gk(e){let t=Kn(e);return t===Kn(C.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(C={...C,worker_limit:t},await gn(C),hi(),Ut(),t===null?`Workers are automatic again: up to ${xo()} side by side for this machine's CPU and memory, for ${Ks} (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: ${Ks}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function gf(e){if(e!==Zc){if(Zc=e,!e)for(let t of kt.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."),Ut()}}function wf(e,t){ut.step(e,t)&&Zc&&console.log(`[${e}] ${t}`)}function sH(){clearInterval(qc);let e=!1,t=()=>{e||kt.size>0||bt.size>0||(e=!0,Wo(C,C.workspace).finally(()=>{e=!1}))};t(),qc=setInterval(t,BB),qc.unref?.()}async function Wo(e,t,n=sr?.healthChecks()??[]){let r=await Yb({config:e,workspace:t,version:Tr,insights:n,agentSession:xn,probes:{inspectAgent:(o,s)=>St?Ue:Ds(o,s),inspectTools:o=>St?Ee.tool_inventory:Xt(o),runnerStatus:_r}});try{ck=(await Zb(e,r,Yn))?.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 wk(e){if(St)return Fo;let t=e instanceof Error?e.message:String(e),n=await Wo(C,C.workspace).catch(()=>null);n&&console.error(Ep(n)),Be(t)}function rk(e){gf(e.connector?.activity_log_enabled===!0),ui=e.project_url??null,si=1e3,aH(),_k(),or.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),cH(),C.onboarding_pending&&el()}var ii=null,rr=!1,yk=0,iH=Date.now();async function aH(){return ii||(ii=(async()=>{hk&&await l_(C.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Jc("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await Ob(C.workspace,{log:Jc}),rr=!0,Ee.tool_inventory=await Xt(C.workspace),Ee.bug_hunt_browser=Yr(Ee.tool_inventory)&&rr,Jc(`Bug Hunter's browser is ready (${je(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${je(Date.now()-e)}: ${t.message}`),Ee.bug_hunt_browser=!1}Ut()})(),ii)}function Jc(e){console.log(`[browser] ${e}`)}async function _k(){if(xn?.state!=="checking"){yk=Date.now(),Ee.agent_session={...Ee.agent_session,status:"checking",message:`Checking that ${Ue.name} can answer.`},Ut(),xn={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 H0(C,Ue.name),xn={state:"ready",detail:`${Ue.name} answered; its session is usable.`},Ee.agent_session={...Ee.agent_session,status:"authenticated",message:xn.detail},console.log(xn.detail)}catch(e){xn={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:C.hunt_host?jb(C.agent_id||C.agent_protocol):So(C.agent_id||C.agent_protocol)},Ee.agent_session={...Ee.agent_session,status:"logged_out",message:xn.remedy},console.error(`${xn.detail}
1009
1009
  ${xn.remedy}`)}Ut(),await Wo(C,C.workspace).catch(()=>null)}}function cH(){clearInterval(ff);let e=!1,t=0,n=0,r=!1,o=()=>{or.tick(),lH(),C.hunt_host&&ii&&Date.now()-yk>=Ib(iH)&&bt.size===0&&kt.size===0&&!(Uo?.active>0)&&_k(),!C.hunt_host&&!r&&Xs(rf.id)&&(r=!0,dk.flush().then(()=>Wc(rf)).catch(s=>Hc(rf,s)).finally(()=>{r=!1})),kt.size>0&&Ut(),!C.hunt_host&&!Pn&&Date.now()-t>=WB&&Xs(ef.id)&&(t=Date.now(),vk().then(()=>Wc(ef)).catch(s=>Hc(ef,s))),!C.hunt_host&&ck&&!Vc&&Xs(tf.id)&&Date.now()-pk>=by&&(Vc=!0,uH().then(()=>Wc(tf)).catch(s=>Hc(tf,s)).finally(()=>{Vc=!1})),!e&&Date.now()-n>=qB&&Xs(nf.id)&&(e=!0,n=Date.now(),Xt(C.workspace).then(async s=>{if(Ee.tool_inventory=s,!rr&&Yr(s))try{await(await Rr(await br(C.workspace))).close(),rr=!0}catch{rr=!1}Ee.bug_hunt_browser=Yr(s)&&rr,Ut(),Wc(nf)}).catch(s=>Hc(nf,s)).finally(()=>{e=!1}))};o(),ff=setInterval(o,1e4),sH()}async function lH(){if(!(!hk||C.agent_protocol!=="acp"||!C.agent_id||lf||xn?.state==="checking"||Date.now()-ZE<VB)){lf=!0;try{if(!await pi())return;ZE=Date.now();let e,t=await M_(C,{verify:async r=>{e=await Ds(r,C.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===C||St)return;C={...t,execution_profiles:e.executionProfiles??null},await gn(C),Ue=e;let n=Ec(C,Ue,Ee.tool_inventory);if(Object.assign(Ee,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),eo.capabilities=Ee,!await pi())return;await As(),lt?.readyState===WebSocket.OPEN&&lt.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{lf=!1}}}function Hc(e,t){let n=Wb(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 Wc(e){qb(e.id)&&console.log(`${e.title} recovered.`)}async function uH(){if(C.hunt_host||!await pi())return;pk=Date.now();let{jobs:e}=await _r(C.workspace).catch(()=>({jobs:[]})),t=await Sy(C.workspace,{jobs:e});if(!Ey(t))return;let n=`${t.fingerprint}:${cf.join(",")}`,r=af?.key===n,o=r?af.candidates:await K0(C,t,cf);af={key:n,candidates:o};let s=await Ho(xy(t,o,{version:Tr}));Array.isArray(s?.refused)&&(cf=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 xr=null,ok=null;async function vk(){if(!C.hunt_host){if(Pn)return Pn;Pn=(async()=>{let e=await fy(C,{knownRevision:xr?.revision??null});if(e.unchanged||(xr=e),ok===xr.revision)return xr;let{jobs:t}=await _r(C.workspace);return!t.some(r=>Yc.includes(r.status))&&Ar===0&&kt.size===0&&(await Ra(C.workspace,xr),ok=xr.revision),xr})();try{return await Pn}finally{Pn=null,hi()}}}function sk(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)),bt.get(e)?.events.push(n)}var ik=null;function hi(){let e=lt.readyState===WebSocket.OPEN,t=kt.values().next().value,n=Kn(C.worker_limit)??Math.min(xo(),Kd(t?.workerLimit??Go[0]?.worker_limit)),r=e&&!Pn&&Ar===0?C0(Go,kt.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:Kd(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};kt.set(i,a),fH(s,a)}r.length>0&&Ut();let o=O0({queued:Go,running:kt.size,workerLimit:n,connected:e,designSync:!!Pn,integrations:Ar});o&&o!==ik&&console.log(o),ik=o}function tl(e){let t=Yd(e);return t?`${Ue.name} on ${t}`:Ue.name}async function bk(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:ab(Ho),executionRevision:Sk(e),sessionKey:cc(e),sessionId:null,replacement:null};bt.set(t,s);let i,a=g=>{let y=g?JSON.stringify(g):null;!y||y===i||bt.get(t)!==s||(i=y,sk(t,g))},c=`${r} \xB7 ${tl(e)}`,l=B0(e,Ue.name);sk(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?[al(d,o)]:[]].join(" ")),ut.status(n,c,o,{link:ui,answerBy:d});let p=g=>{let y=A0(g),w=Hr(g);bt.get(t)===s&&wf(n,w??y?.message);let E=g.type==="forge.output"?null:w;a(y??(E?{kind:"status",message:E}:null))},f="failed",h=[r];try{lc(e)||(p({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await yy(vk,{pinned:!!e.local_design_context,last:xr,onFallback:(E,v)=>p({type:"connector.step",message:`Design context not refreshed (${E.message}); continuing with ${v?"the copy synced earlier":"none"}`})})});let g=await b0(e,C,{onProcess:E=>{bt.get(t)===s&&(s.child=E)},onController:E=>{bt.get(t)===s&&(s.controller=E)},onSession:E=>{s.sessionId=E},onEvent:p},{signal:s.cancellation.signal});if(s.stoppedHere)throw new Error(ak);let y=g.singleTurn?Th(C.sessions,g.sessionKey):Nl(C.sessions,g.sessionKey,g.sessionId);if(JSON.stringify(y)!==JSON.stringify(C.sessions||{})&&(C={...C,sessions:y},await gn(C)),s.cancelled)return;await s.events.close().catch(E=>{console.error(`[${n}] Prompt progress delivery: ${E.message} The agent has finished; submitting its complete response separately.`)});let w=await dc(Ho,{type:"prompt.completed",prompt_id:t,execution_revision:s.executionRevision,content:g.content,model:g.model,session_id:g.sessionId,usage:g.usage});w||console.error(`[${n}] ${tp}`),ci.record("prompt","completed",{durationMs:Date.now()-o,usage:g.usage}),f=w?"finished":"undelivered",h=[yi(g.usage),r]}catch(g){let y=s.stoppedHere?ak:Rt(g);if(ci.record("prompt","failed",{durationMs:Date.now()-o}),s.stoppedHere&&(f="cancelled"),!s.cancelled){try{await dc(Ho,{type:"prompt.failed",prompt_id:t,execution_revision:s.executionRevision,message:y})||console.error(`[${n}] ${tp}`)}catch(w){console.error(`[${n}] Prompt failure delivery: ${w.message}`)}console.error(y)}}finally{s.events.stop();let g=s.replacement;g?(f="replaced",h=[`continuing on ${tl(g)}`,r]):s.cancelled&&(f="cancelled"),ut.finish(n,f,h),bt.get(t)===s&&bt.delete(t),g&&pH(s,g)}}var ak="Cancelled from the connector terminal by the person running it.";async function yf(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function Sk(e){return Number(e.execution_revision)||1}async function dH(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 ${tl(t)}.`),await yf(e))}function pH(e,t){e.sessionId&&(C={...C,sessions:Nl(C.sessions,e.sessionKey,e.sessionId)},gn(C).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),bk(t)}async function fH(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 ${tl(e)}.`),!sf.has(n)){sf.add(n);try{let _=await k0(C.workspace);if(!_.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let S=_.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). ${S}`)}}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,g=()=>!St&&kt.get(t.key)===t,y=async _=>{try{return await dc(Ho,_)||console.warn(`[${s}] ${sb}`),!0}catch(S){return console.error(`Assessment failure delivery: ${S.message}`),!1}},w=(_,{milestone:S=!0}={})=>{if(!g()||S&&f===_)return;S&&(f=_,h.has(_)||(h.add(_),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${_}.`));let m=String(_).slice(0,500);t.progressPercent=c,t.lastMessage=m,ut.status(s,m,o,{link:ui})};w(`Starting ${r} assessment stage`);let E=setInterval(()=>{let _=Date.now(),S=_-t.lastActivityAt,m=i&&!a?x0(r,S):null;if(!d&&m){d=m,console.error(`[assessment:${r}] ${d}`),uc(t.controller,t.child);return}d||sr.observe({at:_,level:"info",message:ut.status(s,`${t.lastMessage} \xB7 last agent activity ${je(S)} ago (${t.eventCount.toLocaleString()} events)`,o)})},15e3),v={onSession:async _=>{g()&&(p=String(_),await ig(C.workspace,n,r,_,{sourceRevision:e.source_revision,targetHeadRevision:e.target_head_revision}))},onController:_=>{g()&&(t.controller=_)},onProcess:_=>{g()&&(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 S=$0(_);if(S&&w(S),!g())return;let m=Hr(_);!m||m===t.lastDetail||(t.lastDetail=m,wf(s,m))}},b=(_,S)=>Vd(_,S,C,v,{draftPath:xt.relative(C.workspace,xt.join(Ht(C.workspace,n),_.report_file)).split(xt.sep).join("/")});try{let _=of-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 S=await dg(C.workspace,e),m=await su(C.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(m)b(m,S),w("Recovered completed stage report from connector storage");else{if(p=await ag(C.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),p&&w("Restoring interrupted agent session"),m=await v0(S,C,v,{previousSessionId:p}),d)throw new Error(d);a=!0,await ou(C.workspace,n,S,m)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let $=T=>fetch(Oh(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(s0)}),A=await G0(m,{submit:T=>z0(T,$,{isActive:()=>g()&&!St,onRetry:(N,M)=>{w("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${Rt(N)} Retrying in ${Math.round(M/1e3)}s without rerunning the agent.`)}}),payloadFor:T=>r==="synthesis"?iu(C.workspace,n,T,{expectedSourceRevision:e.source_revision}):mg(T),rejectionFor:T=>fa(T,"the assessment"),correct:async(T,N)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!T.correctAfterRejection)throw new Error(`${N} The connector could not start the required agent correction.`);return T.correctAfterRejection(N)},onCorrected:async T=>{if(d)throw new Error(d);a=!0,await lg(C.workspace,n,r);let N=await ou(C.workspace,n,S,T);return b(N,S),t.phase="delivering",t.lastMessage="Delivering corrected stage result",N}});if(d)throw new Error(d);m=A.result;let R=A.response;if(!R.ok)throw new Error(await fa(R,"the assessment"));if(l=!0,ci.record("assessment stage","completed",{durationMs:Date.now()-o,usage:m.usage}),r==="synthesis"){let T=await R.json(),N=await pg(C.workspace,n,e,m,T.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${xt.relative(C.workspace,N)}.`);try{let M=await Ei(C.workspace);M.committed&&console.log(`Assessment committed to Git as ${M.revision.slice(0,8)}.`)}catch(M){console.error(`The assessment is saved locally but could not be committed to Git: ${M.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch(_){let S=d||Rt(_),m=M0(e,_),$=D0(_),x=j0(_);$&&(await cg(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||$)&&($||I0(_))&&m<x;if(g()&&A){t.phase="starting",t.lastMessage=$?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=P0(e,_);let R=L0(_,m);Fs(_)&&(of=Math.max(of,Date.now()+R)),console.warn(`[assessment:${r}] ${$?"Agent session became unusable":"Agent session interrupted"}: ${S} ${$?"Starting a fresh session from the saved draft":`Resuming session ${p}`} in ${Math.round(R/1e3)}s (${m+1}/${x}).`),await new Promise(T=>setTimeout(T,R))}else g()&&(u=await y({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:S}));A||(ci.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${S}`))}finally{clearInterval(E),ut.clearStatus(s),r==="synthesis"&&l&&sf.delete(n),g()&&(kt.delete(t.key),U0(Go,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),hi())}}async function hH(e){let t=String(e.run_id||"");Ar+=1;try{Pn&&await Pn;let n=await p0(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 el();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: ${Rt(n)}`)}finally{Ar-=1,hi()}}function mH(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.6",
3
+ "version": "1.56.7",
4
4
  "description": "Connect a local coding agent to EngineerOS, using ACP when supported.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",