@whoz-oss/coday-server 0.0.0-workstream-forge.120 → 0.0.0-workstream-forge.121

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/server.js +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whoz-oss/coday-server",
3
- "version": "0.0.0-workstream-forge.120",
3
+ "version": "0.0.0-workstream-forge.121",
4
4
  "repository": "https://github.com/whoz-oss/coday",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
package/server.js CHANGED
@@ -1840,7 +1840,7 @@ ${m.join(`
1840
1840
  `)){let n=r.trim();if(!n)continue;let i=n.indexOf(" ");if(i===-1)continue;let s=n.slice(0,i).trim(),a=n.slice(i+2).trim();s.length===64&&a&&e.push({hash:s,filename:a})}return e}function kBr(t){return mgt.createHash("sha256").update(t).digest("hex")}function g5(t){return`${t}-service`}function TBr(t,e,r){let n=`-${r}.jar`,i=new RegExp(`^${e}-.+-plugin$`),s=[];for(let a of t){if(!a.filename.endsWith(n))continue;let o=a.filename.slice(0,-n.length);(o===g5(e)||i.test(o))&&s.push({artifactId:o,entry:a})}if(!s.some(a=>a.artifactId===g5(e)))throw new Error(`No '${g5(e)}' entry for version ${r} in the manifest`);return s}function K6e(t,e,r,n){return r===g5(e)?Nf.join(t,`${r}-${n}.jar`):Nf.join(t,"plugins",`${r}-${n}.jar`)}function J6e(t,e,r,n){return K6e(Nf.join(t,e),e,r,n)}function PBr(t,e,r){let n;try{n=Hs.readFileSync(Nf.join(t,e,G6e),"utf8")}catch{return null}let i=`-${r}.jar`,s=[];for(let{filename:a}of ggt(n)){if(!a.endsWith(i))return null;s.push(a.slice(0,-i.length))}return!s.includes(g5(e))||!s.every(a=>Hs.existsSync(J6e(t,e,a,r)))?null:s}function dgt(t,e,r="AGENTOS"){let n=0;try{for(let i of Hs.readdirSync(t).filter(s=>s.endsWith(".jar")||s.endsWith(".tmp")))if(!e.has(i)){let s=Nf.join(t,i);try{Hs.unlinkSync(s),ae(r,` [CLEAN] Removed stale file: ${s}`),n++}catch(a){ae(r,` [CLEAN] Failed to remove ${s}: ${a instanceof Error?a.message:a}`)}}}catch{}return n}async function pgt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),CBr);try{return await fetch(t,{signal:e.signal})}finally{clearTimeout(r)}}function hgt(t,e){let r=`${t}.tmp`;try{Hs.writeFileSync(r,e),Hs.renameSync(r,t)}catch(n){try{Hs.unlinkSync(r)}catch{}throw n}}async function MV(t,e,r){let n=e.toUpperCase(),i=Nf.join(t,e),s=Nf.join(i,"plugins");if(r==="dev"){let o=Hs.existsSync(K6e(i,e,g5(e),r));return ae(n,`[DOWNLOAD] Version is 'dev' sentinel \u2014 no release to download from (JAR placed by hand: ${o})`),o?{outcome:"skipped:all-present",message:"Version is 'dev' sentinel \u2014 using the JAR placed by hand"}:{outcome:"skipped:dev-version",message:"Version is 'dev' sentinel \u2014 no release URL available"}}let a=PBr(t,e,r);if(a)return ae(n,`[DOWNLOAD] ${a.length} JAR(s) already installed at ${r} \u2014 skipping download`),{outcome:"skipped:all-present",message:`All ${a.length} JAR(s) already present at ${r}`};try{Hs.mkdirSync(s,{recursive:!0}),Hs.rmSync(Nf.join(i,G6e),{force:!0});let o=ogt(r);ae(n,`[DOWNLOAD] Version ${r} not fully installed \u2014 fetching ${o}/checksums.sha256`);let c=await pgt(`${o}/checksums.sha256`);if(ae(n,`[DOWNLOAD] Manifest HTTP ${c.status}`),!c.ok)throw new Error(`Manifest HTTP ${c.status}`);let u=TBr(ggt(await c.text()),e,r);ae(n,`[DOWNLOAD] Release provides: ${u.map(h=>h.artifactId).join(", ")}`);for(let{artifactId:h,entry:m}of u){ae(n,`[DOWNLOAD] ${m.filename}`);let g=await pgt(`${o}/${m.filename}`);if(!g.ok)throw new Error(`JAR HTTP ${g.status} for '${m.filename}'`);let v=Buffer.from(await g.arrayBuffer());if(kBr(v)!==m.hash)throw new Error(`Checksum mismatch for '${m.filename}'`);let y=K6e(i,e,h,r);hgt(y,v),ae(n,`[DOWNLOAD] written ${y} (${v.length} bytes)`)}Hs.rmSync(Nf.join(i,"next"),{recursive:!0,force:!0});let f=new Set,d=new Set;for(let{artifactId:h,entry:m}of u)(h===g5(e)?f:d).add(m.filename);let p=dgt(i,f,n)+dgt(s,d,n);return ae(n,`[DOWNLOAD] Cleanup: removed ${p} stale file(s)`),hgt(Nf.join(i,G6e),u.map(({entry:h})=>`${h.hash} ${h.filename}`).join(`
1841
1841
  `)+`
1842
1842
  `),{outcome:"success",message:`Downloaded ${u.length} JAR(s), cleaned ${p} stale file(s)`,downloaded:u.length,cleaned:p}}catch(o){let c=o instanceof Error?o.message:String(o);return ae(n,`[DOWNLOAD] Failed: ${c}`),{outcome:"error:download-failed",message:c}}}function vgt(t,e){return MV(t,"agentos",e)}import{spawn as OBr,execFileSync as RBr}from"child_process";import*as _x from"path";var Z6e=25,ygt=2e3,X6e=6e4,IBr=1e4;function Y6e(){let t=process.env.JAVA_HOME,e=t?_x.join(t,"bin","java"):"java";t&&ae("AGENTOS",`[RUNTIME] Using JAVA_HOME: ${t}`);try{let r=RBr(e,["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),n=r.match(/^\S+\s+(\d+)/);if(!n)return ae("AGENTOS",`[RUNTIME] java --version output could not be parsed: ${r.slice(0,200)}`),{available:!1};let i=parseInt(n[1]??"0",10),s=r.split(`
1843
- `)[0]?.trim()??`Java ${i}`;return i<Z6e?(ae("AGENTOS",`[RUNTIME] WARN: Java ${i} detected but >= ${Z6e} is required by AgentOS toolchain. AgentOS will NOT be started. The proxy will return errors until a suitable JVM is installed.`),{available:!1,version:s}):(ae("AGENTOS",`[RUNTIME] Java ${i} detected \u2014 OK (${s})`),{available:!0,version:s})}catch{return ae("AGENTOS",`[RUNTIME] WARN: java binary not found (tried: ${t?_x.join(t,"bin","java"):"java in PATH"}). AgentOS will NOT be started. Set JAVA_HOME or ensure java >= ${Z6e} is on PATH.`),{available:!1}}}async function DBr(t){try{let e=`http://localhost:${t}/management/health`,r=new AbortController,n=setTimeout(()=>r.abort(),3e3),i;try{i=await fetch(e,{signal:r.signal})}finally{clearTimeout(n)}return i.ok}catch{return!1}}async function FBr(t){let e=`http://localhost:${t}/management/health`,r=Date.now()+X6e;for(;Date.now()<r;){try{let n=await fetch(e);if(n.ok)return ae("AGENTOS",`[RUNTIME] Health check passed on port ${t}`),!0;ae("AGENTOS",`[RUNTIME] Health check on port ${t} returned ${n.status}, retrying in ${ygt}ms...`)}catch{}await new Promise(n=>setTimeout(n,ygt))}return ae("AGENTOS",`[RUNTIME] Health check on port ${t} timed out after ${X6e/1e3} s`),!1}async function bgt(t,e,r){let n=await e5(r+1,10),i=await e5(n+1,10);if(ae("AGENTOS",`[RUNTIME] Selected port ${n} for AgentOS (Express is on ${r})`),ae("AGENTOS",`[RUNTIME] Selected port ${i} for Neo4j embedded Bolt`),await DBr(n))return ae("AGENTOS",`[RUNTIME] An AgentOS instance is already responding at http://localhost:${n}. ADOPTING it \u2014 Coday did NOT start this process and will NOT stop it at shutdown. NOTE: it may be running an older version. If you observe unexpected behaviour, kill it manually and restart Coday.`),{port:n,spawned:!1,shutdown:async()=>{ae("AGENTOS","[RUNTIME] Adopted process \u2014 skipping shutdown")}};if(!Y6e().available)return null;let o=_x.join(t,"agentos"),c=_x.join(o,`agentos-service-${e}.jar`),{existsSync:u}=await import("fs");if(!u(c))return ae("AGENTOS",`[RUNTIME] JAR not found at ${c} \u2014 skipping AgentOS startup`),null;ae("AGENTOS","[RUNTIME] Spawning AgentOS \u2014 config:"),ae("AGENTOS",`[RUNTIME] port: ${n}`),ae("AGENTOS",`[RUNTIME] JAR: ${c}`),ae("AGENTOS",`[RUNTIME] CWD: ${o}`),ae("AGENTOS",`[RUNTIME] JAVA_HOME: ${process.env.JAVA_HOME??"(not set, using PATH)"}`),ae("AGENTOS","[RUNTIME] encryption: NONE (plaintext \u2014 temporary)"),ae("AGENTOS",`[RUNTIME] OAuth redirect: http://localhost:${r}/agentos/oauth/callback`);let f=process.env.JAVA_HOME,d=f?_x.join(f,"bin","java"):"java",p=OBr(d,["-jar",c,`--server.port=${n}`],{cwd:o,env:{...process.env,AGENTOS_ENCRYPTION_KEY:process.env.AGENTOS_ENCRYPTION_KEY??"NONE",AGENTOS_ENCRYPTION_SALT:process.env.AGENTOS_ENCRYPTION_SALT??"NONE",AGENTOS_OAUTH_REDIRECT_URI:process.env.AGENTOS_OAUTH_REDIRECT_URI??`http://localhost:${r}/agentos/oauth/callback`,AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT:process.env.AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT??String(i),SPRING_NEO4J_URI:process.env.SPRING_NEO4J_URI??`bolt://localhost:${process.env.AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT??i}`},stdio:["ignore","pipe","pipe"],detached:!1});p.stdout?.on("data",S=>{for(let C of S.toString().split(`
1843
+ `)[0]?.trim()??`Java ${i}`;return i<Z6e?(ae("AGENTOS",`[RUNTIME] WARN: Java ${i} detected but >= ${Z6e} is required by AgentOS toolchain. AgentOS will NOT be started. The proxy will return errors until a suitable JVM is installed.`),{available:!1,version:s}):(ae("AGENTOS",`[RUNTIME] Java ${i} detected \u2014 OK (${s})`),{available:!0,version:s})}catch{return ae("AGENTOS",`[RUNTIME] WARN: java binary not found (tried: ${t?_x.join(t,"bin","java"):"java in PATH"}). AgentOS will NOT be started. Set JAVA_HOME or ensure java >= ${Z6e} is on PATH.`),{available:!1}}}async function DBr(t){try{let e=`http://localhost:${t}/management/health`,r=new AbortController,n=setTimeout(()=>r.abort(),3e3),i;try{i=await fetch(e,{signal:r.signal})}finally{clearTimeout(n)}return i.ok}catch{return!1}}async function FBr(t){let e=`http://localhost:${t}/management/health`,r=Date.now()+X6e;for(;Date.now()<r;){try{let n=await fetch(e);if(n.ok)return ae("AGENTOS",`[RUNTIME] Health check passed on port ${t}`),!0;ae("AGENTOS",`[RUNTIME] Health check on port ${t} returned ${n.status}, retrying in ${ygt}ms...`)}catch{}await new Promise(n=>setTimeout(n,ygt))}return ae("AGENTOS",`[RUNTIME] Health check on port ${t} timed out after ${X6e/1e3} s`),!1}async function bgt(t,e,r){let n=await e5(r+1,10),i=await e5(n+1,10);if(ae("AGENTOS",`[RUNTIME] Selected port ${n} for AgentOS (Express is on ${r})`),ae("AGENTOS",`[RUNTIME] Selected port ${i} for Neo4j embedded Bolt`),await DBr(n))return ae("AGENTOS",`[RUNTIME] An AgentOS instance is already responding at http://localhost:${n}. ADOPTING it \u2014 Coday did NOT start this process and will NOT stop it at shutdown. NOTE: it may be running an older version. If you observe unexpected behaviour, kill it manually and restart Coday.`),{port:n,spawned:!1,shutdown:async()=>{ae("AGENTOS","[RUNTIME] Adopted process \u2014 skipping shutdown")}};if(!Y6e().available)return null;let o=_x.join(t,"agentos"),c=_x.join(o,`agentos-service-${e}.jar`),{existsSync:u}=await import("fs");if(!u(c))return ae("AGENTOS",`[RUNTIME] JAR not found at ${c} \u2014 skipping AgentOS startup`),null;ae("AGENTOS","[RUNTIME] Spawning AgentOS \u2014 config:"),ae("AGENTOS",`[RUNTIME] port: ${n}`),ae("AGENTOS",`[RUNTIME] JAR: ${c}`),ae("AGENTOS",`[RUNTIME] CWD: ${o}`),ae("AGENTOS",`[RUNTIME] JAVA_HOME: ${process.env.JAVA_HOME??"(not set, using PATH)"}`),ae("AGENTOS","[RUNTIME] encryption: NONE (plaintext \u2014 temporary)"),ae("AGENTOS",`[RUNTIME] OAuth redirect: http://localhost:${r}/agentos/oauth/callback`);let f=process.env.JAVA_HOME,d=f?_x.join(f,"bin","java"):"java",p=OBr(d,["-jar",c,`--server.port=${n}`],{cwd:o,env:{...process.env,AGENTOS_OAUTH_REDIRECT_URI:process.env.AGENTOS_OAUTH_REDIRECT_URI??`http://localhost:${r}/agentos/oauth/callback`,AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT:process.env.AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT??String(i),SPRING_NEO4J_URI:process.env.SPRING_NEO4J_URI??`bolt://localhost:${process.env.AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT??i}`},stdio:["ignore","pipe","pipe"],detached:!1});p.stdout?.on("data",S=>{for(let C of S.toString().split(`
1844
1844
  `))C.trim()&&ae("AGENTOS",C.trim())}),p.stderr?.on("data",S=>{for(let C of S.toString().split(`
1845
1845
  `))C.trim()&&ae("AGENTOS",C.trim())});let h=null,m=!1;p.on("error",S=>{h=S,ae("AGENTOS",`[RUNTIME] Spawn error: ${S.message}`)}),p.on("exit",(S,C)=>{m=!0,ae("AGENTOS",`[RUNTIME] Process exited \u2014 code=${S} signal=${C}`)}),ae("AGENTOS",`[RUNTIME] Waiting for AgentOS to become healthy on port ${n} (up to ${X6e/1e3} s)...`);let g=await FBr(n),v=h?h.message:null;if(!g||m||h){ae("AGENTOS",`[RUNTIME] AgentOS did not become healthy (healthy=${g}, exited=${m}, spawnError=${v}) \u2014 killing process`);try{p.kill("SIGKILL")}catch{}return null}ae("AGENTOS",`[RUNTIME] AgentOS is up and healthy on port ${n}`);let y=()=>{if(p.exitCode===null&&!p.killed)try{p.kill("SIGKILL")}catch{}};process.on("exit",y);let b=()=>new Promise(S=>{if(p.exitCode!==null||p.killed){S();return}let C=setTimeout(()=>{ae("AGENTOS","[RUNTIME] Graceful shutdown timed out \u2014 sending SIGKILL");try{p.kill("SIGKILL")}catch{}},IBr);p.once("exit",()=>{clearTimeout(C),ae("AGENTOS","[RUNTIME] AgentOS process exited"),S()}),ae("AGENTOS","[RUNTIME] Sending SIGTERM to AgentOS");try{p.kill("SIGTERM")}catch(T){clearTimeout(C),ae("AGENTOS",`[RUNTIME] Error sending SIGTERM: ${T}`),S()}});return{port:n,spawned:!0,shutdown:async()=>(process.removeListener("exit",y),b())}}function xgt(t,e,r){return J6e(t,"factory",e,r)}function wgt(t,e){return MV(t,"factory",e)}import{spawn as NBr}from"child_process";import*as LV from"fs";import*as $V from"path";var jBr=8141,MBr=2e3,$Br=9e4,LBr=1e4;async function qBr(t,e){let r=`http://localhost:${t}/actuator/health`,n=Date.now()+$Br;for(;Date.now()<n&&!e();){try{if((await fetch(r)).ok)return ae("FACTORY",`[RUNTIME] Health check passed on port ${t}`),!0}catch{}await new Promise(i=>setTimeout(i,MBr))}return!1}async function _gt(t,e,r){let n=xgt(t,"factory-service",e);if(!LV.existsSync(n))return ae("FACTORY",`[RUNTIME] JAR not found at ${n} \u2014 skipping Factory startup`),null;if(!Y6e().available)return ae("FACTORY","[RUNTIME] No suitable Java \u2014 skipping Factory startup"),null;let i=$V.join(t,"factory");LV.mkdirSync($V.join(i,"plugins"),{recursive:!0});let s=await e5(jBr,10);ae("FACTORY",`[RUNTIME] Spawning Factory \u2014 port ${s}, JAR ${n}, CWD ${i}`);let a=process.env.JAVA_HOME,o=a?$V.join(a,"bin","java"):"java",c=NBr(o,["--enable-native-access=ALL-UNNAMED","-jar",n,`--server.port=${s}`],{cwd:i,env:{...process.env,AGENTOS_URL:r},stdio:["ignore","pipe","pipe"],detached:!1}),u=g=>{for(let v of g.toString().split(`
1846
1846
  `))v.trim()&&ae("FACTORY",v.trim())};c.stdout?.on("data",u),c.stderr?.on("data",u);let f=!1,d=null;if(c.on("error",g=>{d=g.message,ae("FACTORY",`[RUNTIME] Spawn error: ${g.message}`)}),c.on("exit",(g,v)=>{f=!0,ae("FACTORY",`[RUNTIME] Process exited \u2014 code=${g} signal=${v}`)}),!await qBr(s,()=>f||d!==null)||f||d){ae("FACTORY",`[RUNTIME] Factory did not become healthy (exited=${f}, error=${d}) \u2014 killing`);try{c.kill("SIGKILL")}catch{}return null}let h=()=>{if(c.exitCode===null&&!c.killed)try{c.kill("SIGKILL")}catch{}};return process.on("exit",h),{port:s,shutdown:()=>new Promise(g=>{if(process.removeListener("exit",h),c.exitCode!==null||c.killed){g();return}let v=setTimeout(()=>{ae("FACTORY","[RUNTIME] Graceful shutdown timed out \u2014 sending SIGKILL");try{c.kill("SIGKILL")}catch{}},LBr);c.once("exit",()=>{clearTimeout(v),g()});try{c.kill("SIGTERM")}catch{clearTimeout(v),g()}})}}function Q6e(t){let e;try{e=new URL(t)}catch{throw new Error(`Invalid AGENTOS_URL: "${t}". Must be a complete URL including scheme, e.g. "http://localhost:8124".`)}if(!["http:","https:"].includes(e.protocol)||!e.hostname||e.pathname.startsWith("//"))throw new Error(`Invalid AGENTOS_URL: "${t}". Expected an http(s) URL with a hostname, e.g. "http://localhost:8124".`)}var Z5t=Mr(uG(),1);function lG(t){return(e,r,n)=>{e.on("close",()=>{e.complete||(ae(t,`[PROXY] upstream closed before the end of ${r.method} ${r.url}, closing the client connection`),n.destroy())})}}function X5t(t,e={}){return(0,Z5t.createProxyMiddleware)({router:t,changeOrigin:!0,pathRewrite:{"^/api/agentos":""},on:{proxyReq:(r,n)=>e.onProxyReq?.(r,n),proxyRes:lG("AGENTOS")}})}var Q5t=Mr(uG(),1);var Y5t="/api/factory",aWr=t=>t===Y5t||t.startsWith(`${Y5t}/`);function e6t(t,e={}){return(0,Q5t.createProxyMiddleware)({router:t,changeOrigin:!0,pathFilter:aWr,on:{proxyReq:(r,n)=>e.onProxyReq?.(r,n),proxyRes:lG("FACTORY")}})}var eve=Mr(uG(),1),Yi=(0,sP.default)(),oWr=process.env.PORT?parseInt(process.env.PORT):process.env.BUILD_ENV==="development"?4100:3e3,t6t=!!process.env.PORT,r6t=e5(oWr,t6t?0:10,t6t),nn=rgt();ae("INIT","Coday options:",nn);var n6t=!nn.noLog,Dx=new lj(n6t,nn.logFolder);ae("INIT",`Usage logging ${n6t?"enabled":"disabled"} ${nn.logFolder?`(custom folder: ${nn.logFolder})`:""}`);ae("INIT","Webhook service initialized (will be initialized with prompt execution service)");var A5,mG,cWr=process.env.AGENTOS_EXTERNAL_USERID,Ox=process.env.AGENTOS_URL,Rx=process.env.FACTORY_URL;Ox&&Q6e(Ox);Rx&&Q6e(Rx);var aP=Ox??"http://localhost:8124",fG=Rx??"http://localhost:8141",Px=null,nP=null;function i6t(t,e){agt(t,sgt({authEnabled:!!nn.auth,envUserId:cWr,resolveUser:()=>Al(e)}))}Yi.use("/api/agentos",X5t(()=>aP,{onProxyReq:(t,e)=>{ae("AGENTOS",`[PROXY] ${e.method} ${e.url}`),i6t(t,e)}}));ae("INIT",`AgentOS proxy configured: /api/agentos \u2192 ${aP} (${Ox?"external mode":"managed mode"})`);Yi.use(e6t(()=>fG,{onProxyReq:(t,e)=>{ae("FACTORY",`[PROXY] ${e.method} ${e.url}`),i6t(t,e)}}));ae("INIT",`Factory proxy configured: /api/factory \u2192 ${fG}/api/factory (${Rx?"external mode":"managed mode"})`);Yi.use(sP.default.json({limit:"20mb"}));if(process.env.BUILD_ENV==="development"){let t=`http://localhost:${process.env.ANGULAR_CLIENT_PORT??"4200"}`,e=`http://localhost:${process.env.FACTORY_COCKPIT_PORT??"4300"}`,r=i=>i==="/factory"||i.startsWith("/factory/"),n=i=>i.startsWith("/api")||i.startsWith("/events");Yi.use((0,eve.createProxyMiddleware)({target:e,changeOrigin:!0,ws:!0,pathFilter:i=>r(i)})),Yi.use((0,eve.createProxyMiddleware)({target:t,changeOrigin:!0,ws:!0,pathFilter:i=>!n(i)&&!r(i)})),ae("INIT",`Development mode: /factory \u2192 ${e}, other non-API routes \u2192 ${t}`)}else{let t=process.env.CODAY_CLIENT_PATH?Wo.resolve(process.env.CODAY_CLIENT_PATH):Wo.resolve(__dirname,"../coday-client/browser");if(ae("INIT",`Production mode: serving static files from ${t}`),process.env.CODAY_CLIENT_PATH&&ae("INIT","Using client path from CODAY_CLIENT_PATH environment variable"),!Tx.existsSync(t))console.error(`ERROR: Client path does not exist: ${t}`),console.error("Please build the client first with: pnpm nx run client:build");else{let r=Wo.join(t,"index.html");Tx.existsSync(r)?ae("INIT",`Verified index.html exists at ${r}`):(console.error(`ERROR: index.html not found at: ${r}`),console.error("Client build may be incomplete. Try rebuilding with: pnpm nx run client:build"))}let e=process.env.CODAY_FACTORY_COCKPIT_PATH?Wo.resolve(process.env.CODAY_FACTORY_COCKPIT_PATH):Wo.resolve(__dirname,"../coday-factory-cockpit/browser");if(ae("INIT",`Production mode: serving factory cockpit static files from ${e}`),!Tx.existsSync(e))console.error(`ERROR: Factory cockpit path does not exist: ${e}`),console.error("Please build the factory cockpit first with: pnpm nx run factory-cockpit:build");else{let r=Wo.join(e,"index.html");Tx.existsSync(r)?ae("INIT",`Verified factory cockpit index.html exists at ${r}`):(console.error(`ERROR: index.html not found at: ${r}`),console.error("Factory cockpit build may be incomplete. Try rebuilding with: pnpm nx run factory-cockpit:build"))}Yi.use("/factory",sP.default.static(e)),Yi.use(sP.default.static(t))}var dG=new w$(nn.configDir),rP=nn.project;if(rP&&!nn.forcedProject){let t=process.cwd(),e=Wo.basename(t);if(dG.exists(e)){let r=dG.getConfig(e);if(r&&r.path===t&&!r.volatile)ae("INIT",`Default mode: found existing non-volatile project '${e}' for current directory`),rP=e;else{let n=l9.generateProjectId(t);ae("INIT",`Default mode: existing project '${e}' doesn't match path, using volatile ID ${n}`),rP=n}}else{let r=l9.generateProjectId(t);ae("INIT",`Default mode: no existing project found, using volatile ID ${r}`),rP=r}}var C5=new l9(dG,rP,nn.forcedProject);A5=new y$(nn.configDir,C5);A5.registerNativeHandler({id:"handler-delegate",name:"delegate",description:"Delegate a task to a specific agent in an isolated sub-thread",source:"builtin",webhookEnabled:!1,createdBy:"system",createdAt:new Date("2024-01-01").toISOString(),parameterFormat:"@AgentName <task>"});ae("INIT","Prompt service initialized");mG=new b$(A5);ae("INIT","Prompt execution service initialized (will be initialized with dependencies after thread manager)");var s6t=Wo.join(nn.configDir,"projects"),a6t=new A$(s6t),tm=new S$(dG,s6t,a6t),uWr=new v9;ae("INIT","MCP instance pool initialized");var Ix=new dV(Dx,C5,tm,A5,uWr);mG.initialize(Ix,tm,nn,Dx);ae("INIT","Prompt execution service initialized");ae("INIT","Webhook service initialized with prompt execution delegation");var lWr=new Yf("config-api"),tve=new h$(nn.configDir,lWr),fWr=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function Al(t){let e=W6e(t.headers,!!nn.auth);if(fWr.includes(e.toLowerCase()))throw new Error(`Security error: Cannot run with username "${e}". This appears to be a system or service account. When running locally, ensure you are running as a regular user account. When running in production, ensure authentication is properly configured with --auth flag.`);return e}bmt(Yi,Al,nn.configDir,!!nn.auth);pmt(Yi,tve,Al);Pmt(Yi,tve,Al);wmt(Yi,A5,Al);Smt(Yi,mG,Al);mmt(Yi,C5,Ix.projectEventManager,tm,Al,Ix,nn);Tmt(Yi,C5);gmt(Yi,tm,a6t,Ix,Al,nn,tve);vmt(Yi,Ix,Al,tm);var dWr=new d$(nn.configDir,C5);xmt(Yi,C5,Al,nn.configDir,Dx,A5,tm,dWr,nn);var pG=new x$(Dx,A5,nn.configDir);_mt(Yi,pG,Al);Cmt(Yi,Dx,Al,nn.auth);if(process.env.BUILD_ENV!=="development"){let t=process.env.CODAY_CLIENT_PATH?Wo.resolve(process.env.CODAY_CLIENT_PATH):Wo.resolve(__dirname,"../coday-client/browser"),e=Wo.resolve(t,"index.html"),r=process.env.CODAY_FACTORY_COCKPIT_PATH?Wo.resolve(process.env.CODAY_FACTORY_COCKPIT_PATH):Wo.resolve(__dirname,"../coday-factory-cockpit/browser"),n=Wo.resolve(r,"index.html");ae("INIT",`Catch-all route will serve: ${e}`),ae("INIT",`Factory cockpit catch-all route will serve: ${n}`),Yi.use((i,s,a)=>{if(i.path.startsWith("/api")||i.path.startsWith("/events")){s.status(404).send("Not found");return}let o=i.path==="/factory"||i.path.startsWith("/factory/")?n:e;ae("ROUTER",`Serving index.html for client route: ${i.path}`),Tx.readFile(o,"utf8",(c,u)=>{c?(ae("ERROR",`Failed to read index.html from ${o}:`,c),ae("ERROR",`File exists check: ${Tx.existsSync(o)}`),a(c)):s.type("html").send(u)})})}var hG=null;async function pWr(t){if(Ox){ae("AGENTOS",`[PROVISION] External mode \u2014 target: ${Ox}. No provisioning performed.`);return}ae("AGENTOS","[PROVISION] Managed mode \u2014 starting AgentOS provisioning...");try{let e=fgt(),r=await vgt(nn.configDir,e);if(ae("AGENTOS",`[PROVISION] Download outcome: ${r.outcome} \u2014 ${r.message}`),r.outcome!=="success"&&r.outcome!=="skipped:all-present"&&r.outcome!=="skipped:dev-version"){ae("AGENTOS","[PROVISION] Download failed \u2014 AgentOS will not be started. The proxy will return errors.");return}if(ae("AGENTOS","[PROVISION] Starting AgentOS process..."),Px=await bgt(nn.configDir,e,t),!Px){ae("AGENTOS","[PROVISION] AgentOS did not start. The proxy will return errors until AgentOS is available.");return}aP=`http://localhost:${Px.port}`,ae("AGENTOS",`[PROVISION] AgentOS is ready. Proxy target: ${aP} (${Px.spawned?"spawned by Coday":"adopted existing process"})`)}catch(e){ae("AGENTOS","[PROVISION] Unexpected error during provisioning (non-fatal):",e)}}async function hWr(){if(Rx){ae("FACTORY",`[PROVISION] External mode \u2014 target: ${Rx}. No provisioning performed.`);return}ae("FACTORY","[PROVISION] Managed mode \u2014 starting Factory provisioning...");try{let t=lgt(),e=await wgt(nn.configDir,t);if(ae("FACTORY",`[PROVISION] Download outcome: ${e.outcome} \u2014 ${e.message}`),e.outcome!=="success"&&e.outcome!=="skipped:all-present"){ae("FACTORY","[PROVISION] Factory will not be started. The proxy will return errors.");return}if(nP=await _gt(nn.configDir,t,aP),!nP){ae("FACTORY","[PROVISION] Factory did not start. The proxy will return errors until it is available.");return}fG=`http://localhost:${nP.port}`,ae("FACTORY",`[PROVISION] Factory is ready. Proxy target: ${fG}`)}catch(t){ae("FACTORY","[PROVISION] Unexpected error during provisioning (non-fatal):",t)}}Yi.use((t,e,r,n)=>{ae("ERROR",`Request error on ${e.method} ${e.path}:`,t.message),console.error(t.stack),process.env.BUILD_ENV==="development"?r.status(500).json({error:"Internal Server Error",message:t.message,stack:t.stack}):r.status(500).send("Something went wrong!")});async function mWr(){let e=new Date(Date.now()-6048e5).toISOString();try{if(nn.auth){ae("CLEANUP","autoCloseStaleThreads: skipped in --auth mode (no server-side user identity at startup)");return}let r=W6e({},!1),n=C5.listProjects(),i=0;for(let s of n)try{let o=(await tm.listThreads(s.name,r)).filter(c=>!c.closedByUser&&c.modifiedDate<e);for(let c of o)try{await tm.updateThread(s.name,c.id,{closedByUser:!0}),i++}catch(u){console.error(`autoClose: failed to close thread ${c.id} in project ${s.name}:`,u)}}catch(a){console.error(`autoClose: failed to process project ${s.name}:`,a)}i>0&&console.log(`\u2705 Auto-close: ${i} thread(s) paused depuis plus d'1 semaine marqu\xE9s comme done`)}catch(r){console.error("autoCloseStaleThreads: unexpected error (non-fatal):",r)}}r6t.then(async t=>{nn.baseUrl?ae("INIT",`Using configured base URL: ${nn.baseUrl}`):(nn.baseUrl=`http://localhost:${t}`,ae("INIT",`Base URL set to: ${nn.baseUrl}`)),Yi.listen(t,()=>{console.log(`Server is running on http://localhost:${t}`)}),pWr(t).catch(e=>ae("AGENTOS","[PROVISION] Unhandled error:",e)).then(()=>hWr()).catch(e=>ae("FACTORY","[PROVISION] Unhandled error:",e)),mWr().catch(e=>console.error("autoCloseStaleThreads: unhandled error:",e));try{ae("CLEANUP","Starting thread cleanup service...");let e=Wo.join(nn.configDir,"projects");hG=new E$(e,Dx),await hG.start(),ae("CLEANUP","Thread cleanup service started successfully")}catch(e){console.error("Failed to start thread cleanup service:",e)}try{ae("SCHEDULER","Initializing scheduler service..."),await pG.initialize(),pG.initializeExecution(mG),ae("SCHEDULER","Scheduler service initialized successfully")}catch(e){console.error("Failed to initialize scheduler service:",e)}}).catch(t=>{console.error("Failed to start server:",t),process.exit(1)});r6t.catch(t=>{t instanceof Error&&t.message.includes("already in use")&&process.stderr.write(`PORT_IN_USE: ${t.message}