@whoz-oss/coday-server 0.103.1 → 0.103.3

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 +2 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whoz-oss/coday-server",
3
- "version": "0.103.1",
3
+ "version": "0.103.3",
4
4
  "repository": "https://github.com/whoz-oss/coday",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
package/server.js CHANGED
@@ -579,7 +579,7 @@ Verify the memory system's overall health:
579
579
  - List any remaining issues or concerns
580
580
  - Provide recommendations for maintaining memory quality
581
581
 
582
- This ensures the memory system stays efficient and valuable.`],createdBy:"system",createdAt:new Date("2024-01-01").toISOString(),webhookEnabled:!1,parameterFormat:""}];var yu=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="ThreadRepositoryError"}},N4={input:0,output:0,cache_read:0,cache_write:0,price:0,iterations:0,priceThreshold:2,iterationsThreshold:100};function rn(r,e){return r.users.some(t=>t.userId===e)}function Vte(r,e,t=.7){if(!e||!r.length)return{messages:r,overflow:[]};let n=0,i=0,a=e*t;for(let c of r)i+=c.length,n+=i<a?1:0;if(i<e)return{messages:r,overflow:[]};let o=r.slice(0,n),s=r.slice(n);return{messages:o,overflow:s}}var eIe=[Rt.type,ln.type,kn.type,da.type,Di.type,Ii.type,_r.type,fo.type],bu=class r{id;projectId;name;summary;starring=[];username;users=[];createdDate;modifiedDate;runStatus="STOPPED";data={};usage={...N4};price=0;delegationDepth=0;parentThreadId;parentEventId;delegatedAgentName;delegatedTask;parentThread;messages;get messagesLength(){return this.messages.length}constructor(e){this.id=e.id,this.username=e.username??"",this.projectId=e.projectId??"",this.name=e.name??"",this.summary=e.summary??"",this.starring=e.starring??[],this.users=e.users??(e.username?[{userId:e.username}]:[]),this.createdDate=e.createdDate??new Date().toISOString(),this.modifiedDate=e.modifiedDate??this.createdDate,this.price=e.price??0,this.parentThreadId=e.parentThreadId,this.parentEventId=e.parentEventId,this.delegatedAgentName=e.delegatedAgentName,this.delegatedTask=e.delegatedTask;let t=e.messages??[];Array.isArray(t)?this.messages=t.filter(n=>eIe.includes(n.type)).map(n=>cv(n)).filter(n=>n!==void 0):this.messages=[]}async getMessages(e,t){if((!this.messages||!Array.isArray(this.messages))&&(this.messages=[]),!e){let l=this.getMessagesUpToFirstSummary();return{messages:this.cleanToolRequestResponseConsistency(l),compacted:!1}}let n=this.getMessagesUpToFirstSummary(),i=Math.floor(e*.5),a=n.map(l=>{if(l instanceof kn&&l.length>i){let f=Math.floor(e*.15),p=l.getTextOutput(),d=`[... truncated ${l.length-f} chars]
582
+ This ensures the memory system stays efficient and valuable.`],createdBy:"system",createdAt:new Date("2024-01-01").toISOString(),webhookEnabled:!1,parameterFormat:""}];var yu=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="ThreadRepositoryError"}},N4={input:0,output:0,cache_read:0,cache_write:0,price:0,iterations:0,priceThreshold:10,iterationsThreshold:100};function rn(r,e){return r.users.some(t=>t.userId===e)}function Vte(r,e,t=.7){if(!e||!r.length)return{messages:r,overflow:[]};let n=0,i=0,a=e*t;for(let c of r)i+=c.length,n+=i<a?1:0;if(i<e)return{messages:r,overflow:[]};let o=r.slice(0,n),s=r.slice(n);return{messages:o,overflow:s}}var eIe=[Rt.type,ln.type,kn.type,da.type,Di.type,Ii.type,_r.type,fo.type],bu=class r{id;projectId;name;summary;starring=[];username;users=[];createdDate;modifiedDate;runStatus="STOPPED";data={};usage={...N4};price=0;delegationDepth=0;parentThreadId;parentEventId;delegatedAgentName;delegatedTask;parentThread;messages;get messagesLength(){return this.messages.length}constructor(e){this.id=e.id,this.username=e.username??"",this.projectId=e.projectId??"",this.name=e.name??"",this.summary=e.summary??"",this.starring=e.starring??[],this.users=e.users??(e.username?[{userId:e.username}]:[]),this.createdDate=e.createdDate??new Date().toISOString(),this.modifiedDate=e.modifiedDate??this.createdDate,this.price=e.price??0,this.parentThreadId=e.parentThreadId,this.parentEventId=e.parentEventId,this.delegatedAgentName=e.delegatedAgentName,this.delegatedTask=e.delegatedTask;let t=e.messages??[];Array.isArray(t)?this.messages=t.filter(n=>eIe.includes(n.type)).map(n=>cv(n)).filter(n=>n!==void 0):this.messages=[]}async getMessages(e,t){if((!this.messages||!Array.isArray(this.messages))&&(this.messages=[]),!e){let l=this.getMessagesUpToFirstSummary();return{messages:this.cleanToolRequestResponseConsistency(l),compacted:!1}}let n=this.getMessagesUpToFirstSummary(),i=Math.floor(e*.5),a=n.map(l=>{if(l instanceof kn&&l.length>i){let f=Math.floor(e*.15),p=l.getTextOutput(),d=`[... truncated ${l.length-f} chars]
583
583
  `+p.slice(-f);return new kn({...l,output:d})}return l}),{messages:o,overflow:s}=Vte(a.toReversed(),e);if(o=o.toReversed(),s=s.toReversed(),!t||s.length===0)return{messages:this.cleanToolRequestResponseConsistency(o),compacted:s.length>0};let c;try{c=await t(s);let l=s[s.length-1];if(l){let f=this.messages.indexOf(l);f!==-1&&this.messages.splice(f+1,0,c)}}catch(l){return console.error("[AiThread] Compaction failed, keeping recent messages only:",l),{messages:this.cleanToolRequestResponseConsistency(o),compacted:!0}}let u=this.cleanToolRequestResponseConsistency(o);return{messages:[c,...u],compacted:!0}}getAllMessages(){return this.cleanToolRequestResponseConsistency([...this.messages])}getMessagesUpToFirstSummary(){let e=[...this.messages].reverse(),t=[];for(let n of e){if(n instanceof da){t.push(n);break}t.push(n)}return t.reverse()}cleanToolRequestResponseConsistency(e){let t=[],n=new Set,i=new Set;for(let a of e)a instanceof ln&&a.toolRequestId?n.add(a.toolRequestId):a instanceof kn&&a.toolRequestId&&i.add(a.toolRequestId);for(let a of e){let o=!0;a instanceof ln?a.toolRequestId&&!i.has(a.toolRequestId)&&(console.debug(`[AiThread] Removing orphaned tool request: ${a.name} (ID: ${a.toolRequestId})`),o=!1):a instanceof kn&&(a.toolRequestId?n.has(a.toolRequestId)||(console.debug(`[AiThread] Removing orphaned tool response for missing request ID: ${a.toolRequestId}`),o=!1):(console.warn(`[AiThread] Removing tool response without tool reference (timestamp: ${a.timestamp})`),o=!1)),o&&t.push(a)}return t}resetUsageForRun(){this.usage={...N4}}addUsage(e){this.price+=e.price??0,this.usage.price+=e.price??0,this.usage.iterations+=1;let t=this.usage;t.input+=e.input??0,t.output+=e.output??0,t.cache_read+=e.cache_read??0,t.cache_write+=e.cache_write??0}add(e){this.messages.push(e)}findToolRequestById(e){return this.messages.find(t=>t instanceof ln&&t.toolRequestId===e)}findSimilarToolRequests(e){return this.messages.filter(t=>t!==e&&t instanceof ln&&t.name===e.name&&t.args===e.args)}findToolResponsesToRequests(e){return this.messages.filter(t=>t instanceof kn&&e.some(n=>n.toolRequestId===t.toolRequestId))}removeMessages(e){this.messages=this.messages.filter(t=>!e.includes(t))}addUserMessage(e,t){let n=this.messages[this.messages.length-1];n&&n instanceof Rt&&n.role==="user"&&n.name===e?n.content.push(t):this.add(new Rt({role:"user",content:[t],name:e})),this.modifiedDate=new Date().toISOString()}addAnswerEvent(e){this.add(e),this.modifiedDate=new Date().toISOString()}addDelegationEvent(e){this.messages.some(n=>n instanceof fo&&n.subThreadId===e.subThreadId)||this.add(e)}addAgentMessage(e,t){let n=this.messages[this.messages.length-1];n&&n instanceof Rt&&n.role==="assistant"&&n.name===e?n.content.push(t):this.add(new Rt({role:"assistant",content:[t],name:e})),this.modifiedDate=new Date().toISOString()}fork(e,t,n){let i=new r({id:crypto.randomUUID(),username:this.username,projectId:this.projectId,name:e,summary:"",createdDate:new Date().toISOString(),modifiedDate:new Date().toISOString(),price:0,messages:[],users:this.users.map(a=>({...a})),parentThreadId:this.id,parentEventId:n,delegatedAgentName:e,delegatedTask:t});return i.delegationDepth=this.delegationDepth+1,i.parentThread=this,i.runStatus="RUNNING",i}merge(e){this.price+=e.price,e.price=0}get totalPrice(){return this.price+(this.parentThread?.totalPrice??0)}getLastAgentName(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t instanceof Rt&&t.role==="assistant"&&t.name)return t.name}}getUserMessageCount(){return this.messages.filter(e=>e instanceof Rt&&e.role==="user"||e instanceof _r).length}getEventById(e){return this.messages.find(t=>t.timestamp===e)}truncateAtUserMessage(e){let t=this.messages.findIndex(i=>i.timestamp===e);if(t===-1)return!1;let n=this.messages[t];return!(n instanceof Rt)||n.role!=="user"||t===0?!1:(this.messages=this.messages.slice(0,t),this.modifiedDate=new Date().toISOString(),!0)}addToolRequests(e,t){t.forEach(n=>{!n.toolRequestId||!n.name||!n.args||this.add(n)})}addToolResponseEvents(e){e.forEach(t=>{if(!t.toolRequestId||!t.output)return;let n=this.findToolRequestById(t.toolRequestId);if(!n)return;let i=this.findSimilarToolRequests(n),a=this.findToolResponsesToRequests(i);this.removeMessages([...i,...a]),this.add(t)})}addToolCalls(e,t){t.forEach(n=>{!n.id||!n.name||!n.args||this.add(new ln({name:n.name,args:n.args,toolRequestId:n.id}))})}addToolResponses(e,t){t.forEach(n=>{if(!n.id||!n.response)return;let i=this.findToolRequestById(n.id);if(!i)return;let a=this.findSimilarToolRequests(i),o=this.findToolResponsesToRequests(a);this.removeMessages([...a,...o]),this.add(new kn({toolRequestId:n.id,output:n.response}))})}serialize(){return{id:this.id,username:this.username,projectId:this.projectId,name:this.name,summary:this.summary,createdDate:this.createdDate,modifiedDate:this.modifiedDate,price:this.price,starring:this.starring,users:this.users,parentThreadId:this.parentThreadId,parentEventId:this.parentEventId,delegatedAgentName:this.delegatedAgentName,delegatedTask:this.delegatedTask,messages:this.messages}}};var Vie=vr(Go(),1);var k0=class{constructor(e,t){this.aiProviderConfig=e;this.logger=t;this.apiKey=e.apiKey}models=[];apiKey;killed=!1;thinkingInterval=1e3;charsPerToken=3;username;activeThinkingIntervals=new Set;activeDelays=new Set;isShuttingDown=!1;mergeModels(e){let t=new Map(e.map(n=>[n.alias??n.name,n]));this.aiProviderConfig.models?.forEach(n=>{let i=n.alias??n.name,a=t.get(i);a?t.set(i,{...a,...n,price:n.price??a.price}):t.set(i,n)}),this.models=Array.from(t.values())}kill(){this.killed=!0,this.cleanup()}cleanup(){this.isShuttingDown=!0;for(let e of this.activeDelays)clearTimeout(e);this.activeDelays.clear();for(let e of this.activeThinkingIntervals)clearInterval(e);this.activeThinkingIntervals.clear()}async delay(e,t){if(this.isShuttingDown)throw new Error("Client is shutting down");return new Promise((n,i)=>{let a=setTimeout(()=>{this.activeDelays.delete(a),n()},e);this.activeDelays.add(a),this.isShuttingDown&&(clearTimeout(a),this.activeDelays.delete(a),i(new Error(`Delay interrupted by shutdown${t?`: ${t}`:""}`)))})}startThinkingInterval(){let e=setInterval(()=>this.interactor.thinking(),this.thinkingInterval);return this.activeThinkingIntervals.add(e),e}stopThinkingInterval(e){clearInterval(e),this.activeThinkingIntervals.delete(e)}getCompactor(e,t){return async n=>{if(this.interactor.debug(`\u{1F5DC}\uFE0F Starting compaction for ${n.length} messages (budget: ${t} chars)`),t<500)return this.interactor.warn(`\u26A0\uFE0F Budget too small for compaction (${t} chars). Using truncation marker.`),new da({summary:"[Previous conversation truncated due to context window constraints]"});let i=n.filter(d=>d instanceof Rt).map(d=>` - ${d.role}: ${d.getTextContent()}`).join(`
