@segosolutions/auto-task 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +549 -107
- package/dist/index.cjs +42 -36
- package/package.json +10 -8
package/dist/index.cjs
CHANGED
|
@@ -1,54 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(
|
|
4
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,
|
|
2
|
+
"use strict";var qt=Object.create;var qe=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Lt=Object.prototype.hasOwnProperty;var $=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Bt=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Vt(e))!Lt.call(n,o)&&o!==t&&qe(n,o,{get:()=>e[o],enumerable:!(s=Ht(e,o))||s.enumerable});return n};var he=(n,e,t)=>(t=n!=null?qt(Ft(n)):{},Bt(e||!n||!n.__esModule?qe(t,"default",{value:n,enumerable:!0}):t,n));var L=$(me=>{var te=class extends Error{constructor(e,t,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ge=class extends te{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};me.CommanderError=te;me.InvalidArgumentError=ge});var se=$(ye=>{var{InvalidArgumentError:Kt}=L(),fe=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new Kt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Gt(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}ye.Argument=fe;ye.humanReadableArgName=Gt});var ve=$(He=>{var{humanReadableArgName:Wt}=se(),Ce=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(o=>!o._hidden),s=e._getHelpCommand();return s&&!s._hidden&&t.push(s),this.sortSubcommands&&t.sort((o,r)=>o.name().localeCompare(r.name())),t}compareOptions(e,t){let s=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return s(e).localeCompare(s(t))}visibleOptions(e){let t=e.options.filter(o=>!o.hidden),s=e._getHelpOption();if(s&&!s.hidden){let o=s.short&&e._findOption(s.short),r=s.long&&e._findOption(s.long);!o&&!r?t.push(s):s.long&&!r?t.push(e.createOption(s.long,s.description)):s.short&&!o&&t.push(e.createOption(s.short,s.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let s=e.parent;s;s=s.parent){let o=s.options.filter(r=>!r.hidden);t.push(...o)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(s=>Wt(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,o)=>Math.max(s,t.subcommandTerm(o).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,o)=>Math.max(s,t.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,o)=>Math.max(s,t.optionTerm(o).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,o)=>Math.max(s,t.argumentTerm(o).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let o=e.parent;o;o=o.parent)s=o.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,t){let s=t.padWidth(e,t),o=t.helpWidth||80,r=2,i=2;function l(h,d){if(d){let g=`${h.padEnd(s+i)}${d}`;return t.wrap(g,o-r,s+i)}return h}function a(h){return h.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(r))}let c=[`Usage: ${t.commandUsage(e)}`,""],u=t.commandDescription(e);u.length>0&&(c=c.concat([t.wrap(u,o,0),""]));let p=t.visibleArguments(e).map(h=>l(t.argumentTerm(h),t.argumentDescription(h)));p.length>0&&(c=c.concat(["Arguments:",a(p),""]));let f=t.visibleOptions(e).map(h=>l(t.optionTerm(h),t.optionDescription(h)));if(f.length>0&&(c=c.concat(["Options:",a(f),""])),this.showGlobalOptions){let h=t.visibleGlobalOptions(e).map(d=>l(t.optionTerm(d),t.optionDescription(d)));h.length>0&&(c=c.concat(["Global Options:",a(h),""]))}let m=t.visibleCommands(e).map(h=>l(t.subcommandTerm(h),t.subcommandDescription(h)));return m.length>0&&(c=c.concat(["Commands:",a(m),""])),c.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,s,o=40){let r=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${r}]+`);if(e.match(i))return e;let l=t-s;if(l<o)return e;let a=e.slice(0,s),c=e.slice(s).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),
|
|
7
|
-
|.{1,${
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
10
|
-
(Did you mean one of ${
|
|
11
|
-
(Did you mean ${
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=
|
|
6
|
+
`),u=" ".repeat(s),f="\\s\u200B",m=new RegExp(`
|
|
7
|
+
|.{1,${l-1}}([${f}]|$)|[^${f}]+?([${f}]|$)`,"g"),h=c.match(m)||[];return a+h.map((d,g)=>d===`
|
|
8
|
+
`?"":(g>0?u:"")+d.trimEnd()).join(`
|
|
9
|
+
`)}};He.Help=Ce});var _e=$(Ee=>{var{InvalidArgumentError:Yt}=L(),ke=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Qt(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new Yt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Jt(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},be=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,t){let s=t.attributeName();if(!this.dualOptions.has(s))return!0;let o=this.negativeOptions.get(s).presetArg,r=o!==void 0?o:!1;return t.negate===(r===e)}};function Jt(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Qt(n){let e,t,s=n.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),t=s.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Ee.Option=ke;Ee.DualOptions=be});var Fe=$(Ve=>{function zt(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let s=0;s<=n.length;s++)t[s]=[s];for(let s=0;s<=e.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let o=1;o<=n.length;o++){let r=1;n[o-1]===e[s-1]?r=0:r=1,t[o][s]=Math.min(t[o-1][s]+1,t[o][s-1]+1,t[o-1][s-1]+r),o>1&&s>1&&n[o-1]===e[s-2]&&n[o-2]===e[s-1]&&(t[o][s]=Math.min(t[o][s],t[o-2][s-2]+1))}return t[n.length][e.length]}function Xt(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(i=>i.slice(2)));let s=[],o=3,r=.4;return e.forEach(i=>{if(i.length<=1)return;let l=zt(n,i),a=Math.max(n.length,i.length);(a-l)/a>r&&(l<o?(o=l,s=[i]):l===o&&s.push(i))}),s.sort((i,l)=>i.localeCompare(l)),t&&(s=s.map(i=>`--${i}`)),s.length>1?`
|
|
10
|
+
(Did you mean one of ${s.join(", ")}?)`:s.length===1?`
|
|
11
|
+
(Did you mean ${s[0]}?)`:""}Ve.suggestSimilar=Xt});var We=$(Ge=>{var Zt=require("node:events").EventEmitter,Ae=require("node:child_process"),x=require("node:path"),we=require("node:fs"),b=require("node:process"),{Argument:es,humanReadableArgName:ts}=se(),{CommanderError:Te}=L(),{Help:ss}=ve(),{Option:Le,DualOptions:ns}=_e(),{suggestSimilar:Be}=Fe(),Oe=class n extends Zt{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>b.stdout.write(t),writeErr:t=>b.stderr.write(t),getOutHelpWidth:()=>b.stdout.isTTY?b.stdout.columns:void 0,getErrHelpWidth:()=>b.stderr.isTTY?b.stderr.columns:void 0,outputError:(t,s)=>s(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,s){let o=t,r=s;typeof o=="object"&&o!==null&&(r=o,o=null),r=r||{};let[,i,l]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(i);return o&&(a.description(o),a._executableHandler=!0),r.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(r.noHelp||r.hidden),a._executableFile=r.executableFile||null,l&&a.arguments(l),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),o?this:a}createCommand(e){return new n(e)}createHelp(){return Object.assign(new ss,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new es(e,t)}argument(e,t,s,o){let r=this.createArgument(e,t);return typeof s=="function"?r.default(o).argParser(s):r.default(s),this.addArgument(r),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,s,o]=e.match(/([^ ]+) *(.*)/),r=t??"display help for command",i=this.createCommand(s);return i.helpOption(!1),o&&i.arguments(o),r&&i.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=i,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,s){this._exitCallback&&this._exitCallback(new Te(e,t,s)),b.exit(e)}action(e){let t=s=>{let o=this.registeredArguments.length,r=s.slice(0,o);return this._storeOptionsAsProperties?r[o]=this:r[o]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=t,this}createOption(e,t){return new Le(e,t)}_callParseArg(e,t,s,o){try{return e.parseArg(t,s)}catch(r){if(r.code==="commander.invalidArgument"){let i=`${o} ${r.message}`;this.error(i,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=o=>[o.name()].concat(o.aliases()),s=t(e).find(o=>this._findCommand(o));if(s){let o=t(this._findCommand(s)).join("|"),r=t(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();if(e.negate){let r=e.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let o=(r,i,l)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let a=this.getOptionValue(s);r!==null&&e.parseArg?r=this._callParseArg(e,r,a,i):r!==null&&e.variadic&&(r=e._concatValue(r,a)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(s,r,l)};return this.on("option:"+t,r=>{let i=`error: option '${e.flags}' argument '${r}' is invalid.`;o(r,i,"cli")}),e.envVar&&this.on("optionEnv:"+t,r=>{let i=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;o(r,i,"env")}),this}_optionEx(e,t,s,o,r){if(typeof t=="object"&&t instanceof Le)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(t,s);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(r).argParser(o);else if(o instanceof RegExp){let l=o;o=(a,c)=>{let u=l.exec(a);return u?u[0]:c},i.default(r).argParser(o)}else i.default(o);return this.addOption(i)}option(e,t,s,o){return this._optionEx({},e,t,s,o)}requiredOption(e,t,s,o){return this._optionEx({mandatory:!0},e,t,s,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,s){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(t=s.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){b.versions?.electron&&(t.from="electron");let o=b.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(t.from="eval")}e===void 0&&(e=b.argv),this.rawArgs=e.slice();let s;switch(t.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":b.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,t){let s=this._prepareUserArgs(e,t);return this._parseCommand([],s),this}async parseAsync(e,t){let s=this._prepareUserArgs(e,t);return await this._parseCommand([],s),this}_executeSubCommand(e,t){t=t.slice();let s=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function r(u,p){let f=x.resolve(u,p);if(we.existsSync(f))return f;if(o.includes(x.extname(p)))return;let m=o.find(h=>we.existsSync(`${f}${h}`));if(m)return`${f}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let u;try{u=we.realpathSync(this._scriptPath)}catch{u=this._scriptPath}l=x.resolve(x.dirname(u),l)}if(l){let u=r(l,i);if(!u&&!e._executableFile&&this._scriptPath){let p=x.basename(this._scriptPath,x.extname(this._scriptPath));p!==this._name&&(u=r(l,`${p}-${e._name}`))}i=u||i}s=o.includes(x.extname(i));let a;b.platform!=="win32"?s?(t.unshift(i),t=Ke(b.execArgv).concat(t),a=Ae.spawn(b.argv[0],t,{stdio:"inherit"})):a=Ae.spawn(i,t,{stdio:"inherit"}):(t.unshift(i),t=Ke(b.execArgv).concat(t),a=Ae.spawn(b.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{b.on(p,()=>{a.killed===!1&&a.exitCode===null&&a.kill(p)})});let c=this._exitCallback;a.on("close",u=>{u=u??1,c?c(new Te(u,"commander.executeSubCommandAsync","(close)")):b.exit(u)}),a.on("error",u=>{if(u.code==="ENOENT"){let p=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",f=`'${i}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${
|
|
17
|
+
- ${p}`;throw new Error(f)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!c)b.exit(1);else{let p=new Te(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,c(p)}}),this.runningCommand=a}_dispatchSubcommand(e,t,s){let o=this._findCommand(e);o||this.help({error:!0});let r;return r=this._chainOrCallSubCommandHook(r,o,"preSubcommand"),r=this._chainOrCall(r,()=>{if(o._executableHandler)this._executeSubCommand(o,t.concat(s));else return o._parseCommand(t,s)}),r}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,o,r)=>{let i=o;if(o!==null&&s.parseArg){let l=`error: command-argument value '${o}' is invalid for argument '${s.name()}'.`;i=this._callParseArg(s,o,r,l)}return i};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((s,o)=>{let r=s.defaultValue;s.variadic?o<this.args.length?(r=this.args.slice(o),s.parseArg&&(r=r.reduce((i,l)=>e(s,l,i),s.defaultValue))):r===void 0&&(r=[]):o<this.args.length&&(r=this.args[o],s.parseArg&&(r=e(s,r,s.defaultValue))),t[o]=r}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let s=e,o=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[t]!==void 0).forEach(r=>{r._lifeCycleHooks[t].forEach(i=>{o.push({hookedCommand:r,callback:i})})}),t==="postAction"&&o.reverse(),o.forEach(r=>{s=this._chainOrCall(s,()=>r.callback(r.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,t,s){let o=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(r=>{o=this._chainOrCall(o,()=>r(this,t))}),o}_parseCommand(e,t){let s=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),t=s.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(r,e,t)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(r))o(),this._processArguments(),this.parent.emit(r,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let o=s.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let o=e.find(r=>s.conflictsWith.includes(r.attributeName()));o&&this._conflictingOption(s,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],s=[],o=t,r=e.slice();function i(a){return a.length>1&&a[0]==="-"}let l=null;for(;r.length;){let a=r.shift();if(a==="--"){o===s&&o.push(a),o.push(...r);break}if(l&&!i(a)){this.emit(`option:${l.name()}`,a);continue}if(l=null,i(a)){let c=this._findOption(a);if(c){if(c.required){let u=r.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;r.length>0&&!i(r[0])&&(u=r.shift()),this.emit(`option:${c.name()}`,u)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),r.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),u=this._findOption(a.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,a.slice(c+1));continue}}if(i(a)&&(o=s),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&s.length===0){if(this._findCommand(a)){t.push(a),r.length>0&&s.push(...r);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),r.length>0&&t.push(...r);break}else if(this._defaultCommandName){s.push(a),r.length>0&&s.push(...r);break}}if(this._passThroughOptions){o.push(a),r.length>0&&o.push(...r);break}o.push(a)}return{operands:t,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let s=0;s<t;s++){let o=this.options[s].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let
|
|
22
|
-
Expecting one of '${
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(
|
|
24
|
-
`);let
|
|
25
|
-
`),
|
|
26
|
-
`;else if(
|
|
27
|
-
`)}async function
|
|
28
|
-
`)}function
|
|
20
|
+
`),this.outputHelp({error:!0}));let s=t||{},o=s.exitCode||1,r=s.code||"commander.error";this._exit(o,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in b.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,b.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ns(this.options),t=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&t(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(o=>!t(o)).forEach(o=>{this.setOptionValueWithSource(o,s.implied[o],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let s=i=>{let l=i.attributeName(),a=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),u=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:u||i},o=i=>{let l=s(i),a=l.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},r=`error: ${o(e)} cannot be used with ${o(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],r=this;do{let i=r.createHelp().visibleOptions(r).filter(l=>l.long).map(l=>l.long);o=o.concat(i),r=r.parent}while(r&&!r._enablePositionalOptions);t=Be(e,o)}let s=`error: unknown option '${e}'${t}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,s=t===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${s} but got ${e.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(r=>{o.push(r.name()),r.alias()&&o.push(r.alias())}),t=Be(e,o)}let s=`error: unknown command '${e}'${t}`;this.error(s,{code:"commander.unknownCommand"})}version(e,t,s){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",s=s||"output the version number";let o=this.createOption(t,s);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let o=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${o}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(s=>ts(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=x.basename(e,x.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},s;return t.error?s=o=>this._outputConfiguration.writeErr(o):s=o=>this._outputConfiguration.writeOut(o),t.write=e.write||s,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let o=this.helpInformation(s);if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=b.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${s.join("', '")}'`);let o=`${e}Help`;return this.on(o,r=>{let i;typeof t=="function"?i=t({error:r.error,command:r.command}):i=t,i&&r.write(`${i}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(o=>t.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ke(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,s="127.0.0.1",o="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?t=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=r[1],/^\d+$/.test(r[3])?o=r[3]:s=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=r[1],s=r[3],o=r[4]),t&&o!=="0"?`${t}=${s}:${parseInt(o)+1}`:e})}Ge.Command=Oe});var ze=$(I=>{var{Argument:Ye}=se(),{Command:Se}=We(),{CommanderError:os,InvalidArgumentError:Je}=L(),{Help:rs}=ve(),{Option:Qe}=_e();I.program=new Se;I.createCommand=n=>new Se(n);I.createOption=(n,e)=>new Qe(n,e);I.createArgument=(n,e)=>new Ye(n,e);I.Command=Se;I.Option=Qe;I.Argument=Ye;I.Help=rs;I.CommanderError=os;I.InvalidArgumentError=Je;I.InvalidOptionArgumentError=Je});var Ze=$((fn,is)=>{is.exports={name:"dotenv",version:"17.2.3",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var rt=$((yn,M)=>{var Ie=require("fs"),ne=require("path"),as=require("os"),ls=require("crypto"),cs=Ze(),$e=cs.version,et=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F4E1} add observability to secrets: https://dotenvx.com/ops","\u{1F465} sync secrets across teammates & machines: https://dotenvx.com/ops","\u{1F5C2}\uFE0F backup and recover secrets: https://dotenvx.com/ops","\u2705 audit secrets and track compliance: https://dotenvx.com/ops","\u{1F504} add secrets lifecycle management: https://dotenvx.com/ops","\u{1F511} add access controls to secrets: https://dotenvx.com/ops","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function us(){return et[Math.floor(Math.random()*et.length)]}function F(n){return typeof n=="string"?!["false","0","no","off",""].includes(n.toLowerCase()):!!n}function ps(){return process.stdout.isTTY}function ds(n){return ps()?`\x1B[2m${n}\x1B[0m`:n}var hs=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function gs(n){let e={},t=n.toString();t=t.replace(/\r\n?/mg,`
|
|
24
|
+
`);let s;for(;(s=hs.exec(t))!=null;){let o=s[1],r=s[2]||"";r=r.trim();let i=r[0];r=r.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),i==='"'&&(r=r.replace(/\\n/g,`
|
|
25
|
+
`),r=r.replace(/\\r/g,"\r")),e[o]=r}return e}function ms(n){n=n||{};let e=ot(n);n.path=e;let t=A.configDotenv(n);if(!t.parsed){let i=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw i.code="MISSING_DATA",i}let s=nt(n).split(","),o=s.length,r;for(let i=0;i<o;i++)try{let l=s[i].trim(),a=ys(t,l);r=A.decrypt(a.ciphertext,a.key);break}catch(l){if(i+1>=o)throw l}return A.parse(r)}function fs(n){console.error(`[dotenv@${$e}][WARN] ${n}`)}function K(n){console.log(`[dotenv@${$e}][DEBUG] ${n}`)}function st(n){console.log(`[dotenv@${$e}] ${n}`)}function nt(n){return n&&n.DOTENV_KEY&&n.DOTENV_KEY.length>0?n.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function ys(n,e){let t;try{t=new URL(e)}catch(l){if(l.code==="ERR_INVALID_URL"){let a=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw a.code="INVALID_DOTENV_KEY",a}throw l}let s=t.password;if(!s){let l=new Error("INVALID_DOTENV_KEY: Missing key part");throw l.code="INVALID_DOTENV_KEY",l}let o=t.searchParams.get("environment");if(!o){let l=new Error("INVALID_DOTENV_KEY: Missing environment part");throw l.code="INVALID_DOTENV_KEY",l}let r=`DOTENV_VAULT_${o.toUpperCase()}`,i=n.parsed[r];if(!i){let l=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw l.code="NOT_FOUND_DOTENV_ENVIRONMENT",l}return{ciphertext:i,key:s}}function ot(n){let e=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path))for(let t of n.path)Ie.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else e=ne.resolve(process.cwd(),".env.vault");return Ie.existsSync(e)?e:null}function tt(n){return n[0]==="~"?ne.join(as.homedir(),n.slice(1)):n}function Cs(n){let e=F(process.env.DOTENV_CONFIG_DEBUG||n&&n.debug),t=F(process.env.DOTENV_CONFIG_QUIET||n&&n.quiet);(e||!t)&&st("Loading env from encrypted .env.vault");let s=A._parseVault(n),o=process.env;return n&&n.processEnv!=null&&(o=n.processEnv),A.populate(o,s,n),{parsed:s}}function vs(n){let e=ne.resolve(process.cwd(),".env"),t="utf8",s=process.env;n&&n.processEnv!=null&&(s=n.processEnv);let o=F(s.DOTENV_CONFIG_DEBUG||n&&n.debug),r=F(s.DOTENV_CONFIG_QUIET||n&&n.quiet);n&&n.encoding?t=n.encoding:o&&K("No encoding is specified. UTF-8 is used by default");let i=[e];if(n&&n.path)if(!Array.isArray(n.path))i=[tt(n.path)];else{i=[];for(let u of n.path)i.push(tt(u))}let l,a={};for(let u of i)try{let p=A.parse(Ie.readFileSync(u,{encoding:t}));A.populate(a,p,n)}catch(p){o&&K(`Failed to load ${u} ${p.message}`),l=p}let c=A.populate(s,a,n);if(o=F(s.DOTENV_CONFIG_DEBUG||o),r=F(s.DOTENV_CONFIG_QUIET||r),o||!r){let u=Object.keys(c).length,p=[];for(let f of i)try{let m=ne.relative(process.cwd(),f);p.push(m)}catch(m){o&&K(`Failed to load ${f} ${m.message}`),l=m}st(`injecting env (${u}) from ${p.join(",")} ${ds(`-- tip: ${us()}`)}`)}return l?{parsed:a,error:l}:{parsed:a}}function ks(n){if(nt(n).length===0)return A.configDotenv(n);let e=ot(n);return e?A._configVault(n):(fs(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),A.configDotenv(n))}function bs(n,e){let t=Buffer.from(e.slice(-64),"hex"),s=Buffer.from(n,"base64"),o=s.subarray(0,12),r=s.subarray(-16);s=s.subarray(12,-16);try{let i=ls.createDecipheriv("aes-256-gcm",t,o);return i.setAuthTag(r),`${i.update(s)}${i.final()}`}catch(i){let l=i instanceof RangeError,a=i.message==="Invalid key length",c=i.message==="Unsupported state or unable to authenticate data";if(l||a){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(c){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw i}}function Es(n,e,t={}){let s=!!(t&&t.debug),o=!!(t&&t.override),r={};if(typeof e!="object"){let i=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw i.code="OBJECT_REQUIRED",i}for(let i of Object.keys(e))Object.prototype.hasOwnProperty.call(n,i)?(o===!0&&(n[i]=e[i],r[i]=e[i]),s&&K(o===!0?`"${i}" is already defined and WAS overwritten`:`"${i}" is already defined and was NOT overwritten`)):(n[i]=e[i],r[i]=e[i]);return r}var A={configDotenv:vs,_configVault:Cs,_parseVault:ms,config:ks,decrypt:bs,parse:gs,populate:Es};M.exports.configDotenv=A.configDotenv;M.exports._configVault=A._configVault;M.exports._parseVault=A._parseVault;M.exports.config=A.config;M.exports.decrypt=A.decrypt;M.exports.parse=A.parse;M.exports.populate=A.populate;M.exports=A});var Et=$((_n,bt)=>{var yt=require("url").parse,Ms=require("events"),js=require("https"),Ns=require("http"),Ds=require("util"),Rs=["pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","secureProtocol","servername","checkServerIdentity"],kt=[239,187,191],Us=58,qs=32,Ct=10,Hs=13,vt=1024*256,Vs=/^(cookie|authorization)$/i;function Fs(n){return kt.every(function(e,t){return n[t]===e})}function E(n,e){var t=E.CONNECTING,s=e&&e.headers,o=!1;Object.defineProperty(this,"readyState",{get:function(){return t}}),Object.defineProperty(this,"url",{get:function(){return n}});var r=this;r.reconnectInterval=1e3,r.connectionInProgress=!1;function i(g){t!==E.CLOSED&&(t=E.CONNECTING,h("error",new Y("error",{message:g})),f&&(n=f,f=null,o=!1),setTimeout(function(){t!==E.CONNECTING||r.connectionInProgress||(r.connectionInProgress=!0,m())},r.reconnectInterval))}var l,a="";s&&s["Last-Event-ID"]&&(a=s["Last-Event-ID"],delete s["Last-Event-ID"]);var c=!1,u="",p="",f=null;function m(){var g=yt(n),y=g.protocol==="https:";if(g.headers={"Cache-Control":"no-cache",Accept:"text/event-stream"},a&&(g.headers["Last-Event-ID"]=a),s){var C=o?Bs(s):s;for(var k in C){var T=C[k];T&&(g.headers[k]=T)}}g.rejectUnauthorized=!(e&&!e.rejectUnauthorized),e&&e.createConnection!==void 0&&(g.createConnection=e.createConnection);var R=e&&e.proxy;if(R){var O=yt(e.proxy);y=O.protocol==="https:",g.protocol=y?"https:":"http:",g.path=n,g.headers.Host=g.host,g.hostname=O.hostname,g.host=O.host,g.port=O.port}if(e&&e.https){for(var D in e.https)if(Rs.indexOf(D)!==-1){var Q=e.https[D];Q!==void 0&&(g[D]=Q)}}e&&e.withCredentials!==void 0&&(g.withCredentials=e.withCredentials),l=(y?js:Ns).request(g,function(v){if(r.connectionInProgress=!1,v.statusCode===500||v.statusCode===502||v.statusCode===503||v.statusCode===504){h("error",new Y("error",{status:v.statusCode,message:v.statusMessage})),i();return}if(v.statusCode===301||v.statusCode===302||v.statusCode===307){var U=v.headers.location;if(!U){h("error",new Y("error",{status:v.statusCode,message:v.statusMessage}));return}var Rt=new URL(n).origin,Ut=new URL(U).origin;o=Rt!==Ut,v.statusCode===307&&(f=n),n=U,process.nextTick(m);return}if(v.statusCode!==200)return h("error",new Y("error",{status:v.statusCode,message:v.statusMessage})),r.close();t=E.OPEN,v.on("close",function(){v.removeAllListeners("close"),v.removeAllListeners("end"),i()}),v.on("end",function(){v.removeAllListeners("close"),v.removeAllListeners("end"),i()}),h("open",new Y("open"));var _,ue,pe=0,de=-1,z=0,P=0;v.on("data",function(q){_?(q.length>_.length-P&&(z=_.length*2+q.length,z>vt&&(z=_.length+q.length+vt),ue=Buffer.alloc(z),_.copy(ue,0,0,P),_=ue),q.copy(_,P),P+=q.length):(_=q,Fs(_)&&(_=_.slice(kt.length)),P=_.length);for(var S=0,X=P;S<X;){c&&(_[S]===Ct&&++S,c=!1);for(var H=-1,Z=de,ee,V=pe;H<0&&V<X;++V)ee=_[V],ee===Us?Z<0&&(Z=V-S):ee===Hs?(c=!0,H=V-S):ee===Ct&&(H=V-S);if(H<0){pe=X-S,de=Z;break}else pe=0,de=-1;d(_,S,Z,H),S+=H+1}S===X?(_=void 0,P=0):S>0&&(_=_.slice(S,P),P=_.length)})}),l.on("error",function(v){r.connectionInProgress=!1,i(v.message)}),l.setNoDelay&&l.setNoDelay(!0),l.end()}m();function h(){r.listeners(arguments[0]).length>0&&r.emit.apply(r,arguments)}this._close=function(){t!==E.CLOSED&&(t=E.CLOSED,l.abort&&l.abort(),l.xhr&&l.xhr.abort&&l.xhr.abort())};function d(g,y,C,k){if(k===0){if(u.length>0){var T=p||"message";h(T,new Ls(T,{data:u.slice(0,-1),lastEventId:a,origin:new URL(n).origin})),u=""}p=void 0}else if(C>0){var R=C<0,O=0,D=g.slice(y,y+(R?k:C)).toString();R?O=k:g[y+C+1]!==qs?O=C+1:O=C+2,y+=O;var Q=k-O,v=g.slice(y,y+Q).toString();if(D==="data")u+=v+`
|
|
26
|
+
`;else if(D==="event")p=v;else if(D==="id")a=v;else if(D==="retry"){var U=parseInt(v,10);Number.isNaN(U)||(r.reconnectInterval=U)}}}}bt.exports=E;Ds.inherits(E,Ms.EventEmitter);E.prototype.constructor=E;["open","error","message"].forEach(function(n){Object.defineProperty(E.prototype,"on"+n,{get:function(){var t=this.listeners(n)[0];return t?t._listener?t._listener:t:void 0},set:function(t){this.removeAllListeners(n),this.addEventListener(n,t)}})});Object.defineProperty(E,"CONNECTING",{enumerable:!0,value:0});Object.defineProperty(E,"OPEN",{enumerable:!0,value:1});Object.defineProperty(E,"CLOSED",{enumerable:!0,value:2});E.prototype.CONNECTING=0;E.prototype.OPEN=1;E.prototype.CLOSED=2;E.prototype.close=function(){this._close()};E.prototype.addEventListener=function(e,t){typeof t=="function"&&(t._listener=t,this.on(e,t))};E.prototype.dispatchEvent=function(e){if(!e.type)throw new Error("UNSPECIFIED_EVENT_TYPE_ERR");this.emit(e.type,e.detail)};E.prototype.removeEventListener=function(e,t){typeof t=="function"&&(t._listener=void 0,this.removeListener(e,t))};function Y(n,e){if(Object.defineProperty(this,"type",{writable:!1,value:n,enumerable:!0}),e)for(var t in e)e.hasOwnProperty(t)&&Object.defineProperty(this,t,{writable:!1,value:e[t],enumerable:!0})}function Ls(n,e){Object.defineProperty(this,"type",{writable:!1,value:n,enumerable:!0});for(var t in e)e.hasOwnProperty(t)&&Object.defineProperty(this,t,{writable:!1,value:e[t],enumerable:!0})}function Bs(n){var e={};for(var t in n)Vs.test(t)||(e[t]=n[t]);return e}});var Xe=he(ze(),1),{program:B,createCommand:on,createArgument:rn,createOption:an,CommanderError:ln,InvalidArgumentError:cn,InvalidOptionArgumentError:un,Command:pn,Argument:dn,Option:hn,Help:gn}=Xe.default;var jt=he(rt(),1),Ue=require("path"),Nt=require("fs");function it(n){let e=n.apiKey||process.env.SEGO_API_KEY,t=n.apiUrl||process.env.SEGO_API_URL||"https://sego.pm",s=n.pollIntervalMs||(process.env.AUTO_TASK_POLL_INTERVAL_MS?parseInt(process.env.AUTO_TASK_POLL_INTERVAL_MS,10):3e4),o=n.timeoutMs||(process.env.AUTO_TASK_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_TIMEOUT_MS,10):6e5),r=n.clientRequestTimeoutMs||(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS?parseInt(process.env.AUTO_TASK_CLIENT_REQUEST_TIMEOUT_MS,10):3e5);if(!e)throw new Error("API key is required. Set SEGO_API_KEY environment variable or use --api-key flag.");let i=n.projectId||process.env.SEGO_PROJECT_ID,l=n.sseEnabled??process.env.AUTO_TASK_SSE_ENABLED!=="false",a=n.workingDirectory||process.env.SEGO_WORKING_DIR,c=n.useAgentSdk??process.env.USE_AGENT_SDK==="true",u=n.streamProgress??process.env.STREAM_PROGRESS==="true",p=n.conversationOnly??process.env.CONVERSATION_ONLY==="true";return{apiKey:e,apiUrl:t,pollIntervalMs:s,timeoutMs:o,dryRun:n.dryRun??!1,projectId:i,sseEnabled:l,clientRequestTimeoutMs:r,workingDirectory:a,useAgentSdk:c,streamProgress:u,conversationOnly:p}}var oe=class{baseUrl;apiKey;projectId;constructor(e,t,s){this.baseUrl=e.replace(/\/$/,""),this.apiKey=t,this.projectId=s}async request(e,t={}){let s=`${this.baseUrl}${e}`,o=await fetch(s,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...t.headers}});if(!o.ok){let r=await o.text(),i;try{let l=JSON.parse(r);i=l.error||l.message||r}catch{i=r}throw new Error(`API error (${o.status}): ${i}`)}return o.json()}async getEligibleTask(){let e=this.projectId?`/api/mcp/tasks/auto-task/eligible?projectId=${this.projectId}`:"/api/mcp/tasks/auto-task/eligible";return(await this.request(e)).task}async startTask(e){return this.request("/api/mcp/tasks/auto-task/start",{method:"POST",body:JSON.stringify({taskId:e})})}async completeTask(e,t,s){return this.request("/api/mcp/tasks/auto-task/complete",{method:"POST",body:JSON.stringify({runId:e,status:t,comment:s?.comment,errorMessage:s?.errorMessage})})}async sendAlert(e,t,s){return this.request("/api/notifications/auto-task-alert",{method:"POST",body:JSON.stringify({runId:e,alertType:t,errorDetails:s})})}async validateAuth(){try{return await this.request("/api/mcp/auth/validate",{method:"POST"}),!0}catch{return!1}}getClientRequestMonitorUrl(){if(!this.projectId)throw new Error("Project ID is required for client request monitoring");return`${this.baseUrl}/api/projects/${this.projectId}/client-requests/monitor`}getApiKey(){return this.apiKey}getProjectId(){return this.projectId}async submitAnalysis(e,t,s,o){return this.request(`/api/client-requests/${e}/analysis`,{method:"POST",body:JSON.stringify({monitorId:t,analysis:s,processingTimeMs:o})})}async reportAnalysisFailure(e,t,s){return this.request(`/api/client-requests/${e}/analysis`,{method:"PUT",body:JSON.stringify({monitorId:t,error:s})})}async getClientRequest(e){try{let s=(await this.request(`/api/client-requests/${e}`)).request,o=s.project.brief;return{id:s.id,projectId:s.projectId,description:s.description,channel:s.channel,createdById:s.createdById,projectContext:{projectName:s.project.name,projectDescription:s.project.description,techStack:o?.techStack?.split(",").map(r=>r.trim()),existingFeatures:s.project.tasks?.map(r=>r.title),knowledgeBase:s.project.knowledgeBase||void 0}}}catch{return null}}async claimTask(e,t){if(!this.projectId)throw new Error("Project ID is required for claiming tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/claim`,{method:"POST",body:JSON.stringify({monitorId:t})})}async completeBacklogTask(e,t,s){if(!this.projectId)throw new Error("Project ID is required for completing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/complete`,{method:"POST",body:JSON.stringify({monitorId:t,result:s})})}async failBacklogTask(e,t,s,o=!0){if(!this.projectId)throw new Error("Project ID is required for failing tasks");return this.request(`/api/projects/${this.projectId}/tasks/${e}/fail`,{method:"POST",body:JSON.stringify({monitorId:t,error:s,returnToBacklog:o})})}formatEventPayload(e){return{type:e.type,timestamp:e.timestamp,message:e.message,emoji:e.emoji,data:e.data}}async sendAgentProgress(e,t,s){return this.request(`/api/client-requests/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(s)})})}async sendTaskAgentProgress(e,t,s){if(!this.projectId)throw new Error("Project ID is required for task progress events");return this.request(`/api/projects/${this.projectId}/tasks/${e}/progress`,{method:"POST",body:JSON.stringify({monitorId:t,event:this.formatEventPayload(s)})})}};var G=require("child_process"),j=require("fs"),W=require("os"),re=require("path");function ie(){let n=[(0,re.join)((0,W.homedir)(),".claude","local","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude"];for(let e of n)if((0,j.existsSync)(e))return e;return"claude"}var w=null;function _s(n){let e=[`# Task: ${n.title}`,"",`**Project:** ${n.project.name}`,`**Priority:** ${n.priority}`,`**Type:** ${n.type}`,"","## Description",n.description,""];return n.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),n.acceptanceCriteria.forEach((t,s)=>{e.push(`${s+1}. ${t}`)}),e.push("")),n.technicalNotes&&(e.push("## Technical Notes"),e.push(n.technicalNotes),e.push("")),n.project.knowledgeBase&&(e.push("## Project Context"),e.push(n.project.knowledgeBase),e.push("")),e.push("---"),e.push(""),e.push('Please work on this task. When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
27
|
+
`)}async function at(n,e){let t=_s(n);return w||(w=ie()),new Promise(s=>{let o="",r="",i=!1,l=!1,a=(0,G.spawn)(w,["--print","--dangerously-skip-permissions","--mcp-config",'{"mcpServers":{}}'],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()}});a.stdin?.write(t),a.stdin?.end();let c=setTimeout(()=>{i=!0,l=!0,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL")},5e3)},e);a.stdout?.on("data",u=>{o+=u.toString()}),a.stderr?.on("data",u=>{r+=u.toString()}),a.on("close",u=>{if(clearTimeout(c),i){s({success:!1,output:o,error:"Process timed out",timedOut:!0});return}let p=o.includes("TASK_COMPLETE")&&!o.includes("TASK_BLOCKED");if(u!==0&&!l){s({success:!1,output:o,error:r||`Process exited with code ${u}`,timedOut:!1});return}let f=o.match(/TASK_BLOCKED:\s*(.+)/i);if(f){s({success:!1,output:o,error:`Task blocked: ${f[1]}`,timedOut:!1});return}s({success:p,output:o,error:p?void 0:"Task did not complete successfully",timedOut:!1})}),a.on("error",u=>{clearTimeout(c),s({success:!1,output:o,error:`Failed to spawn claude: ${u.message}`,timedOut:!1})})})}async function lt(){return w=ie(),w&&w!=="claude"&&(0,j.existsSync)(w)?(console.log(`Found Claude CLI at: ${w}`),!0):new Promise(n=>{let e=(0,G.spawn)(w,["--version"],{stdio:["pipe","pipe","pipe"]});e.on("close",t=>{n(t===0)}),e.on("error",()=>{n(!1)}),setTimeout(()=>{e.kill(),n(!1)},5e3)})}function As(n){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",n.description,"","## Project Context","",`**Project Name:** ${n.projectContext.projectName}`];return n.projectContext.projectDescription&&e.push(`**Description:** ${n.projectContext.projectDescription}`),n.projectContext.techStack&&n.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${n.projectContext.techStack.join(", ")}`),n.projectContext.existingFeatures&&n.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),n.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
|
|
28
|
+
`)}function ws(n){let e=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=n.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function ct(n,e,t={}){let s=As(n),o=t.verbose??!0;return o&&(console.log("[Claude] Starting analysis..."),console.log("[Claude] Prompt length:",s.length,"characters")),w||(w=ie()),new Promise(r=>{let i="",l="",a=!1,c=!1;o&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let u=(0,re.join)((0,W.tmpdir)(),`claude-prompt-${Date.now()}.txt`);(0,j.writeFileSync)(u,s,"utf-8");let p=`cat "${u}" | ${w} --print --dangerously-skip-permissions`;o&&(console.log("[Claude] Working directory:",process.cwd()),console.log("[Claude] Temp file:",u),console.log("[Claude] Running via shell..."));let f=(0,G.spawn)("sh",["-c",p],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:process.cwd()},cwd:process.cwd()});o&&console.log("[Claude] Shell process started with PID:",f.pid),f.stdin?.end();let m=()=>{try{(0,j.unlinkSync)(u),o&&console.log("[Claude] Temp file cleaned up")}catch{}},h=setTimeout(()=>{a=!0,c=!0,console.log("[Claude] Timeout reached, killing process..."),f.kill("SIGTERM"),setTimeout(()=>{f.killed||f.kill("SIGKILL")},5e3)},e);f.stdout?.on("data",d=>{let g=d.toString();i+=g,o&&process.stdout.write(g)}),f.stderr?.on("data",d=>{let g=d.toString();l+=g,o&&process.stderr.write(`[Claude stderr] ${g}`)}),f.on("close",(d,g)=>{clearTimeout(h),m(),o&&(console.log(""),console.log(`[Claude] Process exited with code ${d}, signal ${g}`),console.log(`[Claude] Output length: ${i.length} characters`),console.log(`[Claude] Error output length: ${l.length} characters`),l&&console.log(`[Claude] Stderr: ${l.substring(0,500)}`));let y=ws(i);if(y&&y.summary&&Array.isArray(y.suggestedTasks)){o&&a&&console.log("[Claude] Timeout was triggered but we got valid output - treating as success"),r({success:!0,analysis:y,output:i,timedOut:!1});return}if(a){r({success:!1,output:i,error:"Process timed out without producing valid output",timedOut:!0});return}if(d!==0&&!c){r({success:!1,output:i,error:l||`Process exited with code ${d}`,timedOut:!1});return}if(!y){r({success:!1,output:i,error:"Failed to parse analysis JSON from output",timedOut:!1});return}if(!y.summary||!Array.isArray(y.suggestedTasks)){r({success:!1,output:i,error:"Invalid analysis structure - missing required fields",timedOut:!1});return}r({success:!0,analysis:y,output:i,timedOut:!1})}),f.on("error",d=>{clearTimeout(h),console.error("[Claude] Spawn error:",d),r({success:!1,output:i,error:`Failed to spawn claude: ${d.message}`,timedOut:!1})}),f.on("spawn",()=>{o&&console.log("[Claude] Process spawned successfully")})})}function Ts(n){let e=[`# Task: ${n.title}`,"",`**Project:** ${n.projectContext.projectName}`,`**Priority:** ${n.priority}`,`**Type:** ${n.type}`,`**Estimated Hours:** ${n.estimatedHours||"N/A"}`,"","## Description",n.description||"No description provided.",""];if(n.acceptanceCriteria&&n.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),n.acceptanceCriteria.forEach((t,s)=>{e.push(`${s+1}. ${t}`)}),e.push("")),n.technicalNotes&&(e.push("## Technical Notes"),e.push(n.technicalNotes),e.push("")),n.projectContext.projectDescription&&(e.push("## Project Description"),e.push(n.projectContext.projectDescription),e.push("")),n.projectContext.knowledgeBase){e.push("## Project Knowledge Base");let t=n.projectContext.knowledgeBase;t.length>1e4?e.push(t.substring(0,1e4)+`
|
|
29
29
|
|
|
30
30
|
[... truncated ...]`):e.push(t),e.push("")}return e.push("---"),e.push(""),e.push("Please work on this task. Implement the required changes according to the acceptance criteria."),e.push(""),e.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
31
|
-
`)}async function at(i,e,t={}){let n=fn(i),s=t.verbose??!0,o=t.workingDirectory||process.cwd();return s&&(console.log("[Claude] Starting backlog task processing..."),console.log("[Claude] Prompt length:",n.length,"characters"),console.log("[Claude] Working directory:",o)),k||(k=oe()),s&&console.log("[Claude] Claude path:",k),new Promise(r=>{let a="",l="",u=!1,c=!1;s&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let h=(0,ie.join)((0,W.tmpdir)(),`claude-task-${Date.now()}.txt`);(0,M.writeFileSync)(h,n,"utf-8");let d=`cat "${h}" | ${k} --print --dangerously-skip-permissions`;s&&(console.log("[Claude] Temp file:",h),console.log("[Claude] Running via shell..."));let f=(0,G.spawn)("sh",["-c",d],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:o},cwd:o});s&&console.log("[Claude] Shell process started with PID:",f.pid);let m=0,v=setInterval(()=>{if(s&&!u){let b=Math.floor((Date.now()-p)/1e3);a.length===m&&console.log(`[Claude] Still running... ${b}s elapsed, ${a.length} bytes output, waiting for response...`),m=a.length}},3e4),p=Date.now();f.stdin?.end();let C=()=>{try{(0,M.unlinkSync)(h),s&&console.log("[Claude] Temp file cleaned up")}catch{}},T=setTimeout(()=>{u=!0,c=!0,clearInterval(v),console.log("[Claude] Timeout reached, killing process..."),console.log(`[Claude] Output collected: ${a.length} characters`),a.length>0&&console.log(`[Claude] Last 500 chars of output: ${a.slice(-500)}`),l.length>0&&console.log(`[Claude] Stderr: ${l.substring(0,500)}`),f.kill("SIGTERM"),setTimeout(()=>{f.killed||f.kill("SIGKILL")},5e3)},e);f.stdout?.on("data",b=>{let w=b.toString();a+=w,s&&process.stdout.write(w)}),f.stderr?.on("data",b=>{let w=b.toString();l+=w,s&&process.stderr.write(`[Claude stderr] ${w}`)}),f.on("close",(b,w)=>{clearTimeout(T),clearInterval(v),C(),s&&(console.log(""),console.log(`[Claude] Process exited with code ${b}, signal ${w}`),console.log(`[Claude] Output length: ${a.length} characters`),l&&console.log(`[Claude] Stderr: ${l.substring(0,1e3)}`));let R=a.includes("TASK_COMPLETE"),A=a.match(/TASK_BLOCKED:\s*(.+)/);if(u&&!R){r({success:!1,output:a,error:"Process timed out",timedOut:!0});return}if(A){r({success:!1,output:a,error:`Task blocked: ${A[1]}`,timedOut:!1});return}if(b!==0&&!c){r({success:!1,output:a,error:l||`Process exited with code ${b}`,timedOut:!1});return}r({success:!0,output:a,timedOut:!1})}),f.on("error",b=>{clearTimeout(T),clearInterval(v),C(),console.error("[Claude] Spawn error:",b),r({success:!1,output:a,error:`Failed to spawn claude: ${b.message}`,timedOut:!1})}),f.on("spawn",()=>{s&&console.log("[Claude] Process spawned successfully")})})}var $e=de(pt(),1),re=class{eventSource=null;url;apiKey;monitorId;reconnectAttempts=0;maxReconnectAttempts;reconnectDelayMs;reconnectTimer=null;isConnecting=!1;isStopped=!1;onClientRequestHandler=null;onTaskAvailableHandler=null;onConnectedHandler=null;onErrorHandler=null;onDisconnectedHandler=null;constructor(e,t,n,s={}){this.url=e,this.apiKey=t,this.monitorId=n,this.maxReconnectAttempts=s.maxReconnectAttempts??10,this.reconnectDelayMs=s.reconnectDelayMs??5e3}connect(){if(this.isConnecting||this.eventSource){console.log("[SSE] Already connected or connecting");return}this.isStopped=!1,this.isConnecting=!0;let e=`${this.url}?monitorId=${encodeURIComponent(this.monitorId)}`;console.log(`[SSE] Connecting to ${e}`),this.eventSource=new $e.default(e,{headers:{Authorization:`Bearer ${this.apiKey}`}}),this.eventSource.onopen=()=>{console.log("[SSE] Connection opened"),this.isConnecting=!1,this.reconnectAttempts=0},this.eventSource.addEventListener("connected",t=>{try{let n=JSON.parse(t.data);console.log(`[SSE] Connected to project: ${n.projectName}`),this.onConnectedHandler&&this.onConnectedHandler(n)}catch(n){console.error("[SSE] Error parsing connected event:",n)}}),this.eventSource.addEventListener("client_request_created",t=>{try{let n=JSON.parse(t.data);console.log(`[SSE] Received client request: ${n.requestId}`),this.onClientRequestHandler&&this.onClientRequestHandler(n.data)}catch(n){console.error("[SSE] Error parsing client_request_created event:",n)}}),this.eventSource.addEventListener("task_available",t=>{try{let n=JSON.parse(t.data);console.log(`[SSE] Received task available: ${n.taskId} - ${n.data.title}`),this.onTaskAvailableHandler&&this.onTaskAvailableHandler(n.data)}catch(n){console.error("[SSE] Error parsing task_available event:",n)}}),this.eventSource.onerror=t=>{console.error("[SSE] Connection error:",t),this.isConnecting=!1,this.onErrorHandler&&this.onErrorHandler(new Error("SSE connection error")),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.onDisconnectedHandler&&this.onDisconnectedHandler(),this.scheduleReconnect()}}scheduleReconnect(){if(this.isStopped){console.log("[SSE] Reconnection cancelled - client stopped");return}if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error(`[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached`),this.onErrorHandler&&this.onErrorHandler(new Error("Max reconnection attempts reached"));return}this.reconnectAttempts++;let e=Math.min(this.reconnectDelayMs*Math.pow(2,this.reconnectAttempts-1),6e4);console.log(`[SSE] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.connect()},e)}disconnect(){console.log("[SSE] Disconnecting"),this.isStopped=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.onDisconnectedHandler&&this.onDisconnectedHandler()}isConnected(){return this.eventSource?.readyState===$e.default.OPEN}onClientRequest(e){this.onClientRequestHandler=e}onTaskAvailable(e){this.onTaskAvailableHandler=e}onConnected(e){this.onConnectedHandler=e}onError(e){this.onErrorHandler=e}onDisconnected(e){this.onDisconnectedHandler=e}};var mt=require("crypto"),ae=class{client;config;isProcessing=!1;isProcessingClientRequest=!1;isProcessingBacklogTask=!1;isRunning=!1;pollTimeout=null;sseClient=null;monitorId;backlogTaskQueue=[];constructor(e){this.config=e,this.client=new se(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${(0,mt.randomBytes)(8).toString("hex")}`}async start(){if(this.isRunning){console.log("[Monitor] Already running");return}if(console.log("[Monitor] Starting auto-task monitor..."),console.log(`[Monitor] Monitor ID: ${this.monitorId}`),console.log(`[Monitor] API URL: ${this.config.apiUrl}`),console.log(`[Monitor] Project ID: ${this.config.projectId||"all projects"}`),console.log(`[Monitor] Poll interval: ${this.config.pollIntervalMs}ms`),console.log(`[Monitor] Task timeout: ${this.config.timeoutMs}ms`),console.log(`[Monitor] SSE enabled: ${this.config.sseEnabled}`),console.log(`[Monitor] Dry run: ${this.config.dryRun}`),console.log(`[Monitor] Working directory: ${this.config.workingDirectory||process.cwd()}`),!await this.client.validateAuth())throw new Error("API key validation failed");console.log("[Monitor] API key validated successfully"),this.isRunning=!0,this.config.sseEnabled&&this.config.projectId?this.startSSE():this.config.sseEnabled&&!this.config.projectId&&console.log("[Monitor] SSE disabled - project ID required for client request monitoring"),await this.poll()}startSSE(){try{let e=this.client.getClientRequestMonitorUrl();console.log(`[Monitor] Connecting to SSE: ${e}`),this.sseClient=new re(e,this.client.getApiKey(),this.monitorId,{maxReconnectAttempts:10,reconnectDelayMs:5e3}),this.sseClient.onConnected(t=>{console.log(`[Monitor] SSE connected to project: ${t.projectName}`),console.log(`[Monitor] Active subscribers: ${t.subscriberCount}`),t.backlogTaskCount!==void 0&&console.log(`[Monitor] Backlog tasks available: ${t.backlogTaskCount}`)}),this.sseClient.onClientRequest(async t=>{await this.processClientRequest(t)}),this.sseClient.onTaskAvailable(async t=>{await this.handleTaskAvailable(t)}),this.sseClient.onError(t=>{console.error("[Monitor] SSE error:",t.message)}),this.sseClient.onDisconnected(()=>{console.log("[Monitor] SSE disconnected")}),this.sseClient.connect()}catch(e){console.error("[Monitor] Failed to start SSE:",e)}}async processClientRequest(e){if(this.isProcessingClientRequest){console.log("[Monitor] Already processing a client request, skipping");return}if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing client request: ${e.id}`),console.log(`[Monitor] Project: ${e.projectContext.projectName}`),console.log(`[Monitor] Description: ${e.description.substring(0,200)}${e.description.length>200?"...":""}`),console.log(`[Monitor] Timeout: ${this.config.clientRequestTimeoutMs}ms`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping client request processing");return}this.isProcessingClientRequest=!0;let t=Date.now();try{console.log("[Monitor] Running Claude for client request analysis..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let n=await rt(e,this.config.clientRequestTimeoutMs,{verbose:!0});console.log("-".repeat(60));let s=Date.now()-t;if(n.timedOut){console.log("[Monitor] Claude timed out for client request"),await this.client.reportAnalysisFailure(e.id,this.monitorId,"Analysis timed out");return}if(!n.success||!n.analysis){console.log(`[Monitor] Claude analysis failed: ${n.error}`),await this.client.reportAnalysisFailure(e.id,this.monitorId,n.error||"Unknown error");return}console.log("[Monitor] Submitting analysis...");let o=await this.client.submitAnalysis(e.id,this.monitorId,n.analysis,s);console.log(`[Monitor] Analysis submitted successfully - ${o.tasksCount} tasks suggested (${s}ms)`)}catch(n){console.error("[Monitor] Error processing client request:",n);try{await this.client.reportAnalysisFailure(e.id,this.monitorId,n instanceof Error?n.message:"Unknown error")}catch(s){console.error("[Monitor] Failed to report analysis failure:",s)}}finally{this.isProcessingClientRequest=!1}}async handleTaskAvailable(e){console.log(`[Monitor] Task available: ${e.id} - ${e.title}`),this.backlogTaskQueue.some(t=>t.id===e.id)||(this.backlogTaskQueue.push(e),console.log(`[Monitor] Added to queue (${this.backlogTaskQueue.length} tasks in queue)`)),await this.processNextBacklogTask()}async processNextBacklogTask(){if(this.isProcessingBacklogTask){console.log("[Monitor] Already processing a backlog task");return}if(this.backlogTaskQueue.length===0){console.log("[Monitor] No backlog tasks in queue");return}let e=this.backlogTaskQueue.shift();if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing backlog task: ${e.id}`),console.log(`[Monitor] Title: ${e.title}`),console.log(`[Monitor] Type: ${e.type} | Priority: ${e.priority}`),console.log(`[Monitor] Estimated hours: ${e.estimatedHours||"N/A"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping backlog task processing"),this.backlogTaskQueue.length>0&&await this.processNextBacklogTask();return}this.isProcessingBacklogTask=!0;let t=Date.now();try{console.log("[Monitor] Claiming task..."),await this.client.claimTask(e.id,this.monitorId),console.log("[Monitor] Task claimed successfully"),console.log("[Monitor] Running Claude for backlog task..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let n=await at(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory});console.log("-".repeat(60));let s=Date.now()-t;if(n.timedOut){console.log("[Monitor] Claude timed out for backlog task"),await this.client.failBacklogTask(e.id,this.monitorId,"Task processing timed out",!0);return}if(!n.success){console.log(`[Monitor] Claude failed: ${n.error}`),await this.client.failBacklogTask(e.id,this.monitorId,n.error||"Unknown error",!0);return}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:n.output?.substring(0,1e3)||"Task completed by auto-monitor"}),console.log(`[Monitor] Task ${e.id} completed successfully (${s}ms)`)}catch(n){console.error("[Monitor] Error processing backlog task:",n);try{await this.client.failBacklogTask(e.id,this.monitorId,n instanceof Error?n.message:"Unknown error",!0)}catch(s){console.error("[Monitor] Failed to report task failure:",s)}}finally{this.isProcessingBacklogTask=!1,this.backlogTaskQueue.length>0&&(console.log(`[Monitor] ${this.backlogTaskQueue.length} more tasks in queue, processing next...`),await this.processNextBacklogTask())}}stop(){console.log("[Monitor] Stopping..."),this.isRunning=!1,this.pollTimeout&&(clearTimeout(this.pollTimeout),this.pollTimeout=null),this.sseClient&&(this.sseClient.disconnect(),this.sseClient=null)}async poll(){if(this.isRunning){try{this.isProcessing||await this.checkForTask()}catch(e){console.error("[Monitor] Poll error:",e)}this.isRunning&&(this.pollTimeout=setTimeout(()=>this.poll(),this.config.pollIntervalMs))}}async checkForTask(){console.log("[Monitor] Checking for eligible tasks...");let e=await this.client.getEligibleTask();if(!e){console.log("[Monitor] No eligible tasks found");return}if(console.log(`[Monitor] Found eligible task: ${e.title} (confidence: ${e.aiConfidence})`),this.config.dryRun){console.log("[Monitor] Dry run - skipping task processing");return}await this.processTask(e)}async processTask(e){this.isProcessing=!0;try{console.log(`[Monitor] Starting task: ${e.id}`);let t=await this.client.startTask(e.id);console.log(`[Monitor] Task started, run ID: ${t.runId}`),console.log("[Monitor] Invoking Claude...");let n=await it(e,this.config.timeoutMs);if(n.timedOut){console.log("[Monitor] Claude timed out"),await this.handleFailure(t.runId,e,"TIMEOUT",n.output,"Task processing timed out");return}if(!n.success){console.log(`[Monitor] Claude failed: ${n.error}`),await this.handleFailure(t.runId,e,"FAILED",n.output,n.error);return}console.log("[Monitor] Claude completed successfully"),await this.handleSuccess(t.runId,e,n.output)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,n){let o=n.length>5e3?`${n.substring(0,5e3)}...
|
|
31
|
+
`)}async function ut(n,e,t={}){let s=Ts(n),o=t.verbose??!0,r=t.workingDirectory||process.cwd();return o&&(console.log("[Claude] Starting backlog task processing..."),console.log("[Claude] Prompt length:",s.length,"characters"),console.log("[Claude] Working directory:",r)),w||(w=ie()),o&&console.log("[Claude] Claude path:",w),new Promise(i=>{let l="",a="",c=!1,u=!1;o&&console.log("[Claude] Spawning Claude CLI via shell with temp file...");let p=(0,re.join)((0,W.tmpdir)(),`claude-task-${Date.now()}.txt`);(0,j.writeFileSync)(p,s,"utf-8");let f=`cat "${p}" | ${w} --print --dangerously-skip-permissions`;o&&(console.log("[Claude] Temp file:",p),console.log("[Claude] Running via shell..."));let m=(0,G.spawn)("sh",["-c",f],{stdio:["pipe","pipe","pipe"],env:{...process.env,PWD:r},cwd:r});o&&console.log("[Claude] Shell process started with PID:",m.pid);let h=0,d=setInterval(()=>{if(o&&!c){let k=Math.floor((Date.now()-g)/1e3);l.length===h&&console.log(`[Claude] Still running... ${k}s elapsed, ${l.length} bytes output, waiting for response...`),h=l.length}},3e4),g=Date.now();m.stdin?.end();let y=()=>{try{(0,j.unlinkSync)(p),o&&console.log("[Claude] Temp file cleaned up")}catch{}},C=setTimeout(()=>{c=!0,u=!0,clearInterval(d),console.log("[Claude] Timeout reached, killing process..."),console.log(`[Claude] Output collected: ${l.length} characters`),l.length>0&&console.log(`[Claude] Last 500 chars of output: ${l.slice(-500)}`),a.length>0&&console.log(`[Claude] Stderr: ${a.substring(0,500)}`),m.kill("SIGTERM"),setTimeout(()=>{m.killed||m.kill("SIGKILL")},5e3)},e);m.stdout?.on("data",k=>{let T=k.toString();l+=T,o&&process.stdout.write(T)}),m.stderr?.on("data",k=>{let T=k.toString();a+=T,o&&process.stderr.write(`[Claude stderr] ${T}`)}),m.on("close",(k,T)=>{clearTimeout(C),clearInterval(d),y(),o&&(console.log(""),console.log(`[Claude] Process exited with code ${k}, signal ${T}`),console.log(`[Claude] Output length: ${l.length} characters`),a&&console.log(`[Claude] Stderr: ${a.substring(0,1e3)}`));let R=l.includes("TASK_COMPLETE"),O=l.match(/TASK_BLOCKED:\s*(.+)/);if(c&&!R){i({success:!1,output:l,error:"Process timed out",timedOut:!0});return}if(O){i({success:!1,output:l,error:`Task blocked: ${O[1]}`,timedOut:!1});return}if(k!==0&&!u){i({success:!1,output:l,error:a||`Process exited with code ${k}`,timedOut:!1});return}i({success:!0,output:l,timedOut:!1})}),m.on("error",k=>{clearTimeout(C),clearInterval(d),y(),console.error("[Claude] Spawn error:",k),i({success:!1,output:l,error:`Failed to spawn claude: ${k.message}`,timedOut:!1})}),m.on("spawn",()=>{o&&console.log("[Claude] Process spawned successfully")})})}var ae=require("@anthropic-ai/claude-agent-sdk");function Os(n,e){let t=e;switch(n){case"Read":return{emoji:"\u{1F4D6}",message:`Reading file: ${t?.file_path||"unknown"}`};case"Write":return{emoji:"\u270F\uFE0F",message:`Writing file: ${t?.file_path||"unknown"}`};case"Edit":return{emoji:"\u{1F4DD}",message:`Editing file: ${t?.file_path||"unknown"}`};case"Glob":return{emoji:"\u{1F50D}",message:`Searching for files: ${t?.pattern||"unknown pattern"}`};case"Grep":return{emoji:"\u{1F50E}",message:`Searching code: ${t?.pattern||"unknown pattern"}`};case"Bash":return{emoji:"\u{1F4BB}",message:`Running command: ${String(t?.command||"").substring(0,80)}${String(t?.command||"").length>80?"...":""}`};case"WebSearch":return{emoji:"\u{1F310}",message:`Web search: ${t?.query||"unknown query"}`};case"WebFetch":return{emoji:"\u{1F310}",message:`Fetching URL: ${t?.url||"unknown"}`};case"Task":return{emoji:"\u{1F916}",message:`Running sub-agent: ${t?.description||"task"}`};case"TodoWrite":return{emoji:"\u{1F4CB}",message:"Updating task list"};default:return{emoji:"\u{1F527}",message:`Using tool: ${n}`}}}function Pe(n){let e={type:n.type,timestamp:n.timestamp};switch(n.type){case"tool_start":{let t=n.data,{message:s,emoji:o}=Os(t.tool,t.input);return{...e,emoji:o,message:s,data:{toolUseId:t.toolUseId,tool:t.tool}}}case"tool_end":{let t=n.data;return{...e,emoji:t.isError?"\u274C":"\u2705",message:t.isError?"Tool failed":"Tool completed",data:{toolUseId:t.toolUseId}}}case"thinking":{let t=n.data,s=t.text.substring(0,150);return{...e,emoji:"\u{1F4AD}",message:`${s}${t.text.length>150?"...":""}`}}case"assistant_message":{let t=n.data,s=t.text.substring(0,200);return{...e,emoji:"\u{1F4AC}",message:`${s}${t.text.length>200?"...":""}`,data:{text:t.text,uuid:t.uuid}}}case"result":{let t=n.data;return{...e,emoji:t.success?"\u{1F389}":"\u26A0\uFE0F",message:t.success?"Analysis complete":"Analysis completed with issues",data:t}}case"error":{let t=n.data;return{...e,emoji:"\u2757",message:`Error: ${t.error}`,data:t}}case"session_start":return{...e,emoji:"\u{1F680}",message:"Starting analysis..."};case"processing":{let t=n.data;return{...e,emoji:"\u23F3",message:t.message||`Processing... (${Math.round((t.elapsedMs||0)/1e3)}s)`,data:t}}default:return{...e,emoji:"\u2139\uFE0F",message:`Event: ${n.type}`,data:n.data}}}function Ss(n){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",n.description,"","## Project Context","",`**Project Name:** ${n.projectContext.projectName}`];return n.projectContext.projectDescription&&e.push(`**Description:** ${n.projectContext.projectDescription}`),n.projectContext.techStack&&n.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${n.projectContext.techStack.join(", ")}`),n.projectContext.existingFeatures&&n.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),n.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
|
|
32
|
+
`)}function pt(n){let e=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=n.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function dt(n,e={}){let{timeoutMs:t=3e5,verbose:s=!0,workingDirectory:o,onEvent:r}=e,i=o||process.cwd(),l=Ss(n),a=Date.now(),c="",u=!1;s&&(console.log("[Agent] Starting analysis with Claude Agent SDK..."),console.log("[Agent] Prompt length:",l.length,"characters"),console.log("[Agent] Working directory:",i),console.log("[Agent] Model: claude-opus-4-5-20250929"));let p=new AbortController,f=setTimeout(()=>{u=!0,p.abort(),s&&console.log("[Agent] Timeout reached, aborting...")},t),m=(h,d)=>{r&&r({type:h,timestamp:Date.now(),data:d})};m("session_start",{prompt:l.substring(0,200),cwd:i});try{let h=(0,ae.query)({prompt:l,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits"}});for await(let d of h)switch(d.type){case"assistant":if(d.message.content){for(let y of d.message.content)if(y.type==="text")c+=y.text,s&&process.stdout.write(y.text),m("assistant_message",{text:y.text,uuid:d.uuid});else if(y.type==="thinking"){let C=y;s&&console.log(`[Agent] Thinking: ${C.thinking.substring(0,100)}...`),m("thinking",{text:C.thinking,uuid:d.uuid})}else if(y.type==="tool_use"||"name"in y){let C=y;s&&console.log(`[Agent] Tool: ${C.name}`),m("tool_start",{tool:C.name,toolUseId:C.id,input:C.input})}}break;case"user":if(d.message.content){for(let y of d.message.content)if(typeof y=="object"&&y!==null&&"type"in y&&y.type==="tool_result"){let C=y;m("tool_end",{toolUseId:C.tool_use_id,isError:C.is_error||!1,hasContent:!!C.content})}}break;case"result":s&&(console.log(""),console.log(`[Agent] Completed in ${d.duration_ms}ms`),console.log(`[Agent] Cost: $${d.total_cost_usd?.toFixed(4)||"N/A"}`)),clearTimeout(f);let g=pt(c);if(g&&g.summary&&Array.isArray(g.suggestedTasks))return m("result",{success:!0,analysis:g,costUsd:d.total_cost_usd,usage:d.usage}),{success:!0,analysis:g,output:c,timedOut:!1,totalCostUsd:d.total_cost_usd,usage:d.usage?{inputTokens:d.usage.input_tokens,outputTokens:d.usage.output_tokens}:void 0};if(d.subtype!=="success"){let y="result"in d?d.result:d.subtype;return m("error",{error:d.subtype,result:y}),{success:!1,output:c,error:`Agent error: ${d.subtype} - ${y}`,timedOut:!1,totalCostUsd:d.total_cost_usd}}return{success:!1,output:c,error:"Failed to parse analysis JSON from output",timedOut:!1,totalCostUsd:d.total_cost_usd}}return clearTimeout(f),{success:!1,output:c,error:"Query stream ended without result",timedOut:u}}catch(h){clearTimeout(f);let d=h instanceof Error?h.message:String(h);s&&console.error("[Agent] Error:",d),m("error",{error:d});let g=pt(c);return g&&g.summary&&Array.isArray(g.suggestedTasks)?(s&&console.log("[Agent] Got valid output despite error - treating as success"),{success:!0,analysis:g,output:c,timedOut:!1}):{success:!1,output:c,error:u?"Process timed out":d,timedOut:u}}}function Is(n){let e=[`# Task: ${n.title}`,"",`**Project:** ${n.projectContext.projectName}`,`**Priority:** ${n.priority}`,`**Type:** ${n.type}`,`**Estimated Hours:** ${n.estimatedHours||"N/A"}`,"","## Description",n.description||"No description provided.",""];if(n.acceptanceCriteria&&n.acceptanceCriteria.length>0&&(e.push("## Acceptance Criteria"),n.acceptanceCriteria.forEach((t,s)=>{e.push(`${s+1}. ${t}`)}),e.push("")),n.technicalNotes&&(e.push("## Technical Notes"),e.push(n.technicalNotes),e.push("")),n.projectContext.projectDescription&&(e.push("## Project Description"),e.push(n.projectContext.projectDescription),e.push("")),n.projectContext.knowledgeBase){e.push("## Project Knowledge Base");let t=n.projectContext.knowledgeBase;t.length>1e4?e.push(t.substring(0,1e4)+`
|
|
32
33
|
|
|
33
|
-
[
|
|
34
|
+
[... truncated ...]`):e.push(t),e.push("")}return e.push("---"),e.push(""),e.push("Please work on this task. Implement the required changes according to the acceptance criteria."),e.push(""),e.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),e.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),e.join(`
|
|
35
|
+
`)}async function ht(n,e={}){let{timeoutMs:t=6e5,verbose:s=!0,workingDirectory:o,onEvent:r}=e,i=o||process.cwd(),l=Is(n),a=Date.now(),c="",u=!1;s&&(console.log("[Agent] Starting backlog task with Claude Agent SDK..."),console.log("[Agent] Task:",n.title),console.log("[Agent] Working directory:",i),console.log("[Agent] Model: claude-opus-4-5-20250929"));let p=new AbortController,f=setTimeout(()=>{u=!0,p.abort(),s&&console.log("[Agent] Timeout reached, aborting...")},t),m=(h,d)=>{r&&r({type:h,timestamp:Date.now(),data:d})};m("session_start",{task:n.title,cwd:i});try{let h=(0,ae.query)({prompt:l,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","Write"],permissionMode:"acceptEdits"}});for await(let d of h)switch(d.type){case"assistant":if(d.message.content){for(let C of d.message.content)if(C.type==="text")c+=C.text,s&&process.stdout.write(C.text);else if("name"in C){let k=C;s&&console.log(`[Agent] Tool: ${k.name}`),m("tool_start",{tool:k.name,toolUseId:k.id,input:k.input})}}break;case"result":clearTimeout(f),s&&(console.log(""),console.log(`[Agent] Completed in ${d.duration_ms}ms`),console.log(`[Agent] Cost: $${d.total_cost_usd?.toFixed(4)||"N/A"}`));let g=c.includes("TASK_COMPLETE"),y=c.match(/TASK_BLOCKED:\s*(.+)/);return y?{success:!1,output:c,error:`Task blocked: ${y[1]}`,timedOut:!1,totalCostUsd:d.total_cost_usd}:{success:g||d.subtype==="success",output:c,timedOut:!1,totalCostUsd:d.total_cost_usd}}return clearTimeout(f),{success:!1,output:c,error:"Query stream ended without result",timedOut:u}}catch(h){clearTimeout(f);let d=h instanceof Error?h.message:String(h);return s&&console.error("[Agent] Error:",d),m("error",{error:d}),{success:!1,output:c,error:u?"Process timed out":d,timedOut:u}}}async function gt(){try{return!0}catch{return!1}}function mt(n){return n.includes("[CONVERSATIONAL SESSION]")}function $s(n){let t=n.replace("[CONVERSATIONAL SESSION]","").trim().split(/\n---\nUser follow-up:\n/);if(t.length===1){let r=t[0].replace(/^User message:\s*/i,"").trim();return{initialMessage:r,followUps:[],latestMessage:r,isFollowUp:!1}}let s=t[0].replace(/^User message:\s*/i,"").trim(),o=t.slice(1).map(r=>r.trim());return{initialMessage:s,followUps:o,latestMessage:o[o.length-1],isFollowUp:!0}}function Ps(n){let e=$s(n.description),t=["You are a helpful assistant for a project management platform. You are having a conversation with a user who wants to discuss and create tasks for their project.","",`**Project Name:** ${n.projectContext.projectName}`];return n.projectContext.projectDescription&&t.push(`**Project Description:** ${n.projectContext.projectDescription}`),n.projectContext.techStack&&n.projectContext.techStack.length>0&&t.push(`**Tech Stack:** ${n.projectContext.techStack.join(", ")}`),t.push(""),t.push("---"),t.push(""),e.isFollowUp?(t.push("## Conversation History"),t.push(""),t.push("This is an ongoing conversation. Here is what was discussed:"),t.push(""),t.push(`**Initial request:** ${e.initialMessage}`),t.push(""),e.followUps.length>1&&(t.push("**Previous follow-ups:**"),e.followUps.slice(0,-1).forEach((s,o)=>{t.push(`${o+1}. ${s}`)}),t.push("")),t.push("---"),t.push(""),t.push("## Latest Message (respond to this)"),t.push(""),t.push(e.latestMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("This is a FOLLOW-UP message in an ongoing conversation. The user is continuing a previous discussion."),t.push(`DO NOT start over or re-introduce yourself. DO NOT say "I'll help you with..." as if this is a new request.`),t.push("Simply respond directly to their latest message, building on the context of the conversation."),t.push(""),t.push("If you already explored the codebase in a previous turn, you do NOT need to explore it again unless the user asks about something new."),t.push(""),t.push("**Refinement mode:** If the user is providing feedback on suggested tasks, immediately update or regenerate the tasks with their input. Don't ask additional clarifying questions unless they specifically ask for options.")):(t.push("## User's Message"),t.push(""),t.push(e.initialMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("You have access to the full codebase, so explore it to understand the project structure."),t.push(""),t.push("**Your goal is to generate actionable tasks within this first exchange.** Don't spend time asking qualifying questions - use the codebase and project context to make informed assumptions. Briefly explore relevant files if needed, then propose concrete tasks."),t.push(""),t.push("The client should feel like their work is being shaped into actionable items immediately, not that they're entering an interview process.")),t.push(""),t.push("## Task Generation Approach"),t.push(""),t.push("**IMPORTANT: Prioritize generating tasks quickly.** Clients want to feel like work is starting immediately."),t.push(""),t.push("- Generate initial task suggestions within your FIRST response whenever possible"),t.push("- Make reasonable assumptions based on the project context and codebase - don't ask questions you can answer yourself"),t.push("- If something is unclear, make a sensible default assumption, note it in the task, and let the client refine it"),t.push("- Only ask 1-2 critical questions if absolutely essential - prefer to suggest tasks with noted assumptions"),t.push("- Tasks can always be refined through follow-up conversation - the goal is momentum, not perfection"),t.push(""),t.push("When you identify work that should become a task, output it in this format:"),t.push("<task>"),t.push("{"),t.push(' "title": "Task title",'),t.push(' "description": "What needs to be done",'),t.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),t.push(' "estimatedHours": 4,'),t.push(' "priority": "MEDIUM",'),t.push(' "type": "FEATURE",'),t.push(' "technicalNotes": "Implementation notes (include any assumptions made)",'),t.push(' "aiConfidence": 0.85'),t.push("}"),t.push("</task>"),t.push(""),t.push('Include an "assumptions" section in technicalNotes if you made decisions the client might want to change.'),t.push(`After suggesting tasks, invite the client to refine: "These tasks are ready for review. Let me know if you'd like to adjust scope, estimates, or approach."`),t.push(""),t.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),t.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),t.join(`
|
|
36
|
+
`)}function xs(n){let e=[],t=n.includes("<task>")&&n.includes("</task>");if(console.log(`[Agent] parseTasksFromOutput: hasTaskTags=${t}, outputLength=${n.length}`),!t)return console.log("[Agent] No <task> tags found in output"),e;let s=/<task>([\s\S]*?)<\/task>/g,o;for(;(o=s.exec(n))!==null;){console.log("[Agent] Found task block, parsing JSON...");try{let r=JSON.parse(o[1].trim());console.log(`[Agent] Parsed task: ${r.title}`),e.push({title:r.title||"Untitled Task",description:r.description||"",acceptanceCriteria:r.acceptanceCriteria||[],estimatedHours:r.estimatedHours||4,priority:r.priority||"MEDIUM",type:r.type||"FEATURE",technicalNotes:r.technicalNotes,aiConfidence:r.aiConfidence||r.confidence||.8})}catch(r){console.error("[Agent] Failed to parse task JSON:",r),console.error("[Agent] Task content:",o[1].substring(0,200))}}return console.log(`[Agent] parseTasksFromOutput: returning ${e.length} tasks`),e}async function ft(n,e={}){let{timeoutMs:t=3e5,verbose:s=!0,workingDirectory:o,onEvent:r}=e,i=o||process.cwd(),l=Ps(n),a="",c=!1;s&&(console.log("[Agent] Starting conversational session..."),console.log("[Agent] Working directory:",i));let u=new AbortController,p=setTimeout(()=>{c=!0,u.abort(),s&&console.log("[Agent] Timeout reached, aborting...")},t),f=(m,h)=>{r&&r({type:m,timestamp:Date.now(),data:h})};f("session_start",{cwd:i});try{let m=(0,ae.query)({prompt:l,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits"}});for await(let h of m)switch(h.type){case"assistant":if(h.message.content){for(let g of h.message.content)if(g.type==="text")a+=g.text,s&&process.stdout.write(g.text),f("assistant_message",{text:g.text,uuid:h.uuid});else if(g.type==="thinking"){let y=g;s&&console.log(`[Agent] Thinking: ${y.thinking.substring(0,100)}...`),f("thinking",{text:y.thinking,uuid:h.uuid})}else if(g.type==="tool_use"||"name"in g){let y=g;s&&console.log(`[Agent] Tool: ${y.name}`),f("tool_start",{tool:y.name,toolUseId:y.id,input:y.input})}}break;case"user":if(h.message.content){for(let g of h.message.content)if(typeof g=="object"&&g!==null&&"type"in g&&g.type==="tool_result"){let y=g;f("tool_end",{toolUseId:y.tool_use_id,isError:y.is_error||!1,hasContent:!!y.content})}}break;case"result":clearTimeout(p),s&&(console.log(""),console.log(`[Agent] Completed in ${h.duration_ms}ms`),console.log(`[Agent] Cost: $${h.total_cost_usd?.toFixed(4)||"N/A"}`));let d=xs(a);return s&&d.length>0&&console.log(`[Agent] Found ${d.length} task(s) in output`),f("result",{success:!0,output:a,tasks:d,costUsd:h.total_cost_usd}),{success:!0,output:a,tasks:d,timedOut:!1,totalCostUsd:h.total_cost_usd}}return clearTimeout(p),{success:!1,output:a,tasks:[],error:"Query stream ended without result",timedOut:c}}catch(m){clearTimeout(p);let h=m instanceof Error?m.message:String(m);return s&&console.error("[Agent] Error:",h),f("error",{error:h}),{success:!1,output:a,tasks:[],error:c?"Process timed out":h,timedOut:c}}}var xe=he(Et(),1),le=class{eventSource=null;url;apiKey;monitorId;reconnectAttempts=0;maxReconnectAttempts;reconnectDelayMs;reconnectTimer=null;isConnecting=!1;isStopped=!1;onClientRequestHandler=null;onConversationMessageHandler=null;onTaskAvailableHandler=null;onConnectedHandler=null;onErrorHandler=null;onDisconnectedHandler=null;constructor(e,t,s,o={}){this.url=e,this.apiKey=t,this.monitorId=s,this.maxReconnectAttempts=o.maxReconnectAttempts??10,this.reconnectDelayMs=o.reconnectDelayMs??5e3}connect(){if(this.isConnecting||this.eventSource){console.log("[SSE] Already connected or connecting");return}this.isStopped=!1,this.isConnecting=!0;let e=`${this.url}?monitorId=${encodeURIComponent(this.monitorId)}`;console.log(`[SSE] Connecting to ${e}`),this.eventSource=new xe.default(e,{headers:{Authorization:`Bearer ${this.apiKey}`}}),this.eventSource.onopen=()=>{console.log("[SSE] Connection opened"),this.isConnecting=!1,this.reconnectAttempts=0},this.eventSource.addEventListener("connected",t=>{try{let s=JSON.parse(t.data);console.log(`[SSE] Connected to project: ${s.projectName}`),this.onConnectedHandler&&this.onConnectedHandler(s)}catch(s){console.error("[SSE] Error parsing connected event:",s)}}),this.eventSource.addEventListener("client_request_created",t=>{try{let s=JSON.parse(t.data);console.log(`[SSE] Received client request: ${s.requestId}`),this.onClientRequestHandler&&this.onClientRequestHandler(s.data)}catch(s){console.error("[SSE] Error parsing client_request_created event:",s)}}),this.eventSource.addEventListener("task_available",t=>{try{let s=JSON.parse(t.data);console.log(`[SSE] Received task available: ${s.taskId} - ${s.data.title}`),this.onTaskAvailableHandler&&this.onTaskAvailableHandler(s.data)}catch(s){console.error("[SSE] Error parsing task_available event:",s)}}),this.eventSource.addEventListener("conversation_message",t=>{try{let s=JSON.parse(t.data);console.log(`[SSE] Received conversation message for request: ${s.requestId}`),this.onConversationMessageHandler&&this.onConversationMessageHandler(s.data)}catch(s){console.error("[SSE] Error parsing conversation_message event:",s)}}),this.eventSource.onerror=t=>{console.error("[SSE] Connection error:",t),this.isConnecting=!1,this.onErrorHandler&&this.onErrorHandler(new Error("SSE connection error")),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.onDisconnectedHandler&&this.onDisconnectedHandler(),this.scheduleReconnect()}}scheduleReconnect(){if(this.isStopped){console.log("[SSE] Reconnection cancelled - client stopped");return}if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error(`[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached`),this.onErrorHandler&&this.onErrorHandler(new Error("Max reconnection attempts reached"));return}this.reconnectAttempts++;let e=Math.min(this.reconnectDelayMs*Math.pow(2,this.reconnectAttempts-1),6e4);console.log(`[SSE] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.connect()},e)}disconnect(){console.log("[SSE] Disconnecting"),this.isStopped=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.onDisconnectedHandler&&this.onDisconnectedHandler()}isConnected(){return this.eventSource?.readyState===xe.default.OPEN}onClientRequest(e){this.onClientRequestHandler=e}onConversationMessage(e){this.onConversationMessageHandler=e}onTaskAvailable(e){this.onTaskAvailableHandler=e}onConnected(e){this.onConnectedHandler=e}onError(e){this.onErrorHandler=e}onDisconnected(e){this.onDisconnectedHandler=e}};var _t=require("crypto"),ce=class{client;config;isProcessing=!1;isProcessingClientRequest=!1;isProcessingBacklogTask=!1;isRunning=!1;pollTimeout=null;sseClient=null;monitorId;backlogTaskQueue=[];constructor(e){this.config=e,this.client=new oe(e.apiUrl,e.apiKey,e.projectId),this.monitorId=`monitor-${(0,_t.randomBytes)(8).toString("hex")}`}async start(){if(this.isRunning){console.log("[Monitor] Already running");return}if(console.log("[Monitor] Starting auto-task monitor..."),console.log(`[Monitor] Monitor ID: ${this.monitorId}`),console.log(`[Monitor] API URL: ${this.config.apiUrl}`),console.log(`[Monitor] Project ID: ${this.config.projectId||"all projects"}`),console.log(`[Monitor] Poll interval: ${this.config.pollIntervalMs}ms`),console.log(`[Monitor] Task timeout: ${this.config.timeoutMs}ms`),console.log(`[Monitor] SSE enabled: ${this.config.sseEnabled}`),console.log(`[Monitor] Dry run: ${this.config.dryRun}`),console.log(`[Monitor] Working directory: ${this.config.workingDirectory||process.cwd()}`),console.log(`[Monitor] Use Agent SDK: ${this.config.useAgentSdk}`),console.log(`[Monitor] Stream progress: ${this.config.streamProgress}`),console.log(`[Monitor] Conversation only: ${this.config.conversationOnly}`),!await this.client.validateAuth())throw new Error("API key validation failed");console.log("[Monitor] API key validated successfully"),this.isRunning=!0,this.config.sseEnabled&&this.config.projectId?this.startSSE():this.config.sseEnabled&&!this.config.projectId&&console.log("[Monitor] SSE disabled - project ID required for client request monitoring"),this.config.conversationOnly?console.log("[Monitor] Conversation-only mode - skipping auto-task polling"):await this.poll()}startSSE(){try{let e=this.client.getClientRequestMonitorUrl();console.log(`[Monitor] Connecting to SSE: ${e}`),this.sseClient=new le(e,this.client.getApiKey(),this.monitorId,{maxReconnectAttempts:10,reconnectDelayMs:5e3}),this.sseClient.onConnected(t=>{console.log(`[Monitor] SSE connected to project: ${t.projectName}`),console.log(`[Monitor] Active subscribers: ${t.subscriberCount}`),t.backlogTaskCount!==void 0&&console.log(`[Monitor] Backlog tasks available: ${t.backlogTaskCount}`)}),this.sseClient.onClientRequest(async t=>{await this.processClientRequest(t)}),this.sseClient.onTaskAvailable(async t=>{await this.handleTaskAvailable(t)}),this.sseClient.onConversationMessage(async t=>{await this.handleConversationMessage(t)}),this.sseClient.onError(t=>{console.error("[Monitor] SSE error:",t.message)}),this.sseClient.onDisconnected(()=>{console.log("[Monitor] SSE disconnected")}),this.sseClient.connect()}catch(e){console.error("[Monitor] Failed to start SSE:",e)}}async processClientRequest(e){if(this.isProcessingClientRequest){console.log("[Monitor] Already processing a client request, skipping");return}let t=mt(e.description);if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing client request: ${e.id}`),console.log(`[Monitor] Project: ${e.projectContext.projectName}`),console.log(`[Monitor] Mode: ${t?"Conversational":"Analysis"}`),console.log(`[Monitor] Description: ${e.description.substring(0,200)}${e.description.length>200?"...":""}`),console.log(`[Monitor] Timeout: ${this.config.clientRequestTimeoutMs}ms`),console.log(`[Monitor] SDK Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping client request processing");return}if(this.config.conversationOnly&&!t){console.log("[Monitor] Conversation-only mode - skipping non-conversational request analysis");return}this.isProcessingClientRequest=!0;let s=Date.now(),o=Date.now(),r="session_start",i=null;this.config.streamProgress&&(i=setInterval(async()=>{let l=Date.now()-o,a=Date.now()-s;if(l>5e3)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"processing",timestamp:Date.now(),message:r==="tool_end"?`Analyzing results... (${Math.round(a/1e3)}s)`:`Processing... (${Math.round(a/1e3)}s)`,emoji:"\u23F3",data:{elapsedMs:a,lastEventType:r,timeSinceLastEventMs:l}})}catch{}},5e3));try{console.log(`[Monitor] Running Claude for ${t?"conversation":"analysis"}...`),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let l=this.config.streamProgress?async p=>{o=Date.now(),r=p.type;let f=Pe(p);console.log(`[Monitor] ${f.emoji} ${f.message}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,f)}catch(m){console.error("[Monitor] Failed to send progress event:",m)}}:void 0;if(t&&this.config.useAgentSdk){let p=await ft(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:l});console.log("-".repeat(60));let f=Date.now()-s;if(p.totalCostUsd&&console.log(`[Monitor] Agent cost: $${p.totalCostUsd.toFixed(4)}`),p.timedOut){console.log("[Monitor] Claude timed out for conversation");try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:"Conversation timed out",emoji:"\u23F1\uFE0F",data:{error:"timeout",message:"The agent took too long to respond"}})}catch(m){console.error("[Monitor] Failed to send timeout event:",m)}return}if(!p.success){console.log(`[Monitor] Conversation error: ${p.error}`);try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"error",timestamp:Date.now(),message:p.error||"Unknown error",emoji:"\u274C",data:{error:p.error}})}catch(m){console.error("[Monitor] Failed to send error event:",m)}return}if(console.log(`[Monitor] Conversation completed (${f}ms)`),console.log(`[Monitor] Result has ${p.tasks?.length||0} tasks`),p.tasks&&p.tasks.length>0){console.log(`[Monitor] Sending ${p.tasks.length} suggested task(s) to frontend`);for(let m of p.tasks)try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"task_suggested",timestamp:Date.now(),message:`Task suggested: ${m.title}`,emoji:"\u{1F4CB}",data:{task:m}}),console.log(`[Monitor] \u{1F4CB} Sent task: ${m.title}`)}catch(h){console.error("[Monitor] Failed to send task_suggested event:",h)}}try{await this.client.sendAgentProgress(e.id,this.monitorId,{type:"result",timestamp:Date.now(),message:`Conversation completed with ${p.tasks?.length||0} task(s)`,emoji:"\u2705",data:{success:!0,tasksCount:p.tasks?.length||0,processingTimeMs:f}}),console.log("[Monitor] \u2705 Sent result event")}catch(m){console.error("[Monitor] Failed to send result event:",m)}return}let a;this.config.useAgentSdk?(a=await dt(e,{timeoutMs:this.config.clientRequestTimeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:l}),a.totalCostUsd&&console.log(`[Monitor] Agent cost: $${a.totalCostUsd.toFixed(4)}`)):a=await ct(e,this.config.clientRequestTimeoutMs,{verbose:!0}),console.log("-".repeat(60));let c=Date.now()-s;if(a.timedOut){console.log("[Monitor] Claude timed out for client request"),await this.client.reportAnalysisFailure(e.id,this.monitorId,"Analysis timed out");return}if(!a.success||!a.analysis){console.log(`[Monitor] Claude analysis failed: ${a.error}`),await this.client.reportAnalysisFailure(e.id,this.monitorId,a.error||"Unknown error");return}console.log("[Monitor] Submitting analysis...");let u=await this.client.submitAnalysis(e.id,this.monitorId,a.analysis,c);console.log(`[Monitor] Analysis submitted successfully - ${u.tasksCount} tasks suggested (${c}ms)`)}catch(l){console.error("[Monitor] Error processing client request:",l);try{await this.client.reportAnalysisFailure(e.id,this.monitorId,l instanceof Error?l.message:"Unknown error")}catch(a){console.error("[Monitor] Failed to report analysis failure:",a)}}finally{i&&clearInterval(i),this.isProcessingClientRequest=!1}}async handleTaskAvailable(e){if(console.log(`[Monitor] Task available: ${e.id} - ${e.title}`),this.config.conversationOnly){console.log("[Monitor] Conversation-only mode - skipping task processing");return}this.backlogTaskQueue.some(t=>t.id===e.id)||(this.backlogTaskQueue.push(e),console.log(`[Monitor] Added to queue (${this.backlogTaskQueue.length} tasks in queue)`)),await this.processNextBacklogTask()}async handleConversationMessage(e){console.log(`[Monitor] Conversation message for request: ${e.requestId}`),console.log(`[Monitor] Message: ${e.message.substring(0,100)}${e.message.length>100?"...":""}`);try{let t=await this.client.getClientRequest(e.requestId);if(!t){console.error(`[Monitor] Client request ${e.requestId} not found`);return}let s={id:t.id,projectId:t.projectId,description:t.description,channel:t.channel,createdById:t.createdById,projectContext:t.projectContext||{projectName:"Unknown Project"}};await this.processClientRequest(s)}catch(t){console.error("[Monitor] Error handling conversation message:",t)}}async processNextBacklogTask(){if(this.isProcessingBacklogTask){console.log("[Monitor] Already processing a backlog task");return}if(this.backlogTaskQueue.length===0){console.log("[Monitor] No backlog tasks in queue");return}let e=this.backlogTaskQueue.shift();if(console.log(""),console.log("=".repeat(60)),console.log(`[Monitor] Processing backlog task: ${e.id}`),console.log(`[Monitor] Title: ${e.title}`),console.log(`[Monitor] Type: ${e.type} | Priority: ${e.priority}`),console.log(`[Monitor] Estimated hours: ${e.estimatedHours||"N/A"}`),console.log(`[Monitor] Mode: ${this.config.useAgentSdk?"Agent SDK":"CLI subprocess"}`),console.log("=".repeat(60)),console.log(""),this.config.dryRun){console.log("[Monitor] Dry run - skipping backlog task processing"),this.backlogTaskQueue.length>0&&await this.processNextBacklogTask();return}this.isProcessingBacklogTask=!0;let t=Date.now();try{console.log("[Monitor] Claiming task..."),await this.client.claimTask(e.id,this.monitorId),console.log("[Monitor] Task claimed successfully"),console.log("[Monitor] Running Claude for backlog task..."),console.log("[Monitor] Claude output will stream below:"),console.log("-".repeat(60));let s;this.config.useAgentSdk?(s=await ht(e,{timeoutMs:this.config.timeoutMs,verbose:!0,workingDirectory:this.config.workingDirectory,onEvent:this.config.streamProgress?async r=>{let i=Pe(r);console.log(`[Monitor] ${i.emoji} ${i.message}`);try{await this.client.sendTaskAgentProgress(e.id,this.monitorId,i)}catch(l){console.error("[Monitor] Failed to send progress event:",l)}}:void 0}),s.totalCostUsd&&console.log(`[Monitor] Agent cost: $${s.totalCostUsd.toFixed(4)}`)):s=await ut(e,this.config.timeoutMs,{verbose:!0,workingDirectory:this.config.workingDirectory}),console.log("-".repeat(60));let o=Date.now()-t;if(s.timedOut){console.log("[Monitor] Claude timed out for backlog task"),await this.client.failBacklogTask(e.id,this.monitorId,"Task processing timed out",!0);return}if(!s.success){console.log(`[Monitor] Claude failed: ${s.error}`),await this.client.failBacklogTask(e.id,this.monitorId,s.error||"Unknown error",!0);return}console.log("[Monitor] Completing task..."),await this.client.completeBacklogTask(e.id,this.monitorId,{summary:s.output?.substring(0,1e3)||"Task completed by auto-monitor"}),console.log(`[Monitor] Task ${e.id} completed successfully (${o}ms)`)}catch(s){console.error("[Monitor] Error processing backlog task:",s);try{await this.client.failBacklogTask(e.id,this.monitorId,s instanceof Error?s.message:"Unknown error",!0)}catch(o){console.error("[Monitor] Failed to report task failure:",o)}}finally{this.isProcessingBacklogTask=!1,this.backlogTaskQueue.length>0&&(console.log(`[Monitor] ${this.backlogTaskQueue.length} more tasks in queue, processing next...`),await this.processNextBacklogTask())}}stop(){console.log("[Monitor] Stopping..."),this.isRunning=!1,this.pollTimeout&&(clearTimeout(this.pollTimeout),this.pollTimeout=null),this.sseClient&&(this.sseClient.disconnect(),this.sseClient=null)}async poll(){if(this.isRunning){try{this.isProcessing||await this.checkForTask()}catch(e){console.error("[Monitor] Poll error:",e)}this.isRunning&&(this.pollTimeout=setTimeout(()=>this.poll(),this.config.pollIntervalMs))}}async checkForTask(){console.log("[Monitor] Checking for eligible tasks...");let e=await this.client.getEligibleTask();if(!e){console.log("[Monitor] No eligible tasks found");return}if(console.log(`[Monitor] Found eligible task: ${e.title} (confidence: ${e.aiConfidence})`),this.config.dryRun){console.log("[Monitor] Dry run - skipping task processing");return}await this.processTask(e)}async processTask(e){this.isProcessing=!0;try{console.log(`[Monitor] Starting task: ${e.id}`);let t=await this.client.startTask(e.id);console.log(`[Monitor] Task started, run ID: ${t.runId}`),console.log("[Monitor] Invoking Claude...");let s=await at(e,this.config.timeoutMs);if(s.timedOut){console.log("[Monitor] Claude timed out"),await this.handleFailure(t.runId,e,"TIMEOUT",s.output,"Task processing timed out");return}if(!s.success){console.log(`[Monitor] Claude failed: ${s.error}`),await this.handleFailure(t.runId,e,"FAILED",s.output,s.error);return}console.log("[Monitor] Claude completed successfully"),await this.handleSuccess(t.runId,e,s.output)}catch(t){console.error("[Monitor] Error processing task:",t)}finally{this.isProcessing=!1}}async handleSuccess(e,t,s){let r=s.length>5e3?`${s.substring(0,5e3)}...
|
|
37
|
+
|
|
38
|
+
[Output truncated]`:s;await this.client.completeTask(e,"COMPLETED",{comment:`## Auto-Task Completed
|
|
34
39
|
|
|
35
|
-
${
|
|
40
|
+
${r}`}),console.log(`[Monitor] Task ${t.id} completed and moved to IN_REVIEW`)}async handleFailure(e,t,s,o,r){let l=o.length>3e3?`${o.substring(0,3e3)}...
|
|
36
41
|
|
|
37
|
-
[Output truncated]`:
|
|
38
|
-
`);await this.client.completeTask(e,
|
|
42
|
+
[Output truncated]`:o,a=[`## Auto-Task ${s==="TIMEOUT"?"Timed Out":"Failed"}`,"",r?`**Error:** ${r}`:"","","### Output","```",l,"```"].filter(Boolean).join(`
|
|
43
|
+
`);await this.client.completeTask(e,s,{comment:a,errorMessage:r}),console.log(`[Monitor] Task ${t.id} marked as ${s}, sending alert...`);try{let c=await this.client.sendAlert(e,s,r);console.log(`[Monitor] Alert sent to ${c.emailsSent} recipients`)}catch(c){console.error("[Monitor] Failed to send alert:",c)}}};var Ot=require("readline"),J=require("fs"),Me=require("path");function Ks(){let n=(0,Ot.createInterface)({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{n.question(e,s=>{t(s.trim())})}),close:()=>n.close()}}async function At(n,e){try{return(await fetch(`${n}/api/mcp/auth/validate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}})).ok}catch{return!1}}function wt(n){let e=`# Sego Auto-Task Monitor Configuration
|
|
39
44
|
# Generated by sego-auto-task init
|
|
40
45
|
|
|
41
46
|
# Required: Your Sego PM API key
|
|
42
|
-
SEGO_API_KEY=${
|
|
47
|
+
SEGO_API_KEY=${n.apiKey}
|
|
43
48
|
|
|
44
49
|
# API URL (default: https://sego.pm)
|
|
45
|
-
SEGO_API_URL=${
|
|
46
|
-
`;return
|
|
50
|
+
SEGO_API_URL=${n.apiUrl}
|
|
51
|
+
`;return n.projectId&&(e+=`
|
|
47
52
|
# Filter to specific project
|
|
48
|
-
SEGO_PROJECT_ID=${
|
|
49
|
-
`),e}async function
|
|
50
|
-
Error: API key
|
|
51
|
-
Error:
|
|
53
|
+
SEGO_PROJECT_ID=${n.projectId}
|
|
54
|
+
`),e}async function St(n={}){let e=n.yes||!1;if(console.log(""),console.log("=".repeat(50)),console.log(" Sego Auto-Task Monitor Setup Wizard"),console.log("=".repeat(50)),console.log(""),e){console.log("Running in non-interactive mode (--yes flag)"),console.log("");let s=process.env.SEGO_API_KEY,o=process.env.SEGO_API_URL||"https://sego.pm",r=process.env.SEGO_PROJECT_ID;s||(console.error("Error: SEGO_API_KEY environment variable is required in non-interactive mode."),console.error(""),console.error("Usage:"),console.error(" SEGO_API_KEY=your_key sego-auto-task init --yes"),console.error(""),console.error("Or run without --yes for interactive setup."),process.exit(1)),console.log("Validating API key..."),await At(o,s)||(console.error(`
|
|
55
|
+
Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${o}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!");let l={apiKey:s,apiUrl:o,projectId:r||void 0},a=(0,Me.resolve)(process.cwd(),".env"),c=wt(l);(0,J.writeFileSync)(a,c),Tt(a);return}let t=Ks();try{console.log("Step 1: API Key"),console.log("Get your API key from: https://sego.pm/developer/api-keys"),console.log("");let s=await t.ask("Enter your Sego PM API key: ");s||(console.error(`
|
|
56
|
+
Error: API key is required.`),process.exit(1)),console.log(""),console.log("Step 2: API URL");let r=await t.ask("Enter API URL (press Enter for https://sego.pm): ")||"https://sego.pm";console.log(""),console.log("Validating API key..."),await At(r,s)||(console.error(`
|
|
57
|
+
Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${r}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let l=await t.ask("Enter Project ID (press Enter to skip): "),a={apiKey:s,apiUrl:r,projectId:l||void 0};console.log(""),console.log("Step 4: Save Configuration");let c=(0,Me.resolve)(process.cwd(),".env");if((0,J.existsSync)(c)&&(console.log(`Warning: .env file already exists at ${c}`),(await t.ask("Overwrite? (y/N): ")).toLowerCase()!=="y")){console.log(""),console.log("Configuration not saved. You can set these environment variables manually:"),console.log(""),console.log(`export SEGO_API_KEY="${a.apiKey}"`),console.log(`export SEGO_API_URL="${a.apiUrl}"`),a.projectId&&console.log(`export SEGO_PROJECT_ID="${a.projectId}"`),console.log(""),t.close();return}let p=wt(a);(0,J.writeFileSync)(c,p),Tt(c)}finally{t.close()}}function Tt(n){console.log(""),console.log("=".repeat(50)),console.log(" Setup Complete!"),console.log("=".repeat(50)),console.log(""),console.log(`Configuration saved to: ${n}`),console.log(""),console.log("Next steps:"),console.log(" 1. Make sure Claude Code CLI is installed and authenticated:"),console.log(" npm install -g @anthropic-ai/claude-code"),console.log(" claude auth login"),console.log(""),console.log(" 2. Start the monitor:"),console.log(" sego-auto-task"),console.log(""),console.log(" 3. Or run in dry-run mode to test:"),console.log(" sego-auto-task --dry-run"),console.log("")}var N=require("fs"),$t=require("os"),De=require("path"),Pt="@segosolutions/auto-task",je=(0,De.join)((0,$t.homedir)(),".sego-auto-task"),Ne=(0,De.join)(je,"version-check.json"),Gs=24*60*60*1e3;function It(n,e){let t=n.replace(/^v/,"").split(".").map(Number),s=e.replace(/^v/,"").split(".").map(Number);for(let o=0;o<Math.max(t.length,s.length);o++){let r=t[o]||0,i=s[o]||0;if(r<i)return-1;if(r>i)return 1}return 0}function Ws(){try{if(!(0,N.existsSync)(Ne))return null;let n=JSON.parse((0,N.readFileSync)(Ne,"utf-8"));return Date.now()-n.checkedAt<Gs?n:null}catch{return null}}function Ys(n){try{(0,N.existsSync)(je)||(0,N.mkdirSync)(je,{recursive:!0});let e={latestVersion:n,checkedAt:Date.now()};(0,N.writeFileSync)(Ne,JSON.stringify(e,null,2))}catch{}}async function Js(){try{let n=new AbortController,e=setTimeout(()=>n.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(Pt)}/latest`,{signal:n.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function xt(n){let e=Ws();if(e)return{currentVersion:n,latestVersion:e.latestVersion,updateAvailable:It(n,e.latestVersion)<0};let t=await Js();return t&&Ys(t),{currentVersion:n,latestVersion:t,updateAvailable:t?It(n,t)<0:!1}}function Mt(n){!n.updateAvailable||!n.latestVersion||(console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m Update available!\x1B[0m"),console.log(` Current version: \x1B[90m${n.currentVersion}\x1B[0m`),console.log(` Latest version: \x1B[32m${n.latestVersion}\x1B[0m`),console.log(""),console.log(" Run to update:"),console.log(` \x1B[36m npm update -g ${Pt}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var Dt="1.2.0",Re=null;B.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
|
|
52
58
|
|
|
53
59
|
Runs in hybrid mode:
|
|
54
60
|
- SSE: Listens for client request events and processes them with local Claude
|
|
@@ -56,5 +62,5 @@ Runs in hybrid mode:
|
|
|
56
62
|
|
|
57
63
|
Environment variables are loaded from .env in the working directory.
|
|
58
64
|
|
|
59
|
-
Use "sego-auto-task init" to run the interactive setup wizard.`).version(
|
|
60
|
-
Received shutdown signal`),
|
|
65
|
+
Use "sego-auto-task init" to run the interactive setup wizard.`).version(Dt);B.command("init").description("Interactive setup wizard to configure your API key and settings").option("-y, --yes","Accept defaults without prompting").action(async n=>{await St({yes:n.yes})});B.option("--api-key <key>","Sego PM API key (or set SEGO_API_KEY env)").option("--api-url <url>","Sego PM API URL (default: https://sego.pm)").option("--project-id <id>","Only process tasks for this project (or set SEGO_PROJECT_ID env). Required for SSE mode.").option("--poll <seconds>","Poll interval in seconds (default: 30)","30").option("--timeout <minutes>","Task timeout in minutes (default: 10)","10").option("--client-request-timeout <minutes>","Client request analysis timeout in minutes (default: 2)","2").option("--no-sse","Disable SSE mode for client request processing").option("--dry-run","Poll but do not process tasks",!1).option("--working-dir <path>","Working directory for Claude and .env loading (or set SEGO_WORKING_DIR env)").option("--no-update-check","Disable update check on startup").option("--use-agent-sdk","Use Claude Agent SDK instead of CLI subprocess (experimental)").option("--stream-progress","Stream agent progress events to the web app via SSE").option("--conversation-only","Only handle conversational sessions, skip automatic task processing").action(async n=>{try{n.updateCheck!==!1&&(Re=xt(Dt).then(Mt).catch(()=>{}));let e=n.workingDir||process.env.SEGO_WORKING_DIR||process.cwd(),t=(0,Ue.resolve)(e),s=(0,Ue.resolve)(t,".env");(0,Nt.existsSync)(s)?(console.log(`Loading environment from: ${s}`),jt.default.config({path:s})):console.log(`No .env file found in: ${t}`),n.useAgentSdk||process.env.USE_AGENT_SDK==="true"?(console.log("Checking for Claude Agent SDK..."),await gt()||(console.error("Error: Claude Agent SDK is not available."),process.exit(1)),console.log("Claude Agent SDK is available")):(console.log("Checking for Claude CLI..."),await lt()||(console.error("Error: Claude CLI is not available. Please install Claude Code first."),console.error(" npm install -g @anthropic-ai/claude-code"),process.exit(1)),console.log("Claude CLI is available"));let r=it({apiKey:n.apiKey,apiUrl:n.apiUrl,projectId:n.projectId,pollIntervalMs:parseInt(n.poll,10)*1e3,timeoutMs:parseInt(n.timeout,10)*60*1e3,clientRequestTimeoutMs:parseInt(n.clientRequestTimeout,10)*60*1e3,sseEnabled:n.sse!==!1,dryRun:n.dryRun,workingDirectory:t,useAgentSdk:n.useAgentSdk||!1,streamProgress:n.streamProgress||!1,conversationOnly:n.conversationOnly||!1}),l=r.apiUrl.includes("sego.pm")||r.apiUrl.includes("vercel")?"PRODUCTION":"DEVELOPMENT";console.log(""),console.log("=".repeat(60)),console.log("Sego Auto-Task Monitor - Environment Configuration"),console.log("=".repeat(60)),console.log(`Environment: ${l}`),console.log(`API URL: ${r.apiUrl}`),console.log(`SSE Mode: ${r.sseEnabled?"enabled":"disabled"}`),console.log(`Project Filter: ${r.projectId||"all projects"}`),console.log(`Poll Interval: ${r.pollIntervalMs/1e3}s`),console.log(`Task Timeout: ${r.timeoutMs/6e4}min`),console.log(`Dry Run: ${r.dryRun?"yes":"no"}`),console.log(`Working Dir: ${r.workingDirectory}`),console.log(`Agent SDK Mode: ${r.useAgentSdk?"yes (experimental)":"no (CLI subprocess)"}`),console.log(`Stream Progress: ${r.streamProgress?"yes":"no"}`),console.log(`Conv. Only: ${r.conversationOnly?"yes (no auto-task processing)":"no"}`),console.log("=".repeat(60)),console.log(""),Re&&await Re;let a=new ce(r),c=()=>{console.log(`
|
|
66
|
+
Received shutdown signal`),a.stop(),process.exit(0)};process.on("SIGINT",c),process.on("SIGTERM",c),await a.start()}catch(e){console.error("Error:",e instanceof Error?e.message:e),process.exit(1)}});B.parse();
|