@engineeros/connector 1.59.5 → 1.59.6
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.
|
@@ -1104,7 +1104,7 @@ It is checked with the provider and stored in this machine's protected vault
|
|
|
1104
1104
|
(Windows Data Protection, the macOS Keychain or the Linux Secret Service).
|
|
1105
1105
|
EngineerOS never receives it; the running connector uses it when EngineerOS asks.`;function IK(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(`
|
|
1106
1106
|
`),c?o(c):r(s.trim())},a=c=>{for(let l of c){if(l==="\r"||l===`
|
|
1107
|
-
`)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 rC=Symbol("missing");function jK(e,t){return new Promise(n=>{let r=CK(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?rC:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function nC(e,t){for(let n of $c){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 oC(e,t,n,{vault:r=fw(),run:o=zd,fetchImpl:s=fetch,secret:i=IK,interactive:a=jK,install:c=Fd,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(OK),n.help?0:2;if(e==="integrations")return nC(l,(await Hd({run:o,vault:r})).providers),0;let p=t[0];if(!$c.includes(p))return u(`Unknown provider ${p}. Choose one of: ${$c.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=hs[p];if(e==="disconnect")return l(`${p} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===rC){let m=await bi(f);if(!m){l(`Installing the ${bc[f].label} ${bc[f].version} for the connector...`);try{m=(await c(f)).path}catch(g){return u(g.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${Gd[p]} is how this machine signs in to ${p}.`),1):(nC(l,{[p]:(await Hd({run:o,vault:r})).providers[p]}),0)}let d=Qt[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await hw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await mw(r,p,{token:f,site:n.site,email:n.email},s);return l(`Connected ${d.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}I();import{spawn as NK}from"node:child_process";async function sC({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=NK,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=mo(await fn(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await MK(o,c.entry,i,t);if(l===Ji){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let p=await fn(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await Tp(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${d.version}.`);continue}catch(d){s(`Automatic rollback failed: ${d.message}`)}}return l??1}}function MK(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[bs]:"1",[kp]:r.entry,[$p]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,p)=>{l(),o({code:u,signal:p})})})}var Fo="1.59.
|
|
1107
|
+
`)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 rC=Symbol("missing");function jK(e,t){return new Promise(n=>{let r=CK(e,t,{stdio:"inherit",shell:!1});r.once("error",o=>n(o?.code==="ENOENT"?rC:o.message)),r.once("close",o=>n(o===0?null:`${e} exited with code ${o}.`))})}function nC(e,t){for(let n of $c){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 oC(e,t,n,{vault:r=fw(),run:o=zd,fetchImpl:s=fetch,secret:i=IK,interactive:a=jK,install:c=Fd,log:l=console.log,error:u=console.error}={}){if(n.help||e!=="integrations"&&!t[0])return l(OK),n.help?0:2;if(e==="integrations")return nC(l,(await Hd({run:o,vault:r})).providers),0;let p=t[0];if(!$c.includes(p))return u(`Unknown provider ${p}. Choose one of: ${$c.join(", ")}.`),2;if(p==="github"||p==="gitlab"){let f=hs[p];if(e==="disconnect")return l(`${p} uses this machine's ${f} sign-in. Run \`${f} auth logout\` to sign out everywhere on this machine.`),0;let h=await a(f,["auth","login"]);if(h===rC){let m=await bi(f);if(!m){l(`Installing the ${bc[f].label} ${bc[f].version} for the connector...`);try{m=(await c(f)).path}catch(g){return u(g.message),1}}h=await a(m,["auth","login"])}return h?(u(`${h} ${Gd[p]} is how this machine signs in to ${p}.`),1):(nC(l,{[p]:(await Hd({run:o,vault:r})).providers[p]}),0)}let d=Qt[p];if(e==="disconnect")return await r.delete("",p),l(`Removed the ${d.label} ${d.tokenName} from this machine.`),0;try{await hw(r);let f=await i(`${d.label} ${d.tokenName} (create one at ${d.tokenUrl}): `),h=await mw(r,p,{token:f,site:n.site,email:n.email},s);return l(`Connected ${d.label}${h.account?` as ${h.account}`:""}. The token stays on this machine.`),0}catch(f){return u(f.message),1}}I();import{spawn as NK}from"node:child_process";async function sC({root:e,bundled:t,argv:n,workspace:r,spawnImpl:o=NK,log:s=console.log}){let i=n,a=!1;for(;;){let c=t;try{c=mo(await fn(e),t)}catch(p){s(`${p.message} Starting the installed connector ${t.version}.`)}let{code:l,signal:u}=await MK(o,c.entry,i,t);if(l===Ji){i=["start","--workspace",r],a=!1,s("Restarting the connector process on the activated update. Goal runs continue in their own processes.");continue}if(l!==0&&!u&&!a){let p=await fn(e).catch(()=>null);if(p&&!p.confirmed&&p.active?.version===c.version)try{let d=await Tp(e,{version:c.version,entry:c.entry,bundled:t},{automatic:!0,reason:`${c.version} exited with code ${l} before connecting to EngineerOS.`});a=!0,s(`Connector ${c.version} stopped before connecting; rolled back to ${d.version}.`);continue}catch(d){s(`Automatic rollback failed: ${d.message}`)}}return l??1}}function MK(e,t,n,r){return new Promise((o,s)=>{let i=e(process.execPath,[...process.execArgv,t,...n],{stdio:"inherit",env:{...process.env,[bs]:"1",[kp]:r.entry,[$p]:r.version}}),a=process.platform==="win32"?[]:["SIGINT","SIGTERM","SIGHUP"],c=u=>i.kill(u);for(let u of a)process.on(u,c);let l=()=>{for(let u of a)process.off(u,c)};i.once("error",u=>{l(),s(u)}),i.once("exit",(u,p)=>{l(),o({code:u,signal:p})})})}var Fo="1.59.6",Yd="1.59.6",UK=3e5,Zd=["queued","running","reporting"],FK=5e3,gw={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."},ww={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."},zK=6e4,BK=3e4,GK=60*6e4,yw={id:"tool_inventory",title:"Tool inventory refresh",remedy:"Run `engineeros-connector tools list` in this workspace for the full registry state."},_w={id:"runner_setup_reporting",title:"Goal runner setup reporting",remedy:"Restore the connection to EngineerOS; saved setup reports will retry automatically."},{command:vt,positional:Ut,flags:Le}=FA(process.argv.slice(2));vt==="version"&&(console.log(Fo),process.exit(0));var io=null,nn=!1,yr=null,bC=!1,SC=null,Ow=null,Ft=null,Oc=null,Tw,iC,aC,vw,cC,$i,xi,kC=Ad({getWorkspace:()=>M.workspace,onRecorded:e=>C1(M,e).then(()=>console.log(`Recorded the ${e.role} sign-in for Bug Hunter; it is kept on this machine.`)).catch(t=>console.error(`The recorded ${e.role} sign-in was not reported to EngineerOS: ${t.message}`))}),HK=eC({getWorkspace:()=>M.workspace,huntSignIns:kC}),Ac=HA();vt==="results"&&(Ut[0]!=="upload"&&(console.log(_d),process.exit(Le.help||!Ut[0]?0:2)),process.exit(await XT(Le)));(vt==="connect"||vt==="disconnect"||vt==="integrations")&&process.exit(await oC(vt,Ut,Le,{fetchImpl:YR}));if(vt==="runner"){let e=tn.resolve(Le.workspace||process.cwd()),t=Ut[0]||"status";try{if(t==="serve"||t==="worker"){let n=t==="worker"?tn.join(tn.dirname($t(e,Le["run-id"])),"worker.log"):tn.join(e,".engineeros","runner","service.log");LK(tn.dirname(n),{recursive:!0});let r=(...s)=>Xa(n,`${DK(...s)}
|
|
1108
1108
|
`),o=(s,i,a)=>(Xa(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(Le["keep-awake"]!==void 0){if(!["on","off"].includes(Le["keep-awake"]))throw new Error("Use --keep-awake on or off.");let n=await Xt(e);if(!n)throw new Error("Pair this workspace before changing its runner keep-awake setting.");await zn({...n,runner_keep_awake:Le["keep-awake"]==="on"})}console.log(`Installed Goal runner service: ${await Xu(e)}`),process.platform==="darwin"&&console.log("macOS may show a Background Items Added notice. Manage the runner in System Settings > General > Login Items.")}else t==="uninstall"?(await kx(e),console.log("Goal runner service removed. Saved and queued jobs are kept.")):t==="start"?await ci(e,{enable:!0}):t==="status"?console.log(JSON.stringify(await Co(e),null,2)):t==="serve"?await Ax(e):t==="worker"?await Tx(e,Le["run-id"]):ut("Usage: engineeros-connector runner [install|start|status|uninstall] --workspace PATH [--keep-awake on|off]");process.exit(0)}catch(n){ut(Gm(n,e).message)}}Le["assessment-workers"]!==void 0&&ut("--assessment-workers is no longer supported. Select 3 to 8 parallel agents in EngineerOS before starting the assessment.");if(vt==="secret")try{let e=Wm(Le),t=Ut[0]||"list",n=await UA({action:t,name:Ut[1],workspace:e,readValue:()=>DA({label:`Value for ${Ut[1]}`}),write:r=>console.log(r)});process.exit(n.ok?0:1)}catch(e){ut(e.message)}if(vt==="tools"){try{let e=Wm(Le),t=Ut[0]||"list";if(["sign-in","auth-status","sign-out"].includes(t)){let r=Ut[1];r||ut(`Usage: engineeros-connector tools ${t} PROVIDER_ID [--workspace PATH | --project PROJECT_UUID]`);let o=await jh(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 Ia(e,{type:"tools.update",command_id:"00000000-0000-4000-8000-000000000002",action:t,provider_id:Ut[1],confirmed:!0},void 0,{confirmLocal:async()=>!0}):t!=="list"&&await Ch(e,t,Ut[1]);let n=await Dn(e);console.log(JSON.stringify(n,null,2)),process.exitCode=n.error?1:0}catch(e){ut(e.message)}process.exit(process.exitCode||0)}if(vt==="agents"){let e;try{e=await Jh()}catch(n){ut(n instanceof Error?n.message:String(n))}let t=await Promise.all(e.map(async n=>{try{return await Na(n.id),`${n.id}: ready (${n.name} ${n.version}, ${n.distribution_type})`}catch(r){let o=r instanceof Error?r.message:String(r);return`${n.id}: setup needed (${n.name} ${n.version}, ${n.distribution_type}) - ${o}`}}));for(let n of t)console.log(n);process.exit(0)}if(vt==="agent"){let e=Ut[0],t=Ut[1]||"check";(!e||!["check","install"].includes(t))&&ut("Usage: engineeros-connector agent AGENT_ID [check|install]");try{let n=t==="install"?await Ma(e):await Na(e);console.log(`${n.name} is ready (${n.version}, ${n.distribution}).`)}catch(n){ut(n instanceof Error?n.message:String(n))}process.exit(0)}if(vt==="mcp"){let e=Le.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=Le["run-id"]||Ut[0]||process.env.ENGINEEROS_MCP_RUN_ID||null,n=await Xt(e);await oT({config:n,runId:t,version:Fo,input:process.stdin,output:process.stdout}),process.exit(0)}if(vt==="context-mcp"){let e=Le["config-workspace"]||Le.workspace||process.env.ENGINEEROS_MCP_WORKSPACE||process.cwd(),t=await Xt(e);t||ut("This workspace is not paired with EngineerOS."),await DT({config:t,workspace:Le.workspace||process.env.ENGINEEROS_CONTEXT_WORKSPACE||t.workspace,version:Fo,input:process.stdin,output:process.stdout}),process.exit(0)}if(vt==="status"){let e=await Xt(Le.workspace||process.cwd());console.log(e?`Paired as ${e.name} (${e.connector_id}) for ${e.workspace}`:"Not paired"),process.exit(e?0:1)}if(vt==="doctor"){let e=tn.resolve(Le.workspace||process.cwd()),t=await Xt(e),n=await QA(e),r=await ji(t||{workspace:e},e,bg(n));console.log(gg(r)),process.exit(r.status==="failed"?1:0)}if(vt==="update"){let e=Ut[0]||"status";try{let t=xp(process.argv[1],Yd),n=await Rp(Lr(),t,{action:e,policy:Ut[1]??null});console.log(Yi(Cp(n,t,{supervised:!0})))}catch(t){ut(`${t.message}
|
|
1109
1109
|
Usage: engineeros-connector update [status|check|apply|rollback|policy manual|approve|auto-patch|auto-minor]`)}process.exit(0)}var Ai=vt==="hunt-host";if(Ai)try{Le.workspace=Ix(Ut,Le)}catch(e){ut(e.message)}if((vt==="start"||vt==="pair"||Ai)&&process.env[bs]!=="1"&&Ot(Yd))try{process.exit(await sC({root:Lr(),bundled:{version:Yd,entry:tn.resolve(process.argv[1])},argv:process.argv.slice(2),workspace:tn.resolve(Le.workspace||process.cwd())}))}catch(e){ut(`The connector process could not be started: ${e.message}`)}if(Ai){try{await jx(Le.workspace,Ut[0]?Le.agent:null)}catch(e){ut(e.message)}vt=Ut[0]?"pair":"start"}var M,gs,Tc;if(vt==="pair"){let e=Ut[0];e||ut("Usage: engineeros-connector pair CODE --url URL [--agent AGENT_ID | --agent-protocol forge] [--name NAME] [--workspace PATH] [--skip-git-repo-check]");let t=Le.url;t||ut("Pairing requires --url with the EngineerOS backend address."),Le.agent&&Le["agent-command"]&&ut("Use either --agent or --agent-command, not both.");let n=Le["agent-protocol"]||(Le["agent-command"]?"acp":"codex");["codex","acp","forge"].includes(n)||ut(`Unknown --agent-protocol '${n}'. Use codex, acp, or forge.`),n==="forge"&&(Le.agent||Le["agent-command"])&&ut("Forge runs its own agents. Drop --agent and --agent-command when pairing with --agent-protocol forge.");let r={};try{Le.agent&&(await Na(Le.agent),r=await Kh(Le.agent))}catch(o){ut(o instanceof Error?o.message:String(o))}M={server_url:Np(t),workspace:tn.resolve(Le.workspace||process.cwd()),onboard:Le.onboard===!0,onboarding_pending:Le.onboard===!0,hunt_host:Ai,agent_protocol:n,agent_command:Le["agent-command"]||null,agent_args:hY(Le["agent-args"]),agent_name:Le["agent-name"]||null,...r,skip_git_repo_check:Ai||Le["skip-git-repo-check"]===!0,name:Le.name||`${PK.hostname()} - ${tn.basename(tn.resolve(Le.workspace||process.cwd()))}`},Tc=await Xt(M.workspace),gs={type:"pair",pairing_code:e,name:M.name,capabilities:{},...Gy(Tc,M.server_url)}}else vt==="start"?(M=await Xt(Le.workspace||process.cwd()),M||ut("This connector is not paired. Create a pairing command in EngineerOS first."),Ai&&!M.hunt_host&&ut("This folder is not a paired hunt host. Generate a new hunt-host command in EngineerOS."),M.token||ut("This connector's token is no longer in this machine's credential store. Create a new pairing command in EngineerOS and pair again."),gs={type:"authenticate",connector_id:M.connector_id,token:M.token}):ut("Use `engineeros-connector pair`, `start`, `status`, `doctor`, `agents`, `agent`, `tools`, `secret`, or `mcp`.");var $C=Rx(M,{reportError:e=>console.error(e)}),Uo=0,Qd=!1,Rc=null,rn=new Map,bw=0,Sw=new Set,Ti=[],en=new Map,jt,Rw,Vd,Ir=null,Xd=!1,EC=0,kw=null,$w=[],Jd,xC,Ec=1e3,Ri,lC=0,Ew=!1,ro=!1,Zn,Do=!1,ep=!1,Cw=0;function ki(e){return Cw+=1,e.finally(()=>{Cw-=1})}var Ei,ms=0;function Cc({exitCode:e=0}={}){if(ms=Math.max(ms,e),Ei)return Ei;let t=setTimeout(()=>{console.error("Connector shutdown exceeded 15 seconds; inspect the retained agent logs before restarting."),process.exit(1)},15e3);return t.unref(),Ei=WK().finally(()=>clearTimeout(t)),Ei}async function WK(){if(nn=!0,Oc?.stop(),io?.stop(),Ow?.stop(),SC?.stop(),clearInterval(Tw),Ft?.stop(),xC?.(),clearTimeout(Jd),clearInterval(Rw),clearInterval(Vd),await Promise.all([...[...rn.values()].map(e=>mn(e.child))]),await Promise.all([...en.values()].map(Nw)),await $i?.cancelAll(),await xi?.abortAll(),await ja(),await Gw().catch(e=>{ms=Math.max(ms,1),console.error(`${e.message}. Stop those processes before restarting the connector.`)}),jt?.close(),ms&&ms!==Ji){let e;await Promise.race([(async()=>{await io?.drain(),await ji(M,M.workspace)})().catch(()=>{}),new Promise(t=>{e=setTimeout(t,1e4)})]).finally(()=>clearTimeout(e))}process.exit(ms)}for(let e of["SIGINT","SIGTERM","SIGHUP"])process.on(e,()=>{Cc()});var uC=!1;for(let e of["uncaughtException","unhandledRejection"])process.on(e,async t=>{uC||(uC=!0,console.error(`Connector stopping after an unhandled failure: ${t instanceof Error?t.stack||t.message:String(t)}`),await Cc({exitCode:1}))});Ft=Kw();process.on("exit",()=>{Oc?.stop(),Ft.stop()});Ft.banner(`EngineerOS connector ${Fo}`,[M.workspace,M.server_url]);io=GA({actions:{refresh_tool_inventory:async()=>{ze.tool_inventory=await Dn(M.workspace),Tn()},restart_goal_runner:()=>ci(M.workspace)},onNotify:()=>ji(M,M.workspace),explain:async e=>{if(!await Ii())return null;let{reading:t}=await QE(M,e);return t},onUpdate:e=>ZA(M.workspace,e)});SC=tT({render:(e,t)=>Ft.write(e,t),onRecord:e=>io.observe(e)});Ow=nT({workspace:M.workspace,onRecord:e=>{io.observe(e),Ft.line(e.channel,e.level,e.message)}});io.start();M.hunt_host||Ow.start();Ft.live&&!M.hunt_host&&(Tw=setInterval(()=>{qK().catch(()=>{})},FK),Tw.unref?.());var xw=new Set;async function qK(){if(M.hunt_host)return;iC??=Fm(M.workspace);let{jobs:e}=await iC(),t=new Set,n=e.filter(r=>r.status!=="queued"&&Zd.includes(r.status)).length;for(let r of e){if(!Zd.includes(r.status))continue;t.add(r.runId),xw.add(r.runId);let o=r.status==="queued"&&n>0?`queued behind running Goals (running: ${n})`:r.activity?.phase||r.status;Ft.status(`goal:${r.runId}`,o,VK(r),{agent:r.status!=="queued",link:Rc&&`${Rc}/goals`}),Ft.step(`goal:${r.runId}`,r.activity?.message)}for(let r of xw)t.has(r)||(xw.delete(r),Ft.clearStatus(`goal:${r}`))}function VK(e){let t=e.startedAt??Date.parse(e.updatedAt??"");return Number.isFinite(t)?t:Date.now()}async function Ii({ignoreBugHunt:e=!1}={}){if(nn||rn.size>0||en.size>0||Uo>0||($i?.active??0)>0||!e&&(xi?.active??0)>0)return!1;try{let{jobs:t}=await Co(M.workspace);return!nn&&!t.some(n=>Zd.includes(n.status))}catch{return!1}}try{let e=M.hunt_host?{}:await _s(M.workspace);e.committed&&(M.onboarding_pending=!0,M.connector_id&&await zn(M),console.log(`Local project repository ready at ${e.revision.slice(0,8)}. Source and design artifacts are committed locally.`))}catch(e){await OC(e)}var AC=await fn(Lr()).then(e=>e.policy!=="manual",()=>!1),rt;try{rt=await Wa(M,M.workspace)}catch(e){await OC(e)}console.log(`Using ${rt.name} through ${rt.protocol} (${rt.version}).`);var TC=async()=>ac({workspace:M.workspace}).names().catch(()=>[]),ze=ud(M,rt,await Dn(M.workspace),{secretNames:await TC()}),so=Cy({running:xp(process.argv[1],Yd),supervised:process.env[bs]==="1",isIdle:async()=>!nn&&rn.size===0&&Ti.length===0&&en.size===0&&Uo===0&&Cw===0&&!Do&&!ep&&!Xd,restart:()=>Cc({exitCode:Ji}),onChange:e=>{ze.runtime_update=e,jt?.readyState===WebSocket.OPEN&&Tn()}});try{await so.refresh()}catch(e){console.error(`Connector updates are unavailable: ${e.message}`)}M={...M,execution_profiles:rt.executionProfiles??null};vt==="pair"&&Tc?.connector_id||await zn(M);ze.agent_session={...ze.agent_session,status:"checking",message:`Checking that ${rt.name} can answer.`};ze.bug_hunt_browser=!1;gs.capabilities=ze;console.log(Kr(M.worker_limit)===null?`Workers: automatic, ${ti()} ${rt.name} workers side by side for this machine's CPU and memory; change it with /workers.`:`Workers: ${Kr(M.worker_limit)} ${rt.name} workers side by side, set with /workers.`);var Ci=e=>Yr(M,e),dC=Hu(Ci,{signature:cx});async function XK(){let e=await Co(M.workspace).catch(()=>({service:null,jobs:[]}));return{version:Fo,now:Date.now(),workspace:M.workspace,config_path:kn(M.workspace),config:M,agent:rt,automatic_worker_limit:ti(),worker_limit:Kr(M.worker_limit),connection:{state:JK(),server_url:M.server_url,last_error:Zn||null},work:{assessments:[...rn.values()].map(t=>({stage:t.stage,message:t.lastMessage,started_at:t.startedAt})),prompts:[...en.values()].map(t=>({id:String(t.runId).slice(0,8),purpose:t.purpose,started_at:t.startedAt})),integrations:Uo},runner:e,runtime_update:so.report(),health:io?.health()??null,activity:Ac.snapshot()}}function JK(){return nn||ro?"stopped":jt?.readyState===WebSocket.OPEN?"connected":"connecting"}var KK={async cancelPrompt(e){let t=[...en.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=>CC(e),setVerbose(e){return e===Qd?`Detailed agent activity is already ${e?"on":"off"}.`:(Iw(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"?(so.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 so.command(e),Yi(await so.refresh()))}};Oc=XA({ui:Ft,snapshot:XK,actions:KK});Oc&&console.log(VA());await RC();var pC=new Set;async function RC(){if(nn||ro)return;console.log(`Connecting ${M.name} to ${M.server_url}`),ro=!1,Zn=void 0;let e=new WebSocket(M.server_url);jt=e;let t=Vv(e,M.server_url,{onTimeout:r=>{jt===e&&(Zn=r,console.error(r),Aw())}});xC=t,e.addEventListener("open",()=>{if(jt!==e){e.close();return}try{if(zv(jt,e,gs))return;throw new Error("The WebSocket was not open when authentication started.")}catch(r){Zn=an(r),console.error(`Could not authenticate the WebSocket connection: ${Zn}`);try{e.close()}catch{}Aw()}}),e.addEventListener("message",r=>{if(jt!==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: ${an(s)}`)})});let n=async r=>{if(r.type==="authenticated"&&r.connector?.capabilities?.http_updates!==!0){nn=!0,ro=!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=Tc?.connector_id===r.connector.id;if(M=Hy(M,Tc,r.connector.id,r.token),await zn(M),r.connector?.capabilities?.http_updates!==!0){nn=!0,ro=!0,console.error("Pairing saved. Update the EngineerOS backend for HTTP updates, then start this connector again."),e.close();return}gs={type:"authenticate",connector_id:M.connector_id,token:M.token,capabilities:ze},console.log(s?`Reconnected existing workspace connector ${M.connector_id}; assessment history is preserved.`:`Paired. Connector ${M.connector_id} is online.`),gC(r);return}if(r.type==="authenticated"){t();let s=M.hunt_host?"Bug Hunter sessions":"EngineerOS runs";console.log(Ri?`Reconnected after ${Ke(Date.now()-Ri)} offline; waiting for ${s}.`:`Connected and waiting for ${s}.`),Ri=void 0,gC(r);return}if(r.type==="provider.login"||r.type==="provider.logout"){ep||ZK(r);return}if(r.type==="workspace.refresh"){Oi();return}if(r.type==="workers.update"){try{console.log(`EngineerOS changed the workers. ${await CC(r.worker_limit??"auto")}`)}catch(s){console.error(`Workers were not changed: ${s.message}`)}return}if(r.type==="logging.update"){Iw(r.activity_log_enabled===!0);return}if(r.type==="tools.update"){let s=r.provider_id==="playwright"&&["setup","upgrade","rollback"].includes(r.action);s&&(oo=!1,ze.bug_hunt_browser=!1,Tn());try{ze.tool_inventory=await Ia(M.workspace,r,void 0,{confirmLocal:i=>Oc?.confirm(i)??!1,log:Kd}),s&&(oo=!0),ze.bug_hunt_browser=fs(ze.tool_inventory)&&oo,e.send(JSON.stringify({type:"tools.updated",command_id:r.command_id,inventory:ze.tool_inventory})),Tn(),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 jh(M.workspace,r,{onStatus:async()=>{ze.tool_inventory=await Dn(M.workspace),Tn()}});ze.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:ze.tool_inventory})),Tn(),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"){js(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===QR){ki(HK(r).then(s=>(s.error&&console.error(`${r.provider} ${r.operation} failed: ${s.error}`),tC(M,s))).catch(s=>console.error(`An integration answer was not delivered: ${s.message}`)));return}if(r.type==="workspace.assessment"){let s=`${r.assessment_id}:${r.stage}`;Tm(Ti,rn.get(s),r)==="deferred"&&console.log(`Assessment stage ${r.stage} is already running here; EngineerOS will be answered when it finishes.`),Ic();return}if(r.type==="prompt.execute"){let s=en.get(r.prompt_id);s?PC(r)>s.executionRevision&&await uY(s,r):MC(r);return}if(r.type==="prompt.cancel"){let s=en.get(r.prompt_id);s&&await Nw(s);return}if(r.type==="agent.warm"){rY(r);return}if(r.type==="run.available"){if(M.hunt_host){console.error("A hunt host cannot run Goals. Use Connect your code to pair a repository connector.");return}try{let s=await $C.dispatch(r);s.blocked?console.error(s.message):console.log(`Goal ${r.run_id} queued for the independent runner. Logs: ${tn.join(M.workspace,".engineeros","runs",r.run_id,"activity.log")}`)}catch(s){console.error(`Goal dispatch failed: ${an(s)}`)}return}if(r.type==="goal.cleanup"){try{await xx(M.workspace),await ci(M.workspace)}catch(s){console.error(`Goal cleanup is pending: ${s.message}`)}return}if(r.type==="run.accepted"){fY(r);return}if(r.type==="run.cancelled"){await Um(M.workspace,r.run_id);return}if(r.type===Wb){$i??=dh({getConfig:()=>M,onTestsCommitted:()=>Oi()}),ki($i.handle(r));return}if(r.type===qb){$i??=dh({getConfig:()=>M,onTestsCommitted:()=>Oi()}),await $i.cancel(r);return}if(r.type===bR){xi??=xR({getConfig:()=>M,isIdle:()=>Ii({ignoreBugHunt:!0}),recordedSignIns:kC,activity:{status:Ft.status,step:jw,agents:Ft.agents,finish:Ft.finish}}),ki(xi.handle(r));return}if(r.type===SR){xi?.stop(r);return}if(r.type===JT){aC??=KT({getConfig:()=>M}),ki(aC.handle(r));return}if(r.type===n1){vw??=d1({getConfig:()=>M}),ki(vw.handle(r));return}if(r.type===r1){await vw?.cancel(r);return}if(r.type===f1){cC??=h1({getConfig:()=>M,isIdle:()=>Ii(),agentTurn:EE}),ki(cC.handle(r));return}if(r.type==="connector.update"){YK(e,r);return}if(r.type==="connector.disconnect"){console.log(r.message),await Cc();return}if(r.type==="connector.revoked"){nn=!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"){ro=!0,console.error(`EngineerOS: ${r.message}`);return}let o=String(r.type??"(missing)").replace(/[^a-zA-Z0-9_.-]/g,"_").slice(0,120);pC.has(o)||(pC.add(o),console.warn(`Unknown EngineerOS message type ${o}; connector ${Fo}. Update the connector and backend to compatible versions.`))};e.addEventListener("close",r=>{if(t(),jt!==e||Ei)return;let o=Bv(r);if(!o.retry||ro||nn){console.error(o.message),o.retry&&ro&&console.error("Connection rejected. Create a new pairing command in EngineerOS if this connector was revoked."),Cc();return}Zn=Zn?`${o.message} ${Zn}`:o.message,Aw()}),e.addEventListener("error",r=>{jt===e&&(Zn=Fv(r),console.error(`WebSocket connection to ${M.server_url} failed: ${Zn}`))})}async function YK(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=so.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 so.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 ZK(e){let t=e.request_id,n=e.type==="provider.logout"?"logout":"login";ep=!0,console.log(`Starting interactive ${rt.name} provider ${n}.`);try{await(n==="logout"?qv:Wv)(rt,M.workspace),rt=await Wa(M,M.workspace),ze=ud(M,rt,ze.tool_inventory,{secretNames:await TC()}),gs.capabilities=ze,jt.readyState===WebSocket.OPEN&&(jt.send(JSON.stringify({type:`provider.${n}.completed`,request_id:t,session:ze.agent_session})),jt.close(1e3,`Provider ${n} completed`)),console.log(`${rt.name} provider ${n} completed.`)}catch(r){let o=an(r).slice(0,500);jt.readyState===WebSocket.OPEN&&jt.send(JSON.stringify({type:`provider.${n}.failed`,request_id:t,message:o})),console.error(`Provider ${n} failed: ${o}`)}finally{ep=!1}}function Aw(){if(nn||ro||Jd)return;let e=Zn?` Last error: ${Zn}`:"",t=Ri?` Offline for ${Ke(Date.now()-Ri)}.`:"";Ri??=Date.now(),console.error(`Connection unavailable.${e}${t} Retrying in ${Math.round(Ec/1e3)}s.`),Jd=setTimeout(()=>{Jd=void 0,RC()},Ec),Ec=Math.min(3e4,Ec*2)}async function Oi(){if(!M.hunt_host&&!(Do||jt.readyState!==WebSocket.OPEN)){Do=!0,console.log("Inspecting the workspace without executing its code.");try{let{snapshot:e,map:t,stats:n}=await Tg({workspace:M.workspace,connectorId:M.connector_id,refresh:Ts,takeSnapshot:nx,buildMap:(i,a)=>gd(M.workspace,i,{head:a.head_revision,branch:a.branch}),log:i=>console.error(i)}),r=await tx(M.workspace,M.last_head_reported??M.last_snapshot_head,e.head_revision).catch(()=>null);r&&(e.changed_since=r);let o=await fetch(Ss(M.server_url,M.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:JSON.stringify(e)});if(!o.ok)throw new Error(await ya(o,"the workspace"));let s=await o.json();M={...M,onboarding_pending:!1,last_snapshot_head:e.head_revision??M.last_snapshot_head,last_head_reported:e.head_revision??M.last_head_reported,last_head_branch:e.head_revision?e.branch??null:M.last_head_branch},await zn(M),t&&await wd(M.workspace,M.connector_id,t).catch(()=>{}),console.log(`Inventoried ${e.total_file_count.toLocaleString()} safe file(s).`),console.log(`Uploaded ${e.evidence_file_count.toLocaleString()} prioritized source file(s).`),console.log(`Excluded ${e.excluded_file_count.toLocaleString()} sensitive or generated file(s).`),e.omitted_evidence_file_count>0&&console.log(`${e.omitted_evidence_file_count.toLocaleString()} additional file(s) remain available to the connected Agent locally.`),console.log(`Workspace inventory registered as ${s.workspace_kind}. Start the baseline assessment in EngineerOS to continue.`),n&&console.log(`Built the local context index: ${n.total_files.toLocaleString()} file(s) ready for assignment context.`),Do=!1}catch(e){Do=!1,console.error(`Workspace assessment failed: ${an(e)}`)}}}var QK=8e6,fC,hC="";async function eY({current:e,previous:t}){if(Do||jt?.readyState!==WebSocket.OPEN)throw new Error("A snapshot is running or the connection is down.");let n=tn.resolve(M.workspace),r=async()=>{M={...M,last_head_reported:e.head,last_head_branch:e.branch??null},await zn(M)},o=await Ag(M.workspace,M.connector_id),s=async()=>{if(await Oi(),M.last_head_reported!==e.head)throw new Error("The snapshot did not report this commit.")};if(!o)return s();let{index:i}=await Ts(M.workspace,M.connector_id),a=null,c=await AT({previous:{head:t.head,branch:t.branch??null},current:e,compare:(d,f)=>Im(M.workspace,d,f),inventoryDelta:d=>x_(n,Object.entries(i.files).map(([f,h])=>({path:f,size:h.size})),d),mapDelta:async()=>(a=await gd(M.workspace,i,{head:e.head,branch:e.branch}),xg(o,a)),contentHead:(await El(n).catch(()=>null))?.content_head_revision??null});if(c.status==="snapshot")return s();if(c.status==="nothing")return r();let l=JSON.stringify(c.report);if(Buffer.byteLength(l)>QK)return s();let u=await fetch(Vy(M.server_url,M.connector_id),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:l});if(!u.ok)throw new Error(await ya(u,"the new commit"));let p=await u.json().catch(()=>({}));if(p.needs_snapshot)return s();await r(),a&&await wd(M.workspace,M.connector_id,a).catch(()=>{}),console.log(`Reported ${c.report.reason==="branch_switch"?"the switch to ":"commit "}${e.head.slice(0,7)}${p.flagged_cases?`: ${p.flagged_cases} test case(s) to check again`:""}.`)}function tY(){M.hunt_host||M.onboarding_pending||Do||jt?.readyState!==WebSocket.OPEN||(fC??=xT({readHead:()=>ET(M.workspace),getLastReported:()=>({head:M.last_head_reported??M.last_snapshot_head,branch:M.last_head_branch}),onChange:eY,onError:e=>{e.message!==hC&&(hC=e.message,console.error(`The new commit could not be reported yet: ${an(e)}`))}}),fC.poll().catch(()=>{}))}var nY=6e4,mC=0;async function rY(e){if(M.hunt_host)return;let t=typeof e.session_key=="string"?e.session_key.trim():"",n=t?M.sessions?.[t]:void 0,r=[];Date.now()-mC>nY&&(mC=Date.now(),r.push(Ts(M.workspace,M.connector_id).catch(o=>console.error(`Context index refresh ahead of a conversation failed: ${o.message}`)))),M.agent_protocol==="acp"&&r.push(Sk(M.workspace,M,{sessionKey:n?t:null,previousSessionId:n,sandbox:e.sandbox_mode==="workspace-write"?"workspace-write":"read-only",profile:e.execution_profile&&typeof e.execution_profile=="object"?e.execution_profile:{}}).catch(o=>console.error(`${rt?.name||"The agent"} could not be started ahead of the conversation: ${o.message}`))),await Promise.all(r)}function Tn(){let e=GE(rn);dC.update({type:"assessment.workers",assessment_workers:e,tool_inventory:ze.tool_inventory,runtime_update:ze.runtime_update,agent_session:ze.agent_session,bug_hunt_browser:ze.bug_hunt_browser,...Fu(M.worker_limit)}),dC.flush().catch(t=>console.error(`Assessment status: ${t.message}`))}async function CC(e){let t=Kr(e);return t===Kr(M.worker_limit)?t===null?"Workers are already automatic.":`Workers are already set to ${t}.`:(M={...M,worker_limit:t},await zn(M),Ic(),Tn(),t===null?`Workers are automatic again: up to ${ti()} side by side for this machine's CPU and memory, for ${lc} (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: ${lc}. A Goal that uses your working folder still runs alone. Running work finishes; waiting work starts as workers free up.`)}function Iw(e){if(e!==Qd){if(Qd=e,!e)for(let t of rn.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."),Tn()}}function jw(e,t,n=null){Ft.step(e,t,n)&&Qd&&console.log(`[${e}] ${n?`${n}: `:""}${t}`)}function oY(){clearInterval(Vd);let e=!1,t=()=>{e||rn.size>0||en.size>0||(e=!0,ji(M,M.workspace).finally(()=>{e=!1}))};t(),Vd=setInterval(t,UK),Vd.unref?.()}async function ji(e,t,n=io?.healthChecks()??[]){let r=await OA({config:e,workspace:t,version:Fo,insights:n,agentSession:yr,probes:{inspectAgent:(o,s)=>nn?rt:Wa(o,s),inspectTools:o=>nn?ze.tool_inventory:Dn(o),runnerStatus:Co}});try{bC=(await IA(e,r,Yr))?.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 OC(e){if(nn)return Ei;let t=e instanceof Error?e.message:String(e),n=await ji(M,M.workspace).catch(()=>null);n&&console.error(gg(n)),ut(t)}function gC(e){Iw(e.connector?.activity_log_enabled===!0),Rc=e.project_url??null,Ec=1e3,iY(),jC(),so.confirm().catch(t=>console.error(`Connector update state: ${t.message}`)),aY(),M.onboarding_pending&&Oi()}var xc=null,oo=!1,IC=0,sY=Date.now();async function iY(){return xc||(xc=(async()=>{AC&&await ok(M.workspace,{log:t=>console.log(`[tools] ${t}`)}).catch(t=>console.error(`[tools] Tool updates were skipped: ${t.message}`));let e=Date.now();try{Kd("Preparing Bug Hunter's browser: Playwright, then a check that a browser starts. The first setup can take a few minutes."),await Nx(M.workspace,{log:Kd}),oo=!0,ze.tool_inventory=await Dn(M.workspace),ze.bug_hunt_browser=fs(ze.tool_inventory)&&oo,Kd(`Bug Hunter's browser is ready (${Ke(Date.now()-e)}).`)}catch(t){console.error(`[browser] Bug Hunter's browser setup failed after ${Ke(Date.now()-e)}: ${t.message}`),ze.bug_hunt_browser=!1}Tn()})(),xc)}function Kd(e){console.log(`[browser] ${e}`)}async function jC(){if(yr?.state!=="checking"){IC=Date.now(),ze.agent_session={...ze.agent_session,status:"checking",message:`Checking that ${rt.name} can answer.`},Tn(),yr={state:"checking",detail:`Asking ${rt.name} one question to confirm its session.`},console.log(`Checking that ${rt.name} can answer before accepting work.`);try{await XE(M,rt.name),yr={state:"ready",detail:`${rt.name} answered; its session is usable.`},ze.agent_session={...ze.agent_session,status:"authenticated",message:yr.detail},console.log(yr.detail)}catch(e){yr={state:"failed",detail:e instanceof Error?e.message:String(e),remedy:M.hunt_host?Px(M.agent_id||M.agent_protocol):Ks(M.agent_id||M.agent_protocol)},ze.agent_session={...ze.agent_session,status:"logged_out",message:yr.remedy},console.error(`${yr.detail}
|
|
1110
1110
|
${yr.remedy}`)}Tn(),await ji(M,M.workspace).catch(()=>null)}}function aY(){clearInterval(Rw);let e=!1,t=0,n=0,r=!1,o=()=>{so.tick(),cY(),tY(),M.hunt_host&&xc&&Date.now()-IC>=Mx(sY)&&en.size===0&&rn.size===0&&!(xi?.active>0)&&jC(),!M.hunt_host&&!r&&oc(_w.id)&&(r=!0,$C.flush().then(()=>qd(_w)).catch(s=>Wd(_w,s)).finally(()=>{r=!1})),rn.size>0&&Tn(),!M.hunt_host&&!Ir&&Date.now()-t>=zK&&oc(gw.id)&&(t=Date.now(),NC().then(()=>qd(gw)).catch(s=>Wd(gw,s))),!M.hunt_host&&bC&&!Xd&&oc(ww.id)&&Date.now()-EC>=gS&&(Xd=!0,lY().then(()=>qd(ww)).catch(s=>Wd(ww,s)).finally(()=>{Xd=!1})),!e&&Date.now()-n>=BK&&oc(yw.id)&&(e=!0,n=Date.now(),Dn(M.workspace).then(async s=>{if(ze.tool_inventory=s,!oo&&fs(s))try{await(await Wo(await jo(M.workspace))).close(),oo=!0}catch{oo=!1}ze.bug_hunt_browser=fs(s)&&oo,Tn(),qd(yw)}).catch(s=>Wd(yw,s)).finally(()=>{e=!1}))};o(),Rw=setInterval(o,1e4),oY()}async function cY(){if(!(!AC||M.agent_protocol!=="acp"||!M.agent_id||Ew||yr?.state==="checking"||Date.now()-lC<GK)){Ew=!0;try{if(!await Ii())return;lC=Date.now();let e,t=await Ck(M,{verify:async r=>{e=await Wa(r,M.workspace)},log:r=>console.log(`[agent] ${r}`)});if(t===M||nn)return;M={...t,execution_profiles:e.executionProfiles??null},await zn(M),rt=e;let n=ud(M,rt,ze.tool_inventory);if(Object.assign(ze,{agent_name:n.agent_name,agent_version:n.agent_version,execution_profiles:n.execution_profiles}),gs.capabilities=ze,!await Ii())return;await ja(),jt?.readyState===WebSocket.OPEN&&jt.close(1e3,"Coding agent updated")}catch(e){console.error(`[agent] The agent update check failed: ${e.message}`)}finally{Ew=!1}}}function Wd(e,t){let n=EA(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 qd(e){xA(e.id)&&console.log(`${e.title} recovered.`)}async function lY(){if(M.hunt_host||!await Ii())return;EC=Date.now();let{jobs:e}=await Co(M.workspace).catch(()=>({jobs:[]})),t=await wS(M.workspace,{jobs:e});if(!yS(t))return;let n=`${t.fingerprint}:${$w.join(",")}`,r=kw?.key===n,o=r?kw.candidates:await ex(M,t,$w);kw={key:n,candidates:o};let s=await Ci(bS(t,o,{version:Fo}));Array.isArray(s?.refused)&&($w=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 Lo=null,wC=null;async function NC(){if(!M.hunt_host){if(Ir)return Ir;Ir=(async()=>{let e=await cS(M,{knownRevision:Lo?.revision??null});if(e.unchanged||(Lo=e),wC===Lo.revision)return Lo;let{jobs:t}=await Co(M.workspace);return!t.some(r=>Zd.includes(r.status))&&Uo===0&&rn.size===0&&(await su(M.workspace,Lo),wC=Lo.revision),Lo})();try{return await Ir}finally{Ir=null,Ic()}}}function yC(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)),en.get(e)?.events.push(n)}var _C=null;function Ic(){let e=jt.readyState===WebSocket.OPEN,t=rn.values().next().value,n=Kr(M.worker_limit)??Math.min(ti(),Rm(t?.workerLimit??Ti[0]?.worker_limit)),r=e&&!Ir&&Uo===0?NE(Ti,rn.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:Rm(s.worker_limit),lastActivityAt:Date.now(),eventCount:0,lastDetail:null};rn.set(i,a),pY(s,a)}r.length>0&&Tn();let o=ME({queued:Ti,running:rn.size,workerLimit:n,connected:e,designSync:!!Ir,integrations:Uo});o&&o!==_C&&console.log(o),_C=o}function tp(e){let t=Cm(e);return t?`${rt.name} on ${t}`:rt.name}async function MC(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:dx(Ci),executionRevision:PC(e),sessionKey:zu(e),sessionId:null,replacement:null};en.set(t,s);let i,a=m=>{let g=m?JSON.stringify(m):null;!g||g===i||en.get(t)!==s||(i=g,yC(t,m))},c=`${r} \xB7 ${tp(e)}`,l=VE(e,rt.name);yC(t,{kind:"status",message:l});let u=Number(e.answer_within_seconds),p=u>0?o+u*1e3:void 0;console.log([`[${n}] ${l} for ${r}.`,`${rt.name} can reason for several minutes without reporting a step.`,...p?[cp(p,o)]:[]].join(" ")),Ft.status(n,c,o,{link:Rc,answerBy:p});let d=m=>{let g=OE(m),w=is(m);en.get(t)===s&&jw(n,w??g?.message);let v=m.type==="forge.output"?null:w;a(g??(v?{kind:"status",message:v}:null))},f="failed",h=[r];try{Bu(e)||(d({type:"connector.step",message:"Syncing the design context from EngineerOS"}),e={...e,design_context:await fS(NC,{pinned:!!e.local_design_context,last:Lo,onFallback:(v,_)=>d({type:"connector.step",message:`Design context not refreshed (${v.message}); continuing with ${_?"the copy synced earlier":"none"}`})})});let m=await $E(e,M,{onProcess:v=>{en.get(t)===s&&(s.child=v)},onController:v=>{en.get(t)===s&&(s.controller=v)},onSession:v=>{s.sessionId=v},onEvent:d},{signal:s.cancellation.signal});if(s.stoppedHere)throw new Error(vC);let g=m.singleTurn?Wy(M.sessions,m.sessionKey):Mp(M.sessions,m.sessionKey,m.sessionId);if(JSON.stringify(g)!==JSON.stringify(M.sessions||{})&&(M={...M,sessions:g},await zn(M)),s.cancelled)return;await s.events.close().catch(v=>{console.error(`[${n}] Prompt progress delivery: ${v.message} The agent has finished; submitting its complete response separately.`)});let w=await Gu(Ci,{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}] ${Mm}`),Ac.record("prompt","completed",{durationMs:Date.now()-o,usage:m.usage}),f=w?"finished":"undelivered",h=[Uc(m.usage),r]}catch(m){let g=s.stoppedHere?vC:an(m);if(Ac.record("prompt","failed",{durationMs:Date.now()-o}),s.stoppedHere&&(f="cancelled"),!s.cancelled){try{await Gu(Ci,{type:"prompt.failed",prompt_id:t,execution_revision:s.executionRevision,message:g})||console.error(`[${n}] ${Mm}`)}catch(w){console.error(`[${n}] Prompt failure delivery: ${w.message}`)}console.error(g)}}finally{s.events.stop();let m=s.replacement;m?(f="replaced",h=[`continuing on ${tp(m)}`,r]):s.cancelled&&(f="cancelled"),Ft.finish(n,f,h),en.get(t)===s&&en.delete(t),m&&dY(s,m)}}var vC="Cancelled from the connector terminal by the person running it.";async function Nw(e){e.cancelled=!0,e.cancellation.abort(),await e.controller?.completed.catch(()=>{})}function PC(e){return Number(e.execution_revision)||1}async function uY(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 ${tp(t)}.`),await Nw(e))}function dY(e,t){e.sessionId&&(M={...M,sessions:Mp(M.sessions,e.sessionKey,e.sessionId)},zn(M).catch(n=>console.error(`Could not save the agent session: ${n.message}`))),MC(t)}async function pY(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 ${tp(e)}.`),!Sw.has(n)){Sw.add(n);try{let $=await TE(M.workspace);if(!$.exists)console.log("No accepted assessment exists yet; this run establishes the baseline.");else{let E=$.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). ${E}`)}}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,p=null,d=null,f=null,h=new Set,m=()=>!nn&&rn.get(t.key)===t,g=async $=>{try{return await Gu(Ci,$)||console.warn(`[${s}] ${lx}`),!0}catch(E){return console.error(`Assessment failure delivery: ${E.message}`),!1}},w=($,{milestone:E=!0}={})=>{if(!m()||E&&f===$)return;E&&(f=$,h.has($)||(h.add($),c=Math.min(90,c+10)),console.log(`[assessment:${r}] ${$}.`));let S=String($).slice(0,500);t.progressPercent=c,t.lastMessage=S,Ft.status(s,S,o,{link:Rc})};w(`Starting ${r} assessment stage`);let v=setInterval(()=>{let $=Date.now(),E=$-t.lastActivityAt,S=i&&!a?CE(r,E):null;if(!p&&S){p=S,console.error(`[assessment:${r}] ${p}`),Va(t.controller,t.child);return}p||io.observe({at:$,level:"info",message:Ft.status(s,`${t.lastMessage} \xB7 last agent activity ${Ke(E)} ago (${t.eventCount.toLocaleString()} events)`,o)})},15e3),_={onSession:async $=>{m()&&(d=String($),await M0(M.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 E=RE($);if(E&&w(E),!m())return;let S=is($);!S||S===t.lastDetail||(t.lastDetail=S,jw(s,S))}},b=($,E)=>xm($,E,M,_,{draftPath:tn.relative(M.workspace,tn.join(jn(M.workspace,n),$.report_file)).split(tn.sep).join("/")});try{let $=bw-Date.now();$>0&&(w(`Waiting ${Math.ceil($/1e3)}s for the model provider's rate limit to clear`),await new Promise(C=>setTimeout(C,$+Math.floor(Math.random()*3e3)))),e.assessment_mode==="incremental"&&(c=15,w("Calculating changed files and affected behavior"));let E=await F0(M.workspace,e),S=await xf(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision});if(S)b(S,E),w("Recovered completed stage report from connector storage");else{if(d=await P0(M.workspace,n,r,{expectedHeadRevision:e.target_head_revision,expectedSourceRevision:e.source_revision}),d&&w("Restoring interrupted agent session"),S=await kE(E,M,_,{previousSessionId:d}),p)throw new Error(p);a=!0,await Ef(M.workspace,n,E,S)}a=!0,t.phase="delivering",t.progressPercent=95,t.lastMessage=r==="synthesis"?"Delivering completed assessment bundle":"Checkpointing connector-local stage result";let T=C=>fetch(Jy(M.server_url,M.connector_id,n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.token}`},body:JSON.stringify(C),signal:AbortSignal.timeout(cE)}),A=await qE(S,{submit:C=>WE(C,T,{isActive:()=>m()&&!nn,onRetry:(O,R)=>{w("Completed result is waiting for EngineerOS",{milestone:!1}),console.warn(`[assessment:${r}] Completed result delivery failed: ${an(O)} Retrying in ${Math.round(R/1e3)}s without rerunning the agent.`)}}),payloadFor:C=>r==="synthesis"?Af(M.workspace,n,C,{expectedSourceRevision:e.source_revision}):H0(C),rejectionFor:C=>ya(C,"the assessment"),correct:async(C,O)=>{if(a=!1,t.phase="correcting",t.lastMessage="Correcting a rejected stage result",!C.correctAfterRejection)throw new Error(`${O} The connector could not start the required agent correction.`);return C.correctAfterRejection(O)},onCorrected:async C=>{if(p)throw new Error(p);a=!0,await D0(M.workspace,n,r);let O=await Ef(M.workspace,n,E,C);return b(O,E),t.phase="delivering",t.lastMessage="Delivering corrected stage result",O}});if(p)throw new Error(p);S=A.result;let x=A.response;if(!x.ok)throw new Error(await ya(x,"the assessment"));if(l=!0,Ac.record("assessment stage","completed",{durationMs:Date.now()-o,usage:S.usage}),r==="synthesis"){let C=await x.json(),O=await z0(M.workspace,n,e,S,C.report_markdown);console.log(`Workspace assessment ${n} was accepted by EngineerOS and saved to ${tn.relative(M.workspace,O)}.`);try{let R=await Gc(M.workspace);R.committed&&console.log(`Assessment committed to Git as ${R.revision.slice(0,8)}.`)}catch(R){console.error(`The assessment is saved locally but could not be committed to Git: ${R.message}`)}}else console.log(`Workspace assessment stage ${r} was checkpointed by EngineerOS.`)}catch($){let E=p||an($),S=UE(e,$),T=BE($),k=LE($);T&&(await L0(M.workspace,n,r).catch(x=>{console.error(`[assessment:${r}] Could not discard the unusable agent session checkpoint: ${x.message}`)}),d=null);let A=!p&&(d||T)&&(T||PE($))&&S<k;if(m()&&A){t.phase="starting",t.lastMessage=T?"Agent session became unusable; restarting from saved assessment work":"Agent session interrupted; resuming checkpoint",t.resumeAssignment=FE(e,$);let x=zE($,S);qa($)&&(bw=Math.max(bw,Date.now()+x)),console.warn(`[assessment:${r}] ${T?"Agent session became unusable":"Agent session interrupted"}: ${E} ${T?"Starting a fresh session from the saved draft":`Resuming session ${d}`} in ${Math.round(x/1e3)}s (${S+1}/${k}).`),await new Promise(C=>setTimeout(C,x))}else m()&&(u=await g({type:"workspace.assessment.failed",assessment_id:n,stage:r,message:E}));A||(Ac.record("assessment stage","failed",{durationMs:Date.now()-o}),console.error(`[assessment:${r}] ${E}`))}finally{clearInterval(v),Ft.clearStatus(s),r==="synthesis"&&l&&Sw.delete(n),m()&&(rn.delete(t.key),HE(Ti,t,{accepted:l,failureReported:u})&&console.log(`Resuming interrupted agent session for assessment stage ${r} from its checkpoint.`),Ic())}}async function fY(e){let t=String(e.run_id||"");Uo+=1;try{Ir&&await Ir;let n=await mE(M.workspace,String(e.base_revision||""),String(e.head_revision||""),String(e.integration_branch||"")||null);if(n.applied){console.log(`Accepted Goal Run ${t} applied to the connected repository at ${n.revision} (${n.method}).`),await Oi();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: ${an(n)}`)}finally{Uo-=1,Ic()}}function hY(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{ut('--agent-args must be a JSON array, for example: --agent-args "[\\"acp\\"]"')}}function ut(e){console.error(e),process.exit(1)}
|