@whoz-oss/coday-server 3.17.0 → 3.18.0
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.
- package/package.json +1 -1
- package/server.js +1 -1
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -1838,7 +1838,7 @@ ${m.join(`
|
|
|
1838
1838
|
`,"f"),kt(this,la,ee(this,la,"f")+e.join(" "),"f")},error:(...e)=>{this[RV]()||console.error(...e),kt(this,Eu,!0,"f"),ee(this,la,"f").length&&kt(this,la,ee(this,la,"f")+`
|
|
1839
1839
|
`,"f"),kt(this,la,ee(this,la,"f")+e.join(" "),"f")}}}[k6e](e){bx(ee(this,Ft,"f")).forEach(r=>{if((i=>i==="configObjects")(r))return;let n=ee(this,Ft,"f")[r];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n=="object"&&delete n[e]}),delete ee(this,lr,"f").getDescriptions()[e]}[C1t](e,r,n){ee(this,EV,"f")[n]||(ee(this,Yt,"f").process.emitWarning(e,r),ee(this,EV,"f")[n]=!0)}[k1t](){ee(this,AV,"f").push({options:ee(this,Ft,"f"),configObjects:ee(this,Ft,"f").configObjects.slice(0),exitProcess:ee(this,wl,"f"),groups:ee(this,Yd,"f"),strict:ee(this,f5,"f"),strictCommands:ee(this,d5,"f"),strictOptions:ee(this,p5,"f"),completionCommand:ee(this,Su,"f"),output:ee(this,la,"f"),exitError:ee(this,Q3,"f"),hasOutput:ee(this,Eu,"f"),parsed:this.parsed,parseFn:ee(this,Au,"f"),parseContext:ee(this,u5,"f")}),ee(this,lr,"f").freeze(),ee(this,Xi,"f").freeze(),ee(this,fs,"f").freeze(),ee(this,_l,"f").freeze()}[T1t](){let e="",r;return/\b(node|iojs|electron)(\.exe)?$/.test(ee(this,Yt,"f").process.argv()[0])?r=ee(this,Yt,"f").process.argv().slice(1,2):r=ee(this,Yt,"f").process.argv().slice(0,1),e=r.map(n=>{let i=this[B1t](ee(this,a5,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&i.length<n.length?i:n}).join(" ").trim(),ee(this,Yt,"f").getEnv("_")&&ee(this,Yt,"f").getProcessArgvBin()===ee(this,Yt,"f").getEnv("_")&&(e=ee(this,Yt,"f").getEnv("_").replace(`${ee(this,Yt,"f").path.dirname(ee(this,Yt,"f").process.execPath())}/`,"")),e}[h5](){return ee(this,TV,"f")}[P1t](){return ee(this,OV,"f")}[T6e](){if(!ee(this,o5,"f"))return;let e=ee(this,Yt,"f").getEnv("LC_ALL")||ee(this,Yt,"f").getEnv("LC_MESSAGES")||ee(this,Yt,"f").getEnv("LANG")||ee(this,Yt,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[O1t](){return this[P6e]().version||"unknown"}[R1t](e){let r=e["--"]?e["--"]:e._;for(let n=0,i;(i=r[n])!==void 0;n++)ee(this,Yt,"f").Parser.looksLikeNumber(i)&&Number.isSafeInteger(Math.floor(parseFloat(`${i}`)))&&(r[n]=Number(i));return e}[P6e](e){let r=e||"*";if(ee(this,wx,"f")[r])return ee(this,wx,"f")[r];let n={};try{let i=e||ee(this,Yt,"f").mainFilename;ee(this,Yt,"f").path.extname(i)&&(i=ee(this,Yt,"f").path.dirname(i));let s=ee(this,Yt,"f").findUp(i,(a,o)=>{if(o.includes("package.json"))return"package.json"});Uo(s,void 0,ee(this,Yt,"f")),n=JSON.parse(ee(this,Yt,"f").readFileSync(s,"utf8"))}catch{}return ee(this,wx,"f")[r]=n||{},ee(this,wx,"f")[r]}[tm](e,r){r=[].concat(r),r.forEach(n=>{n=this[I6e](n),ee(this,Ft,"f")[e].push(n)})}[_x](e,r,n,i){this[R6e](e,r,n,i,(s,a,o)=>{ee(this,Ft,"f")[s][a]=o})}[O6e](e,r,n,i){this[R6e](e,r,n,i,(s,a,o)=>{ee(this,Ft,"f")[s][a]=(ee(this,Ft,"f")[s][a]||[]).concat(o)})}[R6e](e,r,n,i,s){if(Array.isArray(n))n.forEach(a=>{e(a,i)});else if((a=>typeof a=="object")(n))for(let a of bx(n))e(a,n[a]);else s(r,this[I6e](n),i)}[I6e](e){return e==="__proto__"?"___proto___":e}[D6e](e,r){return this[_x](this[D6e].bind(this),"key",e,r),this}[F6e](){var e,r,n,i,s,a,o,c,u,f,d,p;let h=ee(this,AV,"f").pop();Uo(h,void 0,ee(this,Yt,"f"));let m;e=this,r=this,n=this,i=this,s=this,a=this,o=this,c=this,u=this,f=this,d=this,p=this,{options:{set value(g){kt(e,Ft,g,"f")}}.value,configObjects:m,exitProcess:{set value(g){kt(r,wl,g,"f")}}.value,groups:{set value(g){kt(n,Yd,g,"f")}}.value,output:{set value(g){kt(i,la,g,"f")}}.value,exitError:{set value(g){kt(s,Q3,g,"f")}}.value,hasOutput:{set value(g){kt(a,Eu,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){kt(o,f5,g,"f")}}.value,strictCommands:{set value(g){kt(c,d5,g,"f")}}.value,strictOptions:{set value(g){kt(u,p5,g,"f")}}.value,completionCommand:{set value(g){kt(f,Su,g,"f")}}.value,parseFn:{set value(g){kt(d,Au,g,"f")}}.value,parseContext:{set value(g){kt(p,u5,g,"f")}}.value}=h,ee(this,Ft,"f").configObjects=m,ee(this,lr,"f").unfreeze(),ee(this,Xi,"f").unfreeze(),ee(this,fs,"f").unfreeze(),ee(this,_l,"f").unfreeze()}[I1t](e,r){return s5(r,n=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[D1t].bind(this),getContext:this[F1t].bind(this),getHasOutput:this[N1t].bind(this),getLoggerInstance:this[j1t].bind(this),getParseContext:this[$1t].bind(this),getParserConfiguration:this[h5].bind(this),getUsageConfiguration:this[P1t].bind(this),getUsageInstance:this[M1t].bind(this),getValidationInstance:this[L1t].bind(this),hasParseCallback:this[RV].bind(this),isGlobalContext:this[q1t].bind(this),postProcess:this[m5].bind(this),reset:this[N6e].bind(this),runValidation:this[j6e].bind(this),runYargsParserAndExecuteCommands:this[LT].bind(this),setHasOutput:this[z1t].bind(this)}}[D1t](){return ee(this,fs,"f")}[F1t](){return ee(this,MT,"f")}[N1t](){return ee(this,Eu,"f")}[j1t](){return ee(this,c5,"f")}[$1t](){return ee(this,u5,"f")||{}}[M1t](){return ee(this,lr,"f")}[L1t](){return ee(this,Xi,"f")}[RV](){return!!ee(this,Au,"f")}[q1t](){return ee(this,CV,"f")}[m5](e,r,n,i){return n||fi(e)||(r||(e=this[E1t](e)),(this[h5]()["parse-positional-numbers"]||this[h5]()["parse-positional-numbers"]===void 0)&&(e=this[R1t](e)),i&&(e=i5(e,this,ee(this,_l,"f").getMiddleware(),!1))),e}[N6e](e={}){kt(this,Ft,ee(this,Ft,"f")||{},"f");let r={};r.local=ee(this,Ft,"f").local||[],r.configObjects=ee(this,Ft,"f").configObjects||[];let n={};r.local.forEach(a=>{n[a]=!0,(e[a]||[]).forEach(o=>{n[o]=!0})}),Object.assign(ee(this,l5,"f"),Object.keys(ee(this,Yd,"f")).reduce((a,o)=>{let c=ee(this,Yd,"f")[o].filter(u=>!(u in n));return c.length>0&&(a[o]=c),a},{})),kt(this,Yd,{},"f");let i=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],s=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];return i.forEach(a=>{r[a]=(ee(this,Ft,"f")[a]||[]).filter(o=>!n[o])}),s.forEach(a=>{r[a]=X3(ee(this,Ft,"f")[a],o=>!n[o])}),r.envPrefix=ee(this,Ft,"f").envPrefix,kt(this,Ft,r,"f"),kt(this,lr,ee(this,lr,"f")?ee(this,lr,"f").reset(n):g1t(this,ee(this,Yt,"f")),"f"),kt(this,Xi,ee(this,Xi,"f")?ee(this,Xi,"f").reset(n):_1t(this,ee(this,lr,"f"),ee(this,Yt,"f")),"f"),kt(this,fs,ee(this,fs,"f")?ee(this,fs,"f").reset():p1t(ee(this,lr,"f"),ee(this,Xi,"f"),ee(this,_l,"f"),ee(this,Yt,"f")),"f"),ee(this,Nc,"f")||kt(this,Nc,b1t(this,ee(this,lr,"f"),ee(this,fs,"f"),ee(this,Yt,"f")),"f"),ee(this,_l,"f").reset(),kt(this,Su,null,"f"),kt(this,la,"","f"),kt(this,Q3,null,"f"),kt(this,Eu,!1,"f"),this.parsed=!1,this}[B1t](e,r){return ee(this,Yt,"f").path.relative(e,r)}[LT](e,r,n,i=0,s=!1){var a,o,c,u;let f=!!n||s;e=e||ee(this,em,"f"),ee(this,Ft,"f").__=ee(this,Yt,"f").y18n.__,ee(this,Ft,"f").configuration=this[h5]();let d=!!ee(this,Ft,"f").configuration["populate--"],p=Object.assign({},ee(this,Ft,"f").configuration,{"populate--":!0}),h=ee(this,Yt,"f").Parser.detailed(e,Object.assign({},ee(this,Ft,"f"),{configuration:{"parse-positional-numbers":!1,...p}})),m=Object.assign(h.argv,ee(this,u5,"f")),g,v=h.aliases,y=!1,b=!1;Object.keys(m).forEach(x=>{x===ee(this,Sl,"f")&&m[x]?y=!0:x===ee(this,Qd,"f")&&m[x]&&(b=!0)}),m.$0=this.$0,this.parsed=h,i===0&&ee(this,lr,"f").clearCachedHelpMessage();try{if(this[T6e](),r)return this[m5](m,d,!!n,!1);ee(this,Sl,"f")&&[ee(this,Sl,"f")].concat(v[ee(this,Sl,"f")]||[]).filter(I=>I.length>1).includes(""+m._[m._.length-1])&&(m._.pop(),y=!0),kt(this,CV,!1,"f");let x=ee(this,fs,"f").getCommands(),S=!((a=ee(this,Nc,"f"))===null||a===void 0)&&a.completionKey?[(o=ee(this,Nc,"f"))===null||o===void 0?void 0:o.completionKey,...(u=this.getAliases()[(c=ee(this,Nc,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&u!==void 0?u:[]].some(T=>Object.prototype.hasOwnProperty.call(m,T)):!1,C=y||S||s;if(m._.length){if(x.length){let T;for(let I=i||0,F;m._[I]!==void 0;I++)if(F=String(m._[I]),x.includes(F)&&F!==ee(this,Su,"f")){let A=ee(this,fs,"f").runCommand(F,this,h,I+1,s,y||b||s);return this[m5](A,d,!!n,!1)}else if(!T&&F!==ee(this,Su,"f")){T=F;break}!ee(this,fs,"f").hasDefaultCommand()&&ee(this,PV,"f")&&T&&!C&&ee(this,Xi,"f").recommendCommands(T,x)}ee(this,Su,"f")&&m._.includes(ee(this,Su,"f"))&&!S&&(ee(this,wl,"f")&&Y3(!0),this.showCompletionScript(),this.exit(0))}if(ee(this,fs,"f").hasDefaultCommand()&&!C){let T=ee(this,fs,"f").runCommand(null,this,h,0,s,y||b||s);return this[m5](T,d,!!n,!1)}if(S){ee(this,wl,"f")&&Y3(!0),e=[].concat(e);let T=e.slice(e.indexOf(`--${ee(this,Nc,"f").completionKey}`)+1);return ee(this,Nc,"f").getCompletion(T,(I,F)=>{if(I)throw new ls(I.message);(F||[]).forEach(A=>{ee(this,c5,"f").log(A)}),this.exit(0)}),this[m5](m,!d,!!n,!1)}if(ee(this,Eu,"f")||(y?(ee(this,wl,"f")&&Y3(!0),f=!0,this.showHelp(T=>{ee(this,c5,"f").log(T),this.exit(0)})):b&&(ee(this,wl,"f")&&Y3(!0),f=!0,ee(this,lr,"f").showVersion("log"),this.exit(0))),!f&&ee(this,Ft,"f").skipValidation.length>0&&(f=Object.keys(m).some(T=>ee(this,Ft,"f").skipValidation.indexOf(T)>=0&&m[T]===!0)),!f){if(h.error)throw new ls(h.error.message);if(!S){let T=this[j6e](v,{},h.error);n||(g=i5(m,this,ee(this,_l,"f").getMiddleware(),!0)),g=this[I1t](T,g??m),fi(g)&&!n&&(g=g.then(()=>i5(m,this,ee(this,_l,"f").getMiddleware(),!1)))}}}catch(x){if(x instanceof ls)ee(this,lr,"f").fail(x.message,x);else throw x}return this[m5](g??m,d,!!n,!0)}[j6e](e,r,n,i){let s={...this.getDemandedOptions()};return a=>{if(n)throw new ls(n.message);ee(this,Xi,"f").nonOptionCount(a),ee(this,Xi,"f").requiredArguments(a,s);let o=!1;ee(this,d5,"f")&&(o=ee(this,Xi,"f").unknownCommands(a)),ee(this,f5,"f")&&!o?ee(this,Xi,"f").unknownArguments(a,e,r,!!i):ee(this,p5,"f")&&ee(this,Xi,"f").unknownArguments(a,e,{},!1,!1),ee(this,Xi,"f").limitedChoices(a),ee(this,Xi,"f").implications(a),ee(this,Xi,"f").conflicting(a)}}[z1t](){kt(this,Eu,!0,"f")}[g5](e){if(typeof e=="string")ee(this,Ft,"f").key[e]=!0;else for(let r of e)ee(this,Ft,"f").key[r]=!0}};function h1t(t){return!!t&&typeof t.getInternalMethods=="function"}var Jqr=U1t(w6e),H1t=Jqr;import Zqr from"node:os";function W1t(){let t=y6e(process.argv),e=H1t(t).option("coday_project",{type:"string",description:"Project name"}).option("prompt",{type:"array",description:"Prompt(s) to execute"}).option("oneshot",{type:"boolean",description:"Run in one-shot mode (non-interactive)"}).option("auth",{type:"boolean",description:"Enables web auth check (expects x-forwarded-email header from auth proxy)"}).option("local",{type:"boolean",description:"Use current directory as sole project (restricted mode)"}).option("multi",{type:"boolean",description:"Multi-project mode: show project list without default selection"}).option("fileReadOnly",{type:"boolean",description:"Run in read-only mode for files (no write/delete operations)"}).option("configDir",{type:"string",description:"Path to the local .coday config dir"}).option("agentFolders",{type:"array",description:"Additional folders where agent definitions can be found",alias:"af"}).option("log",{type:"boolean",description:"Enable logging (use --no-log to disable)",default:!0}).option("log-folder",{type:"string",description:"Custom folder for log files (defaults to ~/.coday/logs)"}).option("debug",{type:"boolean",description:"Sets debug right at startup"}).option("base-url",{type:"string",description:"Base URL for generating absolute links (default: auto-detected from server port)"}).help().argv,r,n,i=e.prompt||e._.slice(1),s=!!e.oneshot,a=!!e.fileReadOnly,o=M6e.join(Zqr.homedir(),".coday"),c=e.coday_config_dir||o,u=!!e.auth,f=!!e.debug,d=!e.log,p=e.log_folder;return e.coday_project?(r=e.coday_project,n=!0,console.log(`Project mode: restricting to project '${r}'`)):e.local?(r=M6e.basename(process.cwd()),n=!0,console.log(`Local mode: restricting to project '${r}'`)):e.multi?(r="",n=!1,console.log("Multi-project mode: no default project selection")):(r=M6e.basename(process.cwd()),n=!1,console.log(`Default mode: using '${r}' as default project`)),{oneshot:s,debug:f,project:r,prompts:i,fileReadOnly:a,configDir:c,auth:u,agentFolders:e.agentFolders||[],noLog:d,logFolder:p,forcedProject:n,baseUrl:e.base_url}}var F5t=Ur(L8e(),1);import*as b5t from"node:os";var gHr="cf-access-jwt-assertion",vHr="x-forwarded-email";function yHr(t){if(!t)return null;let e=t.split(".");if(e.length!==3)return null;try{let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8"),s=JSON.parse(n)?.email;return typeof s=="string"&&s.length>0?s:null}catch{return null}}function q8e(t,e){if(!e)return b5t.userInfo().username;let r=t[gHr],n=yHr(r);if(n)return n;let i=t[vHr];if(i&&i.length>0)return i;throw new Error("Authentication required but no valid identity header found. Expected either a CF_Authorization JWT (Cloudflare Access) or an x-forwarded-email header from the upstream auth proxy.")}import*as tG from"fs";import*as A5 from"path";var sp=["agentos-service","agentos-bash-plugin","agentos-file-plugin","agentos-mcp-plugin","agentos-http-plugin","agentos-tmux-plugin"],x5t=["agentos-service"];function bHr(t){let e=t.endsWith(".jar")?t.slice(0,-4):t,r=e.match(/^(.*?)-([0-9].*)$/);return r?{artifactId:r[1],version:r[2]}:{artifactId:e,version:null}}function xHr(t,e,r){let n=A5.join(t,"agentos");return x5t.includes(e)?A5.join(n,`${e}-${r}.jar`):A5.join(n,"plugins",`${e}-${r}.jar`)}function w5t(t,e){let r=A5.join(t,"agentos");ie("AGENTOS",`Checking JAR availability (expected version: ${e})`),ie("AGENTOS",`AgentOS directory: ${r}`);let n=sp.map(o=>{let c=xHr(t,o,e),u=null,f=null;try{if(tG.existsSync(c))u=c,f=e;else{let p=x5t.includes(o)?r:A5.join(r,"plugins");try{let h=tG.readdirSync(p).filter(m=>m.endsWith(".jar"));for(let m of h){let g=bHr(m);if(g.artifactId===o){u=A5.join(p,m),f=g.version;break}}}catch{}}}catch{}let d=f===e;return u?d?ie("AGENTOS",` [OK] ${o}-${f}.jar`):ie("AGENTOS",` [MISMATCH] ${o} \u2014 found version ${f} at ${u} (expected ${e})`):ie("AGENTOS",` [MISSING] ${o} \u2014 expected at ${c}`),{artifactId:o,foundAt:u,foundVersion:f,versionMatch:d,expectedPath:c}}),i=n.filter(o=>!o.versionMatch).map(o=>o.artifactId),s=i.length===0,a=n.length-i.length;return ie("AGENTOS",s?`JAR check complete: all ${sp.length} JARs present at version ${e}.`:`JAR check complete: ${a}/${sp.length} JARs match version ${e} \u2014 missing: ${i.join(", ")}`),{allPresent:s,expectedVersion:e,artifacts:n,missing:i}}var _5t="1.3.6";function S5t(){let t=process.env.AGENTOS_VERSION;return t?(ie("VERSION",`AgentOS version from AGENTOS_VERSION env var: ${t}`),t):(ie("VERSION",`AgentOS version (bundled): ${_5t}`),_5t)}import*as A5t from"crypto";import*as Cs from"fs";import*as ku from"path";var E5t=6e4;function wHr(t,e){return`https://github.com/whoz-oss/coday/releases/download/release/${e}/${t}-${e}.jar`}function _Hr(t){return`https://github.com/whoz-oss/coday/releases/download/release/${t}/checksums.sha256`}function SHr(t,e){for(let r of t.split(`
|
|
1840
1840
|
`)){let n=r.trim();if(!n)continue;let i=n.indexOf(" ");if(i===-1)continue;let s=n.slice(0,i).trim();if(n.slice(i+2).trim()===e&&s.length===64)return s}return null}function EHr(t){return A5t.createHash("sha256").update(t).digest("hex")}function QT(t,e,r){return e==="agentos-service"?ku.join(t,`${e}-${r}.jar`):ku.join(t,"plugins",`${e}-${r}.jar`)}function rG(t,e){let r=0;try{for(let n of Cs.readdirSync(t).filter(i=>i.endsWith(".jar")||i.endsWith(".tmp")))if(!e.has(n)){let i=ku.join(t,n);try{Cs.unlinkSync(i),ie("AGENTOS",` [CLEAN] Removed stale file: ${i}`),r++}catch(s){ie("AGENTOS",` [CLEAN] Failed to remove ${i}: ${s instanceof Error?s.message:s}`)}}}catch{}return r}async function C5t(t,e,r){Cs.mkdirSync(ku.join(t,"plugins"),{recursive:!0});let n=_Hr(e);ie("AGENTOS",`${r} Fetching manifest for version ${e}: ${n}`);let i=new AbortController,s=setTimeout(()=>i.abort(),E5t),a;try{a=await fetch(n,{signal:i.signal})}finally{clearTimeout(s)}if(ie("AGENTOS",`${r} Manifest HTTP ${a.status}`),!a.ok)throw new Error(`Manifest HTTP ${a.status}`);let o=await a.text();ie("AGENTOS",`${r} Manifest fetched (${o.length} chars)`);let c=0;for(let u of sp){let f=`${u}-${e}.jar`,d=QT(t,u,e),p=wHr(u,e);ie("AGENTOS",`${r} Downloading ${f}...`),ie("AGENTOS",`${r} URL: ${p}`);let h=SHr(o,f);if(!h)throw new Error(`No manifest entry for '${f}'`);ie("AGENTOS",`${r} Expected SHA-256: ${h}`);let m=new AbortController,g=setTimeout(()=>m.abort(),E5t),v;try{v=await fetch(p,{signal:m.signal})}finally{clearTimeout(g)}if(ie("AGENTOS",`${r} JAR HTTP ${v.status}`),!v.ok)throw new Error(`JAR HTTP ${v.status} for '${f}'`);let y=Buffer.from(await v.arrayBuffer());if(ie("AGENTOS",`${r} Received ${y.length} bytes`),EHr(y)!==h)throw new Error(`Checksum mismatch for '${f}'`);ie("AGENTOS",`${r} Checksum OK`);let x=`${d}.tmp`;try{Cs.writeFileSync(x,y),Cs.renameSync(x,d),ie("AGENTOS",`${r} Written to ${d} (${y.length} bytes)`),c++}catch(S){try{Cs.unlinkSync(x)}catch{}throw S}}return{downloaded:c}}function k5t(t,e){let r=ku.join(t,"agentos"),n=ku.join(r,"next"),i=ku.join(r,"plugins");if(!Cs.existsSync(n))return{outcome:"skipped:no-next",message:"No next/ directory \u2014 nothing to swap"};let s=sp.filter(a=>!Cs.existsSync(QT(n,a,e)));if(s.length>0)return ie("AGENTOS",`[SWAP] next/ incomplete for version ${e} \u2014 missing: ${s.join(", ")} \u2014 skipping`),{outcome:"skipped:incomplete",message:`next/ missing: ${s.join(", ")}`};ie("AGENTOS",`[SWAP] Promoting next/ (version ${e}) to active layout...`);try{Cs.renameSync(QT(n,"agentos-service",e),ku.join(r,`agentos-service-${e}.jar`)),ie("AGENTOS",`[SWAP] agentos-service-${e}.jar`),Cs.mkdirSync(i,{recursive:!0});for(let u of sp.filter(f=>f!=="agentos-service"))Cs.renameSync(QT(n,u,e),ku.join(i,`${u}-${e}.jar`)),ie("AGENTOS",`[SWAP] ${u}-${e}.jar`);Cs.rmSync(n,{recursive:!0,force:!0}),ie("AGENTOS","[SWAP] next/ removed");let a=new Set([`agentos-service-${e}.jar`]),o=new Set(sp.filter(u=>u!=="agentos-service").map(u=>`${u}-${e}.jar`)),c=rG(r,a)+rG(i,o);return c>0&&ie("AGENTOS",`[SWAP] Removed ${c} stale JAR(s) from previous version`),ie("AGENTOS",`[SWAP] Complete \u2014 AgentOS ${e} is now active`),{outcome:"swapped",message:`Promoted version ${e} from next/`,version:e}}catch(a){let o=a instanceof Error?a.message:String(a);return ie("AGENTOS",`[SWAP] Error during swap: ${o}`),{outcome:"error",message:o}}}async function T5t(t,e){if(e==="dev")return{outcome:"skipped:dev-version",message:"Version is 'dev' \u2014 nothing to pre-fetch"};let r=ku.join(t,"agentos","next");if(sp.every(i=>Cs.existsSync(QT(r,i,e))))return ie("AGENTOS",`[UPDATE] next/ already complete for version ${e} \u2014 skipping`),{outcome:"skipped:already-in-next",message:`next/ already complete for ${e}`};ie("AGENTOS",`[UPDATE] Pre-fetching version ${e} into next/ (background)...`);try{let{downloaded:i}=await C5t(r,e,"[UPDATE]");return ie("AGENTOS",`[UPDATE] Pre-fetch complete: ${i} JAR(s) ready in next/. Will activate on next Coday startup.`),{outcome:"success",message:`Pre-fetched ${i} JAR(s) to next/`,downloaded:i}}catch(i){let s=i instanceof Error?i.message:String(i);return ie("AGENTOS",`[UPDATE] Pre-fetch failed (non-fatal): ${s}`),{outcome:"error:download-failed",message:s}}}async function P5t(t,e,r){if(r.length===0)return ie("AGENTOS","[DOWNLOAD] All JARs already present at the expected version \u2014 skipping download"),{outcome:"skipped:all-present",message:"All JARs already present at the expected version"};if(e==="dev")return ie("AGENTOS","[DOWNLOAD] Version is 'dev' sentinel \u2014 no release to download from"),{outcome:"skipped:dev-version",message:"Version is 'dev' sentinel \u2014 no release URL available"};let n=ku.join(t,"agentos"),i=ku.join(n,"plugins");ie("AGENTOS",`[DOWNLOAD] Starting download of ${r.length} artifact(s) for version ${e}`),ie("AGENTOS",`[DOWNLOAD] Missing: ${r.join(", ")}`);try{await C5t(n,e,"[DOWNLOAD]")}catch(f){let d=f instanceof Error?f.message:String(f);return ie("AGENTOS",`[DOWNLOAD] Download failed: ${d}`),{outcome:"error:download-failed",message:d}}let s=new Set([`agentos-service-${e}.jar`]),a=new Set(sp.filter(f=>f!=="agentos-service").map(f=>`${f}-${e}.jar`));ie("AGENTOS","[DOWNLOAD] Running strict cleanup...");let o=rG(n,s),c=rG(i,a),u=o+c;return u>0?ie("AGENTOS",`[DOWNLOAD] Cleanup: removed ${u} stale file(s)`):ie("AGENTOS","[DOWNLOAD] Cleanup: no stale files found"),{outcome:"success",message:`Downloaded ${r.length} JAR(s), cleaned ${u} stale file(s)`,downloaded:r.length,cleaned:u}}import{spawn as AHr,execFileSync as CHr}from"child_process";import*as Tx from"path";var B8e=25,O5t=2e3,z8e=6e4,kHr=1e4;function THr(){let t=process.env.JAVA_HOME,e=t?Tx.join(t,"bin","java"):"java";t&&ie("AGENTOS",`[RUNTIME] Using JAVA_HOME: ${t}`);try{let r=CHr(e,["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),n=r.match(/^\S+\s+(\d+)/);if(!n)return ie("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(`
|
|
1841
|
-
`)[0]?.trim()??`Java ${i}`;return i<B8e?(ie("AGENTOS",`[RUNTIME] WARN: Java ${i} detected but >= ${B8e} 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}):(ie("AGENTOS",`[RUNTIME] Java ${i} detected \u2014 OK (${s})`),{available:!0,version:s})}catch{return ie("AGENTOS",`[RUNTIME] WARN: java binary not found (tried: ${t?Tx.join(t,"bin","java"):"java in PATH"}). AgentOS will NOT be started. Set JAVA_HOME or ensure java >= ${B8e} is on PATH.`),{available:!1}}}async function PHr(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 OHr(t){let e=`http://localhost:${t}/management/health`,r=Date.now()+z8e;for(;Date.now()<r;){try{let n=await fetch(e);if(n.ok)return ie("AGENTOS",`[RUNTIME] Health check passed on port ${t}`),!0;ie("AGENTOS",`[RUNTIME] Health check on port ${t} returned ${n.status}, retrying in ${O5t}ms...`)}catch{}await new Promise(n=>setTimeout(n,O5t))}return ie("AGENTOS",`[RUNTIME] Health check on port ${t} timed out after ${z8e/1e3} s`),!1}async function U8e(t,e,r){let n=await DT(r+1,10),i=await DT(n+1,10);if(ie("AGENTOS",`[RUNTIME] Selected port ${n} for AgentOS (Express is on ${r})`),ie("AGENTOS",`[RUNTIME] Selected port ${i} for Neo4j embedded Bolt`),await PHr(n))return ie("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()=>{ie("AGENTOS","[RUNTIME] Adopted process \u2014 skipping shutdown")}};if(!THr().available)return null;let o=Tx.join(t,"agentos"),c=Tx.join(o,`agentos-service-${e}.jar`),{existsSync:u}=await import("fs");if(!u(c))return ie("AGENTOS",`[RUNTIME] JAR not found at ${c} \u2014 skipping AgentOS startup`),null;ie("AGENTOS","[RUNTIME] Spawning AgentOS \u2014 config:"),ie("AGENTOS",`[RUNTIME] port: ${n}`),ie("AGENTOS",`[RUNTIME] JAR: ${c}`),ie("AGENTOS",`[RUNTIME] CWD: ${o}`),ie("AGENTOS",`[RUNTIME] JAVA_HOME: ${process.env.JAVA_HOME??"(not set, using PATH)"}`),ie("AGENTOS","[RUNTIME] encryption: NONE (plaintext \u2014 temporary)"),ie("AGENTOS",`[RUNTIME] OAuth redirect: http://localhost:${r}/agentos/oauth/callback`);let f=process.env.JAVA_HOME,d=f?Tx.join(f,"bin","java"):"java",p=AHr(d,["-jar",c,`--server.port=${n}`],{cwd:o,env:{...process.env,
|
|
1841
|
+
`)[0]?.trim()??`Java ${i}`;return i<B8e?(ie("AGENTOS",`[RUNTIME] WARN: Java ${i} detected but >= ${B8e} 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}):(ie("AGENTOS",`[RUNTIME] Java ${i} detected \u2014 OK (${s})`),{available:!0,version:s})}catch{return ie("AGENTOS",`[RUNTIME] WARN: java binary not found (tried: ${t?Tx.join(t,"bin","java"):"java in PATH"}). AgentOS will NOT be started. Set JAVA_HOME or ensure java >= ${B8e} is on PATH.`),{available:!1}}}async function PHr(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 OHr(t){let e=`http://localhost:${t}/management/health`,r=Date.now()+z8e;for(;Date.now()<r;){try{let n=await fetch(e);if(n.ok)return ie("AGENTOS",`[RUNTIME] Health check passed on port ${t}`),!0;ie("AGENTOS",`[RUNTIME] Health check on port ${t} returned ${n.status}, retrying in ${O5t}ms...`)}catch{}await new Promise(n=>setTimeout(n,O5t))}return ie("AGENTOS",`[RUNTIME] Health check on port ${t} timed out after ${z8e/1e3} s`),!1}async function U8e(t,e,r){let n=await DT(r+1,10),i=await DT(n+1,10);if(ie("AGENTOS",`[RUNTIME] Selected port ${n} for AgentOS (Express is on ${r})`),ie("AGENTOS",`[RUNTIME] Selected port ${i} for Neo4j embedded Bolt`),await PHr(n))return ie("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()=>{ie("AGENTOS","[RUNTIME] Adopted process \u2014 skipping shutdown")}};if(!THr().available)return null;let o=Tx.join(t,"agentos"),c=Tx.join(o,`agentos-service-${e}.jar`),{existsSync:u}=await import("fs");if(!u(c))return ie("AGENTOS",`[RUNTIME] JAR not found at ${c} \u2014 skipping AgentOS startup`),null;ie("AGENTOS","[RUNTIME] Spawning AgentOS \u2014 config:"),ie("AGENTOS",`[RUNTIME] port: ${n}`),ie("AGENTOS",`[RUNTIME] JAR: ${c}`),ie("AGENTOS",`[RUNTIME] CWD: ${o}`),ie("AGENTOS",`[RUNTIME] JAVA_HOME: ${process.env.JAVA_HOME??"(not set, using PATH)"}`),ie("AGENTOS","[RUNTIME] encryption: NONE (plaintext \u2014 temporary)"),ie("AGENTOS",`[RUNTIME] OAuth redirect: http://localhost:${r}/agentos/oauth/callback`);let f=process.env.JAVA_HOME,d=f?Tx.join(f,"bin","java"):"java",p=AHr(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(`
|
|
1842
1842
|
`))C.trim()&&ie("AGENTOS",C.trim())}),p.stderr?.on("data",S=>{for(let C of S.toString().split(`
|
|
1843
1843
|
`))C.trim()&&ie("AGENTOS",C.trim())});let h=null,m=!1;p.on("error",S=>{h=S,ie("AGENTOS",`[RUNTIME] Spawn error: ${S.message}`)}),p.on("exit",(S,C)=>{m=!0,ie("AGENTOS",`[RUNTIME] Process exited \u2014 code=${S} signal=${C}`)}),ie("AGENTOS",`[RUNTIME] Waiting for AgentOS to become healthy on port ${n} (up to ${z8e/1e3} s)...`);let g=await OHr(n),v=h?h.message:null;if(!g||m||h){ie("AGENTOS",`[RUNTIME] AgentOS did not become healthy (healthy=${g}, exited=${m}, spawnError=${v}) \u2014 killing process`);try{p.kill("SIGKILL")}catch{}return null}ie("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(()=>{ie("AGENTOS","[RUNTIME] Graceful shutdown timed out \u2014 sending SIGKILL");try{p.kill("SIGKILL")}catch{}},kHr);p.once("exit",()=>{clearTimeout(C),ie("AGENTOS","[RUNTIME] AgentOS process exited"),S()}),ie("AGENTOS","[RUNTIME] Sending SIGTERM to AgentOS");try{p.kill("SIGTERM")}catch(T){clearTimeout(C),ie("AGENTOS",`[RUNTIME] Error sending SIGTERM: ${T}`),S()}});return{port:n,spawned:!0,shutdown:async()=>(process.removeListener("exit",y),b())}}function R5t(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 Hs=(0,cG.default)(),RHr=process.env.PORT?parseInt(process.env.PORT):process.env.BUILD_ENV==="development"?4100:3e3,I5t=!!process.env.PORT,N5t=DT(RHr,I5t?0:10,I5t),Jr=W1t();ie("INIT","Coday options:",Jr);var j5t=!Jr.noLog,Rx=new sj(j5t,Jr.logFolder);ie("INIT",`Usage logging ${j5t?"enabled":"disabled"} ${Jr.logFolder?`(custom folder: ${Jr.logFolder})`:""}`);ie("INIT","Webhook service initialized (will be initialized with prompt execution service)");var C5,uG,D5t=process.env.AGENTOS_EXTERNAL_USERID,Px=process.env.AGENTOS_URL;Px&&R5t(Px);var iG=Px??"http://localhost:8124",rm=null;Hs.use("/api/agentos",(t,e,r)=>{ie("AGENTOS",`[PROXY] ${t.method} ${t.path}`),D5t&&(t.headers["X-External-User-Id"]=D5t),r()},(0,F5t.createProxyMiddleware)({router:()=>iG,changeOrigin:!0,pathRewrite:{"^/api/agentos":""}}));ie("INIT",`AgentOS proxy configured: /api/agentos \u2192 ${iG} (${Px?"external mode":"managed mode"})`);Hs.use(cG.default.json({limit:"20mb"}));if(process.env.BUILD_ENV==="development"){let e=`http://localhost:${process.env.ANGULAR_CLIENT_PORT??"4200"}`;ie("INIT",`Development mode: proxying to Angular dev server at ${e}`),Promise.resolve().then(()=>Ur(L8e(),1)).then(({createProxyMiddleware:r})=>{let n=r({target:e,changeOrigin:!0,ws:!0});Hs.use("/",(i,s,a)=>{i.path.startsWith("/api")||i.path.startsWith("/events")?a():n(i,s,a)}),ie("INIT","Proxy middleware configured successfully")}).catch(r=>{console.error("Failed to load http-proxy-middleware:",r)})}else{let t=process.env.CODAY_CLIENT_PATH?Lh.resolve(process.env.CODAY_CLIENT_PATH):Lh.resolve(__dirname,"../coday-client/browser");if(ie("INIT",`Production mode: serving static files from ${t}`),process.env.CODAY_CLIENT_PATH&&ie("INIT","Using client path from CODAY_CLIENT_PATH environment variable"),!nG.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 e=Lh.join(t,"index.html");nG.existsSync(e)?ie("INIT",`Verified index.html exists at ${e}`):(console.error(`ERROR: index.html not found at: ${e}`),console.error("Client build may be incomplete. Try rebuilding with: pnpm nx run client:build"))}Hs.use(cG.default.static(t))}var sG=new gM(Jr.configDir),eP=Jr.project;if(eP&&!Jr.forcedProject){let t=process.cwd(),e=Lh.basename(t);if(sG.exists(e)){let r=sG.getConfig(e);if(r&&r.path===t&&!r.volatile)ie("INIT",`Default mode: found existing non-volatile project '${e}' for current directory`),eP=e;else{let n=fy.generateProjectId(t);ie("INIT",`Default mode: existing project '${e}' doesn't match path, using volatile ID ${n}`),eP=n}}else{let r=fy.generateProjectId(t);ie("INIT",`Default mode: no existing project found, using volatile ID ${r}`),eP=r}}var k5=new fy(sG,eP,Jr.forcedProject);C5=new pM(Jr.configDir,k5);C5.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>"});ie("INIT","Prompt service initialized");uG=new hM(C5);ie("INIT","Prompt execution service initialized (will be initialized with dependencies after thread manager)");var $5t=Lh.join(Jr.configDir,"projects"),M5t=new xM($5t),nm=new yM(sG,$5t,M5t),IHr=new yy;ie("INIT","MCP instance pool initialized");var Ox=new oV(Rx,k5,nm,C5,IHr);uG.initialize(Ox,nm,Jr,Rx);ie("INIT","Prompt execution service initialized");ie("INIT","Webhook service initialized with prompt execution delegation");var DHr=new Xf("config-api"),H8e=new uM(Jr.configDir,DHr),FHr=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function Ff(t){let e=q8e(t.headers,!!Jr.auth);if(FHr.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}cmt(Hs,Ff,Jr.configDir,!!Jr.auth);rmt(Hs,H8e,Ff);ymt(Hs,H8e,Ff);lmt(Hs,C5,Ff);dmt(Hs,uG,Ff);imt(Hs,k5,Ox.projectEventManager,nm,Ff,Ox,Jr);vmt(Hs,k5);smt(Hs,nm,M5t,Ox,Ff,Jr,H8e);amt(Hs,Ox,Ff,nm);var NHr=new oM(Jr.configDir,k5);umt(Hs,k5,Ff,Jr.configDir,Rx,C5,nm,NHr,Jr);var aG=new mM(Rx,C5,Jr.configDir);fmt(Hs,aG,Ff);mmt(Hs,Rx,Ff,Jr.auth);if(process.env.BUILD_ENV!=="development"){let t=process.env.CODAY_CLIENT_PATH?Lh.resolve(process.env.CODAY_CLIENT_PATH):Lh.resolve(__dirname,"../coday-client/browser"),e=Lh.resolve(t,"index.html");ie("INIT",`Catch-all route will serve: ${e}`),Hs.use((r,n,i)=>{if(r.path.startsWith("/api")||r.path.startsWith("/events")){n.status(404).send("Not found");return}ie("ROUTER",`Serving index.html for client route: ${r.path}`),nG.readFile(e,"utf8",(s,a)=>{s?(ie("ERROR",`Failed to read index.html from ${e}:`,s),ie("ERROR",`File exists check: ${nG.existsSync(e)}`),i(s)):n.type("html").send(a)})})}var oG=null;async function jHr(t){if(Px){ie("AGENTOS",`[PROVISION] External mode \u2014 target: ${Px}. No provisioning performed.`);return}ie("AGENTOS","[PROVISION] Managed mode \u2014 starting AgentOS provisioning...");try{let e=S5t(),r=k5t(Jr.configDir,e);r.outcome==="swapped"&&ie("AGENTOS",`[PROVISION] Swap applied: ${r.message}`);let n=w5t(Jr.configDir,e),i=n.artifacts[0]?.foundVersion??null,s=i!==null&&n.artifacts.every(a=>a.foundVersion===i);if(!n.allPresent&&s){if(ie("AGENTOS",`[PROVISION] Active version ${i} differs from target ${e} \u2014 spawning current, pre-fetching target in background`),ie("AGENTOS","[PROVISION] Starting AgentOS process..."),rm=await U8e(Jr.configDir,i,t),!rm){ie("AGENTOS","[PROVISION] AgentOS did not start. The proxy will return errors until AgentOS is available.");return}T5t(Jr.configDir,e).catch(a=>ie("AGENTOS","[UPDATE] Unhandled error in background pre-fetch:",a))}else{let a=await P5t(Jr.configDir,e,n.missing);if(ie("AGENTOS",`[PROVISION] Download outcome: ${a.outcome} \u2014 ${a.message}`),a.outcome!=="success"&&a.outcome!=="skipped:all-present"&&a.outcome!=="skipped:dev-version"){ie("AGENTOS","[PROVISION] Download failed \u2014 AgentOS will not be started. The proxy will return errors.");return}if(ie("AGENTOS","[PROVISION] Starting AgentOS process..."),rm=await U8e(Jr.configDir,e,t),!rm){ie("AGENTOS","[PROVISION] AgentOS did not start. The proxy will return errors until AgentOS is available.");return}}iG=`http://localhost:${rm.port}`,ie("AGENTOS",`[PROVISION] AgentOS is ready. Proxy target: ${iG} (${rm.spawned?"spawned by Coday":"adopted existing process"})`)}catch(e){ie("AGENTOS","[PROVISION] Unexpected error during provisioning (non-fatal):",e)}}Hs.use((t,e,r,n)=>{ie("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 $Hr(){let e=new Date(Date.now()-6048e5).toISOString();try{if(Jr.auth){ie("CLEANUP","autoCloseStaleThreads: skipped in --auth mode (no server-side user identity at startup)");return}let r=q8e({},!1),n=k5.listProjects(),i=0;for(let s of n)try{let o=(await nm.listThreads(s.name,r)).filter(c=>!c.closedByUser&&c.modifiedDate<e);for(let c of o)try{await nm.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)}}N5t.then(async t=>{Jr.baseUrl?ie("INIT",`Using configured base URL: ${Jr.baseUrl}`):(Jr.baseUrl=`http://localhost:${t}`,ie("INIT",`Base URL set to: ${Jr.baseUrl}`)),Hs.listen(t,()=>{console.log(`Server is running on http://localhost:${t}`)}),jHr(t).catch(e=>ie("AGENTOS","[PROVISION] Unhandled error:",e)),$Hr().catch(e=>console.error("autoCloseStaleThreads: unhandled error:",e));try{ie("CLEANUP","Starting thread cleanup service...");let e=Lh.join(Jr.configDir,"projects");oG=new bM(e,Rx),await oG.start(),ie("CLEANUP","Thread cleanup service started successfully")}catch(e){console.error("Failed to start thread cleanup service:",e)}try{ie("SCHEDULER","Initializing scheduler service..."),await aG.initialize(),aG.initializeExecution(uG),ie("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)});N5t.catch(t=>{t instanceof Error&&t.message.includes("already in use")&&process.stderr.write(`PORT_IN_USE: ${t.message}
|
|
1844
1844
|
`)});var tP=0;async function Ix(t){if(tP++,tP===2){console.log(`Received ${t} during shutdown (likely from child process cascade) \u2014 shutdown in progress, press Ctrl+C again to force exit`);return}tP>=3&&(console.log(`Received ${t} \u2014 forcing exit`),process.exit(1)),console.log(`Received ${t}, shutting down gracefully...`);try{rm?.spawned&&(console.log("Stopping AgentOS..."),await rm.shutdown()),console.log("Stopping scheduler service..."),aG.stop(),oG&&(console.log("Stopping thread cleanup service..."),await oG.stop()),console.log("Cleaning up thread Coday instances..."),await Ox.shutdown(),console.log("Graceful shutdown completed"),process.exit(0)}catch(e){console.error("Error during graceful shutdown:",e),process.exit(1)}}process.on("SIGTERM",()=>Ix("SIGTERM"));process.on("SIGINT",()=>Ix("SIGINT"));process.on("SIGUSR2",()=>Ix("SIGUSR2"));process.on("SIGHUP",()=>Ix("SIGHUP"));process.on("uncaughtException",t=>{if(console.error("Uncaught exception:",t),t.message==="no elements in sequence"||t.constructor.name==="EmptyErrorImpl"){console.log("Detected RxJS EmptyError during system sleep - this is expected behavior"),console.log("Process will continue normally after system wake");return}tP===0&&Ix("uncaughtException")});process.on("unhandledRejection",(t,e)=>{if(console.error("Unhandled rejection at:",e,"reason:",t),t&&typeof t=="object"){let r=t;if(r.message==="no elements in sequence"||r.constructor?.name==="EmptyErrorImpl"){console.log("Detected RxJS EmptyError rejection during system sleep - this is expected behavior");return}if(r.name==="TimeoutError"||r.message?.includes("timeout")){console.log("Detected timeout error - handling gracefully without shutdown");return}if(r.name==="AbortError"||r.message?.includes("aborted")){console.log("Detected abort error - handling gracefully without shutdown");return}}console.error("Critical unhandled rejection detected"),tP===0&&Ix("unhandledRejection")});
|