@whoz-oss/coday-server 0.0.0-workstream-forge.165 → 0.0.0-workstream-forge.167

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.165",
3
+ "version": "0.0.0-workstream-forge.167",
4
4
  "repository": "https://github.com/whoz-oss/coday",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
package/server.js CHANGED
@@ -173,7 +173,7 @@ ${m.join(`
173
173
  `,n===void 0?void 0:{mode:n}),n!==void 0&&Mt.chmodSync(r,n),Mt.renameSync(r,t)}import*as Lt from"path";var Lo=t=>Lt.join(t,"runtime"),b5=t=>Lt.join(t,"logs"),Oi=(t,e)=>Lt.join(b5(t),`${e}.log`),rl=t=>Lt.join(Lo(t),"state.json"),B1=t=>Lt.join(Lo(t),"secrets.json"),No=t=>Lt.join(t,"web-setup.json"),gn=t=>Lt.join(t,"agentos","data","database"),$1=t=>Lt.join(t,"agentos","data","exchange"),qo=t=>Lt.join(t,"factory","data","database");var y5=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function il(t){return typeof t=="string"&&t.length<=254&&y5.test(t.trim())}var al=t=>t.trim().toLowerCase();function gt(t){return Br(No(t))??{}}function Ri(t){let e=gt(t).identity?.email;return e&&il(e)?e:void 0}function L1(t,e){let n={...gt(t),identity:{email:al(e)}};return tr(No(t),n),n}function N1(t,e=()=>new Date){let n={...gt(t),setupDone:!0,setupDoneAt:e().toISOString()};return tr(No(t),n),n}function q1(t){try{return M1.readdirSync(gn(t)).length>0}catch{return!1}}var ol=(t,e)=>({orchestrator:t,profile:e,ports:{},downloads:{},provisioned:!1,updatedAt:new Date(0).toISOString()});function Ie(t){return Br(rl(t))}function D5(t,e,n=()=>new Date){return{...t,...e,ports:{...t.ports,...e.ports},downloads:{...t.downloads,...e.downloads},updatedAt:n().toISOString()}}function Zt(t,e,n=ol("in-process","managed")){let r=D5(Ie(t)??n,e);return tr(rl(t),r),r}function H1(t){let n=[[.85,t.agentos],[.15,t.factory]].filter(([,o])=>!!o);if(n.length===0)return{state:"idle"};let r=n.find(([,o])=>o.state==="error");if(r)return{state:"error",message:r[1].message};let i=n.reduce((o,[s])=>o+s,0),a=Math.round(n.reduce((o,[s,c])=>o+s*(c.state==="done"?100:c.percent??0),0)/i);return n.every(([,o])=>o.state==="done")?{state:"done",percent:100}:{state:n.some(([,o])=>o.state==="running")?"running":"idle",percent:a}}function U1(t,e=process.env){return()=>{if(e.AGENTOS_EXTERNAL_USERID)return e.AGENTOS_EXTERNAL_USERID;if(Ie(t)?.profile==="laptop")return Ri(t)}}var sl=8224,w5=7788,cl=8241;async function z1(t,e=sa){let n=new Set([t]),r=async s=>{let c=await e(s,10);for(;n.has(c);)c=await e(c+1,10);return n.add(c),c},i=await r(sl),a=await r(w5),o=await r(cl);return{express:t,agentos:i,agentosBolt:a,factory:o}}var Zo=bn(np(),1);import{spawn as E5}from"child_process";import*as vn from"fs";import*as W1 from"path";var C5=1e4;function ul(t,e,n){let r=Oi(t,e);vn.mkdirSync(W1.dirname(r),{recursive:!0});let i=vn.openSync(r,"a"),a=!1;return{write(o){n(o),a||vn.writeSync(i,o+`
174
174
  `)},close(){a||(a=!0,vn.closeSync(i))}}}function G1(t,e){if(!t)return;let n="";t.on("data",r=>{n+=r.toString();let i=n.split(`
175
175
  `);n=i.pop()??"";for(let a of i)a.trim()&&e.write(a.trimEnd())}),t.on("end",()=>{n.trim()&&e.write(n.trimEnd())})}function pl(t,e,n=E5){e.write(`[runtime] ${t.bin} ${t.args.join(" ")} (cwd ${t.cwd})`);let r=n(t.bin,t.args,{cwd:t.cwd,env:t.env,stdio:["ignore","pipe","pipe"],detached:!1});G1(r.stdout,e),G1(r.stderr,e);let i=!1,a=new Promise(c=>{r.once("error",u=>{i=!0,e.write(`[runtime] spawn error: ${u.message}`),c({code:null,signal:null,error:u.message})}),r.once("exit",(u,p)=>{i=!0,e.write(`[runtime] process exited code=${u} signal=${p}`),c({code:u,signal:p})})}),o=()=>{if(!i)try{r.kill("SIGKILL")}catch{}};return process.on("exit",o),a.then(()=>process.removeListener("exit",o)),{spec:t,child:r,exited:a,isDead:()=>i,stop:async()=>{if(i)return;let c=setTimeout(()=>{try{r.kill("SIGKILL")}catch{}},C5);try{r.kill("SIGTERM")}catch{clearTimeout(c);return}await a,clearTimeout(c)}}}var K1=t=>new Promise(e=>setTimeout(e,t));async function ll(t,e){let{timeoutMs:n,intervalMs:r=2e3,isDead:i=()=>!1,fetchFn:a=fetch,sleep:o=K1}=e,s=Date.now()+n;for(;Date.now()<s&&!i();){try{if((await a(t,{signal:AbortSignal.timeout(3e3)})).ok)return!0}catch{}await o(r)}return!1}async function Nt(t,e=fetch){try{return(await e(t,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}async function Ho(t,e={}){let{intervalMs:n=1e3,signal:r,sleep:i=K1}=e;for(;!r?.aborted;){let a=await t();if(a)return a;await i(n)}}import*as Pi from"path";import{execFileSync as F5}from"child_process";import*as V1 from"path";var $r=25;function Uo(t=process.env){return t.JAVA_HOME?V1.join(t.JAVA_HOME,"bin","java"):"java"}function A5(t){let e=t.match(/^\S+\s+(\d+)/);return e?{major:parseInt(e[1]??"0",10),line:t.split(`
176
- `)[0]?.trim()??`Java ${e[1]}`}:null}function S5(t=process.platform){let e=`Coday needs Java ${$r} or newer.`;return t==="darwin"?`${e} Install it with: brew install --cask temurin@${$r}`:t==="win32"?`${e} Install it with: winget install EclipseAdoptium.Temurin.${$r}.JDK`:`${e} Install it with SDKMAN (sdk install java ${$r}-tem) or from https://adoptium.net/temurin/releases/?version=${$r}`}function zo(t=r=>F5(r,["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),e=process.env,n=process.platform){let r=S5(n),i;try{i=t(Uo(e))}catch{return{state:"missing",hint:r}}let a=A5(i);return a?a.major<$r?{state:"too-old",version:a.line,major:a.major,hint:r}:{state:"ok",version:a.line,major:a.major}:{state:"missing",hint:r}}var Ne="127.0.0.1";function Go(t,e){return Pi.join(t,"agentos",`agentos-service-${e}.jar`)}function Wo(t,e){return Pi.join(t,"factory",`factory-service-${e}.jar`)}function Y1(t){let{configDir:e,profile:n,baseEnv:r,port:i,boltPort:a,expressPort:o}=t,s=Pi.join(e,"agentos"),c=r.AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT??String(a),u={...r,AGENTOS_OAUTH_REDIRECT_URI:r.AGENTOS_OAUTH_REDIRECT_URI??`http://localhost:${o}/agentos/oauth/callback`,AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT:c,SPRING_NEO4J_URI:r.SPRING_NEO4J_URI??`bolt://localhost:${c}`},p=["-jar",Go(e,t.version),`--server.port=${i}`];return n==="laptop"&&(p.push(`--server.address=${Ne}`),u.AGENTOS_SECURITY_MODE="auth",t.identityEmail&&(u.AGENTOS_BOOTSTRAP_ADMIN_EXTERNAL_ID=t.identityEmail),u.AGENTOS_PERSISTENCE_DATA_DIR=gn(e),u.AGENTOS_EXCHANGE_MOUNT_ROOT=$1(e),u.AGENTOS_ENCRYPTION_KEY=t.secrets?.agentosEncryptionKey??"NONE",u.AGENTOS_ENCRYPTION_SALT=t.secrets?.agentosEncryptionSalt??"NONE"),{name:"agentos",bin:Uo(r),args:p,env:u,cwd:s,port:i,healthUrl:`http://${Ne}:${i}/management/health`}}function J1(t){let{configDir:e,profile:n,baseEnv:r,port:i}=t,a={...r,AGENTOS_URL:t.agentosUrl},o=["--enable-native-access=ALL-UNNAMED","-jar",Wo(e,t.version),`--server.port=${i}`];return n==="laptop"&&(a.FACTORY_SECURITY_MODE="auth",a.FACTORY_BIND_HOST=Ne,o.push(`--server.address=${Ne}`),a.FACTORY_PERSISTENCE_DATA_DIR=qo(e),t.secrets&&(a.FACTORY_FAKE_IDP_SECRET=t.secrets.factoryFakeIdpSecret,a.FACTORY_ENCRYPTION_KEY=t.secrets.factoryEncryptionKey,a.FACTORY_ENCRYPTION_SALT=t.secrets.factoryEncryptionSalt)),{name:"factory",bin:Uo(r),args:o,env:a,cwd:Pi.join(e,"factory"),port:i,healthUrl:`http://${Ne}:${i}/actuator/health`}}var Mr=class extends Error{constructor(n,r,i,a){super(`AgentOS ${r} ${i} -> HTTP ${n}${a?`: ${a.slice(0,300)}`:""}`);this.status=n;this.method=r;this.path=i;this.body=a}},Ko=class{constructor(e,n,r=fetch){this.baseUrl=e;this.userExternalId=n;this.fetchFn=r}base(){return typeof this.baseUrl=="function"?this.baseUrl():this.baseUrl}async request(e,n,r){let i=await this.fetchFn(`${this.base()}${n}`,{method:e,headers:{Accept:"application/json","X-External-User-Id":this.userExternalId,...r===void 0?{}:{"Content-Type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(3e4)}),a=await i.text();if(!i.ok)throw new Mr(i.status,e,n,a);return a?JSON.parse(a):void 0}listPlatformProviders(){return this.request("GET","/api/ai-providers?namespaceId=none")}createProvider(e){return this.request("POST","/api/ai-providers",{...e,namespaceId:null,userId:null})}updateProvider(e,n){return this.request("PUT",`/api/ai-providers/${e}`,{...n,namespaceId:null,userId:null})}listModelsOfProvider(e){return this.request("GET",`/api/ai-models/by-parentId/${e}`)}createModel(e){return this.request("POST","/api/ai-models",e)}updateModel(e,n){return this.request("PUT",`/api/ai-models/${e}`,n)}getMe(){return this.request("GET","/api/users/me")}findNamespacesByExternalIds(e){return this.request("POST","/api/namespaces/by-external-ids",e)}updateNamespace(e,n){return this.request("PUT",`/api/namespaces/${e}`,n)}searchAgents(e){return this.request("POST","/api/agent-configs/search",{namespaceId:e,userExternalId:this.userExternalId})}};import*as eD from"fs";import*as en from"path";var fl=["FRONTIER","BIGGEST","BIG","SMALL"],_5={FRONTIER:{inputMTokens:10,outputMTokens:50,cacheRead:.25,cacheWrite:12.5},BIGGEST:{inputMTokens:4,outputMTokens:20,cacheRead:.2,cacheWrite:5},BIG:{inputMTokens:2,outputMTokens:10,cacheRead:.1,cacheWrite:2.5},SMALL:{inputMTokens:.1,outputMTokens:.5,cacheRead:.01,cacheWrite:.125}},O5={FRONTIER:{inputMTokens:10,outputMTokens:50,cacheRead:.25},BIGGEST:{inputMTokens:4,outputMTokens:20,cacheRead:.2},BIG:{inputMTokens:2,outputMTokens:10,cacheRead:.2},SMALL:{inputMTokens:.1,outputMTokens:.5,cacheRead:.01}},Vo={FRONTIER:{inputMTokens:10,outputMTokens:50,cacheRead:1},BIGGEST:{inputMTokens:2,outputMTokens:10,cacheRead:.1},BIG:{inputMTokens:1,outputMTokens:5,cacheRead:.05},SMALL:{inputMTokens:.1,outputMTokens:.5,cacheRead:.01}},X1=(t,e,n)=>({FRONTIER:{apiModelName:`${t}${e}`,description:"Claude Fable 5.1: demanding reasoning and long-horizon agentic work",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.FRONTIER},BIGGEST:{apiModelName:`${t}claude-opus-5-5`,description:"Claude Opus 5.5: long-running agentic coding and knowledge work",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.BIGGEST},BIG:{apiModelName:`${t}claude-sonnet-5-5`,description:"Claude Sonnet 5.5: the best combination of speed and intelligence",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.BIG},SMALL:{apiModelName:`${t}claude-haiku-5-5`,description:"Claude Haiku 5.5: fast, high-volume tasks",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.SMALL}}),R5=t=>({FRONTIER:{apiModelName:`${t}gpt-6-astra`,description:"GPT-6 Astra: the most capable model for the most demanding work",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.FRONTIER},BIGGEST:{apiModelName:`${t}gpt-6.1-sol`,description:"GPT-6.1 Sol: near-Astra performance for complex work at a lower cost",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.BIGGEST},BIG:{apiModelName:`${t}gpt-6.1-terra`,description:"GPT-6.1 Terra: fast and efficient, the everyday model",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.BIG},SMALL:{apiModelName:`${t}gpt-6-luna`,description:"GPT-6 Luna: the most efficient model for focused, high-volume tasks",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.SMALL}}),Yo={anthropic:{id:"anthropic",name:"anthropic",label:"Anthropic",description:"Claude models, directly from Anthropic.",apiType:"Anthropic",baseUrl:"https://api.anthropic.com",keyUrl:"https://console.anthropic.com/settings/keys",models:X1("","claude-fable-5-1",_5)},openai:{id:"openai",name:"openai",label:"OpenAI",description:"GPT models, directly from OpenAI.",apiType:"OpenAI",baseUrl:"https://api.openai.com",keyUrl:"https://platform.openai.com/api-keys",models:R5("")},requesty:{id:"requesty",name:"requesty",label:"Requesty",description:"One key for Claude, GPT and 600+ other models through the Requesty router.",apiType:"OpenAI",baseUrl:"https://router.eu.requesty.ai",keyUrl:"https://app.requesty.ai/api-keys",models:X1("anthropic/","claude-fable-5.1",O5)}},FB=Object.keys(Yo);function Jo(t){return Yo[t]}function Q1(t,e){let n=Math.min(Math.max(Math.trunc(t),1),Math.max(e,1));return(e-n+1)*10}var Ti="Coday",wt=class extends Error{},Z1=(t,e)=>{let n=en.relative(e,t);return n===""||!n.startsWith("..")&&!en.isAbsolute(n)};function tD(t,e){let n=t;if(!n||!Array.isArray(n.providers)||n.providers.length===0)throw new wt("Choose at least one provider and give its API key.");let r=new Set;for(let a of n.providers){if(!a||typeof a.id!="string"||!Jo(a.id))throw new wt(`Unknown provider '${String(a?.id)}'.`);if(r.has(a.id))throw new wt(`Provider '${a.id}' is listed twice.`);if(r.add(a.id),typeof a.apiKey!="string"||a.apiKey.trim().length<8)throw new wt(`The API key of ${a.id} looks too short.`);if(!Number.isFinite(a.rank))throw new wt(`The rank of ${a.id} is missing.`)}if(typeof n.sharedExchangePath!="string"||!en.isAbsolute(n.sharedExchangePath))throw new wt("The files folder must be an absolute path.");let i=en.normalize(n.sharedExchangePath);if(e){let a=en.resolve(e);if(Z1(i,a)||Z1(a,i))throw new wt(`The files folder cannot contain or be inside ${a}, where Coday keeps its data and keys. Choose another folder.`)}return{providers:n.providers.map(a=>({id:a.id,apiKey:a.apiKey.trim(),rank:a.rank})),sharedExchangePath:i}}var nD=t=>new Promise(e=>setTimeout(e,t)),P5=t=>t instanceof Error?t.message:String(t);function T5(t,e,n){return t instanceof Mr&&t.status===403&&n===!1?`AgentOS refused: ${e} is not an administrator of this AgentOS, and only an administrator can configure the providers and the files folder. Use the email of its administrator, or start again with an empty AgentOS data folder.`:P5(t)}var I5=(t,e)=>e.reduce((n,r)=>r?n.split(r).join("***"):n,t);async function j5(t,e,n,r){let i={name:e.name,description:`${e.label} (created by the first-run setup)`,apiType:e.apiType,baseUrl:e.baseUrl,apiKey:n},a=r.find(s=>s.name.toLowerCase()===e.name.toLowerCase());if(a?.id)return await t.client.updateProvider(a.id,i),a.id;let o=await t.client.createProvider(i);if(!o.id)throw new Error(`AgentOS returned no id for the ${e.label} provider`);return o.id}var k5=["inputMTokens","outputMTokens","cacheRead","cacheWrite"],B5=(t,e)=>k5.every(n=>(t?.[n]??null)===(e?.[n]??null));async function $5(t,e,n,r){let i=await t.client.listModelsOfProvider(n);for(let a of fl){let o=e.models[a],s={aiProviderId:n,apiModelName:o.apiModelName,alias:a,priority:r,description:o.description,pricing:o.pricing,...o.contextWindow?{contextWindow:o.contextWindow}:{},...o.maxCompletionTokens?{maxCompletionTokens:o.maxCompletionTokens}:{}},c=i.find(u=>u.alias?.toLowerCase()===a.toLowerCase());c?c.id&&(c.apiModelName!==s.apiModelName||c.priority!==r||!B5(c.pricing,s.pricing))&&await t.client.updateModel(c.id,s):await t.client.createModel(s)}}async function M5(t){let e=t.namespaceAttempts??30,n=t.namespaceIntervalMs??2e3,r=t.sleep??nD,i=`user:${t.userEmail}`;for(let a=1;a<=e;a++){let o=await t.client.findNamespacesByExternalIds([i]).catch(c=>{if(c instanceof Mr&&[401,403,404].includes(c.status))return[];throw c}),s=o.find(c=>c.externalId===i)??o[0];if(s?.id)return s;await r(n)}throw new Error(`Your personal namespace (${i}) was not created by AgentOS in time. Retry in a moment.`)}async function L5(t,e){let n=t.namespaceAttempts??30,r=t.namespaceIntervalMs??2e3,i=t.sleep??nD;for(let a=1;a<=n;a++){if((await t.client.searchAgents(e)).some(s=>s.name.toLowerCase()===Ti.toLowerCase()&&s.enabled!==!1))return;await i(r)}throw new Error(`The ${Ti} agent is not deployed in your namespace.`)}async function rD(t,e,n=()=>{}){let{tracker:r}=e,i=t.providers.map(s=>s.apiKey),a=e.mkdir??(s=>void eD.mkdirSync(s,{recursive:!0}));r.start();let o;try{if(r.step("providers","running","Waiting for AgentOS"),!await e.waitForAgentos())throw new Error("AgentOS did not start. Check the agentos log.");r.step("providers","running","Identifying you"),o=(await e.client.getMe()).isAdmin;let s=[...t.providers].sort((f,d)=>f.rank-d.rank),c=await e.client.listPlatformProviders(),u=new Map;for(let[f,d]of s.entries()){let m=Jo(d.id);r.step("providers","running",`Configuring ${m.label}`),u.set(d.id,await j5(e,m,d.apiKey,c))}r.step("providers","done"),r.step("models","running");for(let[f,d]of s.entries()){let m=Jo(d.id);await $5(e,m,u.get(d.id),Q1(f+1,s.length))}r.step("models","done",`${s.length*fl.length} models`),r.step("namespace","running","Waiting for your personal namespace");let p=await M5(e);return r.setNamespaceId(p.id),a(t.sharedExchangePath),(p.sharedExchangePath!==t.sharedExchangePath||p.defaultAgentName!==Ti)&&await e.client.updateNamespace(p.id,{...p,sharedExchangePath:t.sharedExchangePath,defaultAgentName:Ti}),r.step("namespace","done",t.sharedExchangePath),r.step("agent","running",`Checking the ${Ti} agent`),await L5(e,p.id),r.step("agent","done"),r.finish(),n(),!0}catch(s){return r.fail(I5(T5(s,e.userEmail,o),i)),!1}}import*as Et from"fs";import*as Xo from"os";import*as vt from"path";var $e=class extends Error{constructor(n,r){super(r);this.status=n}},iD=(t=Xo.homedir(),e=process.env)=>e.CODAY_DEFAULT_FILES_DIR&&vt.isAbsolute(e.CODAY_DEFAULT_FILES_DIR)?vt.normalize(e.CODAY_DEFAULT_FILES_DIR):vt.join(t,"Coday");function aD(t,e){let n=t===void 0||t===""?e:t;if(n.includes("\0"))throw new $e(400,"Invalid path.");if(!vt.isAbsolute(n))throw new $e(400,"The path must be absolute.");return vt.normalize(n)}function oD(t,e={}){let n=e.home??Xo.homedir(),r=aD(t,n),i;try{i=Et.realpathSync(r)}catch{throw new $e(404,"This folder does not exist.")}let a;try{a=Et.statSync(i)}catch{throw new $e(404,"This folder does not exist.")}if(!a.isDirectory())throw new $e(400,"This path is not a folder.");let o;try{o=Et.readdirSync(i,{withFileTypes:!0})}catch{throw new $e(403,"This folder cannot be read.")}let s=[],c=0;for(let p of o){let l=vt.join(i,p.name),f=p.isDirectory(),d=p.isSymbolicLink();if(d)try{f=Et.statSync(l).isDirectory()}catch{f=!1}if(f){if(!e.showHidden&&p.name.startsWith(".")){c++;continue}s.push({name:p.name,path:l,...d?{symlink:!0}:{}})}}s.sort((p,l)=>p.name.localeCompare(l.name,void 0,{sensitivity:"base"}));let u=vt.dirname(i);return{path:i,parent:u===i?null:u,home:n,entries:s,hiddenCount:c}}var N5=/[\\/\0]|^\.{1,2}$/;function sD(t,e){if(typeof e!="string"||e.trim()===""||N5.test(e.trim())||e.length>255)throw new $e(400,"Use a plain folder name (no slashes).");let n=aD(t,Xo.homedir()),r;try{if(r=Et.realpathSync(n),!Et.statSync(r).isDirectory())throw new Error("not a directory")}catch{throw new $e(404,"The parent folder does not exist.")}let i=vt.join(r,e.trim());try{Et.mkdirSync(i)}catch(a){let o=a.code;throw o==="EEXIST"?new $e(409,"This folder already exists."):o==="EACCES"||o==="EPERM"?new $e(403,"Not allowed to create a folder here."):new $e(400,"The folder could not be created.")}return{path:i}}var q5=["providers","models","namespace","agent"],cD=()=>({status:"idle",steps:{providers:{state:"pending"},models:{state:"pending"},namespace:{state:"pending"},agent:{state:"pending"}}}),Qo=class{snapshot=cD();get(){return JSON.parse(JSON.stringify(this.snapshot))}isRunning(){return this.snapshot.status==="running"}start(){this.snapshot={...cD(),status:"running"}}step(e,n,r){this.snapshot.steps[e]={state:n,...r?{message:r}:{}}}setNamespaceId(e){this.snapshot.namespaceId=e}finish(){this.snapshot.status="done"}fail(e){this.snapshot.status="error",this.snapshot.error=e;for(let n of q5)this.snapshot.steps[n].state==="running"&&(this.snapshot.steps[n]={state:"error",message:e})}};function uD(t,e,n,r,i=!1){if(!t)return{ok:!1,status:403,message:"First-run setup is not available here."};if(e.setupDone)return{ok:!1,status:403,message:"Setup is already done."};let a=e.identity?.email;return a&&a===r?{ok:!0}:a&&(n?.agentosStarted||i)?{ok:!1,status:409,message:`AgentOS already started for ${a}; to use another email, stop Coday and delete web-setup.json and the agentos data folder.`}:{ok:!0}}function H5(t){return t?t.state==="ok"?{state:"done",version:t.version}:{state:"blocked",hint:t.hint,...t.state==="too-old"?{version:t.version}:{}}:{state:"pending"}}function U5(t,e={}){if(!t)return{state:"pending"};if(e.agentos&&e.factory)return{state:"done",percent:100};let{agentos:n,factory:r}=t.downloads,i=H1({agentos:e.agentos?void 0:n,factory:e.factory||r?.state==="error"?void 0:r});switch(i.state){case"done":return{state:"done",percent:100};case"error":return{state:"error",message:i.message};case"running":return{state:"running",percent:i.percent};default:return{state:"pending"}}}function pD(t){let{setup:e,state:n,apply:r}=t,i=t.external??{},a=!!e.setupDone,o=i.agentos&&i.factory?{state:"done"}:H5(n?.java),s=U5(n,i),c;t.agentosHealthy?c={state:"done"}:i.agentos?c=n?{state:"running",message:"Waiting for AgentOS"}:{state:"pending"}:s.state==="error"?c={state:"error",message:s.message}:o.state==="blocked"?c={state:"blocked",message:"Waiting for Java"}:!e.identity&&n?.profile==="laptop"?c={state:"pending",message:"Waiting for your email"}:n?n.agentosStarted?c={state:"running",message:"Starting AgentOS"}:c={state:"running",message:s.state==="done"?"Starting AgentOS":"Preparing AgentOS"}:c={state:"pending"};let u=n?.downloads.factory,p=t.factoryHealthy?{state:"done"}:u?.state==="error"?{state:"error",message:u.message}:c.state==="done"?{state:"running"}:{state:"pending"},l={state:"done"},f=a?{providers:l,models:l,namespace:l,agent:l}:r.steps;return{mode:n?.profile??"managed",setupEnabled:t.setupEnabled,setupDone:a,...e.identity?{identity:e.identity}:{},steps:{download:s,java:o,agentos:c,factory:p,...f},apply:{status:a?"done":r.status,...r.error?{error:r.error}:{}},...r.namespaceId?{namespaceId:r.namespaceId}:{}}}var z5=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]),lD=t=>t.replace(/\/+$/,""),G5=t=>!!t&&z5.has(t),W5=new Set(["localhost","127.0.0.1","[::1]"]),fD=t=>{try{return W5.has(new URL(t).hostname)}catch{return!1}},K5=(t,e)=>!!t&&fD(`http://${t}`)&&(e===void 0||fD(e));function dl(t){let e=Ie(t)?.ports.agentos;return e?`http://${Ne}:${e}`:void 0}function dD(t){let{configDir:e,setupEnabled:n}=t,r=t.fetchFn??fetch,i=t.tracker??new Qo,a=(0,Zo.Router)();a.use(Zo.default.json({limit:"100kb"}));let o=(c,u,p)=>{if(!n){u.status(403).json({error:"First-run setup is not available here."});return}if(!G5(c.socket.remoteAddress)||!K5(c.headers.host,c.headers.origin)){u.status(403).json({error:"First-run setup is only available from this machine."});return}p()},s=(c,u,p)=>{if(gt(e).setupDone){u.status(403).json({error:"Setup is already done."});return}p()};return a.get("/status",async(c,u)=>{let p=Ie(e),l=dl(e),f=p?.ports.factory,d=t.externalAgentosUrl?`${lD(t.externalAgentosUrl)}/management/health`:l&&`${l}/management/health`,m=t.externalFactoryUrl?`${lD(t.externalFactoryUrl)}/actuator/health`:f&&`http://${Ne}:${f}/actuator/health`,[h,g]=await Promise.all([d?Nt(d,r):!1,m?Nt(m,r):!1]);u.setHeader("Cache-Control","no-store"),u.json({...pD({setupEnabled:n,setup:gt(e),state:p,agentosHealthy:h,factoryHealthy:g,apply:i.get(),external:{agentos:!!t.externalAgentosUrl,factory:!!t.externalFactoryUrl}}),defaults:{sharedExchangePath:iD(t.homeDir)},providers:Object.values(Yo).map(F=>({id:F.id,label:F.label,description:F.description,keyUrl:F.keyUrl}))})}),a.post("/identity",o,s,(c,u)=>{let p=c.body?.email;if(!il(p)){u.status(400).json({error:"Enter a valid email address."});return}let l=al(p),f=uD(n,gt(e),Ie(e),l,q1(e));if(!f.ok){u.status(f.status).json({error:f.message});return}u.json({identity:L1(e,l).identity})}),a.get("/browse",o,s,(c,u)=>{try{let p=typeof c.query.path=="string"?c.query.path:void 0;u.json(oD(p,{home:t.homeDir,showHidden:c.query.hidden==="true"}))}catch(p){p instanceof $e?u.status(p.status).json({error:p.message}):u.status(500).json({error:"Could not list this folder."})}}),a.post("/mkdir",o,s,(c,u)=>{let{path:p,name:l}=c.body??{};try{if(typeof p!="string"||typeof l!="string")throw new $e(400,"path and name are required.");u.status(201).json(sD(p,l))}catch(f){f instanceof $e?u.status(f.status).json({error:f.message}):u.status(500).json({error:"The folder could not be created."})}}),a.post("/apply",o,s,(c,u)=>{let p=gt(e).identity?.email;if(!p){u.status(409).json({error:"Enter your email first."});return}if(i.isRunning()){u.status(202).json({status:"running"});return}let l;try{l=tD(c.body,e)}catch(f){u.status(400).json({error:f instanceof wt?f.message:"Invalid request."});return}rD(l,{client:new Ko(()=>dl(e)??`http://${Ne}:0`,p,r),waitForAgentos:async()=>{let f=Date.now()+6e5;for(;Date.now()<f;){let d=dl(e);if(d&&await Nt(`${d}/management/health`,r))return!0;await new Promise(m=>setTimeout(m,1500))}return!1},tracker:i,userEmail:p,...t.applyTimings},()=>N1(e)),u.status(202).json({status:"running"})}),a}function ml(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 V5=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function vl({codayOptions:t,setupEnabled:e}){let n=(0,Ii.default)(),{configDir:r}=t,i=process.env.AGENTOS_URL,a=process.env.FACTORY_URL;i&&ml(i),a&&ml(a);let o=(f,d)=>`http://127.0.0.1:${Ie(r)?.ports[f]??d}`,s=()=>i??o("agentos",sl),c=()=>a??o("factory",cl),u=U1(r),p=(f,d)=>{T1(f,P1({authEnabled:!!t.auth,envUserId:u(),resolveUser:()=>l(d)}))};function l(f){let d=j1(f.headers,!!t.auth);if(V5.includes(d.toLowerCase()))throw new Error(`Security error: Cannot run with username "${d}". 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 d}if(n.use("/api/setup",dD({configDir:r,setupEnabled:e,externalAgentosUrl:i,externalFactoryUrl:a})),n.use("/api/agentos",A1(s,{onProxyReq:(f,d)=>{ae("AGENTOS",`[PROXY] ${d.method} ${d.url}`),p(f,d)}})),n.use(O1(c,{onProxyReq:(f,d)=>{ae("FACTORY",`[PROXY] ${d.method} ${d.url}`),p(f,d)}})),ae("INIT",`Proxies: /api/agentos -> ${i??"managed AgentOS (state.json)"}, /api/factory -> ${a??"managed Factory (state.json)"}`),n.use(Ii.default.json({limit:"20mb"})),process.env.BUILD_ENV==="development"){let f=`http://localhost:${process.env.ANGULAR_CLIENT_PORT??"4200"}`,d=`http://localhost:${process.env.FACTORY_COCKPIT_PORT??"4300"}`,m=g=>g==="/factory"||g.startsWith("/factory/"),h=g=>g.startsWith("/api")||g.startsWith("/events");n.use((0,gl.createProxyMiddleware)({target:d,changeOrigin:!0,ws:!0,pathFilter:g=>m(g)})),n.use((0,gl.createProxyMiddleware)({target:f,changeOrigin:!0,ws:!0,pathFilter:g=>!h(g)&&!m(g)})),ae("INIT",`Development mode: /factory \u2192 ${d}, other non-API routes \u2192 ${f}`)}else{let f=process.env.CODAY_CLIENT_PATH?nr.resolve(process.env.CODAY_CLIENT_PATH):nr.resolve(__dirname,"../coday-client/browser"),d=process.env.CODAY_FACTORY_COCKPIT_PATH?nr.resolve(process.env.CODAY_FACTORY_COCKPIT_PATH):nr.resolve(__dirname,"../coday-factory-cockpit/browser");ae("INIT",`Production mode: serving static files from ${f}`),ae("INIT",`Production mode: serving factory cockpit static files from ${d}`),mD(f,"client","pnpm nx run client:build"),mD(d,"factory cockpit","pnpm nx run factory-cockpit:build"),n.use("/factory",Ii.default.static(d)),n.use(Ii.default.static(f));let m=nr.resolve(f,"index.html"),h=nr.resolve(d,"index.html");n.use((g,F,R)=>{if(g.path.startsWith("/api")||g.path.startsWith("/events")){F.status(404).send("Not found");return}let A=g.path==="/factory"||g.path.startsWith("/factory/")?h:m;ae("ROUTER",`Serving index.html for client route: ${g.path}`),hl.readFile(A,"utf8",(k,$)=>{k?(ae("ERROR",`Failed to read index.html from ${A}:`,k),R(k)):F.type("html").send($)})})}return n.use((f,d,m,h)=>{ae("ERROR",`Request error on ${d.method} ${d.path}:`,f.message),console.error(f.stack),process.env.BUILD_ENV==="development"?m.status(500).json({error:"Internal Server Error",message:f.message,stack:f.stack}):m.status(500).send("Something went wrong!")}),n}function mD(t,e,n){(!hl.existsSync(t)||!hl.existsSync(nr.join(t,"index.html")))&&(console.error(`ERROR: ${e} build not found at ${t}`),console.error(`Please build it first with: ${n}`))}import*as xn from"fs";import*as hD from"path";import{format as Y5}from"util";function xl(t){xn.mkdirSync(hD.dirname(t),{recursive:!0});let e=xn.openSync(t,"a"),n={log:console.log,warn:console.warn,error:console.error};for(let r of["log","warn","error"]){let i=n[r].bind(console);console[r]=(...a)=>{i(...a);try{xn.writeSync(e,Y5(...a)+`
176
+ `)[0]?.trim()??`Java ${e[1]}`}:null}function S5(t=process.platform){let e=`Coday needs Java ${$r} or newer.`;return t==="darwin"?`${e} Install it with: brew install --cask temurin@${$r}`:t==="win32"?`${e} Install it with: winget install EclipseAdoptium.Temurin.${$r}.JDK`:`${e} Install it with SDKMAN (sdk install java ${$r}-tem) or from https://adoptium.net/temurin/releases/?version=${$r}`}function zo(t=r=>F5(r,["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),e=process.env,n=process.platform){let r=S5(n),i;try{i=t(Uo(e))}catch{return{state:"missing",hint:r}}let a=A5(i);return a?a.major<$r?{state:"too-old",version:a.line,major:a.major,hint:r}:{state:"ok",version:a.line,major:a.major}:{state:"missing",hint:r}}var Ne="127.0.0.1";function Go(t,e){return Pi.join(t,"agentos",`agentos-service-${e}.jar`)}function Wo(t,e){return Pi.join(t,"factory",`factory-service-${e}.jar`)}function Y1(t){let{configDir:e,profile:n,baseEnv:r,port:i,boltPort:a,expressPort:o}=t,s=Pi.join(e,"agentos"),c=r.AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT??String(a),u={...r,AGENTOS_OAUTH_REDIRECT_URI:r.AGENTOS_OAUTH_REDIRECT_URI??`http://localhost:${o}/oauth/callback`,AGENTOS_PERSISTENCE_EMBEDDED_BOLT_PORT:c,SPRING_NEO4J_URI:r.SPRING_NEO4J_URI??`bolt://localhost:${c}`},p=["-jar",Go(e,t.version),`--server.port=${i}`];return n==="laptop"&&(p.push(`--server.address=${Ne}`),u.AGENTOS_SECURITY_MODE="auth",t.identityEmail&&(u.AGENTOS_BOOTSTRAP_ADMIN_EXTERNAL_ID=t.identityEmail),u.AGENTOS_PERSISTENCE_DATA_DIR=gn(e),u.AGENTOS_EXCHANGE_MOUNT_ROOT=$1(e),u.AGENTOS_ENCRYPTION_KEY=t.secrets?.agentosEncryptionKey??"NONE",u.AGENTOS_ENCRYPTION_SALT=t.secrets?.agentosEncryptionSalt??"NONE"),{name:"agentos",bin:Uo(r),args:p,env:u,cwd:s,port:i,healthUrl:`http://${Ne}:${i}/management/health`}}function J1(t){let{configDir:e,profile:n,baseEnv:r,port:i}=t,a={...r,AGENTOS_URL:t.agentosUrl},o=["--enable-native-access=ALL-UNNAMED","-jar",Wo(e,t.version),`--server.port=${i}`];return n==="laptop"&&(a.FACTORY_SECURITY_MODE="auth",a.FACTORY_BIND_HOST=Ne,o.push(`--server.address=${Ne}`),a.FACTORY_PERSISTENCE_DATA_DIR=qo(e),t.secrets&&(a.FACTORY_FAKE_IDP_SECRET=t.secrets.factoryFakeIdpSecret,a.FACTORY_ENCRYPTION_KEY=t.secrets.factoryEncryptionKey,a.FACTORY_ENCRYPTION_SALT=t.secrets.factoryEncryptionSalt)),{name:"factory",bin:Uo(r),args:o,env:a,cwd:Pi.join(e,"factory"),port:i,healthUrl:`http://${Ne}:${i}/actuator/health`}}var Mr=class extends Error{constructor(n,r,i,a){super(`AgentOS ${r} ${i} -> HTTP ${n}${a?`: ${a.slice(0,300)}`:""}`);this.status=n;this.method=r;this.path=i;this.body=a}},Ko=class{constructor(e,n,r=fetch){this.baseUrl=e;this.userExternalId=n;this.fetchFn=r}base(){return typeof this.baseUrl=="function"?this.baseUrl():this.baseUrl}async request(e,n,r){let i=await this.fetchFn(`${this.base()}${n}`,{method:e,headers:{Accept:"application/json","X-External-User-Id":this.userExternalId,...r===void 0?{}:{"Content-Type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r),signal:AbortSignal.timeout(3e4)}),a=await i.text();if(!i.ok)throw new Mr(i.status,e,n,a);return a?JSON.parse(a):void 0}listPlatformProviders(){return this.request("GET","/api/ai-providers?namespaceId=none")}createProvider(e){return this.request("POST","/api/ai-providers",{...e,namespaceId:null,userId:null})}updateProvider(e,n){return this.request("PUT",`/api/ai-providers/${e}`,{...n,namespaceId:null,userId:null})}listModelsOfProvider(e){return this.request("GET",`/api/ai-models/by-parentId/${e}`)}createModel(e){return this.request("POST","/api/ai-models",e)}updateModel(e,n){return this.request("PUT",`/api/ai-models/${e}`,n)}getMe(){return this.request("GET","/api/users/me")}findNamespacesByExternalIds(e){return this.request("POST","/api/namespaces/by-external-ids",e)}updateNamespace(e,n){return this.request("PUT",`/api/namespaces/${e}`,n)}searchAgents(e){return this.request("POST","/api/agent-configs/search",{namespaceId:e,userExternalId:this.userExternalId})}};import*as eD from"fs";import*as en from"path";var fl=["FRONTIER","BIGGEST","BIG","SMALL"],_5={FRONTIER:{inputMTokens:10,outputMTokens:50,cacheRead:.25,cacheWrite:12.5},BIGGEST:{inputMTokens:4,outputMTokens:20,cacheRead:.2,cacheWrite:5},BIG:{inputMTokens:2,outputMTokens:10,cacheRead:.1,cacheWrite:2.5},SMALL:{inputMTokens:.1,outputMTokens:.5,cacheRead:.01,cacheWrite:.125}},O5={FRONTIER:{inputMTokens:10,outputMTokens:50,cacheRead:.25},BIGGEST:{inputMTokens:4,outputMTokens:20,cacheRead:.2},BIG:{inputMTokens:2,outputMTokens:10,cacheRead:.2},SMALL:{inputMTokens:.1,outputMTokens:.5,cacheRead:.01}},Vo={FRONTIER:{inputMTokens:10,outputMTokens:50,cacheRead:1},BIGGEST:{inputMTokens:2,outputMTokens:10,cacheRead:.1},BIG:{inputMTokens:1,outputMTokens:5,cacheRead:.05},SMALL:{inputMTokens:.1,outputMTokens:.5,cacheRead:.01}},X1=(t,e,n)=>({FRONTIER:{apiModelName:`${t}${e}`,description:"Claude Fable 5.1: demanding reasoning and long-horizon agentic work",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.FRONTIER},BIGGEST:{apiModelName:`${t}claude-opus-5-5`,description:"Claude Opus 5.5: long-running agentic coding and knowledge work",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.BIGGEST},BIG:{apiModelName:`${t}claude-sonnet-5-5`,description:"Claude Sonnet 5.5: the best combination of speed and intelligence",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.BIG},SMALL:{apiModelName:`${t}claude-haiku-5-5`,description:"Claude Haiku 5.5: fast, high-volume tasks",contextWindow:1e6,maxCompletionTokens:128e3,pricing:n.SMALL}}),R5=t=>({FRONTIER:{apiModelName:`${t}gpt-6-astra`,description:"GPT-6 Astra: the most capable model for the most demanding work",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.FRONTIER},BIGGEST:{apiModelName:`${t}gpt-6.1-sol`,description:"GPT-6.1 Sol: near-Astra performance for complex work at a lower cost",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.BIGGEST},BIG:{apiModelName:`${t}gpt-6.1-terra`,description:"GPT-6.1 Terra: fast and efficient, the everyday model",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.BIG},SMALL:{apiModelName:`${t}gpt-6-luna`,description:"GPT-6 Luna: the most efficient model for focused, high-volume tasks",contextWindow:105e4,maxCompletionTokens:128e3,pricing:Vo.SMALL}}),Yo={anthropic:{id:"anthropic",name:"anthropic",label:"Anthropic",description:"Claude models, directly from Anthropic.",apiType:"Anthropic",baseUrl:"https://api.anthropic.com",keyUrl:"https://console.anthropic.com/settings/keys",models:X1("","claude-fable-5-1",_5)},openai:{id:"openai",name:"openai",label:"OpenAI",description:"GPT models, directly from OpenAI.",apiType:"OpenAI",baseUrl:"https://api.openai.com",keyUrl:"https://platform.openai.com/api-keys",models:R5("")},requesty:{id:"requesty",name:"requesty",label:"Requesty",description:"One key for Claude, GPT and 600+ other models through the Requesty router.",apiType:"OpenAI",baseUrl:"https://router.eu.requesty.ai",keyUrl:"https://app.requesty.ai/api-keys",models:X1("anthropic/","claude-fable-5.1",O5)}},FB=Object.keys(Yo);function Jo(t){return Yo[t]}function Q1(t,e){let n=Math.min(Math.max(Math.trunc(t),1),Math.max(e,1));return(e-n+1)*10}var Ti="Coday",wt=class extends Error{},Z1=(t,e)=>{let n=en.relative(e,t);return n===""||!n.startsWith("..")&&!en.isAbsolute(n)};function tD(t,e){let n=t;if(!n||!Array.isArray(n.providers)||n.providers.length===0)throw new wt("Choose at least one provider and give its API key.");let r=new Set;for(let a of n.providers){if(!a||typeof a.id!="string"||!Jo(a.id))throw new wt(`Unknown provider '${String(a?.id)}'.`);if(r.has(a.id))throw new wt(`Provider '${a.id}' is listed twice.`);if(r.add(a.id),typeof a.apiKey!="string"||a.apiKey.trim().length<8)throw new wt(`The API key of ${a.id} looks too short.`);if(!Number.isFinite(a.rank))throw new wt(`The rank of ${a.id} is missing.`)}if(typeof n.sharedExchangePath!="string"||!en.isAbsolute(n.sharedExchangePath))throw new wt("The files folder must be an absolute path.");let i=en.normalize(n.sharedExchangePath);if(e){let a=en.resolve(e);if(Z1(i,a)||Z1(a,i))throw new wt(`The files folder cannot contain or be inside ${a}, where Coday keeps its data and keys. Choose another folder.`)}return{providers:n.providers.map(a=>({id:a.id,apiKey:a.apiKey.trim(),rank:a.rank})),sharedExchangePath:i}}var nD=t=>new Promise(e=>setTimeout(e,t)),P5=t=>t instanceof Error?t.message:String(t);function T5(t,e,n){return t instanceof Mr&&t.status===403&&n===!1?`AgentOS refused: ${e} is not an administrator of this AgentOS, and only an administrator can configure the providers and the files folder. Use the email of its administrator, or start again with an empty AgentOS data folder.`:P5(t)}var I5=(t,e)=>e.reduce((n,r)=>r?n.split(r).join("***"):n,t);async function j5(t,e,n,r){let i={name:e.name,description:`${e.label} (created by the first-run setup)`,apiType:e.apiType,baseUrl:e.baseUrl,apiKey:n},a=r.find(s=>s.name.toLowerCase()===e.name.toLowerCase());if(a?.id)return await t.client.updateProvider(a.id,i),a.id;let o=await t.client.createProvider(i);if(!o.id)throw new Error(`AgentOS returned no id for the ${e.label} provider`);return o.id}var k5=["inputMTokens","outputMTokens","cacheRead","cacheWrite"],B5=(t,e)=>k5.every(n=>(t?.[n]??null)===(e?.[n]??null));async function $5(t,e,n,r){let i=await t.client.listModelsOfProvider(n);for(let a of fl){let o=e.models[a],s={aiProviderId:n,apiModelName:o.apiModelName,alias:a,priority:r,description:o.description,pricing:o.pricing,...o.contextWindow?{contextWindow:o.contextWindow}:{},...o.maxCompletionTokens?{maxCompletionTokens:o.maxCompletionTokens}:{}},c=i.find(u=>u.alias?.toLowerCase()===a.toLowerCase());c?c.id&&(c.apiModelName!==s.apiModelName||c.priority!==r||!B5(c.pricing,s.pricing))&&await t.client.updateModel(c.id,s):await t.client.createModel(s)}}async function M5(t){let e=t.namespaceAttempts??30,n=t.namespaceIntervalMs??2e3,r=t.sleep??nD,i=`user:${t.userEmail}`;for(let a=1;a<=e;a++){let o=await t.client.findNamespacesByExternalIds([i]).catch(c=>{if(c instanceof Mr&&[401,403,404].includes(c.status))return[];throw c}),s=o.find(c=>c.externalId===i)??o[0];if(s?.id)return s;await r(n)}throw new Error(`Your personal namespace (${i}) was not created by AgentOS in time. Retry in a moment.`)}async function L5(t,e){let n=t.namespaceAttempts??30,r=t.namespaceIntervalMs??2e3,i=t.sleep??nD;for(let a=1;a<=n;a++){if((await t.client.searchAgents(e)).some(s=>s.name.toLowerCase()===Ti.toLowerCase()&&s.enabled!==!1))return;await i(r)}throw new Error(`The ${Ti} agent is not deployed in your namespace.`)}async function rD(t,e,n=()=>{}){let{tracker:r}=e,i=t.providers.map(s=>s.apiKey),a=e.mkdir??(s=>void eD.mkdirSync(s,{recursive:!0}));r.start();let o;try{if(r.step("providers","running","Waiting for AgentOS"),!await e.waitForAgentos())throw new Error("AgentOS did not start. Check the agentos log.");r.step("providers","running","Identifying you"),o=(await e.client.getMe()).isAdmin;let s=[...t.providers].sort((f,d)=>f.rank-d.rank),c=await e.client.listPlatformProviders(),u=new Map;for(let[f,d]of s.entries()){let m=Jo(d.id);r.step("providers","running",`Configuring ${m.label}`),u.set(d.id,await j5(e,m,d.apiKey,c))}r.step("providers","done"),r.step("models","running");for(let[f,d]of s.entries()){let m=Jo(d.id);await $5(e,m,u.get(d.id),Q1(f+1,s.length))}r.step("models","done",`${s.length*fl.length} models`),r.step("namespace","running","Waiting for your personal namespace");let p=await M5(e);return r.setNamespaceId(p.id),a(t.sharedExchangePath),(p.sharedExchangePath!==t.sharedExchangePath||p.defaultAgentName!==Ti)&&await e.client.updateNamespace(p.id,{...p,sharedExchangePath:t.sharedExchangePath,defaultAgentName:Ti}),r.step("namespace","done",t.sharedExchangePath),r.step("agent","running",`Checking the ${Ti} agent`),await L5(e,p.id),r.step("agent","done"),r.finish(),n(),!0}catch(s){return r.fail(I5(T5(s,e.userEmail,o),i)),!1}}import*as Et from"fs";import*as Xo from"os";import*as vt from"path";var $e=class extends Error{constructor(n,r){super(r);this.status=n}},iD=(t=Xo.homedir(),e=process.env)=>e.CODAY_DEFAULT_FILES_DIR&&vt.isAbsolute(e.CODAY_DEFAULT_FILES_DIR)?vt.normalize(e.CODAY_DEFAULT_FILES_DIR):vt.join(t,"Coday");function aD(t,e){let n=t===void 0||t===""?e:t;if(n.includes("\0"))throw new $e(400,"Invalid path.");if(!vt.isAbsolute(n))throw new $e(400,"The path must be absolute.");return vt.normalize(n)}function oD(t,e={}){let n=e.home??Xo.homedir(),r=aD(t,n),i;try{i=Et.realpathSync(r)}catch{throw new $e(404,"This folder does not exist.")}let a;try{a=Et.statSync(i)}catch{throw new $e(404,"This folder does not exist.")}if(!a.isDirectory())throw new $e(400,"This path is not a folder.");let o;try{o=Et.readdirSync(i,{withFileTypes:!0})}catch{throw new $e(403,"This folder cannot be read.")}let s=[],c=0;for(let p of o){let l=vt.join(i,p.name),f=p.isDirectory(),d=p.isSymbolicLink();if(d)try{f=Et.statSync(l).isDirectory()}catch{f=!1}if(f){if(!e.showHidden&&p.name.startsWith(".")){c++;continue}s.push({name:p.name,path:l,...d?{symlink:!0}:{}})}}s.sort((p,l)=>p.name.localeCompare(l.name,void 0,{sensitivity:"base"}));let u=vt.dirname(i);return{path:i,parent:u===i?null:u,home:n,entries:s,hiddenCount:c}}var N5=/[\\/\0]|^\.{1,2}$/;function sD(t,e){if(typeof e!="string"||e.trim()===""||N5.test(e.trim())||e.length>255)throw new $e(400,"Use a plain folder name (no slashes).");let n=aD(t,Xo.homedir()),r;try{if(r=Et.realpathSync(n),!Et.statSync(r).isDirectory())throw new Error("not a directory")}catch{throw new $e(404,"The parent folder does not exist.")}let i=vt.join(r,e.trim());try{Et.mkdirSync(i)}catch(a){let o=a.code;throw o==="EEXIST"?new $e(409,"This folder already exists."):o==="EACCES"||o==="EPERM"?new $e(403,"Not allowed to create a folder here."):new $e(400,"The folder could not be created.")}return{path:i}}var q5=["providers","models","namespace","agent"],cD=()=>({status:"idle",steps:{providers:{state:"pending"},models:{state:"pending"},namespace:{state:"pending"},agent:{state:"pending"}}}),Qo=class{snapshot=cD();get(){return JSON.parse(JSON.stringify(this.snapshot))}isRunning(){return this.snapshot.status==="running"}start(){this.snapshot={...cD(),status:"running"}}step(e,n,r){this.snapshot.steps[e]={state:n,...r?{message:r}:{}}}setNamespaceId(e){this.snapshot.namespaceId=e}finish(){this.snapshot.status="done"}fail(e){this.snapshot.status="error",this.snapshot.error=e;for(let n of q5)this.snapshot.steps[n].state==="running"&&(this.snapshot.steps[n]={state:"error",message:e})}};function uD(t,e,n,r,i=!1){if(!t)return{ok:!1,status:403,message:"First-run setup is not available here."};if(e.setupDone)return{ok:!1,status:403,message:"Setup is already done."};let a=e.identity?.email;return a&&a===r?{ok:!0}:a&&(n?.agentosStarted||i)?{ok:!1,status:409,message:`AgentOS already started for ${a}; to use another email, stop Coday and delete web-setup.json and the agentos data folder.`}:{ok:!0}}function H5(t){return t?t.state==="ok"?{state:"done",version:t.version}:{state:"blocked",hint:t.hint,...t.state==="too-old"?{version:t.version}:{}}:{state:"pending"}}function U5(t,e={}){if(!t)return{state:"pending"};if(e.agentos&&e.factory)return{state:"done",percent:100};let{agentos:n,factory:r}=t.downloads,i=H1({agentos:e.agentos?void 0:n,factory:e.factory||r?.state==="error"?void 0:r});switch(i.state){case"done":return{state:"done",percent:100};case"error":return{state:"error",message:i.message};case"running":return{state:"running",percent:i.percent};default:return{state:"pending"}}}function pD(t){let{setup:e,state:n,apply:r}=t,i=t.external??{},a=!!e.setupDone,o=i.agentos&&i.factory?{state:"done"}:H5(n?.java),s=U5(n,i),c;t.agentosHealthy?c={state:"done"}:i.agentos?c=n?{state:"running",message:"Waiting for AgentOS"}:{state:"pending"}:s.state==="error"?c={state:"error",message:s.message}:o.state==="blocked"?c={state:"blocked",message:"Waiting for Java"}:!e.identity&&n?.profile==="laptop"?c={state:"pending",message:"Waiting for your email"}:n?n.agentosStarted?c={state:"running",message:"Starting AgentOS"}:c={state:"running",message:s.state==="done"?"Starting AgentOS":"Preparing AgentOS"}:c={state:"pending"};let u=n?.downloads.factory,p=t.factoryHealthy?{state:"done"}:u?.state==="error"?{state:"error",message:u.message}:c.state==="done"?{state:"running"}:{state:"pending"},l={state:"done"},f=a?{providers:l,models:l,namespace:l,agent:l}:r.steps;return{mode:n?.profile??"managed",setupEnabled:t.setupEnabled,setupDone:a,...e.identity?{identity:e.identity}:{},steps:{download:s,java:o,agentos:c,factory:p,...f},apply:{status:a?"done":r.status,...r.error?{error:r.error}:{}},...r.namespaceId?{namespaceId:r.namespaceId}:{}}}var z5=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]),lD=t=>t.replace(/\/+$/,""),G5=t=>!!t&&z5.has(t),W5=new Set(["localhost","127.0.0.1","[::1]"]),fD=t=>{try{return W5.has(new URL(t).hostname)}catch{return!1}},K5=(t,e)=>!!t&&fD(`http://${t}`)&&(e===void 0||fD(e));function dl(t){let e=Ie(t)?.ports.agentos;return e?`http://${Ne}:${e}`:void 0}function dD(t){let{configDir:e,setupEnabled:n}=t,r=t.fetchFn??fetch,i=t.tracker??new Qo,a=(0,Zo.Router)();a.use(Zo.default.json({limit:"100kb"}));let o=(c,u,p)=>{if(!n){u.status(403).json({error:"First-run setup is not available here."});return}if(!G5(c.socket.remoteAddress)||!K5(c.headers.host,c.headers.origin)){u.status(403).json({error:"First-run setup is only available from this machine."});return}p()},s=(c,u,p)=>{if(gt(e).setupDone){u.status(403).json({error:"Setup is already done."});return}p()};return a.get("/status",async(c,u)=>{let p=Ie(e),l=dl(e),f=p?.ports.factory,d=t.externalAgentosUrl?`${lD(t.externalAgentosUrl)}/management/health`:l&&`${l}/management/health`,m=t.externalFactoryUrl?`${lD(t.externalFactoryUrl)}/actuator/health`:f&&`http://${Ne}:${f}/actuator/health`,[h,g]=await Promise.all([d?Nt(d,r):!1,m?Nt(m,r):!1]);u.setHeader("Cache-Control","no-store"),u.json({...pD({setupEnabled:n,setup:gt(e),state:p,agentosHealthy:h,factoryHealthy:g,apply:i.get(),external:{agentos:!!t.externalAgentosUrl,factory:!!t.externalFactoryUrl}}),defaults:{sharedExchangePath:iD(t.homeDir)},providers:Object.values(Yo).map(F=>({id:F.id,label:F.label,description:F.description,keyUrl:F.keyUrl}))})}),a.post("/identity",o,s,(c,u)=>{let p=c.body?.email;if(!il(p)){u.status(400).json({error:"Enter a valid email address."});return}let l=al(p),f=uD(n,gt(e),Ie(e),l,q1(e));if(!f.ok){u.status(f.status).json({error:f.message});return}u.json({identity:L1(e,l).identity})}),a.get("/browse",o,s,(c,u)=>{try{let p=typeof c.query.path=="string"?c.query.path:void 0;u.json(oD(p,{home:t.homeDir,showHidden:c.query.hidden==="true"}))}catch(p){p instanceof $e?u.status(p.status).json({error:p.message}):u.status(500).json({error:"Could not list this folder."})}}),a.post("/mkdir",o,s,(c,u)=>{let{path:p,name:l}=c.body??{};try{if(typeof p!="string"||typeof l!="string")throw new $e(400,"path and name are required.");u.status(201).json(sD(p,l))}catch(f){f instanceof $e?u.status(f.status).json({error:f.message}):u.status(500).json({error:"The folder could not be created."})}}),a.post("/apply",o,s,(c,u)=>{let p=gt(e).identity?.email;if(!p){u.status(409).json({error:"Enter your email first."});return}if(i.isRunning()){u.status(202).json({status:"running"});return}let l;try{l=tD(c.body,e)}catch(f){u.status(400).json({error:f instanceof wt?f.message:"Invalid request."});return}rD(l,{client:new Ko(()=>dl(e)??`http://${Ne}:0`,p,r),waitForAgentos:async()=>{let f=Date.now()+6e5;for(;Date.now()<f;){let d=dl(e);if(d&&await Nt(`${d}/management/health`,r))return!0;await new Promise(m=>setTimeout(m,1500))}return!1},tracker:i,userEmail:p,...t.applyTimings},()=>N1(e)),u.status(202).json({status:"running"})}),a}function ml(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 V5=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function vl({codayOptions:t,setupEnabled:e}){let n=(0,Ii.default)(),{configDir:r}=t,i=process.env.AGENTOS_URL,a=process.env.FACTORY_URL;i&&ml(i),a&&ml(a);let o=(f,d)=>`http://127.0.0.1:${Ie(r)?.ports[f]??d}`,s=()=>i??o("agentos",sl),c=()=>a??o("factory",cl),u=U1(r),p=(f,d)=>{T1(f,P1({authEnabled:!!t.auth,envUserId:u(),resolveUser:()=>l(d)}))};function l(f){let d=j1(f.headers,!!t.auth);if(V5.includes(d.toLowerCase()))throw new Error(`Security error: Cannot run with username "${d}". 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 d}if(n.use("/api/setup",dD({configDir:r,setupEnabled:e,externalAgentosUrl:i,externalFactoryUrl:a})),n.use("/api/agentos",A1(s,{onProxyReq:(f,d)=>{ae("AGENTOS",`[PROXY] ${d.method} ${d.url}`),p(f,d)}})),n.use(O1(c,{onProxyReq:(f,d)=>{ae("FACTORY",`[PROXY] ${d.method} ${d.url}`),p(f,d)}})),ae("INIT",`Proxies: /api/agentos -> ${i??"managed AgentOS (state.json)"}, /api/factory -> ${a??"managed Factory (state.json)"}`),n.use(Ii.default.json({limit:"20mb"})),process.env.BUILD_ENV==="development"){let f=`http://localhost:${process.env.ANGULAR_CLIENT_PORT??"4200"}`,d=`http://localhost:${process.env.FACTORY_COCKPIT_PORT??"4300"}`,m=g=>g==="/factory"||g.startsWith("/factory/"),h=g=>g.startsWith("/api")||g.startsWith("/events");n.use((0,gl.createProxyMiddleware)({target:d,changeOrigin:!0,ws:!0,pathFilter:g=>m(g)})),n.use((0,gl.createProxyMiddleware)({target:f,changeOrigin:!0,ws:!0,pathFilter:g=>!h(g)&&!m(g)})),ae("INIT",`Development mode: /factory \u2192 ${d}, other non-API routes \u2192 ${f}`)}else{let f=process.env.CODAY_CLIENT_PATH?nr.resolve(process.env.CODAY_CLIENT_PATH):nr.resolve(__dirname,"../coday-client/browser"),d=process.env.CODAY_FACTORY_COCKPIT_PATH?nr.resolve(process.env.CODAY_FACTORY_COCKPIT_PATH):nr.resolve(__dirname,"../coday-factory-cockpit/browser");ae("INIT",`Production mode: serving static files from ${f}`),ae("INIT",`Production mode: serving factory cockpit static files from ${d}`),mD(f,"client","pnpm nx run client:build"),mD(d,"factory cockpit","pnpm nx run factory-cockpit:build"),n.use("/factory",Ii.default.static(d)),n.use(Ii.default.static(f));let m=nr.resolve(f,"index.html"),h=nr.resolve(d,"index.html");n.use((g,F,R)=>{if(g.path.startsWith("/api")||g.path.startsWith("/events")){F.status(404).send("Not found");return}let A=g.path==="/factory"||g.path.startsWith("/factory/")?h:m;ae("ROUTER",`Serving index.html for client route: ${g.path}`),hl.readFile(A,"utf8",(k,$)=>{k?(ae("ERROR",`Failed to read index.html from ${A}:`,k),R(k)):F.type("html").send($)})})}return n.use((f,d,m,h)=>{ae("ERROR",`Request error on ${d.method} ${d.path}:`,f.message),console.error(f.stack),process.env.BUILD_ENV==="development"?m.status(500).json({error:"Internal Server Error",message:f.message,stack:f.stack}):m.status(500).send("Something went wrong!")}),n}function mD(t,e,n){(!hl.existsSync(t)||!hl.existsSync(nr.join(t,"index.html")))&&(console.error(`ERROR: ${e} build not found at ${t}`),console.error(`Please build it first with: ${n}`))}import*as xn from"fs";import*as hD from"path";import{format as Y5}from"util";function xl(t){xn.mkdirSync(hD.dirname(t),{recursive:!0});let e=xn.openSync(t,"a"),n={log:console.log,warn:console.warn,error:console.error};for(let r of["log","warn","error"]){let i=n[r].bind(console);console[r]=(...a)=>{i(...a);try{xn.writeSync(e,Y5(...a)+`
177
177
  `)}catch{}}}return()=>{console.log=n.log,console.warn=n.warn,console.error=n.error;try{xn.closeSync(e)}catch{}}}function bl(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections()})}import*as yD from"crypto";import*as Ae from"fs";import*as Ct from"path";var J5="https://github.com/whoz-oss/coday/releases/download",X5=/^\d+\.\d+\.\d+-workstream-([a-z0-9]+(?:-[a-z0-9]+)*)\.(\d+)$/;function yl(t,e){return t?{version:t,source:"env"}:{version:e,source:"package"}}function Q5(t){let e=X5.exec(t);return e?`workstream-${e[1]}-${e[2]}`:`release/${t}`}function gD(t){return`${J5}/${Q5(t)}`}var Z5=6e4,Dl="installed.sha256";function DD(t){let e=[];for(let n of t.split(`
178
178
  `)){let r=n.trim();if(!r)continue;let i=r.indexOf(" ");if(i===-1)continue;let a=r.slice(0,i).trim(),o=r.slice(i+2).trim();a.length===64&&o&&e.push({hash:a,filename:o})}return e}function eR(t){return yD.createHash("sha256").update(t).digest("hex")}function rr(t){return`${t}-service`}function tR(t,e,n){let r=`-${n}.jar`,i=new RegExp(`^${e}-.+-plugin$`),a=[];for(let o of t){if(!o.filename.endsWith(r))continue;let s=o.filename.slice(0,-r.length);(s===rr(e)||i.test(s))&&a.push({artifactId:s,entry:o})}if(!a.some(o=>o.artifactId===rr(e)))throw new Error(`No '${rr(e)}' entry for version ${n} in the manifest`);return a}function wl(t,e,n,r){return n===rr(e)?Ct.join(t,`${n}-${r}.jar`):Ct.join(t,"plugins",`${n}-${r}.jar`)}function nR(t,e,n,r){return wl(Ct.join(t,e),e,n,r)}function rR(t,e,n){let r;try{r=Ae.readFileSync(Ct.join(t,e,Dl),"utf8")}catch{return null}let i=`-${n}.jar`,a=[];for(let{filename:o}of DD(r)){if(!o.endsWith(i))return null;a.push(o.slice(0,-i.length))}return!a.includes(rr(e))||!a.every(o=>Ae.existsSync(nR(t,e,o,n)))?null:a}function vD(t,e,n="AGENTOS"){let r=0;try{for(let i of Ae.readdirSync(t).filter(a=>a.endsWith(".jar")||a.endsWith(".tmp")))if(!e.has(i)){let a=Ct.join(t,i);try{Ae.unlinkSync(a),ae(n,` [CLEAN] Removed stale file: ${a}`),r++}catch(o){ae(n,` [CLEAN] Failed to remove ${a}: ${o instanceof Error?o.message:o}`)}}}catch{}return r}async function El(t,e={}){let n=new AbortController,r=setTimeout(()=>n.abort(),Z5);try{return await fetch(t,{...e,signal:n.signal})}finally{clearTimeout(r)}}async function iR(t,e){if(!e||!t.body)return Buffer.from(await t.arrayBuffer());let n=t.body.getReader(),r=[],i=0;for(;;){let{done:a,value:o}=await n.read();if(a)break;r.push(Buffer.from(o)),i+=o.byteLength,e(i)}return Buffer.concat(r)}async function aR(t,e){let n=new Map;return await Promise.all(e.map(async r=>{try{let i=await El(`${t}/${r}`,{method:"HEAD"}),a=Number(i.headers.get("content-length"));i.ok&&Number.isFinite(a)&&a>0&&n.set(r,a)}catch{}})),n}function xD(t,e,n){let r=t.reduce((o,s)=>o+s,0);if(r<=0)return 0;let i=t.slice(0,e).reduce((o,s)=>o+s,0),a=(t[e]??0)*Math.min(1,Math.max(0,n));return Math.min(100,Math.round((i+a)/r*100))}function bD(t,e){let n=`${t}.tmp`;try{Ae.writeFileSync(n,e),Ae.renameSync(n,t)}catch(r){try{Ae.unlinkSync(n)}catch{}throw r}}async function wD(t,e,n,r){let i=e.toUpperCase(),a=Ct.join(t,e),o=Ct.join(a,"plugins");if(n==="dev"){let c=Ae.existsSync(wl(a,e,rr(e),n));return ae(i,`[DOWNLOAD] Version is 'dev' sentinel \u2014 no release to download from (JAR placed by hand: ${c})`),c?{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 s=rR(t,e,n);if(s)return ae(i,`[DOWNLOAD] ${s.length} JAR(s) already installed at ${n} \u2014 skipping download`),{outcome:"skipped:all-present",message:`All ${s.length} JAR(s) already present at ${n}`};try{Ae.mkdirSync(o,{recursive:!0}),Ae.rmSync(Ct.join(a,Dl),{force:!0});let c=gD(n);ae(i,`[DOWNLOAD] Version ${n} not fully installed \u2014 fetching ${c}/checksums.sha256`);let u=await El(`${c}/checksums.sha256`);if(ae(i,`[DOWNLOAD] Manifest HTTP ${u.status}`),!u.ok)throw new Error(`Manifest HTTP ${u.status}`);let p=tR(DD(await u.text()),e,n);ae(i,`[DOWNLOAD] Release provides: ${p.map(R=>R.artifactId).join(", ")}`);let l=r?await aR(c,p.map(R=>R.entry.filename)):new Map,f=[...l.values()],d=f.length?f.reduce((R,A)=>R+A,0)/f.length:1,m=p.map(R=>l.get(R.entry.filename)??d);for(let[R,{artifactId:A,entry:k}]of p.entries()){ae(i,`[DOWNLOAD] ${k.filename}`);let $=(y,O)=>r?.({kind:e,artifactId:A,index:R,count:p.length,receivedBytes:y,totalBytes:O,overallPercent:xD(m,R,O?y/O:0)});$(0);let U=await El(`${c}/${k.filename}`);if(!U.ok)throw new Error(`JAR HTTP ${U.status} for '${k.filename}'`);let K=Number(U.headers.get("content-length")),B=Number.isFinite(K)&&K>0?K:l.get(k.filename),q=await iR(U,r?y=>$(y,B):void 0);if(eR(q)!==k.hash)throw new Error(`Checksum mismatch for '${k.filename}'`);let W=wl(a,e,A,n);bD(W,q),ae(i,`[DOWNLOAD] written ${W} (${q.length} bytes)`),r?.({kind:e,artifactId:A,index:R,count:p.length,receivedBytes:q.length,totalBytes:q.length,overallPercent:xD(m,R+1,0)})}Ae.rmSync(Ct.join(a,"next"),{recursive:!0,force:!0});let h=new Set,g=new Set;for(let{artifactId:R,entry:A}of p)(R===rr(e)?h:g).add(A.filename);let F=vD(a,h,i)+vD(o,g,i);return ae(i,`[DOWNLOAD] Cleanup: removed ${F} stale file(s)`),bD(Ct.join(a,Dl),p.map(({entry:R})=>`${R.hash} ${R.filename}`).join(`
179
179
  `)+`