584
584
  `);this.interactor.debug(`\u{1F4DD} Built transcript from ${n.filter(d=>d instanceof Rt).length} messages (${i.length} chars)`);let a=Math.max(100,Math.floor(t/20)),o=150,s=.2,c=Math.max(0,Math.floor((t-o-a)*(1-s)));this.interactor.debug(`\u{1F4CA} Compaction budget: summary=${a} chars, max transcript=${c} chars (overhead=${o}, margin=${Math.round(s*100)}%)`);let u=i,l=!1;i.length>c&&(u="..."+i.slice(-(c-3)),l=!0,this.interactor.debug(`\u2702\uFE0F Transcript truncated: ${i.length} \u2192 ${u.length} chars (removed ${i.length-u.length} chars from beginning)`));let f=`Here is a transcript of a conversation:
585
585
  <transcript>${u}</transcript>
@@ -1520,7 +1520,7 @@ ${m.join(`
1520
1520
  `;p.forEach(m=>{d+=m}),e.fail(d)}};let c={};a.conflicts=function(f,p){Ke("<string|object> [array|string]",[f,p],arguments.length),typeof f=="object"?Object.keys(f).forEach(d=>{a.conflicts(d,f[d])}):(r.global(f),c[f]||(c[f]=[]),Array.isArray(p)?p.forEach(d=>a.conflicts(f,d)):c[f].push(p))},a.getConflicting=()=>c,a.conflicting=function(f){Object.keys(f).forEach(p=>{c[p]&&c[p].forEach(d=>{d&&f[p]!==void 0&&f[d]!==void 0&&e.fail(n("Arguments %s and %s are mutually exclusive",p,d))})}),r.getInternalMethods().getParserConfiguration()["strip-dashed"]&&Object.keys(c).forEach(p=>{c[p].forEach(d=>{d&&f[t.Parser.camelCase(p)]!==void 0&&f[t.Parser.camelCase(d)]!==void 0&&e.fail(n("Arguments %s and %s are mutually exclusive",p,d))})})},a.recommendCommands=function(f,p){p=p.sort((g,v)=>v.length-g.length);let m=null,h=1/0;for(let g=0,v;(v=p[g])!==void 0;g++){let y=Hve(f,v);y<=3&&y<h&&(h=y,m=v)}m&&e.fail(n("Did you mean %s?",m))},a.reset=function(f){return o=bf(o,p=>!f[p]),c=bf(c,p=>!f[p]),a};let u=[];return a.freeze=function(){u.push({implied:o,conflicting:c})},a.unfreeze=function(){let f=u.pop();Pa(f,void 0,t),{implied:o,conflicting:c}=f},a}var ZG=[],O9;function $9(r,e,t,n){O9=n;let i={};if(Object.prototype.hasOwnProperty.call(r,"extends")){if(typeof r.extends!="string")return i;let a=/\.json|\..*rc$/.test(r.extends),o=null;if(a)o=mvt(e,r.extends);else try{o=import.meta.resolve(r.extends)}catch{return r}hvt(o),ZG.push(o),i=a?JSON.parse(O9.readFileSync(o,"utf8")):n.require(r.extends),delete r.extends,i=$9(i,O9.path.dirname(o),t,O9)}return ZG=[],t?Gve(i,r):Object.assign({},i,r)}function hvt(r){if(ZG.indexOf(r)>-1)throw new zn(`Circular extended configurations: '${r}'.`)}function mvt(r,e){return O9.path.resolve(r,e)}function Gve(r,e){let t={};function n(i){return i&&typeof i=="object"&&!Array.isArray(i)}Object.assign(t,r);for(let i of Object.keys(e))n(e[i])&&n(t[i])?t[i]=Gve(r[i],e[i]):t[i]=e[i];return t}var Ye=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},z=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Bn,zd,j9,ao,jo,IT,wf,Bd,OT,ds,$T,hs,nu,Ro,ms,jT,Hd,Si,nt,RT,NT,No,Wd,X1,Vd,_f,FT,_t,Gd,Zd,Jd,Ot,MT,iu,In;function dye(r){return(e=[],t=r.process.cwd(),n)=>{let i=new aZ(e,t,n,r);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}var Zve=Symbol("copyDoubleDash"),Jve=Symbol("copyDoubleDash"),JG=Symbol("deleteFromParserHintObject"),Kve=Symbol("emitWarning"),Yve=Symbol("freeze"),Xve=Symbol("getDollarZero"),Kd=Symbol("getParserConfiguration"),Qve=Symbol("getUsageConfiguration"),KG=Symbol("guessLocale"),eye=Symbol("guessVersion"),tye=Symbol("parsePositionalNumbers"),YG=Symbol("pkgUp"),Sf=Symbol("populateParserHintArray"),Q1=Symbol("populateParserHintSingleValueDictionary"),XG=Symbol("populateParserHintArrayDictionary"),QG=Symbol("populateParserHintDictionary"),eZ=Symbol("sanitizeKey"),tZ=Symbol("setKey"),rZ=Symbol("unfreeze"),rye=Symbol("validateAsync"),nye=Symbol("getCommandInstance"),iye=Symbol("getContext"),aye=Symbol("getHasOutput"),oye=Symbol("getLoggerInstance"),sye=Symbol("getParseContext"),cye=Symbol("getUsageInstance"),uye=Symbol("getValidationInstance"),LT=Symbol("hasParseCallback"),lye=Symbol("isGlobalContext"),Yd=Symbol("postProcess"),fye=Symbol("rebase"),nZ=Symbol("reset"),R9=Symbol("runYargsParserAndExecuteCommands"),iZ=Symbol("runValidation"),pye=Symbol("setHasOutput"),Xd=Symbol("kTrackManuallySetKeys"),gvt="en_US",aZ=class{constructor(e=[],t,n,i){this.customScriptName=!1,this.parsed=!1,Bn.set(this,void 0),zd.set(this,void 0),j9.set(this,{commands:[],fullCommands:[]}),ao.set(this,null),jo.set(this,null),IT.set(this,"show-hidden"),wf.set(this,null),Bd.set(this,!0),OT.set(this,{}),ds.set(this,!0),$T.set(this,[]),hs.set(this,void 0),nu.set(this,{}),Ro.set(this,!1),ms.set(this,null),jT.set(this,!0),Hd.set(this,void 0),Si.set(this,""),nt.set(this,void 0),RT.set(this,void 0),NT.set(this,{}),No.set(this,null),Wd.set(this,null),X1.set(this,{}),Vd.set(this,{}),_f.set(this,void 0),FT.set(this,!1),_t.set(this,void 0),Gd.set(this,!1),Zd.set(this,!1),Jd.set(this,!1),Ot.set(this,void 0),MT.set(this,{}),iu.set(this,null),In.set(this,void 0),Ye(this,_t,i,"f"),Ye(this,_f,e,"f"),Ye(this,zd,t,"f"),Ye(this,RT,n,"f"),Ye(this,hs,new TT(this),"f"),this.$0=this[Xve](),this[nZ](),Ye(this,Bn,z(this,Bn,"f"),"f"),Ye(this,Ot,z(this,Ot,"f"),"f"),Ye(this,In,z(this,In,"f"),"f"),Ye(this,nt,z(this,nt,"f"),"f"),z(this,nt,"f").showHiddenOpt=z(this,IT,"f"),Ye(this,Hd,this[Jve](),"f"),z(this,_t,"f").y18n.setLocale(gvt)}addHelpOpt(e,t){let n="help";return Ke("[string|boolean] [string]",[e,t],arguments.length),z(this,ms,"f")&&(this[JG](z(this,ms,"f")),Ye(this,ms,null,"f")),e===!1&&t===void 0?this:(Ye(this,ms,typeof e=="string"?e:n,"f"),this.boolean(z(this,ms,"f")),this.describe(z(this,ms,"f"),t||z(this,Ot,"f").deferY18nLookup("Show help")),this)}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(Ke("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e=="string"?e:z(this,IT,"f");return this.boolean(n),this.describe(n,t||z(this,Ot,"f").deferY18nLookup("Show hidden options")),z(this,nt,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return Ke("<object|string|array> [string|array]",[e,t],arguments.length),this[XG](this.alias.bind(this),"alias",e,t),this}array(e){return Ke("<array|string>",[e],arguments.length),this[Sf]("array",e),this[Xd](e),this}boolean(e){return Ke("<array|string>",[e],arguments.length),this[Sf]("boolean",e),this[Xd](e),this}check(e,t){return Ke("<function> [boolean]",[e,t],arguments.length),this.middleware((n,i)=>Ud(()=>e(n,i.getOptions()),a=>(a?(typeof a=="string"||a instanceof Error)&&z(this,Ot,"f").fail(a.toString(),a):z(this,Ot,"f").fail(z(this,_t,"f").y18n.__("Argument check failed: %s",e.toString())),n),a=>(z(this,Ot,"f").fail(a.message?a.message:a.toString(),a),n)),!1,t),this}choices(e,t){return Ke("<object|string|array> [string|array]",[e,t],arguments.length),this[XG](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(Ke("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new zn("coerce callback must be provided");for(let i of e)this.coerce(i,t);return this}else if(typeof e=="object"){for(let i of Object.keys(e))this.coerce(i,e[i]);return this}if(!t)throw new zn("coerce callback must be provided");let n=e;return z(this,nt,"f").key[n]=!0,z(this,hs,"f").addCoerceMiddleware((i,a)=>{var o;let s=(o=a.getAliases()[n])!==null&&o!==void 0?o:[],c=[n,...s].filter(u=>Object.prototype.hasOwnProperty.call(i,u));return c.length===0?i:Ud(()=>t(i[c[0]]),u=>(c.forEach(l=>{i[l]=u}),i),u=>{throw new zn(u.message)})},n),this}conflicts(e,t){return Ke("<string|object> [string|array]",[e,t],arguments.length),z(this,In,"f").conflicts(e,t),this}config(e="config",t,n){return Ke("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e=="object"&&!Array.isArray(e)?(e=$9(e,z(this,zd,"f"),this[Kd]()["deep-merge-config"]||!1,z(this,_t,"f")),z(this,nt,"f").configObjects=(z(this,nt,"f").configObjects||[]).concat(e),this):(typeof t=="function"&&(n=t,t=void 0),this.describe(e,t||z(this,Ot,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach(i=>{z(this,nt,"f").config[i]=n||!0}),this)}completion(e,t,n){return Ke("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t=="function"&&(n=t,t=void 0),Ye(this,jo,e||z(this,jo,"f")||"completion","f"),!t&&t!==!1&&(t="generate completion script"),this.command(z(this,jo,"f"),t),n&&z(this,ao,"f").registerFunction(n),this}command(e,t,n,i,a,o){return Ke("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,i,a,o],arguments.length),z(this,Bn,"f").addHandler(e,t,n,i,a,o),this}commands(e,t,n,i,a,o){return this.command(e,t,n,i,a,o)}commandDir(e,t){Ke("<string> [object]",[e,t],arguments.length);let n=z(this,RT,"f")||z(this,_t,"f").require;return z(this,Bn,"f").addDirectory(e,n,z(this,_t,"f").getCallerFile(),t),this}count(e){return Ke("<array|string>",[e],arguments.length),this[Sf]("count",e),this[Xd](e),this}default(e,t,n){return Ke("<object|string|array> [*] [string]",[e,t,n],arguments.length),n&&(HG(e,z(this,_t,"f")),z(this,nt,"f").defaultDescription[e]=n),typeof t=="function"&&(HG(e,z(this,_t,"f")),z(this,nt,"f").defaultDescription[e]||(z(this,nt,"f").defaultDescription[e]=z(this,Ot,"f").functionDescription(t)),t=t.call()),this[Q1](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,i){return Ke("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,i],arguments.length),typeof t!="number"&&(n=t,t=1/0),this.global("_",!1),z(this,nt,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:i},this}demand(e,t,n){return Array.isArray(t)?(t.forEach(i=>{Pa(n,!0,z(this,_t,"f")),this.demandOption(i,n)}),t=1/0):typeof t!="number"&&(n=t,t=1/0),typeof e=="number"?(Pa(n,!0,z(this,_t,"f")),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(i=>{Pa(n,!0,z(this,_t,"f")),this.demandOption(i,n)}):typeof n=="string"?this.demandOption(e,n):(n===!0||typeof n>"u")&&this.demandOption(e),this}demandOption(e,t){return Ke("<object|string|array> [string]",[e,t],arguments.length),this[Q1](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return Ke("<string> [string|boolean]",[e,t],arguments.length),z(this,nt,"f").deprecatedOptions[e]=t,this}describe(e,t){return Ke("<object|string|array> [string]",[e,t],arguments.length),this[tZ](e,!0),z(this,Ot,"f").describe(e,t),this}detectLocale(e){return Ke("<boolean>",[e],arguments.length),Ye(this,Bd,e,"f"),this}env(e){return Ke("[string|boolean]",[e],arguments.length),e===!1?delete z(this,nt,"f").envPrefix:z(this,nt,"f").envPrefix=e||"",this}epilogue(e){return Ke("<string>",[e],arguments.length),z(this,Ot,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){return Ke("<string|array> [string]",[e,t],arguments.length),Array.isArray(e)?e.forEach(n=>this.example(...n)):z(this,Ot,"f").example(e,t),this}exit(e,t){Ye(this,Ro,!0,"f"),Ye(this,wf,t,"f"),z(this,ds,"f")&&z(this,_t,"f").process.exit(e)}exitProcess(e=!0){return Ke("[boolean]",[e],arguments.length),Ye(this,ds,e,"f"),this}fail(e){if(Ke("<function|boolean>",[e],arguments.length),typeof e=="boolean"&&e!==!1)throw new zn("Invalid first argument. Expected function or boolean 'false'");return z(this,Ot,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return Ke("<array> [function]",[e,t],arguments.length),t?z(this,ao,"f").getCompletion(e,t):new Promise((n,i)=>{z(this,ao,"f").getCompletion(e,(a,o)=>{a?i(a):n(o)})})}getDemandedOptions(){return Ke([],0),z(this,nt,"f").demandedOptions}getDemandedCommands(){return Ke([],0),z(this,nt,"f").demandedCommands}getDeprecatedOptions(){return Ke([],0),z(this,nt,"f").deprecatedOptions}getDetectLocale(){return z(this,Bd,"f")}getExitProcess(){return z(this,ds,"f")}getGroups(){return Object.assign({},z(this,nu,"f"),z(this,Vd,"f"))}getHelp(){if(Ye(this,Ro,!0,"f"),!z(this,Ot,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[R9](z(this,_f,"f"),void 0,void 0,0,!0);if(cn(t))return t.then(()=>z(this,Ot,"f").help())}let e=z(this,Bn,"f").runDefaultBuilderOn(this);if(cn(e))return e.then(()=>z(this,Ot,"f").help())}return Promise.resolve(z(this,Ot,"f").help())}getOptions(){return z(this,nt,"f")}getStrict(){return z(this,Gd,"f")}getStrictCommands(){return z(this,Zd,"f")}getStrictOptions(){return z(this,Jd,"f")}global(e,t){return Ke("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1?z(this,nt,"f").local=z(this,nt,"f").local.filter(n=>e.indexOf(n)===-1):e.forEach(n=>{z(this,nt,"f").local.includes(n)||z(this,nt,"f").local.push(n)}),this}group(e,t){Ke("<string|array> <string>",[e,t],arguments.length);let n=z(this,Vd,"f")[t]||z(this,nu,"f")[t];z(this,Vd,"f")[t]&&delete z(this,Vd,"f")[t];let i={};return z(this,nu,"f")[t]=(n||[]).concat(e).filter(a=>i[a]?!1:i[a]=!0),this}hide(e){return Ke("<string>",[e],arguments.length),z(this,nt,"f").hiddenOptions.push(e),this}implies(e,t){return Ke("<string|object> [number|string|array]",[e,t],arguments.length),z(this,In,"f").implies(e,t),this}locale(e){return Ke("[string]",[e],arguments.length),e===void 0?(this[KG](),z(this,_t,"f").y18n.getLocale()):(Ye(this,Bd,!1,"f"),z(this,_t,"f").y18n.setLocale(e),this)}middleware(e,t,n){return z(this,hs,"f").addMiddleware(e,!!t,n)}nargs(e,t){return Ke("<string|object|array> [number]",[e,t],arguments.length),this[Q1](this.nargs.bind(this),"narg",e,t),this}normalize(e){return Ke("<array|string>",[e],arguments.length),this[Sf]("normalize",e),this}number(e){return Ke("<array|string>",[e],arguments.length),this[Sf]("number",e),this[Xd](e),this}option(e,t){if(Ke("<string|object> [object]",[e,t],arguments.length),typeof e=="object")Object.keys(e).forEach(n=>{this.options(n,e[n])});else{typeof t!="object"&&(t={}),this[Xd](e),z(this,iu,"f")&&(e==="version"||t?.alias==="version")&&this[Kve](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
1521
1521
  `),void 0,"versionWarning"),z(this,nt,"f").key[e]=!0,t.alias&&this.alias(e,t.alias);let n=t.deprecate||t.deprecated;n&&this.deprecateOption(e,n);let i=t.demand||t.required||t.require;i&&this.demand(e,i),t.demandOption&&this.demandOption(e,typeof t.demandOption=="string"?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),"default"in t&&this.default(e,t.default),t.implies!==void 0&&this.implies(e,t.implies),t.nargs!==void 0&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||t.type==="boolean")&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||t.type==="array")&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||t.type==="number")&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||t.type==="string")&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||t.type==="count")&&this.count(e),typeof t.global=="boolean"&&this.global(e,t.global),t.defaultDescription&&(z(this,nt,"f").defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let a=t.describe||t.description||t.desc,o=z(this,Ot,"f").getDescriptions();(!Object.prototype.hasOwnProperty.call(o,e)||typeof a=="string")&&this.describe(e,a),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){Ke("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[Yve](),typeof e>"u"&&(e=z(this,_f,"f")),typeof t=="object"&&(Ye(this,Wd,t,"f"),t=n),typeof t=="function"&&(Ye(this,No,t,"f"),t=!1),t||Ye(this,_f,e,"f"),z(this,No,"f")&&Ye(this,ds,!1,"f");let i=this[R9](e,!!t),a=this.parsed;return z(this,ao,"f").setParsed(this.parsed),cn(i)?i.then(o=>(z(this,No,"f")&&z(this,No,"f").call(this,z(this,wf,"f"),o,z(this,Si,"f")),o)).catch(o=>{throw z(this,No,"f")&&z(this,No,"f")(o,this.parsed.argv,z(this,Si,"f")),o}).finally(()=>{this[rZ](),this.parsed=a}):(z(this,No,"f")&&z(this,No,"f").call(this,z(this,wf,"f"),i,z(this,Si,"f")),this[rZ](),this.parsed=a,i)}parseAsync(e,t,n){let i=this.parse(e,t,n);return cn(i)?i:Promise.resolve(i)}parseSync(e,t,n){let i=this.parse(e,t,n);if(cn(i))throw new zn(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return i}parserConfiguration(e){return Ke("<object>",[e],arguments.length),Ye(this,NT,e,"f"),this}pkgConf(e,t){Ke("<string> [string]",[e,t],arguments.length);let n=null,i=this[YG](t||z(this,zd,"f"));return i[e]&&typeof i[e]=="object"&&(n=$9(i[e],t||z(this,zd,"f"),this[Kd]()["deep-merge-config"]||!1,z(this,_t,"f")),z(this,nt,"f").configObjects=(z(this,nt,"f").configObjects||[]).concat(n)),this}positional(e,t){Ke("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=bf(t,(o,s)=>o==="type"&&!["string","number","boolean"].includes(s)?!1:n.includes(o));let i=z(this,j9,"f").fullCommands[z(this,j9,"f").fullCommands.length-1],a=i?z(this,Bn,"f").cmdToParseOptions(i):{array:[],alias:{},default:{},demand:{}};return K1(a).forEach(o=>{let s=a[o];Array.isArray(s)?s.indexOf(e)!==-1&&(t[o]=!0):s[e]&&!(o in t)&&(t[o]=s[e])}),this.group(e,z(this,Ot,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return Ke("[boolean]",[e],arguments.length),Ye(this,FT,e,"f"),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){return Ke("<array|string|object> [number]",[e],arguments.length),typeof e=="string"&&z(this,nt,"f").narg[e]?this:(this[Q1](this.requiresArg.bind(this),"narg",e,NaN),this)}showCompletionScript(e,t){return Ke("[string] [string]",[e,t],arguments.length),e=e||this.$0,z(this,Hd,"f").log(z(this,ao,"f").generateCompletionScript(e,t||z(this,jo,"f")||"completion")),this}showHelp(e){if(Ke("[string|function]",[e],arguments.length),Ye(this,Ro,!0,"f"),!z(this,Ot,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[R9](z(this,_f,"f"),void 0,void 0,0,!0);if(cn(n))return n.then(()=>{z(this,Ot,"f").showHelp(e)}),this}let t=z(this,Bn,"f").runDefaultBuilderOn(this);if(cn(t))return t.then(()=>{z(this,Ot,"f").showHelp(e)}),this}return z(this,Ot,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return Ke("[boolean|string] [string]",[e,t],arguments.length),z(this,Ot,"f").showHelpOnFail(e,t),this}showVersion(e){return Ke("[string|function]",[e],arguments.length),z(this,Ot,"f").showVersion(e),this}skipValidation(e){return Ke("<array|string>",[e],arguments.length),this[Sf]("skipValidation",e),this}strict(e){return Ke("[boolean]",[e],arguments.length),Ye(this,Gd,e!==!1,"f"),this}strictCommands(e){return Ke("[boolean]",[e],arguments.length),Ye(this,Zd,e!==!1,"f"),this}strictOptions(e){return Ke("[boolean]",[e],arguments.length),Ye(this,Jd,e!==!1,"f"),this}string(e){return Ke("<array|string>",[e],arguments.length),this[Sf]("string",e),this[Xd](e),this}terminalWidth(){return Ke([],0),z(this,_t,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return Ke("<object>",[e],arguments.length),Ye(this,Bd,!1,"f"),z(this,_t,"f").y18n.updateLocale(e),this}usage(e,t,n,i){if(Ke("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,i],arguments.length),t!==void 0){if(Pa(e,null,z(this,_t,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,i);throw new zn(".usage() description must start with $0 if being used as alias for .command()")}else return z(this,Ot,"f").usage(e),this}usageConfiguration(e){return Ke("<object>",[e],arguments.length),Ye(this,MT,e,"f"),this}version(e,t,n){let i="version";if(Ke("[boolean|string] [string] [string]",[e,t,n],arguments.length),z(this,iu,"f")&&(this[JG](z(this,iu,"f")),z(this,Ot,"f").version(void 0),Ye(this,iu,null,"f")),arguments.length===0)n=this[eye](),e=i;else if(arguments.length===1){if(e===!1)return this;n=e,e=i}else arguments.length===2&&(n=t,t=void 0);return Ye(this,iu,typeof e=="string"?e:i,"f"),t=t||z(this,Ot,"f").deferY18nLookup("Show version number"),z(this,Ot,"f").version(n||void 0),this.boolean(z(this,iu,"f")),this.describe(z(this,iu,"f"),t),this}wrap(e){return Ke("<number|null|undefined>",[e],arguments.length),z(this,Ot,"f").wrap(e),this}[(Bn=new WeakMap,zd=new WeakMap,j9=new WeakMap,ao=new WeakMap,jo=new WeakMap,IT=new WeakMap,wf=new WeakMap,Bd=new WeakMap,OT=new WeakMap,ds=new WeakMap,$T=new WeakMap,hs=new WeakMap,nu=new WeakMap,Ro=new WeakMap,ms=new WeakMap,jT=new WeakMap,Hd=new WeakMap,Si=new WeakMap,nt=new WeakMap,RT=new WeakMap,NT=new WeakMap,No=new WeakMap,Wd=new WeakMap,X1=new WeakMap,Vd=new WeakMap,_f=new WeakMap,FT=new WeakMap,_t=new WeakMap,Gd=new WeakMap,Zd=new WeakMap,Jd=new WeakMap,Ot=new WeakMap,MT=new WeakMap,iu=new WeakMap,In=new WeakMap,Zve)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch{}return e}[Jve](){return{log:(...e)=>{this[LT]()||console.log(...e),Ye(this,Ro,!0,"f"),z(this,Si,"f").length&&Ye(this,Si,z(this,Si,"f")+`
1522
1522
  `,"f"),Ye(this,Si,z(this,Si,"f")+e.join(" "),"f")},error:(...e)=>{this[LT]()||console.error(...e),Ye(this,Ro,!0,"f"),z(this,Si,"f").length&&Ye(this,Si,z(this,Si,"f")+`
1523
- `,"f"),Ye(this,Si,z(this,Si,"f")+e.join(" "),"f")}}}[JG](e){K1(z(this,nt,"f")).forEach(t=>{if((i=>i==="configObjects")(t))return;let n=z(this,nt,"f")[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n=="object"&&delete n[e]}),delete z(this,Ot,"f").getDescriptions()[e]}[Kve](e,t,n){z(this,OT,"f")[n]||(z(this,_t,"f").process.emitWarning(e,t),z(this,OT,"f")[n]=!0)}[Yve](){z(this,$T,"f").push({options:z(this,nt,"f"),configObjects:z(this,nt,"f").configObjects.slice(0),exitProcess:z(this,ds,"f"),groups:z(this,nu,"f"),strict:z(this,Gd,"f"),strictCommands:z(this,Zd,"f"),strictOptions:z(this,Jd,"f"),completionCommand:z(this,jo,"f"),output:z(this,Si,"f"),exitError:z(this,wf,"f"),hasOutput:z(this,Ro,"f"),parsed:this.parsed,parseFn:z(this,No,"f"),parseContext:z(this,Wd,"f")}),z(this,Ot,"f").freeze(),z(this,In,"f").freeze(),z(this,Bn,"f").freeze(),z(this,hs,"f").freeze()}[Xve](){let e="",t;return/\b(node|iojs|electron)(\.exe)?$/.test(z(this,_t,"f").process.argv()[0])?t=z(this,_t,"f").process.argv().slice(1,2):t=z(this,_t,"f").process.argv().slice(0,1),e=t.map(n=>{let i=this[fye](z(this,zd,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&i.length<n.length?i:n}).join(" ").trim(),z(this,_t,"f").getEnv("_")&&z(this,_t,"f").getProcessArgvBin()===z(this,_t,"f").getEnv("_")&&(e=z(this,_t,"f").getEnv("_").replace(`${z(this,_t,"f").path.dirname(z(this,_t,"f").process.execPath())}/`,"")),e}[Kd](){return z(this,NT,"f")}[Qve](){return z(this,MT,"f")}[KG](){if(!z(this,Bd,"f"))return;let e=z(this,_t,"f").getEnv("LC_ALL")||z(this,_t,"f").getEnv("LC_MESSAGES")||z(this,_t,"f").getEnv("LANG")||z(this,_t,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[eye](){return this[YG]().version||"unknown"}[tye](e){let t=e["--"]?e["--"]:e._;for(let n=0,i;(i=t[n])!==void 0;n++)z(this,_t,"f").Parser.looksLikeNumber(i)&&Number.isSafeInteger(Math.floor(parseFloat(`${i}`)))&&(t[n]=Number(i));return e}[YG](e){let t=e||"*";if(z(this,X1,"f")[t])return z(this,X1,"f")[t];let n={};try{let i=e||z(this,_t,"f").mainFilename;z(this,_t,"f").path.extname(i)&&(i=z(this,_t,"f").path.dirname(i));let a=z(this,_t,"f").findUp(i,(o,s)=>{if(s.includes("package.json"))return"package.json"});Pa(a,void 0,z(this,_t,"f")),n=JSON.parse(z(this,_t,"f").readFileSync(a,"utf8"))}catch{}return z(this,X1,"f")[t]=n||{},z(this,X1,"f")[t]}[Sf](e,t){t=[].concat(t),t.forEach(n=>{n=this[eZ](n),z(this,nt,"f")[e].push(n)})}[Q1](e,t,n,i){this[QG](e,t,n,i,(a,o,s)=>{z(this,nt,"f")[a][o]=s})}[XG](e,t,n,i){this[QG](e,t,n,i,(a,o,s)=>{z(this,nt,"f")[a][o]=(z(this,nt,"f")[a][o]||[]).concat(s)})}[QG](e,t,n,i,a){if(Array.isArray(n))n.forEach(o=>{e(o,i)});else if((o=>typeof o=="object")(n))for(let o of K1(n))e(o,n[o]);else a(t,this[eZ](n),i)}[eZ](e){return e==="__proto__"?"___proto___":e}[tZ](e,t){return this[Q1](this[tZ].bind(this),"key",e,t),this}[rZ](){var e,t,n,i,a,o,s,c,u,l,f,p;let d=z(this,$T,"f").pop();Pa(d,void 0,z(this,_t,"f"));let m;e=this,t=this,n=this,i=this,a=this,o=this,s=this,c=this,u=this,l=this,f=this,p=this,{options:{set value(h){Ye(e,nt,h,"f")}}.value,configObjects:m,exitProcess:{set value(h){Ye(t,ds,h,"f")}}.value,groups:{set value(h){Ye(n,nu,h,"f")}}.value,output:{set value(h){Ye(i,Si,h,"f")}}.value,exitError:{set value(h){Ye(a,wf,h,"f")}}.value,hasOutput:{set value(h){Ye(o,Ro,h,"f")}}.value,parsed:this.parsed,strict:{set value(h){Ye(s,Gd,h,"f")}}.value,strictCommands:{set value(h){Ye(c,Zd,h,"f")}}.value,strictOptions:{set value(h){Ye(u,Jd,h,"f")}}.value,completionCommand:{set value(h){Ye(l,jo,h,"f")}}.value,parseFn:{set value(h){Ye(f,No,h,"f")}}.value,parseContext:{set value(h){Ye(p,Wd,h,"f")}}.value}=d,z(this,nt,"f").configObjects=m,z(this,Ot,"f").unfreeze(),z(this,In,"f").unfreeze(),z(this,Bn,"f").unfreeze(),z(this,hs,"f").unfreeze()}[rye](e,t){return Ud(t,n=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[nye].bind(this),getContext:this[iye].bind(this),getHasOutput:this[aye].bind(this),getLoggerInstance:this[oye].bind(this),getParseContext:this[sye].bind(this),getParserConfiguration:this[Kd].bind(this),getUsageConfiguration:this[Qve].bind(this),getUsageInstance:this[cye].bind(this),getValidationInstance:this[uye].bind(this),hasParseCallback:this[LT].bind(this),isGlobalContext:this[lye].bind(this),postProcess:this[Yd].bind(this),reset:this[nZ].bind(this),runValidation:this[iZ].bind(this),runYargsParserAndExecuteCommands:this[R9].bind(this),setHasOutput:this[pye].bind(this)}}[nye](){return z(this,Bn,"f")}[iye](){return z(this,j9,"f")}[aye](){return z(this,Ro,"f")}[oye](){return z(this,Hd,"f")}[sye](){return z(this,Wd,"f")||{}}[cye](){return z(this,Ot,"f")}[uye](){return z(this,In,"f")}[LT](){return!!z(this,No,"f")}[lye](){return z(this,jT,"f")}[Yd](e,t,n,i){return n||cn(e)||(t||(e=this[Zve](e)),(this[Kd]()["parse-positional-numbers"]||this[Kd]()["parse-positional-numbers"]===void 0)&&(e=this[tye](e)),i&&(e=qd(e,this,z(this,hs,"f").getMiddleware(),!1))),e}[nZ](e={}){Ye(this,nt,z(this,nt,"f")||{},"f");let t={};t.local=z(this,nt,"f").local||[],t.configObjects=z(this,nt,"f").configObjects||[];let n={};t.local.forEach(o=>{n[o]=!0,(e[o]||[]).forEach(s=>{n[s]=!0})}),Object.assign(z(this,Vd,"f"),Object.keys(z(this,nu,"f")).reduce((o,s)=>{let c=z(this,nu,"f")[s].filter(u=>!(u in n));return c.length>0&&(o[s]=c),o},{})),Ye(this,nu,{},"f");let i=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],a=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];return i.forEach(o=>{t[o]=(z(this,nt,"f")[o]||[]).filter(s=>!n[s])}),a.forEach(o=>{t[o]=bf(z(this,nt,"f")[o],s=>!n[s])}),t.envPrefix=z(this,nt,"f").envPrefix,Ye(this,nt,t,"f"),Ye(this,Ot,z(this,Ot,"f")?z(this,Ot,"f").reset(n):qve(this,z(this,_t,"f")),"f"),Ye(this,In,z(this,In,"f")?z(this,In,"f").reset(n):Vve(this,z(this,Ot,"f"),z(this,_t,"f")),"f"),Ye(this,Bn,z(this,Bn,"f")?z(this,Bn,"f").reset():Fve(z(this,Ot,"f"),z(this,In,"f"),z(this,hs,"f"),z(this,_t,"f")),"f"),z(this,ao,"f")||Ye(this,ao,Bve(this,z(this,Ot,"f"),z(this,Bn,"f"),z(this,_t,"f")),"f"),z(this,hs,"f").reset(),Ye(this,jo,null,"f"),Ye(this,Si,"","f"),Ye(this,wf,null,"f"),Ye(this,Ro,!1,"f"),this.parsed=!1,this}[fye](e,t){return z(this,_t,"f").path.relative(e,t)}[R9](e,t,n,i=0,a=!1){var o,s,c,u;let l=!!n||a;e=e||z(this,_f,"f"),z(this,nt,"f").__=z(this,_t,"f").y18n.__,z(this,nt,"f").configuration=this[Kd]();let f=!!z(this,nt,"f").configuration["populate--"],p=Object.assign({},z(this,nt,"f").configuration,{"populate--":!0}),d=z(this,_t,"f").Parser.detailed(e,Object.assign({},z(this,nt,"f"),{configuration:{"parse-positional-numbers":!1,...p}})),m=Object.assign(d.argv,z(this,Wd,"f")),h,g=d.aliases,v=!1,y=!1;Object.keys(m).forEach(x=>{x===z(this,ms,"f")&&m[x]?v=!0:x===z(this,iu,"f")&&m[x]&&(y=!0)}),m.$0=this.$0,this.parsed=d,i===0&&z(this,Ot,"f").clearCachedHelpMessage();try{if(this[KG](),t)return this[Yd](m,f,!!n,!1);z(this,ms,"f")&&[z(this,ms,"f")].concat(g[z(this,ms,"f")]||[]).filter($=>$.length>1).includes(""+m._[m._.length-1])&&(m._.pop(),v=!0),Ye(this,jT,!1,"f");let x=z(this,Bn,"f").getCommands(),k=!((o=z(this,ao,"f"))===null||o===void 0)&&o.completionKey?[(s=z(this,ao,"f"))===null||s===void 0?void 0:s.completionKey,...(u=this.getAliases()[(c=z(this,ao,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&u!==void 0?u:[]].some(A=>Object.prototype.hasOwnProperty.call(m,A)):!1,S=v||k||a;if(m._.length){if(x.length){let A;for(let $=i||0,O;m._[$]!==void 0;$++)if(O=String(m._[$]),x.includes(O)&&O!==z(this,jo,"f")){let w=z(this,Bn,"f").runCommand(O,this,d,$+1,a,v||y||a);return this[Yd](w,f,!!n,!1)}else if(!A&&O!==z(this,jo,"f")){A=O;break}!z(this,Bn,"f").hasDefaultCommand()&&z(this,FT,"f")&&A&&!S&&z(this,In,"f").recommendCommands(A,x)}z(this,jo,"f")&&m._.includes(z(this,jo,"f"))&&!k&&(z(this,ds,"f")&&xf(!0),this.showCompletionScript(),this.exit(0))}if(z(this,Bn,"f").hasDefaultCommand()&&!S){let A=z(this,Bn,"f").runCommand(null,this,d,0,a,v||y||a);return this[Yd](A,f,!!n,!1)}if(k){z(this,ds,"f")&&xf(!0),e=[].concat(e);let A=e.slice(e.indexOf(`--${z(this,ao,"f").completionKey}`)+1);return z(this,ao,"f").getCompletion(A,($,O)=>{if($)throw new zn($.message);(O||[]).forEach(w=>{z(this,Hd,"f").log(w)}),this.exit(0)}),this[Yd](m,!f,!!n,!1)}if(z(this,Ro,"f")||(v?(z(this,ds,"f")&&xf(!0),l=!0,this.showHelp(A=>{z(this,Hd,"f").log(A),this.exit(0)})):y&&(z(this,ds,"f")&&xf(!0),l=!0,z(this,Ot,"f").showVersion("log"),this.exit(0))),!l&&z(this,nt,"f").skipValidation.length>0&&(l=Object.keys(m).some(A=>z(this,nt,"f").skipValidation.indexOf(A)>=0&&m[A]===!0)),!l){if(d.error)throw new zn(d.error.message);if(!k){let A=this[iZ](g,{},d.error);n||(h=qd(m,this,z(this,hs,"f").getMiddleware(),!0)),h=this[rye](A,h??m),cn(h)&&!n&&(h=h.then(()=>qd(m,this,z(this,hs,"f").getMiddleware(),!1)))}}}catch(x){if(x instanceof zn)z(this,Ot,"f").fail(x.message,x);else throw x}return this[Yd](h??m,f,!!n,!0)}[iZ](e,t,n,i){let a={...this.getDemandedOptions()};return o=>{if(n)throw new zn(n.message);z(this,In,"f").nonOptionCount(o),z(this,In,"f").requiredArguments(o,a);let s=!1;z(this,Zd,"f")&&(s=z(this,In,"f").unknownCommands(o)),z(this,Gd,"f")&&!s?z(this,In,"f").unknownArguments(o,e,t,!!i):z(this,Jd,"f")&&z(this,In,"f").unknownArguments(o,e,{},!1,!1),z(this,In,"f").limitedChoices(o),z(this,In,"f").implications(o),z(this,In,"f").conflicting(o)}}[pye](){Ye(this,Ro,!0,"f")}[Xd](e){if(typeof e=="string")z(this,nt,"f").key[e]=!0;else for(let t of e)z(this,nt,"f").key[t]=!0}};function Mve(r){return!!r&&typeof r.getInternalMethods=="function"}var vvt=dye(BG),hye=vvt;import yvt from"node:os";function mye(){let r=qG(process.argv),e=hye(r).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,t,n,i=e.prompt||e._.slice(1),a=!!e.oneshot,o=!!e.fileReadOnly,s=oZ.join(yvt.homedir(),".coday"),c=e.coday_config_dir||s,u=!!e.auth,l=!!e.debug,f=!e.log,p=e.log_folder;return e.coday_project?(t=e.coday_project,n=!0,console.log(`Project mode: restricting to project '${t}'`)):e.local?(t=oZ.basename(process.cwd()),n=!0,console.log(`Local mode: restricting to project '${t}'`)):e.multi?(t="",n=!1,console.log("Multi-project mode: no default project selection")):(t=oZ.basename(process.cwd()),n=!1,console.log(`Default mode: using '${t}' as default project`)),{oneshot:a,debug:l,project:t,prompts:i,fileReadOnly:o,configDir:c,auth:u,agentFolders:e.agentFolders||[],noLog:f,logFolder:p,forcedProject:n,baseUrl:e.base_url}}var Rxe=vr(JZ(),1);import*as $xe from"node:os";var yxt="cf_authorization",bxt="x-forwarded-email";function xxt(r){if(!r)return null;let e=r.split(".");if(e.length!==3)return null;try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(t,"base64").toString("utf8"),a=JSON.parse(n)?.email;return typeof a=="string"&&a.length>0?a:null}catch{return null}}function jxe(r,e){if(!e)return $xe.userInfo().username;let t=r[yxt],n=xxt(t);if(n)return n;let i=r[bxt];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.")}var Ei=(0,mP.default)(),wxt=process.env.PORT?parseInt(process.env.PORT):process.env.BUILD_ENV==="development"?4100:3e3,_xt=D7e(wxt),Xr=mye();ce("INIT","Coday options:",Xr);var Nxe=!Xr.noLog,a4=new r_(Nxe,Xr.logFolder);ce("INIT",`Usage logging ${Nxe?"enabled":"disabled"} ${Xr.logFolder?`(custom folder: ${Xr.logFolder})`:""}`);ce("INIT","Webhook service initialized (will be initialized with prompt execution service)");var a3,gP,Sxt=process.env.AGENTOS_PORT?parseInt(process.env.AGENTOS_PORT):8123,Fxe=`http://localhost:${Sxt}`;Ei.use("/api/agentos",(r,e,t)=>{console.log(`[AGENTOS PROXY] ${r.method} ${r.path}`),t()},(0,Rxe.createProxyMiddleware)({target:Fxe,changeOrigin:!0,pathRewrite:{"^/api/agentos":""}}));ce("INIT",`AgentOS proxy configured: /api/agentos \u2192 ${Fxe}`);Ei.use(mP.default.json({limit:"20mb"}));if(process.env.BUILD_ENV==="development"){let e=`http://localhost:${process.env.ANGULAR_CLIENT_PORT??"4200"}`;ce("INIT",`Development mode: proxying to Angular dev server at ${e}`),Promise.resolve().then(()=>vr(JZ(),1)).then(({createProxyMiddleware:t})=>{let n=t({target:e,changeOrigin:!0,ws:!0});Ei.use("/",(i,a,o)=>{i.path.startsWith("/api")||i.path.startsWith("/events")?o():n(i,a,o)}),ce("INIT","Proxy middleware configured successfully")}).catch(t=>{console.error("Failed to load http-proxy-middleware:",t)})}else{let r=process.env.CODAY_CLIENT_PATH?bl.resolve(process.env.CODAY_CLIENT_PATH):bl.resolve(__dirname,"../coday-client/browser");if(ce("INIT",`Production mode: serving static files from ${r}`),process.env.CODAY_CLIENT_PATH&&ce("INIT","Using client path from CODAY_CLIENT_PATH environment variable"),!lP.existsSync(r))console.error(`ERROR: Client path does not exist: ${r}`),console.error("Please build the client first with: pnpm nx run client:build");else{let e=bl.join(r,"index.html");lP.existsSync(e)?ce("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"))}Ei.use(mP.default.static(r))}var fP=new aE(Xr.configDir),H9=Xr.project;if(H9&&!Xr.forcedProject){let r=process.cwd(),e=bl.basename(r);if(fP.exists(e)){let t=fP.getConfig(e);if(t&&t.path===r&&!t.volatile)ce("INIT",`Default mode: found existing non-volatile project '${e}' for current directory`),H9=e;else{let n=xm.generateProjectId(r);ce("INIT",`Default mode: existing project '${e}' doesn't match path, using volatile ID ${n}`),H9=n}}else{let t=xm.generateProjectId(r);ce("INIT",`Default mode: no existing project found, using volatile ID ${t}`),H9=t}}var o4=new xm(fP,H9,Xr.forcedProject);a3=new rE(Xr.configDir,o4);a3.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>"});ce("INIT","Prompt service initialized");gP=new nE(a3);ce("INIT","Prompt execution service initialized (will be initialized with dependencies after thread manager)");var Mxe=bl.join(Xr.configDir,"projects"),Lxe=new uE(Mxe),vP=new sE(fP,Mxe,Lxe),Ext=new Cm;ce("INIT","MCP instance pool initialized");var yP=new hT(a4,o4,vP,a3,Ext);gP.initialize(yP,vP,Xr,a4);ce("INIT","Prompt execution service initialized");ce("INIT","Webhook service initialized with prompt execution delegation");var kxt=new yc("config-api"),Axt=new QS(Xr.configDir,kxt),Cxt=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function xl(r){let e=jxe(r.headers,!!Xr.auth);if(Cxt.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}N7e(Ei,xl,Xr.configDir);I7e(Ei,Axt,xl);M7e(Ei,a3,xl);q7e(Ei,gP,xl);O7e(Ei,o4);Z7e(Ei,o4);$7e(Ei,vP,Lxe,yP,xl,Xr);j7e(Ei,yP,xl);var Txt=new YS(Xr.configDir,o4);F7e(Ei,o4,xl,Xr.configDir,a4,a3,vP,Txt,Xr);var pP=new iE(a4,a3,Xr.configDir);L7e(Ei,pP,xl);B7e(Ei,a4,xl,Xr.auth);if(process.env.BUILD_ENV!=="development"){let r=process.env.CODAY_CLIENT_PATH?bl.resolve(process.env.CODAY_CLIENT_PATH):bl.resolve(__dirname,"../coday-client/browser"),e=bl.resolve(r,"index.html");ce("INIT",`Catch-all route will serve: ${e}`),Ei.use((t,n,i)=>{if(t.path.startsWith("/api")||t.path.startsWith("/events")){n.status(404).send("Not found");return}ce("ROUTER",`Serving index.html for client route: ${t.path}`),lP.readFile(e,"utf8",(a,o)=>{a?(ce("ERROR",`Failed to read index.html from ${e}:`,a),ce("ERROR",`File exists check: ${lP.existsSync(e)}`),i(a)):n.type("html").send(o)})})}var dP=null;Ei.use((r,e,t,n)=>{ce("ERROR",`Request error on ${e.method} ${e.path}:`,r.message),console.error(r.stack),process.env.BUILD_ENV==="development"?t.status(500).json({error:"Internal Server Error",message:r.message,stack:r.stack}):t.status(500).send("Something went wrong!")});_xt.then(async r=>{Xr.baseUrl?ce("INIT",`Using configured base URL: ${Xr.baseUrl}`):(Xr.baseUrl=`http://localhost:${r}`,ce("INIT",`Base URL set to: ${Xr.baseUrl}`)),Ei.listen(r,()=>{console.log(`Server is running on http://localhost:${r}`)});try{ce("CLEANUP","Starting thread cleanup service...");let e=bl.join(Xr.configDir,"projects");dP=new cE(e,a4),await dP.start(),ce("CLEANUP","Thread cleanup service started successfully")}catch(e){console.error("Failed to start thread cleanup service:",e)}try{ce("SCHEDULER","Initializing scheduler service..."),await pP.initialize(),pP.initializeExecution(gP),ce("SCHEDULER","Scheduler service initialized successfully")}catch(e){console.error("Failed to initialize scheduler service:",e)}}).catch(r=>{console.error("Failed to start server:",r),process.exit(1)});var hP=!1;async function s4(r){hP&&(console.log(`Received ${r} during shutdown, forcing exit...`),process.exit(1)),hP=!0,console.log(`Received ${r}, shutting down gracefully...`);try{console.log("Stopping scheduler service..."),pP.stop(),dP&&(console.log("Stopping thread cleanup service..."),await dP.stop()),console.log("Cleaning up thread Coday instances..."),await yP.shutdown(),console.log("Graceful shutdown completed"),process.exit(0)}catch(e){console.error("Error during graceful shutdown:",e),process.exit(1)}}process.on("SIGTERM",()=>s4("SIGTERM"));process.on("SIGINT",()=>s4("SIGINT"));process.on("SIGUSR2",()=>s4("SIGUSR2"));process.on("SIGHUP",()=>s4("SIGHUP"));process.on("uncaughtException",r=>{if(console.error("Uncaught exception:",r),r.message==="no elements in sequence"||r.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}hP||s4("uncaughtException")});process.on("unhandledRejection",(r,e)=>{if(console.error("Unhandled rejection at:",e,"reason:",r),r&&typeof r=="object"){let t=r;if(t.message==="no elements in sequence"||t.constructor?.name==="EmptyErrorImpl"){console.log("Detected RxJS EmptyError rejection during system sleep - this is expected behavior");return}if(t.name==="TimeoutError"||t.message?.includes("timeout")){console.log("Detected timeout error - handling gracefully without shutdown");return}if(t.name==="AbortError"||t.message?.includes("aborted")){console.log("Detected abort error - handling gracefully without shutdown");return}}console.error("Critical unhandled rejection detected"),hP||s4("unhandledRejection")});
1523
+ `,"f"),Ye(this,Si,z(this,Si,"f")+e.join(" "),"f")}}}[JG](e){K1(z(this,nt,"f")).forEach(t=>{if((i=>i==="configObjects")(t))return;let n=z(this,nt,"f")[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n=="object"&&delete n[e]}),delete z(this,Ot,"f").getDescriptions()[e]}[Kve](e,t,n){z(this,OT,"f")[n]||(z(this,_t,"f").process.emitWarning(e,t),z(this,OT,"f")[n]=!0)}[Yve](){z(this,$T,"f").push({options:z(this,nt,"f"),configObjects:z(this,nt,"f").configObjects.slice(0),exitProcess:z(this,ds,"f"),groups:z(this,nu,"f"),strict:z(this,Gd,"f"),strictCommands:z(this,Zd,"f"),strictOptions:z(this,Jd,"f"),completionCommand:z(this,jo,"f"),output:z(this,Si,"f"),exitError:z(this,wf,"f"),hasOutput:z(this,Ro,"f"),parsed:this.parsed,parseFn:z(this,No,"f"),parseContext:z(this,Wd,"f")}),z(this,Ot,"f").freeze(),z(this,In,"f").freeze(),z(this,Bn,"f").freeze(),z(this,hs,"f").freeze()}[Xve](){let e="",t;return/\b(node|iojs|electron)(\.exe)?$/.test(z(this,_t,"f").process.argv()[0])?t=z(this,_t,"f").process.argv().slice(1,2):t=z(this,_t,"f").process.argv().slice(0,1),e=t.map(n=>{let i=this[fye](z(this,zd,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&i.length<n.length?i:n}).join(" ").trim(),z(this,_t,"f").getEnv("_")&&z(this,_t,"f").getProcessArgvBin()===z(this,_t,"f").getEnv("_")&&(e=z(this,_t,"f").getEnv("_").replace(`${z(this,_t,"f").path.dirname(z(this,_t,"f").process.execPath())}/`,"")),e}[Kd](){return z(this,NT,"f")}[Qve](){return z(this,MT,"f")}[KG](){if(!z(this,Bd,"f"))return;let e=z(this,_t,"f").getEnv("LC_ALL")||z(this,_t,"f").getEnv("LC_MESSAGES")||z(this,_t,"f").getEnv("LANG")||z(this,_t,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[eye](){return this[YG]().version||"unknown"}[tye](e){let t=e["--"]?e["--"]:e._;for(let n=0,i;(i=t[n])!==void 0;n++)z(this,_t,"f").Parser.looksLikeNumber(i)&&Number.isSafeInteger(Math.floor(parseFloat(`${i}`)))&&(t[n]=Number(i));return e}[YG](e){let t=e||"*";if(z(this,X1,"f")[t])return z(this,X1,"f")[t];let n={};try{let i=e||z(this,_t,"f").mainFilename;z(this,_t,"f").path.extname(i)&&(i=z(this,_t,"f").path.dirname(i));let a=z(this,_t,"f").findUp(i,(o,s)=>{if(s.includes("package.json"))return"package.json"});Pa(a,void 0,z(this,_t,"f")),n=JSON.parse(z(this,_t,"f").readFileSync(a,"utf8"))}catch{}return z(this,X1,"f")[t]=n||{},z(this,X1,"f")[t]}[Sf](e,t){t=[].concat(t),t.forEach(n=>{n=this[eZ](n),z(this,nt,"f")[e].push(n)})}[Q1](e,t,n,i){this[QG](e,t,n,i,(a,o,s)=>{z(this,nt,"f")[a][o]=s})}[XG](e,t,n,i){this[QG](e,t,n,i,(a,o,s)=>{z(this,nt,"f")[a][o]=(z(this,nt,"f")[a][o]||[]).concat(s)})}[QG](e,t,n,i,a){if(Array.isArray(n))n.forEach(o=>{e(o,i)});else if((o=>typeof o=="object")(n))for(let o of K1(n))e(o,n[o]);else a(t,this[eZ](n),i)}[eZ](e){return e==="__proto__"?"___proto___":e}[tZ](e,t){return this[Q1](this[tZ].bind(this),"key",e,t),this}[rZ](){var e,t,n,i,a,o,s,c,u,l,f,p;let d=z(this,$T,"f").pop();Pa(d,void 0,z(this,_t,"f"));let m;e=this,t=this,n=this,i=this,a=this,o=this,s=this,c=this,u=this,l=this,f=this,p=this,{options:{set value(h){Ye(e,nt,h,"f")}}.value,configObjects:m,exitProcess:{set value(h){Ye(t,ds,h,"f")}}.value,groups:{set value(h){Ye(n,nu,h,"f")}}.value,output:{set value(h){Ye(i,Si,h,"f")}}.value,exitError:{set value(h){Ye(a,wf,h,"f")}}.value,hasOutput:{set value(h){Ye(o,Ro,h,"f")}}.value,parsed:this.parsed,strict:{set value(h){Ye(s,Gd,h,"f")}}.value,strictCommands:{set value(h){Ye(c,Zd,h,"f")}}.value,strictOptions:{set value(h){Ye(u,Jd,h,"f")}}.value,completionCommand:{set value(h){Ye(l,jo,h,"f")}}.value,parseFn:{set value(h){Ye(f,No,h,"f")}}.value,parseContext:{set value(h){Ye(p,Wd,h,"f")}}.value}=d,z(this,nt,"f").configObjects=m,z(this,Ot,"f").unfreeze(),z(this,In,"f").unfreeze(),z(this,Bn,"f").unfreeze(),z(this,hs,"f").unfreeze()}[rye](e,t){return Ud(t,n=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[nye].bind(this),getContext:this[iye].bind(this),getHasOutput:this[aye].bind(this),getLoggerInstance:this[oye].bind(this),getParseContext:this[sye].bind(this),getParserConfiguration:this[Kd].bind(this),getUsageConfiguration:this[Qve].bind(this),getUsageInstance:this[cye].bind(this),getValidationInstance:this[uye].bind(this),hasParseCallback:this[LT].bind(this),isGlobalContext:this[lye].bind(this),postProcess:this[Yd].bind(this),reset:this[nZ].bind(this),runValidation:this[iZ].bind(this),runYargsParserAndExecuteCommands:this[R9].bind(this),setHasOutput:this[pye].bind(this)}}[nye](){return z(this,Bn,"f")}[iye](){return z(this,j9,"f")}[aye](){return z(this,Ro,"f")}[oye](){return z(this,Hd,"f")}[sye](){return z(this,Wd,"f")||{}}[cye](){return z(this,Ot,"f")}[uye](){return z(this,In,"f")}[LT](){return!!z(this,No,"f")}[lye](){return z(this,jT,"f")}[Yd](e,t,n,i){return n||cn(e)||(t||(e=this[Zve](e)),(this[Kd]()["parse-positional-numbers"]||this[Kd]()["parse-positional-numbers"]===void 0)&&(e=this[tye](e)),i&&(e=qd(e,this,z(this,hs,"f").getMiddleware(),!1))),e}[nZ](e={}){Ye(this,nt,z(this,nt,"f")||{},"f");let t={};t.local=z(this,nt,"f").local||[],t.configObjects=z(this,nt,"f").configObjects||[];let n={};t.local.forEach(o=>{n[o]=!0,(e[o]||[]).forEach(s=>{n[s]=!0})}),Object.assign(z(this,Vd,"f"),Object.keys(z(this,nu,"f")).reduce((o,s)=>{let c=z(this,nu,"f")[s].filter(u=>!(u in n));return c.length>0&&(o[s]=c),o},{})),Ye(this,nu,{},"f");let i=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],a=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];return i.forEach(o=>{t[o]=(z(this,nt,"f")[o]||[]).filter(s=>!n[s])}),a.forEach(o=>{t[o]=bf(z(this,nt,"f")[o],s=>!n[s])}),t.envPrefix=z(this,nt,"f").envPrefix,Ye(this,nt,t,"f"),Ye(this,Ot,z(this,Ot,"f")?z(this,Ot,"f").reset(n):qve(this,z(this,_t,"f")),"f"),Ye(this,In,z(this,In,"f")?z(this,In,"f").reset(n):Vve(this,z(this,Ot,"f"),z(this,_t,"f")),"f"),Ye(this,Bn,z(this,Bn,"f")?z(this,Bn,"f").reset():Fve(z(this,Ot,"f"),z(this,In,"f"),z(this,hs,"f"),z(this,_t,"f")),"f"),z(this,ao,"f")||Ye(this,ao,Bve(this,z(this,Ot,"f"),z(this,Bn,"f"),z(this,_t,"f")),"f"),z(this,hs,"f").reset(),Ye(this,jo,null,"f"),Ye(this,Si,"","f"),Ye(this,wf,null,"f"),Ye(this,Ro,!1,"f"),this.parsed=!1,this}[fye](e,t){return z(this,_t,"f").path.relative(e,t)}[R9](e,t,n,i=0,a=!1){var o,s,c,u;let l=!!n||a;e=e||z(this,_f,"f"),z(this,nt,"f").__=z(this,_t,"f").y18n.__,z(this,nt,"f").configuration=this[Kd]();let f=!!z(this,nt,"f").configuration["populate--"],p=Object.assign({},z(this,nt,"f").configuration,{"populate--":!0}),d=z(this,_t,"f").Parser.detailed(e,Object.assign({},z(this,nt,"f"),{configuration:{"parse-positional-numbers":!1,...p}})),m=Object.assign(d.argv,z(this,Wd,"f")),h,g=d.aliases,v=!1,y=!1;Object.keys(m).forEach(x=>{x===z(this,ms,"f")&&m[x]?v=!0:x===z(this,iu,"f")&&m[x]&&(y=!0)}),m.$0=this.$0,this.parsed=d,i===0&&z(this,Ot,"f").clearCachedHelpMessage();try{if(this[KG](),t)return this[Yd](m,f,!!n,!1);z(this,ms,"f")&&[z(this,ms,"f")].concat(g[z(this,ms,"f")]||[]).filter($=>$.length>1).includes(""+m._[m._.length-1])&&(m._.pop(),v=!0),Ye(this,jT,!1,"f");let x=z(this,Bn,"f").getCommands(),k=!((o=z(this,ao,"f"))===null||o===void 0)&&o.completionKey?[(s=z(this,ao,"f"))===null||s===void 0?void 0:s.completionKey,...(u=this.getAliases()[(c=z(this,ao,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&u!==void 0?u:[]].some(A=>Object.prototype.hasOwnProperty.call(m,A)):!1,S=v||k||a;if(m._.length){if(x.length){let A;for(let $=i||0,O;m._[$]!==void 0;$++)if(O=String(m._[$]),x.includes(O)&&O!==z(this,jo,"f")){let w=z(this,Bn,"f").runCommand(O,this,d,$+1,a,v||y||a);return this[Yd](w,f,!!n,!1)}else if(!A&&O!==z(this,jo,"f")){A=O;break}!z(this,Bn,"f").hasDefaultCommand()&&z(this,FT,"f")&&A&&!S&&z(this,In,"f").recommendCommands(A,x)}z(this,jo,"f")&&m._.includes(z(this,jo,"f"))&&!k&&(z(this,ds,"f")&&xf(!0),this.showCompletionScript(),this.exit(0))}if(z(this,Bn,"f").hasDefaultCommand()&&!S){let A=z(this,Bn,"f").runCommand(null,this,d,0,a,v||y||a);return this[Yd](A,f,!!n,!1)}if(k){z(this,ds,"f")&&xf(!0),e=[].concat(e);let A=e.slice(e.indexOf(`--${z(this,ao,"f").completionKey}`)+1);return z(this,ao,"f").getCompletion(A,($,O)=>{if($)throw new zn($.message);(O||[]).forEach(w=>{z(this,Hd,"f").log(w)}),this.exit(0)}),this[Yd](m,!f,!!n,!1)}if(z(this,Ro,"f")||(v?(z(this,ds,"f")&&xf(!0),l=!0,this.showHelp(A=>{z(this,Hd,"f").log(A),this.exit(0)})):y&&(z(this,ds,"f")&&xf(!0),l=!0,z(this,Ot,"f").showVersion("log"),this.exit(0))),!l&&z(this,nt,"f").skipValidation.length>0&&(l=Object.keys(m).some(A=>z(this,nt,"f").skipValidation.indexOf(A)>=0&&m[A]===!0)),!l){if(d.error)throw new zn(d.error.message);if(!k){let A=this[iZ](g,{},d.error);n||(h=qd(m,this,z(this,hs,"f").getMiddleware(),!0)),h=this[rye](A,h??m),cn(h)&&!n&&(h=h.then(()=>qd(m,this,z(this,hs,"f").getMiddleware(),!1)))}}}catch(x){if(x instanceof zn)z(this,Ot,"f").fail(x.message,x);else throw x}return this[Yd](h??m,f,!!n,!0)}[iZ](e,t,n,i){let a={...this.getDemandedOptions()};return o=>{if(n)throw new zn(n.message);z(this,In,"f").nonOptionCount(o),z(this,In,"f").requiredArguments(o,a);let s=!1;z(this,Zd,"f")&&(s=z(this,In,"f").unknownCommands(o)),z(this,Gd,"f")&&!s?z(this,In,"f").unknownArguments(o,e,t,!!i):z(this,Jd,"f")&&z(this,In,"f").unknownArguments(o,e,{},!1,!1),z(this,In,"f").limitedChoices(o),z(this,In,"f").implications(o),z(this,In,"f").conflicting(o)}}[pye](){Ye(this,Ro,!0,"f")}[Xd](e){if(typeof e=="string")z(this,nt,"f").key[e]=!0;else for(let t of e)z(this,nt,"f").key[t]=!0}};function Mve(r){return!!r&&typeof r.getInternalMethods=="function"}var vvt=dye(BG),hye=vvt;import yvt from"node:os";function mye(){let r=qG(process.argv),e=hye(r).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,t,n,i=e.prompt||e._.slice(1),a=!!e.oneshot,o=!!e.fileReadOnly,s=oZ.join(yvt.homedir(),".coday"),c=e.coday_config_dir||s,u=!!e.auth,l=!!e.debug,f=!e.log,p=e.log_folder;return e.coday_project?(t=e.coday_project,n=!0,console.log(`Project mode: restricting to project '${t}'`)):e.local?(t=oZ.basename(process.cwd()),n=!0,console.log(`Local mode: restricting to project '${t}'`)):e.multi?(t="",n=!1,console.log("Multi-project mode: no default project selection")):(t=oZ.basename(process.cwd()),n=!1,console.log(`Default mode: using '${t}' as default project`)),{oneshot:a,debug:l,project:t,prompts:i,fileReadOnly:o,configDir:c,auth:u,agentFolders:e.agentFolders||[],noLog:f,logFolder:p,forcedProject:n,baseUrl:e.base_url}}var Rxe=vr(JZ(),1);import*as $xe from"node:os";var yxt="cf-access-jwt-assertion",bxt="x-forwarded-email";function xxt(r){if(!r)return null;let e=r.split(".");if(e.length!==3)return null;try{let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(t,"base64").toString("utf8"),a=JSON.parse(n)?.email;return typeof a=="string"&&a.length>0?a:null}catch{return null}}function jxe(r,e){if(!e)return $xe.userInfo().username;let t=r[yxt],n=xxt(t);if(n)return n;let i=r[bxt];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.")}var Ei=(0,mP.default)(),wxt=process.env.PORT?parseInt(process.env.PORT):process.env.BUILD_ENV==="development"?4100:3e3,_xt=D7e(wxt),Xr=mye();ce("INIT","Coday options:",Xr);var Nxe=!Xr.noLog,a4=new r_(Nxe,Xr.logFolder);ce("INIT",`Usage logging ${Nxe?"enabled":"disabled"} ${Xr.logFolder?`(custom folder: ${Xr.logFolder})`:""}`);ce("INIT","Webhook service initialized (will be initialized with prompt execution service)");var a3,gP,Sxt=process.env.AGENTOS_PORT?parseInt(process.env.AGENTOS_PORT):8123,Fxe=`http://localhost:${Sxt}`;Ei.use("/api/agentos",(r,e,t)=>{console.log(`[AGENTOS PROXY] ${r.method} ${r.path}`),t()},(0,Rxe.createProxyMiddleware)({target:Fxe,changeOrigin:!0,pathRewrite:{"^/api/agentos":""}}));ce("INIT",`AgentOS proxy configured: /api/agentos \u2192 ${Fxe}`);Ei.use(mP.default.json({limit:"20mb"}));if(process.env.BUILD_ENV==="development"){let e=`http://localhost:${process.env.ANGULAR_CLIENT_PORT??"4200"}`;ce("INIT",`Development mode: proxying to Angular dev server at ${e}`),Promise.resolve().then(()=>vr(JZ(),1)).then(({createProxyMiddleware:t})=>{let n=t({target:e,changeOrigin:!0,ws:!0});Ei.use("/",(i,a,o)=>{i.path.startsWith("/api")||i.path.startsWith("/events")?o():n(i,a,o)}),ce("INIT","Proxy middleware configured successfully")}).catch(t=>{console.error("Failed to load http-proxy-middleware:",t)})}else{let r=process.env.CODAY_CLIENT_PATH?bl.resolve(process.env.CODAY_CLIENT_PATH):bl.resolve(__dirname,"../coday-client/browser");if(ce("INIT",`Production mode: serving static files from ${r}`),process.env.CODAY_CLIENT_PATH&&ce("INIT","Using client path from CODAY_CLIENT_PATH environment variable"),!lP.existsSync(r))console.error(`ERROR: Client path does not exist: ${r}`),console.error("Please build the client first with: pnpm nx run client:build");else{let e=bl.join(r,"index.html");lP.existsSync(e)?ce("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"))}Ei.use(mP.default.static(r))}var fP=new aE(Xr.configDir),H9=Xr.project;if(H9&&!Xr.forcedProject){let r=process.cwd(),e=bl.basename(r);if(fP.exists(e)){let t=fP.getConfig(e);if(t&&t.path===r&&!t.volatile)ce("INIT",`Default mode: found existing non-volatile project '${e}' for current directory`),H9=e;else{let n=xm.generateProjectId(r);ce("INIT",`Default mode: existing project '${e}' doesn't match path, using volatile ID ${n}`),H9=n}}else{let t=xm.generateProjectId(r);ce("INIT",`Default mode: no existing project found, using volatile ID ${t}`),H9=t}}var o4=new xm(fP,H9,Xr.forcedProject);a3=new rE(Xr.configDir,o4);a3.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>"});ce("INIT","Prompt service initialized");gP=new nE(a3);ce("INIT","Prompt execution service initialized (will be initialized with dependencies after thread manager)");var Mxe=bl.join(Xr.configDir,"projects"),Lxe=new uE(Mxe),vP=new sE(fP,Mxe,Lxe),Ext=new Cm;ce("INIT","MCP instance pool initialized");var yP=new hT(a4,o4,vP,a3,Ext);gP.initialize(yP,vP,Xr,a4);ce("INIT","Prompt execution service initialized");ce("INIT","Webhook service initialized with prompt execution delegation");var kxt=new yc("config-api"),Axt=new QS(Xr.configDir,kxt),Cxt=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function xl(r){let e=jxe(r.headers,!!Xr.auth);if(Cxt.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}N7e(Ei,xl,Xr.configDir);I7e(Ei,Axt,xl);M7e(Ei,a3,xl);q7e(Ei,gP,xl);O7e(Ei,o4);Z7e(Ei,o4);$7e(Ei,vP,Lxe,yP,xl,Xr);j7e(Ei,yP,xl);var Txt=new YS(Xr.configDir,o4);F7e(Ei,o4,xl,Xr.configDir,a4,a3,vP,Txt,Xr);var pP=new iE(a4,a3,Xr.configDir);L7e(Ei,pP,xl);B7e(Ei,a4,xl,Xr.auth);if(process.env.BUILD_ENV!=="development"){let r=process.env.CODAY_CLIENT_PATH?bl.resolve(process.env.CODAY_CLIENT_PATH):bl.resolve(__dirname,"../coday-client/browser"),e=bl.resolve(r,"index.html");ce("INIT",`Catch-all route will serve: ${e}`),Ei.use((t,n,i)=>{if(t.path.startsWith("/api")||t.path.startsWith("/events")){n.status(404).send("Not found");return}ce("ROUTER",`Serving index.html for client route: ${t.path}`),lP.readFile(e,"utf8",(a,o)=>{a?(ce("ERROR",`Failed to read index.html from ${e}:`,a),ce("ERROR",`File exists check: ${lP.existsSync(e)}`),i(a)):n.type("html").send(o)})})}var dP=null;Ei.use((r,e,t,n)=>{ce("ERROR",`Request error on ${e.method} ${e.path}:`,r.message),console.error(r.stack),process.env.BUILD_ENV==="development"?t.status(500).json({error:"Internal Server Error",message:r.message,stack:r.stack}):t.status(500).send("Something went wrong!")});_xt.then(async r=>{Xr.baseUrl?ce("INIT",`Using configured base URL: ${Xr.baseUrl}`):(Xr.baseUrl=`http://localhost:${r}`,ce("INIT",`Base URL set to: ${Xr.baseUrl}`)),Ei.listen(r,()=>{console.log(`Server is running on http://localhost:${r}`)});try{ce("CLEANUP","Starting thread cleanup service...");let e=bl.join(Xr.configDir,"projects");dP=new cE(e,a4),await dP.start(),ce("CLEANUP","Thread cleanup service started successfully")}catch(e){console.error("Failed to start thread cleanup service:",e)}try{ce("SCHEDULER","Initializing scheduler service..."),await pP.initialize(),pP.initializeExecution(gP),ce("SCHEDULER","Scheduler service initialized successfully")}catch(e){console.error("Failed to initialize scheduler service:",e)}}).catch(r=>{console.error("Failed to start server:",r),process.exit(1)});var hP=!1;async function s4(r){hP&&(console.log(`Received ${r} during shutdown, forcing exit...`),process.exit(1)),hP=!0,console.log(`Received ${r}, shutting down gracefully...`);try{console.log("Stopping scheduler service..."),pP.stop(),dP&&(console.log("Stopping thread cleanup service..."),await dP.stop()),console.log("Cleaning up thread Coday instances..."),await yP.shutdown(),console.log("Graceful shutdown completed"),process.exit(0)}catch(e){console.error("Error during graceful shutdown:",e),process.exit(1)}}process.on("SIGTERM",()=>s4("SIGTERM"));process.on("SIGINT",()=>s4("SIGINT"));process.on("SIGUSR2",()=>s4("SIGUSR2"));process.on("SIGHUP",()=>s4("SIGHUP"));process.on("uncaughtException",r=>{if(console.error("Uncaught exception:",r),r.message==="no elements in sequence"||r.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}hP||s4("uncaughtException")});process.on("unhandledRejection",(r,e)=>{if(console.error("Unhandled rejection at:",e,"reason:",r),r&&typeof r=="object"){let t=r;if(t.message==="no elements in sequence"||t.constructor?.name==="EmptyErrorImpl"){console.log("Detected RxJS EmptyError rejection during system sleep - this is expected behavior");return}if(t.name==="TimeoutError"||t.message?.includes("timeout")){console.log("Detected timeout error - handling gracefully without shutdown");return}if(t.name==="AbortError"||t.message?.includes("aborted")){console.log("Detected abort error - handling gracefully without shutdown");return}}console.error("Critical unhandled rejection detected"),hP||s4("unhandledRejection")});
1524
1524
  /*! Bundled license information:
1525
1525
 
1526
1526
  depd/index.js: