@whoz-oss/coday-server 0.80.0 → 0.80.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server.js +2 -2
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -1020,7 +1020,7 @@ ${u}`:u="File write successfully edited by chunks",u}catch(a){return t.error(`Er
|
|
|
1020
1020
|
${s}`:`${c}
|
|
1021
1021
|
[binary or unreadable]`}).join(`
|
|
1022
1022
|
|
|
1023
|
-
`)};import{existsSync as BN,mkdirSync as fit,renameSync as pit}from"node:fs";import*as afe from"path";var ofe=({fromAbsolute:r,toAbsolute:e})=>{if(!BN(r))return{success:!1,message:`Source file not found: ${r}`};if(BN(e))return{success:!1,message:`Destination already exists: ${e}. Remove it explicitly before moving.`};let t=afe.dirname(e);BN(t)||fit(t,{recursive:!0});try{return pit(r,e),{success:!0,message:"File moved successfully"}}catch(n){return{success:!1,message:`Error moving file: ${n}`}}};var j6=class extends xr{static TYPE="FILES";constructor(e,t,n){super(e,t,n)}async buildTools(e,t){let n=[];if(!e.fileReadOnly){let c=({path:l})=>{let f=zp(l,e);if(f.scope==="project"&&e.fileReadOnly)throw new Error("Cannot delete project files in read-only mode");try{if(dit(f.absolutePath),f.scope==="exchange"){let p=new nc({filename:f.relativePath,operation:"deleted"});this.interactor.sendEvent(p)}return"File deleted successfully"}catch(p){return this.interactor.error(`Error deleting file ${f.absolutePath}`),`Error deleting file: ${p}`}},u={type:"function",function:{name:`${this.name}__remove`,description:'Remove a file. File path must start with "project://" (for project files) or "exchange://" (for files shared with the user).',parameters:{type:"object",properties:{path:{type:"string",description:'File path with prefix (e.g., "project://temp/old.txt" or "exchange://draft.md")'}}},parse:JSON.parse,function:c}};n.push(u)}let i=({relPath:c})=>{if(!c||c==="."||c==="/")throw new Error('Path must start with "project://" or "exchange://" prefix. Use "project://" to list project files or "exchange://" to list files shared with the users.');let u=zp(c,e);return oE({relPath:".",root:u.absolutePath})},a={type:"function",function:{name:`${this.name}__ls`,description:'List directories and files in a folder (similar to ls command). Directories end with a slash. Path must start with "project://" or "exchange://" prefix.',parameters:{type:"object",properties:{relPath:{type:"string",description:'Path with prefix (e.g., "project://src" or "exchange://")'}}},parse:JSON.parse,function:i}};n.push(a);let s={type:"function",function:{name
|
|
1023
|
+
`)};import{existsSync as BN,mkdirSync as fit,renameSync as pit}from"node:fs";import*as afe from"path";var ofe=({fromAbsolute:r,toAbsolute:e})=>{if(!BN(r))return{success:!1,message:`Source file not found: ${r}`};if(BN(e))return{success:!1,message:`Destination already exists: ${e}. Remove it explicitly before moving.`};let t=afe.dirname(e);BN(t)||fit(t,{recursive:!0});try{return pit(r,e),{success:!0,message:"File moved successfully"}}catch(n){return{success:!1,message:`Error moving file: ${n}`}}};var j6=class extends xr{static TYPE="FILES";constructor(e,t,n){super(e,t,n)}async buildTools(e,t){let n=[];if(!e.fileReadOnly){let c=({path:l})=>{let f=zp(l,e);if(f.scope==="project"&&e.fileReadOnly)throw new Error("Cannot delete project files in read-only mode");try{if(dit(f.absolutePath),f.scope==="exchange"){let p=new nc({filename:f.relativePath,operation:"deleted"});this.interactor.sendEvent(p)}return"File deleted successfully"}catch(p){return this.interactor.error(`Error deleting file ${f.absolutePath}`),`Error deleting file: ${p}`}},u={type:"function",function:{name:`${this.name}__remove`,description:'Remove a file. File path must start with "project://" (for project files) or "exchange://" (for files shared with the user).',parameters:{type:"object",properties:{path:{type:"string",description:'File path with prefix (e.g., "project://temp/old.txt" or "exchange://draft.md")'}}},parse:JSON.parse,function:c}};n.push(u)}let i=({relPath:c})=>{if(!c||c==="."||c==="/")throw new Error('Path must start with "project://" or "exchange://" prefix. Use "project://" to list project files or "exchange://" to list files shared with the users.');let u=zp(c,e);return oE({relPath:".",root:u.absolutePath})},a={type:"function",function:{name:`${this.name}__ls`,description:'List directories and files in a folder (similar to ls command). Directories end with a slash. Path must start with "project://" or "exchange://" prefix.',parameters:{type:"object",properties:{relPath:{type:"string",description:'Path with prefix (e.g., "project://src" or "exchange://")'}}},parse:JSON.parse,function:i}};n.push(a);let o=async({filePath:c})=>{let u=zp(c,e);return vse({absolutePath:u.absolutePath,interactor:this.interactor})},s={type:"function",function:{name:`${this.name}__readFile`,description:'Read content from any file type. Supports text files, PDFs, and image files (PNG, JPEG, GIF, WebP). File path must start with "project://" (for project files) or "exchange://" (for files shared with the user). Use searchFiles to find files across both spaces.',parameters:{type:"object",properties:{filePath:{type:"string",description:'File path with prefix (e.g., "project://src/main.ts" or "exchange://document.pdf")'}}},parse:JSON.parse,function:o}};return n.push(s),n.push(this.buildSearchFilesTool(e)),e.fileReadOnly||(n.push(this.buildEditFilesTool(e)),n.push(this.buildMoveFileTool(e))),n}buildSearchFilesTool(e){let t=async({fileName:n,fileContent:i,path:a,fileTypes:o})=>{if(!n&&!i)return"At least one of fileName or fileContent must be provided.";let s=[];if(e.threadFilesRoot&&(!a||a.startsWith(wo.EXCHANGE))){let u=a?.replace(wo.EXCHANGE,""),{files:l}=await zN({fileName:n,fileContent:i,searchPath:u,root:e.threadFilesRoot,fileTypes:o,interactor:this.interactor}),f=UN({files:l,root:e.threadFilesRoot,prefix:wo.EXCHANGE});s.push(f)}if(!a?.startsWith(wo.EXCHANGE)){let u=a?.replace(wo.PROJECT,""),{files:l}=await zN({fileName:n,fileContent:i,searchPath:u,root:e.project.root,fileTypes:o,interactor:this.interactor}),f=UN({files:l,root:e.project.root,prefix:wo.PROJECT});s.push(f)}return s.filter(u=>u!=="No matching files found.").join(`
|
|
1024
1024
|
|
|
1025
1025
|
`)||"No matching files found."};return{type:"function",function:{name:`${this.name}__searchFiles`,description:'Search for files by name pattern and/or content text. At least one of fileName or fileContent must be provided. When both are provided, only files whose name matches fileName AND whose content matches fileContent are returned. If the total size of matching files is reasonable, their content is returned directly. Otherwise, only the list of matching paths is returned. Paths are prefixed with "project://" or "exchange://".',parameters:{type:"object",properties:{fileName:{type:"string",description:'Partial file name or pattern to match against file names (e.g. "config", "user.service").'},fileContent:{type:"string",description:"Text to search for inside file contents."},path:{type:"string",description:'Optional path to restrict the search scope. Use "project://" or "exchange://" prefix.'},fileTypes:{type:"array",items:{type:"string"},description:'Optional array of file extensions to restrict content search (e.g. ["ts", "json"]).'}}},parse:JSON.parse,function:t}}}buildEditFilesTool(e){return{type:"function",function:{name:"editFiles",description:'Edit one or more files in a single tool call. Each edit targets a specific file and specifies an operation: "write" replaces the entire file content (or creates it), "patch" replaces specific chunks within an existing file. Edits are executed independently: a failure on one file does not prevent others from being processed. File paths must start with "project://" or "exchange://".',parameters:{type:"object",properties:{edits:{type:"array",description:"List of file edits to perform.",items:{type:"object",properties:{operation:{type:"string",enum:["write","patch"],description:'"write" to overwrite/create the file, "patch" to replace specific chunks.'},path:{type:"string",description:'File path with prefix (e.g. "project://src/main.ts" or "exchange://report.md").'},content:{type:"string",description:'Full file content. Required for "write" operation.'},replacements:{type:"array",description:'Required for "patch" operation.',items:{type:"object",properties:{oldPart:{type:"string",description:"Existing content to replace (must be unique and at least 15 chars)."},newPart:{type:"string",description:"Replacement content."}}}}}}}}},parse:JSON.parse,function:({edits:n})=>{if(!n||!Array.isArray(n)||n.length===0)return"No edits provided.";let i=[];for(let a of n)try{let o=zp(a.path,e);if(a.operation==="write"){let s=Q2e({relPath:mm.basename(o.absolutePath),root:mm.dirname(o.absolutePath),interactor:this.interactor,content:a.content});if(o.scope==="exchange"){let c=new nc({filename:o.relativePath,operation:"created",size:Buffer.from(a.content).length});this.interactor.sendEvent(c)}i.push(`${a.path}: ${s}`)}else if(a.operation==="patch"){let s=tfe({relPath:mm.basename(o.absolutePath),root:mm.dirname(o.absolutePath),interactor:this.interactor,replacements:a.replacements});if(o.scope==="exchange"){let c=new nc({filename:o.relativePath,operation:"updated"});this.interactor.sendEvent(c)}i.push(`${a.path}: ${s}`)}else i.push(`${a.path}: Unknown operation`)}catch(o){i.push(`${a.path}: Error \u2014 ${o}`)}return i.join(`
|
|
1026
1026
|
`)}}}}buildMoveFileTool(e){let t=({from:n,to:i})=>{let a=zp(n,e),o=zp(i,e);if(a.scope!==o.scope)return`Cannot move files between scopes: "${n}" (${a.scope}) \u2192 "${i}" (${o.scope}). Use separate copy and delete operations.`;let{success:s,message:c}=ofe({fromAbsolute:a.absolutePath,toAbsolute:o.absolutePath});return s&&a.scope==="exchange"&&(this.interactor.sendEvent(new nc({filename:a.relativePath,operation:"deleted"})),this.interactor.sendEvent(new nc({filename:o.relativePath,operation:"created"}))),c};return{type:"function",function:{name:`${this.name}__moveFile`,description:'Move or rename a file within the same scope (project or exchange). Fails if the source does not exist or the destination already exists. Cross-scope moves (project \u2194 exchange) are not allowed. File paths must start with "project://" or "exchange://".',parameters:{type:"object",properties:{from:{type:"string",description:'Source file path with prefix (e.g. "project://old/path.ts").'},to:{type:"string",description:'Destination file path with prefix (e.g. "project://new/path.ts").'}}},parse:JSON.parse,function:t}}}};import*as sfe from"fs";import{promisify as hit}from"util";var lGt=hit(sfe.unlink);var sE=class extends Fe{constructor(t){super({commandWord:"folder",description:"Loads files from a folder, does not do depth nor recursive."});this.interactor=t}async handle(t,n){let i=this.getSubCommand(t);if(!i)return this.interactor.error("Please provide a valid folder path."),n;i.startsWith(".")||(i=`.${i}`);let a;try{a=await oE({relPath:i,root:n.project.root});let o=a.filter(s=>!s.endsWith("/")).map(s=>`load file ${i}/${s}`);n.addCommands(...o),this.interactor.displayText(`Folder loaded: ${i}`)}catch(o){this.interactor.error(`Failed to load folder: ${o}`)}return n}};var cE=class extends Vn{constructor(e){super({commandWord:"load",description:"handles load related commands"},e),this.handlers=[new iE(e),new sE(e)]}};var uE=class extends Fe{constructor(t,n){super({commandWord:"agents",description:"Show agent usage statistics sorted by number of calls. Use --from=YYYY-MM-DD and --to=YYYY-MM-DD for custom date range (default: last 7 days)"});this.interactor=t;this.services=n}async handle(t,n){try{let i=this.getSubCommand(t),a=Tt(i,[{key:"from",alias:"f"},{key:"to",alias:"t"}]),o,s;if(a.to&&typeof a.to=="string"){let p=this.parseDate(a.to);if(!p)return this.interactor.error("Invalid --to date format. Please use YYYY-MM-DD"),n;o=p,o.setHours(23,59,59,999)}else o=new Date,o.setHours(23,59,59,999);if(a.from&&typeof a.from=="string"){let p=this.parseDate(a.from);if(!p)return this.interactor.error("Invalid --from date format. Please use YYYY-MM-DD"),n;s=p,s.setHours(0,0,0,0)}else s=new Date(o),s.setDate(s.getDate()-7),s.setHours(0,0,0,0);if(s>o)return this.interactor.error("Invalid date range: --from date must be before --to date"),n;let c=(await this.services.logger.readLogs(s,o)).filter(p=>!p.type||p.type==="AGENT_USAGE");if(c.length===0){let p=this.formatDateRange(s,o);return this.interactor.displayText(`\u{1F4CA} No usage data found for ${p}`),n}let u=new Map;for(let p of c){let d=u.get(p.agent)||{calls:0,totalCost:0};u.set(p.agent,{calls:d.calls+1,totalCost:d.totalCost+p.cost})}let l=Array.from(u.entries()).map(([p,d])=>({agent:p,calls:d.calls,totalCost:d.totalCost,avgCost:d.totalCost/d.calls}));l.sort((p,d)=>d.calls-p.calls);let f=this.formatAgentStats(l,s,o);this.interactor.displayText(f)}catch(i){this.interactor.error(`Failed to retrieve agent statistics: ${i}`)}return n}parseDate(t){if(!t.match(/^(\d{4})-(\d{2})-(\d{2})$/))return null;let i=new Date(t);return isNaN(i.getTime())?null:i}formatDateRange(t,n){let i=t.toISOString().split("T")[0],a=n.toISOString().split("T")[0];return`${i} to ${a}`}formatAgentStats(t,n,i){let o=`\u{1F4CA} Agent Usage Statistics (${this.formatDateRange(n,i)})
|
|
@@ -1433,7 +1433,7 @@ ${m.join(`
|
|
|
1433
1433
|
`;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=U7e(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=cf(o,p=>!f[p]),c=cf(c,p=>!f[p]),a};let u=[];return a.freeze=function(){u.push({implied:o,conflicting:c})},a.unfreeze=function(){let f=u.pop();Ca(f,void 0,t),{implied:o,conflicting:c}=f},a}var XV=[],o9;function s9(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=B9t(e,r.extends);else try{o=import.meta.resolve(r.extends)}catch{return r}U9t(o),XV.push(o),i=a?JSON.parse(o9.readFileSync(o,"utf8")):n.require(r.extends),delete r.extends,i=s9(i,o9.path.dirname(o),t,o9)}return XV=[],t?W7e(i,r):Object.assign({},i,r)}function U9t(r){if(XV.indexOf(r)>-1)throw new qn(`Circular extended configurations: '${r}'.`)}function B9t(r,e){return o9.path.resolve(r,e)}function W7e(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]=W7e(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},U=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)},zn,Od,c9,ro,Do,VC,lf,Id,ZC,ss,GC,cs,Gc,Oo,us,JC,$d,wi,nt,KC,YC,Io,Rd,L1,jd,ff,XC,_t,Fd,Nd,Md,It,QC,Jc,Dn;function fve(r){return(e=[],t=r.process.cwd(),n)=>{let i=new uZ(e,t,n,r);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}}var V7e=Symbol("copyDoubleDash"),Z7e=Symbol("copyDoubleDash"),QV=Symbol("deleteFromParserHintObject"),G7e=Symbol("emitWarning"),J7e=Symbol("freeze"),K7e=Symbol("getDollarZero"),Ld=Symbol("getParserConfiguration"),Y7e=Symbol("getUsageConfiguration"),eZ=Symbol("guessLocale"),X7e=Symbol("guessVersion"),Q7e=Symbol("parsePositionalNumbers"),tZ=Symbol("pkgUp"),pf=Symbol("populateParserHintArray"),q1=Symbol("populateParserHintSingleValueDictionary"),rZ=Symbol("populateParserHintArrayDictionary"),nZ=Symbol("populateParserHintDictionary"),iZ=Symbol("sanitizeKey"),aZ=Symbol("setKey"),oZ=Symbol("unfreeze"),eve=Symbol("validateAsync"),tve=Symbol("getCommandInstance"),rve=Symbol("getContext"),nve=Symbol("getHasOutput"),ive=Symbol("getLoggerInstance"),ave=Symbol("getParseContext"),ove=Symbol("getUsageInstance"),sve=Symbol("getValidationInstance"),eT=Symbol("hasParseCallback"),cve=Symbol("isGlobalContext"),qd=Symbol("postProcess"),uve=Symbol("rebase"),sZ=Symbol("reset"),u9=Symbol("runYargsParserAndExecuteCommands"),cZ=Symbol("runValidation"),lve=Symbol("setHasOutput"),zd=Symbol("kTrackManuallySetKeys"),H9t="en_US",uZ=class{constructor(e=[],t,n,i){this.customScriptName=!1,this.parsed=!1,zn.set(this,void 0),Od.set(this,void 0),c9.set(this,{commands:[],fullCommands:[]}),ro.set(this,null),Do.set(this,null),VC.set(this,"show-hidden"),lf.set(this,null),Id.set(this,!0),ZC.set(this,{}),ss.set(this,!0),GC.set(this,[]),cs.set(this,void 0),Gc.set(this,{}),Oo.set(this,!1),us.set(this,null),JC.set(this,!0),$d.set(this,void 0),wi.set(this,""),nt.set(this,void 0),KC.set(this,void 0),YC.set(this,{}),Io.set(this,null),Rd.set(this,null),L1.set(this,{}),jd.set(this,{}),ff.set(this,void 0),XC.set(this,!1),_t.set(this,void 0),Fd.set(this,!1),Nd.set(this,!1),Md.set(this,!1),It.set(this,void 0),QC.set(this,{}),Jc.set(this,null),Dn.set(this,void 0),Ye(this,_t,i,"f"),Ye(this,ff,e,"f"),Ye(this,Od,t,"f"),Ye(this,KC,n,"f"),Ye(this,cs,new BC(this),"f"),this.$0=this[K7e](),this[sZ](),Ye(this,zn,U(this,zn,"f"),"f"),Ye(this,It,U(this,It,"f"),"f"),Ye(this,Dn,U(this,Dn,"f"),"f"),Ye(this,nt,U(this,nt,"f"),"f"),U(this,nt,"f").showHiddenOpt=U(this,VC,"f"),Ye(this,$d,this[Z7e](),"f"),U(this,_t,"f").y18n.setLocale(H9t)}addHelpOpt(e,t){let n="help";return Ke("[string|boolean] [string]",[e,t],arguments.length),U(this,us,"f")&&(this[QV](U(this,us,"f")),Ye(this,us,null,"f")),e===!1&&t===void 0?this:(Ye(this,us,typeof e=="string"?e:n,"f"),this.boolean(U(this,us,"f")),this.describe(U(this,us,"f"),t||U(this,It,"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:U(this,VC,"f");return this.boolean(n),this.describe(n,t||U(this,It,"f").deferY18nLookup("Show hidden options")),U(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[rZ](this.alias.bind(this),"alias",e,t),this}array(e){return Ke("<array|string>",[e],arguments.length),this[pf]("array",e),this[zd](e),this}boolean(e){return Ke("<array|string>",[e],arguments.length),this[pf]("boolean",e),this[zd](e),this}check(e,t){return Ke("<function> [boolean]",[e,t],arguments.length),this.middleware((n,i)=>Dd(()=>e(n,i.getOptions()),a=>(a?(typeof a=="string"||a instanceof Error)&&U(this,It,"f").fail(a.toString(),a):U(this,It,"f").fail(U(this,_t,"f").y18n.__("Argument check failed: %s",e.toString())),n),a=>(U(this,It,"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[rZ](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 qn("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 qn("coerce callback must be provided");let n=e;return U(this,nt,"f").key[n]=!0,U(this,cs,"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:Dd(()=>t(i[c[0]]),u=>(c.forEach(l=>{i[l]=u}),i),u=>{throw new qn(u.message)})},n),this}conflicts(e,t){return Ke("<string|object> [string|array]",[e,t],arguments.length),U(this,Dn,"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=s9(e,U(this,Od,"f"),this[Ld]()["deep-merge-config"]||!1,U(this,_t,"f")),U(this,nt,"f").configObjects=(U(this,nt,"f").configObjects||[]).concat(e),this):(typeof t=="function"&&(n=t,t=void 0),this.describe(e,t||U(this,It,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach(i=>{U(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,Do,e||U(this,Do,"f")||"completion","f"),!t&&t!==!1&&(t="generate completion script"),this.command(U(this,Do,"f"),t),n&&U(this,ro,"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),U(this,zn,"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=U(this,KC,"f")||U(this,_t,"f").require;return U(this,zn,"f").addDirectory(e,n,U(this,_t,"f").getCallerFile(),t),this}count(e){return Ke("<array|string>",[e],arguments.length),this[pf]("count",e),this[zd](e),this}default(e,t,n){return Ke("<object|string|array> [*] [string]",[e,t,n],arguments.length),n&&(GV(e,U(this,_t,"f")),U(this,nt,"f").defaultDescription[e]=n),typeof t=="function"&&(GV(e,U(this,_t,"f")),U(this,nt,"f").defaultDescription[e]||(U(this,nt,"f").defaultDescription[e]=U(this,It,"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),U(this,nt,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:i},this}demand(e,t,n){return Array.isArray(t)?(t.forEach(i=>{Ca(n,!0,U(this,_t,"f")),this.demandOption(i,n)}),t=1/0):typeof t!="number"&&(n=t,t=1/0),typeof e=="number"?(Ca(n,!0,U(this,_t,"f")),this.demandCommand(e,t,n,n)):Array.isArray(e)?e.forEach(i=>{Ca(n,!0,U(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),U(this,nt,"f").deprecatedOptions[e]=t,this}describe(e,t){return Ke("<object|string|array> [string]",[e,t],arguments.length),this[aZ](e,!0),U(this,It,"f").describe(e,t),this}detectLocale(e){return Ke("<boolean>",[e],arguments.length),Ye(this,Id,e,"f"),this}env(e){return Ke("[string|boolean]",[e],arguments.length),e===!1?delete U(this,nt,"f").envPrefix:U(this,nt,"f").envPrefix=e||"",this}epilogue(e){return Ke("<string>",[e],arguments.length),U(this,It,"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)):U(this,It,"f").example(e,t),this}exit(e,t){Ye(this,Oo,!0,"f"),Ye(this,lf,t,"f"),U(this,ss,"f")&&U(this,_t,"f").process.exit(e)}exitProcess(e=!0){return Ke("[boolean]",[e],arguments.length),Ye(this,ss,e,"f"),this}fail(e){if(Ke("<function|boolean>",[e],arguments.length),typeof e=="boolean"&&e!==!1)throw new qn("Invalid first argument. Expected function or boolean 'false'");return U(this,It,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){return Ke("<array> [function]",[e,t],arguments.length),t?U(this,ro,"f").getCompletion(e,t):new Promise((n,i)=>{U(this,ro,"f").getCompletion(e,(a,o)=>{a?i(a):n(o)})})}getDemandedOptions(){return Ke([],0),U(this,nt,"f").demandedOptions}getDemandedCommands(){return Ke([],0),U(this,nt,"f").demandedCommands}getDeprecatedOptions(){return Ke([],0),U(this,nt,"f").deprecatedOptions}getDetectLocale(){return U(this,Id,"f")}getExitProcess(){return U(this,ss,"f")}getGroups(){return Object.assign({},U(this,Gc,"f"),U(this,jd,"f"))}getHelp(){if(Ye(this,Oo,!0,"f"),!U(this,It,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[u9](U(this,ff,"f"),void 0,void 0,0,!0);if(on(t))return t.then(()=>U(this,It,"f").help())}let e=U(this,zn,"f").runDefaultBuilderOn(this);if(on(e))return e.then(()=>U(this,It,"f").help())}return Promise.resolve(U(this,It,"f").help())}getOptions(){return U(this,nt,"f")}getStrict(){return U(this,Fd,"f")}getStrictCommands(){return U(this,Nd,"f")}getStrictOptions(){return U(this,Md,"f")}global(e,t){return Ke("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1?U(this,nt,"f").local=U(this,nt,"f").local.filter(n=>e.indexOf(n)===-1):e.forEach(n=>{U(this,nt,"f").local.includes(n)||U(this,nt,"f").local.push(n)}),this}group(e,t){Ke("<string|array> <string>",[e,t],arguments.length);let n=U(this,jd,"f")[t]||U(this,Gc,"f")[t];U(this,jd,"f")[t]&&delete U(this,jd,"f")[t];let i={};return U(this,Gc,"f")[t]=(n||[]).concat(e).filter(a=>i[a]?!1:i[a]=!0),this}hide(e){return Ke("<string>",[e],arguments.length),U(this,nt,"f").hiddenOptions.push(e),this}implies(e,t){return Ke("<string|object> [number|string|array]",[e,t],arguments.length),U(this,Dn,"f").implies(e,t),this}locale(e){return Ke("[string]",[e],arguments.length),e===void 0?(this[eZ](),U(this,_t,"f").y18n.getLocale()):(Ye(this,Id,!1,"f"),U(this,_t,"f").y18n.setLocale(e),this)}middleware(e,t,n){return U(this,cs,"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[pf]("normalize",e),this}number(e){return Ke("<array|string>",[e],arguments.length),this[pf]("number",e),this[zd](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[zd](e),U(this,Jc,"f")&&(e==="version"||t?.alias==="version")&&this[G7e](['"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(`
|
|
1434
1434
|
`),void 0,"versionWarning"),U(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&&(U(this,nt,"f").defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let a=t.describe||t.description||t.desc,o=U(this,It,"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[J7e](),typeof e>"u"&&(e=U(this,ff,"f")),typeof t=="object"&&(Ye(this,Rd,t,"f"),t=n),typeof t=="function"&&(Ye(this,Io,t,"f"),t=!1),t||Ye(this,ff,e,"f"),U(this,Io,"f")&&Ye(this,ss,!1,"f");let i=this[u9](e,!!t),a=this.parsed;return U(this,ro,"f").setParsed(this.parsed),on(i)?i.then(o=>(U(this,Io,"f")&&U(this,Io,"f").call(this,U(this,lf,"f"),o,U(this,wi,"f")),o)).catch(o=>{throw U(this,Io,"f")&&U(this,Io,"f")(o,this.parsed.argv,U(this,wi,"f")),o}).finally(()=>{this[oZ](),this.parsed=a}):(U(this,Io,"f")&&U(this,Io,"f").call(this,U(this,lf,"f"),i,U(this,wi,"f")),this[oZ](),this.parsed=a,i)}parseAsync(e,t,n){let i=this.parse(e,t,n);return on(i)?i:Promise.resolve(i)}parseSync(e,t,n){let i=this.parse(e,t,n);if(on(i))throw new qn(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return i}parserConfiguration(e){return Ke("<object>",[e],arguments.length),Ye(this,YC,e,"f"),this}pkgConf(e,t){Ke("<string> [string]",[e,t],arguments.length);let n=null,i=this[tZ](t||U(this,Od,"f"));return i[e]&&typeof i[e]=="object"&&(n=s9(i[e],t||U(this,Od,"f"),this[Ld]()["deep-merge-config"]||!1,U(this,_t,"f")),U(this,nt,"f").configObjects=(U(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=cf(t,(o,s)=>o==="type"&&!["string","number","boolean"].includes(s)?!1:n.includes(o));let i=U(this,c9,"f").fullCommands[U(this,c9,"f").fullCommands.length-1],a=i?U(this,zn,"f").cmdToParseOptions(i):{array:[],alias:{},default:{},demand:{}};return N1(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,U(this,It,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return Ke("[boolean]",[e],arguments.length),Ye(this,XC,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"&&U(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,U(this,$d,"f").log(U(this,ro,"f").generateCompletionScript(e,t||U(this,Do,"f")||"completion")),this}showHelp(e){if(Ke("[string|function]",[e],arguments.length),Ye(this,Oo,!0,"f"),!U(this,It,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[u9](U(this,ff,"f"),void 0,void 0,0,!0);if(on(n))return n.then(()=>{U(this,It,"f").showHelp(e)}),this}let t=U(this,zn,"f").runDefaultBuilderOn(this);if(on(t))return t.then(()=>{U(this,It,"f").showHelp(e)}),this}return U(this,It,"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),U(this,It,"f").showHelpOnFail(e,t),this}showVersion(e){return Ke("[string|function]",[e],arguments.length),U(this,It,"f").showVersion(e),this}skipValidation(e){return Ke("<array|string>",[e],arguments.length),this[pf]("skipValidation",e),this}strict(e){return Ke("[boolean]",[e],arguments.length),Ye(this,Fd,e!==!1,"f"),this}strictCommands(e){return Ke("[boolean]",[e],arguments.length),Ye(this,Nd,e!==!1,"f"),this}strictOptions(e){return Ke("[boolean]",[e],arguments.length),Ye(this,Md,e!==!1,"f"),this}string(e){return Ke("<array|string>",[e],arguments.length),this[pf]("string",e),this[zd](e),this}terminalWidth(){return Ke([],0),U(this,_t,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return Ke("<object>",[e],arguments.length),Ye(this,Id,!1,"f"),U(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(Ca(e,null,U(this,_t,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,i);throw new qn(".usage() description must start with $0 if being used as alias for .command()")}else return U(this,It,"f").usage(e),this}usageConfiguration(e){return Ke("<object>",[e],arguments.length),Ye(this,QC,e,"f"),this}version(e,t,n){let i="version";if(Ke("[boolean|string] [string] [string]",[e,t,n],arguments.length),U(this,Jc,"f")&&(this[QV](U(this,Jc,"f")),U(this,It,"f").version(void 0),Ye(this,Jc,null,"f")),arguments.length===0)n=this[X7e](),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,Jc,typeof e=="string"?e:i,"f"),t=t||U(this,It,"f").deferY18nLookup("Show version number"),U(this,It,"f").version(n||void 0),this.boolean(U(this,Jc,"f")),this.describe(U(this,Jc,"f"),t),this}wrap(e){return Ke("<number|null|undefined>",[e],arguments.length),U(this,It,"f").wrap(e),this}[(zn=new WeakMap,Od=new WeakMap,c9=new WeakMap,ro=new WeakMap,Do=new WeakMap,VC=new WeakMap,lf=new WeakMap,Id=new WeakMap,ZC=new WeakMap,ss=new WeakMap,GC=new WeakMap,cs=new WeakMap,Gc=new WeakMap,Oo=new WeakMap,us=new WeakMap,JC=new WeakMap,$d=new WeakMap,wi=new WeakMap,nt=new WeakMap,KC=new WeakMap,YC=new WeakMap,Io=new WeakMap,Rd=new WeakMap,L1=new WeakMap,jd=new WeakMap,ff=new WeakMap,XC=new WeakMap,_t=new WeakMap,Fd=new WeakMap,Nd=new WeakMap,Md=new WeakMap,It=new WeakMap,QC=new WeakMap,Jc=new WeakMap,Dn=new WeakMap,V7e)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch{}return e}[Z7e](){return{log:(...e)=>{this[eT]()||console.log(...e),Ye(this,Oo,!0,"f"),U(this,wi,"f").length&&Ye(this,wi,U(this,wi,"f")+`
|
|
1435
1435
|
`,"f"),Ye(this,wi,U(this,wi,"f")+e.join(" "),"f")},error:(...e)=>{this[eT]()||console.error(...e),Ye(this,Oo,!0,"f"),U(this,wi,"f").length&&Ye(this,wi,U(this,wi,"f")+`
|
|
1436
|
-
`,"f"),Ye(this,wi,U(this,wi,"f")+e.join(" "),"f")}}}[QV](e){N1(U(this,nt,"f")).forEach(t=>{if((i=>i==="configObjects")(t))return;let n=U(this,nt,"f")[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n=="object"&&delete n[e]}),delete U(this,It,"f").getDescriptions()[e]}[G7e](e,t,n){U(this,ZC,"f")[n]||(U(this,_t,"f").process.emitWarning(e,t),U(this,ZC,"f")[n]=!0)}[J7e](){U(this,GC,"f").push({options:U(this,nt,"f"),configObjects:U(this,nt,"f").configObjects.slice(0),exitProcess:U(this,ss,"f"),groups:U(this,Gc,"f"),strict:U(this,Fd,"f"),strictCommands:U(this,Nd,"f"),strictOptions:U(this,Md,"f"),completionCommand:U(this,Do,"f"),output:U(this,wi,"f"),exitError:U(this,lf,"f"),hasOutput:U(this,Oo,"f"),parsed:this.parsed,parseFn:U(this,Io,"f"),parseContext:U(this,Rd,"f")}),U(this,It,"f").freeze(),U(this,Dn,"f").freeze(),U(this,zn,"f").freeze(),U(this,cs,"f").freeze()}[K7e](){let e="",t;return/\b(node|iojs|electron)(\.exe)?$/.test(U(this,_t,"f").process.argv()[0])?t=U(this,_t,"f").process.argv().slice(1,2):t=U(this,_t,"f").process.argv().slice(0,1),e=t.map(n=>{let i=this[uve](U(this,Od,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&i.length<n.length?i:n}).join(" ").trim(),U(this,_t,"f").getEnv("_")&&U(this,_t,"f").getProcessArgvBin()===U(this,_t,"f").getEnv("_")&&(e=U(this,_t,"f").getEnv("_").replace(`${U(this,_t,"f").path.dirname(U(this,_t,"f").process.execPath())}/`,"")),e}[Ld](){return U(this,YC,"f")}[Y7e](){return U(this,QC,"f")}[eZ](){if(!U(this,Id,"f"))return;let e=U(this,_t,"f").getEnv("LC_ALL")||U(this,_t,"f").getEnv("LC_MESSAGES")||U(this,_t,"f").getEnv("LANG")||U(this,_t,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[X7e](){return this[tZ]().version||"unknown"}[Q7e](e){let t=e["--"]?e["--"]:e._;for(let n=0,i;(i=t[n])!==void 0;n++)U(this,_t,"f").Parser.looksLikeNumber(i)&&Number.isSafeInteger(Math.floor(parseFloat(`${i}`)))&&(t[n]=Number(i));return e}[tZ](e){let t=e||"*";if(U(this,L1,"f")[t])return U(this,L1,"f")[t];let n={};try{let i=e||U(this,_t,"f").mainFilename;U(this,_t,"f").path.extname(i)&&(i=U(this,_t,"f").path.dirname(i));let a=U(this,_t,"f").findUp(i,(o,s)=>{if(s.includes("package.json"))return"package.json"});Ca(a,void 0,U(this,_t,"f")),n=JSON.parse(U(this,_t,"f").readFileSync(a,"utf8"))}catch{}return U(this,L1,"f")[t]=n||{},U(this,L1,"f")[t]}[pf](e,t){t=[].concat(t),t.forEach(n=>{n=this[iZ](n),U(this,nt,"f")[e].push(n)})}[q1](e,t,n,i){this[nZ](e,t,n,i,(a,o,s)=>{U(this,nt,"f")[a][o]=s})}[rZ](e,t,n,i){this[nZ](e,t,n,i,(a,o,s)=>{U(this,nt,"f")[a][o]=(U(this,nt,"f")[a][o]||[]).concat(s)})}[nZ](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 N1(n))e(o,n[o]);else a(t,this[iZ](n),i)}[iZ](e){return e==="__proto__"?"___proto___":e}[aZ](e,t){return this[q1](this[aZ].bind(this),"key",e,t),this}[oZ](){var e,t,n,i,a,o,s,c,u,l,f,p;let d=U(this,GC,"f").pop();Ca(d,void 0,U(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,ss,h,"f")}}.value,groups:{set value(h){Ye(n,Gc,h,"f")}}.value,output:{set value(h){Ye(i,wi,h,"f")}}.value,exitError:{set value(h){Ye(a,lf,h,"f")}}.value,hasOutput:{set value(h){Ye(o,Oo,h,"f")}}.value,parsed:this.parsed,strict:{set value(h){Ye(s,Fd,h,"f")}}.value,strictCommands:{set value(h){Ye(c,Nd,h,"f")}}.value,strictOptions:{set value(h){Ye(u,Md,h,"f")}}.value,completionCommand:{set value(h){Ye(l,Do,h,"f")}}.value,parseFn:{set value(h){Ye(f,Io,h,"f")}}.value,parseContext:{set value(h){Ye(p,Rd,h,"f")}}.value}=d,U(this,nt,"f").configObjects=m,U(this,It,"f").unfreeze(),U(this,Dn,"f").unfreeze(),U(this,zn,"f").unfreeze(),U(this,cs,"f").unfreeze()}[eve](e,t){return Dd(t,n=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[tve].bind(this),getContext:this[rve].bind(this),getHasOutput:this[nve].bind(this),getLoggerInstance:this[ive].bind(this),getParseContext:this[ave].bind(this),getParserConfiguration:this[Ld].bind(this),getUsageConfiguration:this[Y7e].bind(this),getUsageInstance:this[ove].bind(this),getValidationInstance:this[sve].bind(this),hasParseCallback:this[eT].bind(this),isGlobalContext:this[cve].bind(this),postProcess:this[qd].bind(this),reset:this[sZ].bind(this),runValidation:this[cZ].bind(this),runYargsParserAndExecuteCommands:this[u9].bind(this),setHasOutput:this[lve].bind(this)}}[tve](){return U(this,zn,"f")}[rve](){return U(this,c9,"f")}[nve](){return U(this,Oo,"f")}[ive](){return U(this,$d,"f")}[ave](){return U(this,Rd,"f")||{}}[ove](){return U(this,It,"f")}[sve](){return U(this,Dn,"f")}[eT](){return!!U(this,Io,"f")}[cve](){return U(this,JC,"f")}[qd](e,t,n,i){return n||on(e)||(t||(e=this[V7e](e)),(this[Ld]()["parse-positional-numbers"]||this[Ld]()["parse-positional-numbers"]===void 0)&&(e=this[Q7e](e)),i&&(e=Pd(e,this,U(this,cs,"f").getMiddleware(),!1))),e}[sZ](e={}){Ye(this,nt,U(this,nt,"f")||{},"f");let t={};t.local=U(this,nt,"f").local||[],t.configObjects=U(this,nt,"f").configObjects||[];let n={};t.local.forEach(o=>{n[o]=!0,(e[o]||[]).forEach(s=>{n[s]=!0})}),Object.assign(U(this,jd,"f"),Object.keys(U(this,Gc,"f")).reduce((o,s)=>{let c=U(this,Gc,"f")[s].filter(u=>!(u in n));return c.length>0&&(o[s]=c),o},{})),Ye(this,Gc,{},"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]=(U(this,nt,"f")[o]||[]).filter(s=>!n[s])}),a.forEach(o=>{t[o]=cf(U(this,nt,"f")[o],s=>!n[s])}),t.envPrefix=U(this,nt,"f").envPrefix,Ye(this,nt,t,"f"),Ye(this,It,U(this,It,"f")?U(this,It,"f").reset(n):M7e(this,U(this,_t,"f")),"f"),Ye(this,Dn,U(this,Dn,"f")?U(this,Dn,"f").reset(n):H7e(this,U(this,It,"f"),U(this,_t,"f")),"f"),Ye(this,zn,U(this,zn,"f")?U(this,zn,"f").reset():j7e(U(this,It,"f"),U(this,Dn,"f"),U(this,cs,"f"),U(this,_t,"f")),"f"),U(this,ro,"f")||Ye(this,ro,z7e(this,U(this,It,"f"),U(this,zn,"f"),U(this,_t,"f")),"f"),U(this,cs,"f").reset(),Ye(this,Do,null,"f"),Ye(this,wi,"","f"),Ye(this,lf,null,"f"),Ye(this,Oo,!1,"f"),this.parsed=!1,this}[uve](e,t){return U(this,_t,"f").path.relative(e,t)}[u9](e,t,n,i=0,a=!1){var o,s,c,u;let l=!!n||a;e=e||U(this,ff,"f"),U(this,nt,"f").__=U(this,_t,"f").y18n.__,U(this,nt,"f").configuration=this[Ld]();let f=!!U(this,nt,"f").configuration["populate--"],p=Object.assign({},U(this,nt,"f").configuration,{"populate--":!0}),d=U(this,_t,"f").Parser.detailed(e,Object.assign({},U(this,nt,"f"),{configuration:{"parse-positional-numbers":!1,...p}})),m=Object.assign(d.argv,U(this,Rd,"f")),h,g=d.aliases,v=!1,y=!1;Object.keys(m).forEach(x=>{x===U(this,us,"f")&&m[x]?v=!0:x===U(this,Jc,"f")&&m[x]&&(y=!0)}),m.$0=this.$0,this.parsed=d,i===0&&U(this,It,"f").clearCachedHelpMessage();try{if(this[eZ](),t)return this[qd](m,f,!!n,!1);U(this,us,"f")&&[U(this,us,"f")].concat(g[U(this,us,"f")]||[]).filter(R=>R.length>1).includes(""+m._[m._.length-1])&&(m._.pop(),v=!0),Ye(this,JC,!1,"f");let x=U(this,zn,"f").getCommands(),k=!((o=U(this,ro,"f"))===null||o===void 0)&&o.completionKey?[(s=U(this,ro,"f"))===null||s===void 0?void 0:s.completionKey,...(u=this.getAliases()[(c=U(this,ro,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&u!==void 0?u:[]].some(A=>Object.prototype.hasOwnProperty.call(m,A)):!1,E=v||k||a;if(m._.length){if(x.length){let A;for(let R=i||0,I;m._[R]!==void 0;R++)if(I=String(m._[R]),x.includes(I)&&I!==U(this,Do,"f")){let w=U(this,zn,"f").runCommand(I,this,d,R+1,a,v||y||a);return this[qd](w,f,!!n,!1)}else if(!A&&I!==U(this,Do,"f")){A=I;break}!U(this,zn,"f").hasDefaultCommand()&&U(this,XC,"f")&&A&&!E&&U(this,Dn,"f").recommendCommands(A,x)}U(this,Do,"f")&&m._.includes(U(this,Do,"f"))&&!k&&(U(this,ss,"f")&&uf(!0),this.showCompletionScript(),this.exit(0))}if(U(this,zn,"f").hasDefaultCommand()&&!E){let A=U(this,zn,"f").runCommand(null,this,d,0,a,v||y||a);return this[qd](A,f,!!n,!1)}if(k){U(this,ss,"f")&&uf(!0),e=[].concat(e);let A=e.slice(e.indexOf(`--${U(this,ro,"f").completionKey}`)+1);return U(this,ro,"f").getCompletion(A,(R,I)=>{if(R)throw new qn(R.message);(I||[]).forEach(w=>{U(this,$d,"f").log(w)}),this.exit(0)}),this[qd](m,!f,!!n,!1)}if(U(this,Oo,"f")||(v?(U(this,ss,"f")&&uf(!0),l=!0,this.showHelp(A=>{U(this,$d,"f").log(A),this.exit(0)})):y&&(U(this,ss,"f")&&uf(!0),l=!0,U(this,It,"f").showVersion("log"),this.exit(0))),!l&&U(this,nt,"f").skipValidation.length>0&&(l=Object.keys(m).some(A=>U(this,nt,"f").skipValidation.indexOf(A)>=0&&m[A]===!0)),!l){if(d.error)throw new qn(d.error.message);if(!k){let A=this[cZ](g,{},d.error);n||(h=Pd(m,this,U(this,cs,"f").getMiddleware(),!0)),h=this[eve](A,h??m),on(h)&&!n&&(h=h.then(()=>Pd(m,this,U(this,cs,"f").getMiddleware(),!1)))}}}catch(x){if(x instanceof qn)U(this,It,"f").fail(x.message,x);else throw x}return this[qd](h??m,f,!!n,!0)}[cZ](e,t,n,i){let a={...this.getDemandedOptions()};return o=>{if(n)throw new qn(n.message);U(this,Dn,"f").nonOptionCount(o),U(this,Dn,"f").requiredArguments(o,a);let s=!1;U(this,Nd,"f")&&(s=U(this,Dn,"f").unknownCommands(o)),U(this,Fd,"f")&&!s?U(this,Dn,"f").unknownArguments(o,e,t,!!i):U(this,Md,"f")&&U(this,Dn,"f").unknownArguments(o,e,{},!1,!1),U(this,Dn,"f").limitedChoices(o),U(this,Dn,"f").implications(o),U(this,Dn,"f").conflicting(o)}}[lve](){Ye(this,Oo,!0,"f")}[zd](e){if(typeof e=="string")U(this,nt,"f").key[e]=!0;else for(let t of e)U(this,nt,"f").key[t]=!0}};function F7e(r){return!!r&&typeof r.getInternalMethods=="function"}var W9t=fve(ZV),pve=W9t;import V9t from"node:os";function dve(){let r=HV(process.argv),e=pve(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=lZ.join(V9t.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=lZ.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=lZ.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 Ibe=Er(QZ(),1),sa=(0,DT.default)(),Vyt=process.env.PORT?parseInt(process.env.PORT):process.env.BUILD_ENV==="development"?4100:3e3,Zyt=M9e(Vyt),Gyt="x-forwarded-email",hn=dve();me("INIT","Coday options:",hn);var $be=!hn.noLog,b9=new $w($be,hn.logFolder);me("INIT",`Usage logging ${$be?"enabled":"disabled"} ${hn.logFolder?`(custom folder: ${hn.logFolder})`:""}`);me("INIT","Webhook service initialized (will be initialized with prompt execution service)");var V1,OT,Jyt=process.env.AGENTOS_PORT?parseInt(process.env.AGENTOS_PORT):8123,Rbe=`http://localhost:${Jyt}`;sa.use("/api/agentos",(r,e,t)=>{console.log(`[AGENTOS PROXY] ${r.method} ${r.path}`),t()},(0,Ibe.createProxyMiddleware)({target:Rbe,changeOrigin:!0,pathRewrite:{"^/api/agentos/api":"/api"}}));me("INIT",`AgentOS proxy configured: /api/agentos \u2192 ${Rbe}`);sa.use(DT.default.json({limit:"20mb"}));if(process.env.BUILD_ENV==="development"){let r="http://localhost:4200";me("INIT",`Development mode: proxying to Angular dev server at ${r}`),Promise.resolve().then(()=>Er(QZ(),1)).then(({createProxyMiddleware:e})=>{let t=e({target:r,changeOrigin:!0,ws:!0});sa.use("/",(n,i,a)=>{n.path.startsWith("/api")||n.path.startsWith("/events")?a():t(n,i,a)}),me("INIT","Proxy middleware configured successfully")}).catch(e=>{console.error("Failed to load http-proxy-middleware:",e)})}else{let r=process.env.CODAY_CLIENT_PATH?ll.resolve(process.env.CODAY_CLIENT_PATH):ll.resolve(__dirname,"../coday-client/browser");if(me("INIT",`Production mode: serving static files from ${r}`),process.env.CODAY_CLIENT_PATH&&me("INIT","Using client path from CODAY_CLIENT_PATH environment variable"),!kT.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=ll.join(r,"index.html");kT.existsSync(e)?me("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"))}sa.use(DT.default.static(r))}var AT=new NS(hn.configDir),y9=hn.project;if(y9&&!hn.forcedProject){let r=process.cwd(),e=ll.basename(r);if(AT.exists(e)){let t=AT.getConfig(e);if(t&&t.path===r&&!t.volatile)me("INIT",`Default mode: found existing non-volatile project '${e}' for current directory`),y9=e;else{let n=fm.generateProjectId(r);me("INIT",`Default mode: existing project '${e}' doesn't match path, using volatile ID ${n}`),y9=n}}else{let t=fm.generateProjectId(r);me("INIT",`Default mode: no existing project found, using volatile ID ${t}`),y9=t}}var x9=new fm(AT,y9,hn.forcedProject);V1=new RS(hn.configDir,x9);me("INIT","Prompt service initialized");OT=new jS(V1);me("INIT","Prompt execution service initialized (will be initialized with dependencies after thread manager)");var jbe=ll.join(hn.configDir,"projects"),Fbe=new zS(jbe),IT=new LS(AT,jbe,Fbe),Kyt=new vm;me("INIT","MCP instance pool initialized");var $T=new jC(b9,x9,IT,V1,Kyt);OT.initialize($T,IT,hn,b9);me("INIT","Prompt execution service initialized");me("INIT","Webhook service initialized with prompt execution delegation");var Yyt=new fc("config-api"),Xyt=new DS(hn.configDir,Yyt),Qyt=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function df(r){let e=hn.auth?r.headers[Gyt]:Obe.userInfo().username;if(Qyt.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}B9e(sa,df);L9e(sa,Xyt,df);W9e(sa,V1,df);Z9e(sa,OT,df);q9e(sa,x9);z9e(sa,IT,Fbe,$T,df,hn);U9e(sa,$T,df);var ebt=new TS(hn.configDir,x9);H9e(sa,x9,df,hn.configDir,b9,V1,IT,ebt,hn);var CT=new FS(b9,V1,hn.configDir);V9e(sa,CT,df);if(process.env.BUILD_ENV!=="development"){let r=process.env.CODAY_CLIENT_PATH?ll.resolve(process.env.CODAY_CLIENT_PATH):ll.resolve(__dirname,"../coday-client/browser"),e=ll.resolve(r,"index.html");me("INIT",`Catch-all route will serve: ${e}`),sa.use((t,n,i)=>{if(t.path.startsWith("/api")||t.path.startsWith("/events")){n.status(404).send("Not found");return}me("ROUTER",`Serving index.html for client route: ${t.path}`),kT.readFile(e,"utf8",(a,o)=>{a?(me("ERROR",`Failed to read index.html from ${e}:`,a),me("ERROR",`File exists check: ${kT.existsSync(e)}`),i(a)):n.type("html").send(o)})})}var TT=null;sa.use((r,e,t,n)=>{me("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!")});Zyt.then(async r=>{hn.baseUrl?me("INIT",`Using configured base URL: ${hn.baseUrl}`):(hn.baseUrl=`http://localhost:${r}`,me("INIT",`Base URL set to: ${hn.baseUrl}`)),sa.listen(r,()=>{console.log(`Server is running on http://localhost:${r}`)});try{me("CLEANUP","Starting thread cleanup service...");let e=ll.join(hn.configDir,"projects");TT=new qS(e,b9),await TT.start(),me("CLEANUP","Thread cleanup service started successfully")}catch(e){console.error("Failed to start thread cleanup service:",e)}try{me("SCHEDULER","Initializing scheduler service..."),await CT.initialize(),CT.initializeExecution(OT),me("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 PT=!1;async function Z1(r){PT&&(console.log(`Received ${r} during shutdown, forcing exit...`),process.exit(1)),PT=!0,console.log(`Received ${r}, shutting down gracefully...`);try{console.log("Stopping scheduler service..."),CT.stop(),TT&&(console.log("Stopping thread cleanup service..."),await TT.stop()),console.log("Cleaning up thread Coday instances..."),await $T.shutdown(),console.log("Graceful shutdown completed"),process.exit(0)}catch(e){console.error("Error during graceful shutdown:",e),process.exit(1)}}process.on("SIGTERM",()=>Z1("SIGTERM"));process.on("SIGINT",()=>Z1("SIGINT"));process.on("SIGUSR2",()=>Z1("SIGUSR2"));process.on("SIGHUP",()=>Z1("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}PT||Z1("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"),PT||Z1("unhandledRejection")});
|
|
1436
|
+
`,"f"),Ye(this,wi,U(this,wi,"f")+e.join(" "),"f")}}}[QV](e){N1(U(this,nt,"f")).forEach(t=>{if((i=>i==="configObjects")(t))return;let n=U(this,nt,"f")[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n=="object"&&delete n[e]}),delete U(this,It,"f").getDescriptions()[e]}[G7e](e,t,n){U(this,ZC,"f")[n]||(U(this,_t,"f").process.emitWarning(e,t),U(this,ZC,"f")[n]=!0)}[J7e](){U(this,GC,"f").push({options:U(this,nt,"f"),configObjects:U(this,nt,"f").configObjects.slice(0),exitProcess:U(this,ss,"f"),groups:U(this,Gc,"f"),strict:U(this,Fd,"f"),strictCommands:U(this,Nd,"f"),strictOptions:U(this,Md,"f"),completionCommand:U(this,Do,"f"),output:U(this,wi,"f"),exitError:U(this,lf,"f"),hasOutput:U(this,Oo,"f"),parsed:this.parsed,parseFn:U(this,Io,"f"),parseContext:U(this,Rd,"f")}),U(this,It,"f").freeze(),U(this,Dn,"f").freeze(),U(this,zn,"f").freeze(),U(this,cs,"f").freeze()}[K7e](){let e="",t;return/\b(node|iojs|electron)(\.exe)?$/.test(U(this,_t,"f").process.argv()[0])?t=U(this,_t,"f").process.argv().slice(1,2):t=U(this,_t,"f").process.argv().slice(0,1),e=t.map(n=>{let i=this[uve](U(this,Od,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&i.length<n.length?i:n}).join(" ").trim(),U(this,_t,"f").getEnv("_")&&U(this,_t,"f").getProcessArgvBin()===U(this,_t,"f").getEnv("_")&&(e=U(this,_t,"f").getEnv("_").replace(`${U(this,_t,"f").path.dirname(U(this,_t,"f").process.execPath())}/`,"")),e}[Ld](){return U(this,YC,"f")}[Y7e](){return U(this,QC,"f")}[eZ](){if(!U(this,Id,"f"))return;let e=U(this,_t,"f").getEnv("LC_ALL")||U(this,_t,"f").getEnv("LC_MESSAGES")||U(this,_t,"f").getEnv("LANG")||U(this,_t,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[X7e](){return this[tZ]().version||"unknown"}[Q7e](e){let t=e["--"]?e["--"]:e._;for(let n=0,i;(i=t[n])!==void 0;n++)U(this,_t,"f").Parser.looksLikeNumber(i)&&Number.isSafeInteger(Math.floor(parseFloat(`${i}`)))&&(t[n]=Number(i));return e}[tZ](e){let t=e||"*";if(U(this,L1,"f")[t])return U(this,L1,"f")[t];let n={};try{let i=e||U(this,_t,"f").mainFilename;U(this,_t,"f").path.extname(i)&&(i=U(this,_t,"f").path.dirname(i));let a=U(this,_t,"f").findUp(i,(o,s)=>{if(s.includes("package.json"))return"package.json"});Ca(a,void 0,U(this,_t,"f")),n=JSON.parse(U(this,_t,"f").readFileSync(a,"utf8"))}catch{}return U(this,L1,"f")[t]=n||{},U(this,L1,"f")[t]}[pf](e,t){t=[].concat(t),t.forEach(n=>{n=this[iZ](n),U(this,nt,"f")[e].push(n)})}[q1](e,t,n,i){this[nZ](e,t,n,i,(a,o,s)=>{U(this,nt,"f")[a][o]=s})}[rZ](e,t,n,i){this[nZ](e,t,n,i,(a,o,s)=>{U(this,nt,"f")[a][o]=(U(this,nt,"f")[a][o]||[]).concat(s)})}[nZ](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 N1(n))e(o,n[o]);else a(t,this[iZ](n),i)}[iZ](e){return e==="__proto__"?"___proto___":e}[aZ](e,t){return this[q1](this[aZ].bind(this),"key",e,t),this}[oZ](){var e,t,n,i,a,o,s,c,u,l,f,p;let d=U(this,GC,"f").pop();Ca(d,void 0,U(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,ss,h,"f")}}.value,groups:{set value(h){Ye(n,Gc,h,"f")}}.value,output:{set value(h){Ye(i,wi,h,"f")}}.value,exitError:{set value(h){Ye(a,lf,h,"f")}}.value,hasOutput:{set value(h){Ye(o,Oo,h,"f")}}.value,parsed:this.parsed,strict:{set value(h){Ye(s,Fd,h,"f")}}.value,strictCommands:{set value(h){Ye(c,Nd,h,"f")}}.value,strictOptions:{set value(h){Ye(u,Md,h,"f")}}.value,completionCommand:{set value(h){Ye(l,Do,h,"f")}}.value,parseFn:{set value(h){Ye(f,Io,h,"f")}}.value,parseContext:{set value(h){Ye(p,Rd,h,"f")}}.value}=d,U(this,nt,"f").configObjects=m,U(this,It,"f").unfreeze(),U(this,Dn,"f").unfreeze(),U(this,zn,"f").unfreeze(),U(this,cs,"f").unfreeze()}[eve](e,t){return Dd(t,n=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[tve].bind(this),getContext:this[rve].bind(this),getHasOutput:this[nve].bind(this),getLoggerInstance:this[ive].bind(this),getParseContext:this[ave].bind(this),getParserConfiguration:this[Ld].bind(this),getUsageConfiguration:this[Y7e].bind(this),getUsageInstance:this[ove].bind(this),getValidationInstance:this[sve].bind(this),hasParseCallback:this[eT].bind(this),isGlobalContext:this[cve].bind(this),postProcess:this[qd].bind(this),reset:this[sZ].bind(this),runValidation:this[cZ].bind(this),runYargsParserAndExecuteCommands:this[u9].bind(this),setHasOutput:this[lve].bind(this)}}[tve](){return U(this,zn,"f")}[rve](){return U(this,c9,"f")}[nve](){return U(this,Oo,"f")}[ive](){return U(this,$d,"f")}[ave](){return U(this,Rd,"f")||{}}[ove](){return U(this,It,"f")}[sve](){return U(this,Dn,"f")}[eT](){return!!U(this,Io,"f")}[cve](){return U(this,JC,"f")}[qd](e,t,n,i){return n||on(e)||(t||(e=this[V7e](e)),(this[Ld]()["parse-positional-numbers"]||this[Ld]()["parse-positional-numbers"]===void 0)&&(e=this[Q7e](e)),i&&(e=Pd(e,this,U(this,cs,"f").getMiddleware(),!1))),e}[sZ](e={}){Ye(this,nt,U(this,nt,"f")||{},"f");let t={};t.local=U(this,nt,"f").local||[],t.configObjects=U(this,nt,"f").configObjects||[];let n={};t.local.forEach(o=>{n[o]=!0,(e[o]||[]).forEach(s=>{n[s]=!0})}),Object.assign(U(this,jd,"f"),Object.keys(U(this,Gc,"f")).reduce((o,s)=>{let c=U(this,Gc,"f")[s].filter(u=>!(u in n));return c.length>0&&(o[s]=c),o},{})),Ye(this,Gc,{},"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]=(U(this,nt,"f")[o]||[]).filter(s=>!n[s])}),a.forEach(o=>{t[o]=cf(U(this,nt,"f")[o],s=>!n[s])}),t.envPrefix=U(this,nt,"f").envPrefix,Ye(this,nt,t,"f"),Ye(this,It,U(this,It,"f")?U(this,It,"f").reset(n):M7e(this,U(this,_t,"f")),"f"),Ye(this,Dn,U(this,Dn,"f")?U(this,Dn,"f").reset(n):H7e(this,U(this,It,"f"),U(this,_t,"f")),"f"),Ye(this,zn,U(this,zn,"f")?U(this,zn,"f").reset():j7e(U(this,It,"f"),U(this,Dn,"f"),U(this,cs,"f"),U(this,_t,"f")),"f"),U(this,ro,"f")||Ye(this,ro,z7e(this,U(this,It,"f"),U(this,zn,"f"),U(this,_t,"f")),"f"),U(this,cs,"f").reset(),Ye(this,Do,null,"f"),Ye(this,wi,"","f"),Ye(this,lf,null,"f"),Ye(this,Oo,!1,"f"),this.parsed=!1,this}[uve](e,t){return U(this,_t,"f").path.relative(e,t)}[u9](e,t,n,i=0,a=!1){var o,s,c,u;let l=!!n||a;e=e||U(this,ff,"f"),U(this,nt,"f").__=U(this,_t,"f").y18n.__,U(this,nt,"f").configuration=this[Ld]();let f=!!U(this,nt,"f").configuration["populate--"],p=Object.assign({},U(this,nt,"f").configuration,{"populate--":!0}),d=U(this,_t,"f").Parser.detailed(e,Object.assign({},U(this,nt,"f"),{configuration:{"parse-positional-numbers":!1,...p}})),m=Object.assign(d.argv,U(this,Rd,"f")),h,g=d.aliases,v=!1,y=!1;Object.keys(m).forEach(x=>{x===U(this,us,"f")&&m[x]?v=!0:x===U(this,Jc,"f")&&m[x]&&(y=!0)}),m.$0=this.$0,this.parsed=d,i===0&&U(this,It,"f").clearCachedHelpMessage();try{if(this[eZ](),t)return this[qd](m,f,!!n,!1);U(this,us,"f")&&[U(this,us,"f")].concat(g[U(this,us,"f")]||[]).filter(R=>R.length>1).includes(""+m._[m._.length-1])&&(m._.pop(),v=!0),Ye(this,JC,!1,"f");let x=U(this,zn,"f").getCommands(),k=!((o=U(this,ro,"f"))===null||o===void 0)&&o.completionKey?[(s=U(this,ro,"f"))===null||s===void 0?void 0:s.completionKey,...(u=this.getAliases()[(c=U(this,ro,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&u!==void 0?u:[]].some(A=>Object.prototype.hasOwnProperty.call(m,A)):!1,E=v||k||a;if(m._.length){if(x.length){let A;for(let R=i||0,I;m._[R]!==void 0;R++)if(I=String(m._[R]),x.includes(I)&&I!==U(this,Do,"f")){let w=U(this,zn,"f").runCommand(I,this,d,R+1,a,v||y||a);return this[qd](w,f,!!n,!1)}else if(!A&&I!==U(this,Do,"f")){A=I;break}!U(this,zn,"f").hasDefaultCommand()&&U(this,XC,"f")&&A&&!E&&U(this,Dn,"f").recommendCommands(A,x)}U(this,Do,"f")&&m._.includes(U(this,Do,"f"))&&!k&&(U(this,ss,"f")&&uf(!0),this.showCompletionScript(),this.exit(0))}if(U(this,zn,"f").hasDefaultCommand()&&!E){let A=U(this,zn,"f").runCommand(null,this,d,0,a,v||y||a);return this[qd](A,f,!!n,!1)}if(k){U(this,ss,"f")&&uf(!0),e=[].concat(e);let A=e.slice(e.indexOf(`--${U(this,ro,"f").completionKey}`)+1);return U(this,ro,"f").getCompletion(A,(R,I)=>{if(R)throw new qn(R.message);(I||[]).forEach(w=>{U(this,$d,"f").log(w)}),this.exit(0)}),this[qd](m,!f,!!n,!1)}if(U(this,Oo,"f")||(v?(U(this,ss,"f")&&uf(!0),l=!0,this.showHelp(A=>{U(this,$d,"f").log(A),this.exit(0)})):y&&(U(this,ss,"f")&&uf(!0),l=!0,U(this,It,"f").showVersion("log"),this.exit(0))),!l&&U(this,nt,"f").skipValidation.length>0&&(l=Object.keys(m).some(A=>U(this,nt,"f").skipValidation.indexOf(A)>=0&&m[A]===!0)),!l){if(d.error)throw new qn(d.error.message);if(!k){let A=this[cZ](g,{},d.error);n||(h=Pd(m,this,U(this,cs,"f").getMiddleware(),!0)),h=this[eve](A,h??m),on(h)&&!n&&(h=h.then(()=>Pd(m,this,U(this,cs,"f").getMiddleware(),!1)))}}}catch(x){if(x instanceof qn)U(this,It,"f").fail(x.message,x);else throw x}return this[qd](h??m,f,!!n,!0)}[cZ](e,t,n,i){let a={...this.getDemandedOptions()};return o=>{if(n)throw new qn(n.message);U(this,Dn,"f").nonOptionCount(o),U(this,Dn,"f").requiredArguments(o,a);let s=!1;U(this,Nd,"f")&&(s=U(this,Dn,"f").unknownCommands(o)),U(this,Fd,"f")&&!s?U(this,Dn,"f").unknownArguments(o,e,t,!!i):U(this,Md,"f")&&U(this,Dn,"f").unknownArguments(o,e,{},!1,!1),U(this,Dn,"f").limitedChoices(o),U(this,Dn,"f").implications(o),U(this,Dn,"f").conflicting(o)}}[lve](){Ye(this,Oo,!0,"f")}[zd](e){if(typeof e=="string")U(this,nt,"f").key[e]=!0;else for(let t of e)U(this,nt,"f").key[t]=!0}};function F7e(r){return!!r&&typeof r.getInternalMethods=="function"}var W9t=fve(ZV),pve=W9t;import V9t from"node:os";function dve(){let r=HV(process.argv),e=pve(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=lZ.join(V9t.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=lZ.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=lZ.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 Ibe=Er(QZ(),1),sa=(0,DT.default)(),Vyt=process.env.PORT?parseInt(process.env.PORT):process.env.BUILD_ENV==="development"?4100:3e3,Zyt=M9e(Vyt),Gyt="x-forwarded-email",hn=dve();me("INIT","Coday options:",hn);var $be=!hn.noLog,b9=new $w($be,hn.logFolder);me("INIT",`Usage logging ${$be?"enabled":"disabled"} ${hn.logFolder?`(custom folder: ${hn.logFolder})`:""}`);me("INIT","Webhook service initialized (will be initialized with prompt execution service)");var V1,OT,Jyt=process.env.AGENTOS_PORT?parseInt(process.env.AGENTOS_PORT):8123,Rbe=`http://localhost:${Jyt}`;sa.use("/api/agentos",(r,e,t)=>{console.log(`[AGENTOS PROXY] ${r.method} ${r.path}`),t()},(0,Ibe.createProxyMiddleware)({target:Rbe,changeOrigin:!0,pathRewrite:{"^/api/agentos":""}}));me("INIT",`AgentOS proxy configured: /api/agentos \u2192 ${Rbe}`);sa.use(DT.default.json({limit:"20mb"}));if(process.env.BUILD_ENV==="development"){let r="http://localhost:4200";me("INIT",`Development mode: proxying to Angular dev server at ${r}`),Promise.resolve().then(()=>Er(QZ(),1)).then(({createProxyMiddleware:e})=>{let t=e({target:r,changeOrigin:!0,ws:!0});sa.use("/",(n,i,a)=>{n.path.startsWith("/api")||n.path.startsWith("/events")?a():t(n,i,a)}),me("INIT","Proxy middleware configured successfully")}).catch(e=>{console.error("Failed to load http-proxy-middleware:",e)})}else{let r=process.env.CODAY_CLIENT_PATH?ll.resolve(process.env.CODAY_CLIENT_PATH):ll.resolve(__dirname,"../coday-client/browser");if(me("INIT",`Production mode: serving static files from ${r}`),process.env.CODAY_CLIENT_PATH&&me("INIT","Using client path from CODAY_CLIENT_PATH environment variable"),!kT.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=ll.join(r,"index.html");kT.existsSync(e)?me("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"))}sa.use(DT.default.static(r))}var AT=new NS(hn.configDir),y9=hn.project;if(y9&&!hn.forcedProject){let r=process.cwd(),e=ll.basename(r);if(AT.exists(e)){let t=AT.getConfig(e);if(t&&t.path===r&&!t.volatile)me("INIT",`Default mode: found existing non-volatile project '${e}' for current directory`),y9=e;else{let n=fm.generateProjectId(r);me("INIT",`Default mode: existing project '${e}' doesn't match path, using volatile ID ${n}`),y9=n}}else{let t=fm.generateProjectId(r);me("INIT",`Default mode: no existing project found, using volatile ID ${t}`),y9=t}}var x9=new fm(AT,y9,hn.forcedProject);V1=new RS(hn.configDir,x9);me("INIT","Prompt service initialized");OT=new jS(V1);me("INIT","Prompt execution service initialized (will be initialized with dependencies after thread manager)");var jbe=ll.join(hn.configDir,"projects"),Fbe=new zS(jbe),IT=new LS(AT,jbe,Fbe),Kyt=new vm;me("INIT","MCP instance pool initialized");var $T=new jC(b9,x9,IT,V1,Kyt);OT.initialize($T,IT,hn,b9);me("INIT","Prompt execution service initialized");me("INIT","Webhook service initialized with prompt execution delegation");var Yyt=new fc("config-api"),Xyt=new DS(hn.configDir,Yyt),Qyt=["root","admin","administrator","system","daemon","nobody","node","app","service","docker","www-data","nginx","apache","ansible"];function df(r){let e=hn.auth?r.headers[Gyt]:Obe.userInfo().username;if(Qyt.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}B9e(sa,df);L9e(sa,Xyt,df);W9e(sa,V1,df);Z9e(sa,OT,df);q9e(sa,x9);z9e(sa,IT,Fbe,$T,df,hn);U9e(sa,$T,df);var ebt=new TS(hn.configDir,x9);H9e(sa,x9,df,hn.configDir,b9,V1,IT,ebt,hn);var CT=new FS(b9,V1,hn.configDir);V9e(sa,CT,df);if(process.env.BUILD_ENV!=="development"){let r=process.env.CODAY_CLIENT_PATH?ll.resolve(process.env.CODAY_CLIENT_PATH):ll.resolve(__dirname,"../coday-client/browser"),e=ll.resolve(r,"index.html");me("INIT",`Catch-all route will serve: ${e}`),sa.use((t,n,i)=>{if(t.path.startsWith("/api")||t.path.startsWith("/events")){n.status(404).send("Not found");return}me("ROUTER",`Serving index.html for client route: ${t.path}`),kT.readFile(e,"utf8",(a,o)=>{a?(me("ERROR",`Failed to read index.html from ${e}:`,a),me("ERROR",`File exists check: ${kT.existsSync(e)}`),i(a)):n.type("html").send(o)})})}var TT=null;sa.use((r,e,t,n)=>{me("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!")});Zyt.then(async r=>{hn.baseUrl?me("INIT",`Using configured base URL: ${hn.baseUrl}`):(hn.baseUrl=`http://localhost:${r}`,me("INIT",`Base URL set to: ${hn.baseUrl}`)),sa.listen(r,()=>{console.log(`Server is running on http://localhost:${r}`)});try{me("CLEANUP","Starting thread cleanup service...");let e=ll.join(hn.configDir,"projects");TT=new qS(e,b9),await TT.start(),me("CLEANUP","Thread cleanup service started successfully")}catch(e){console.error("Failed to start thread cleanup service:",e)}try{me("SCHEDULER","Initializing scheduler service..."),await CT.initialize(),CT.initializeExecution(OT),me("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 PT=!1;async function Z1(r){PT&&(console.log(`Received ${r} during shutdown, forcing exit...`),process.exit(1)),PT=!0,console.log(`Received ${r}, shutting down gracefully...`);try{console.log("Stopping scheduler service..."),CT.stop(),TT&&(console.log("Stopping thread cleanup service..."),await TT.stop()),console.log("Cleaning up thread Coday instances..."),await $T.shutdown(),console.log("Graceful shutdown completed"),process.exit(0)}catch(e){console.error("Error during graceful shutdown:",e),process.exit(1)}}process.on("SIGTERM",()=>Z1("SIGTERM"));process.on("SIGINT",()=>Z1("SIGINT"));process.on("SIGUSR2",()=>Z1("SIGUSR2"));process.on("SIGHUP",()=>Z1("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}PT||Z1("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"),PT||Z1("unhandledRejection")});
|
|
1437
1437
|
/*! Bundled license information:
|
|
1438
1438
|
|
|
1439
1439
|
depd/index.js:
|