ace-assistant-cli 0.2.0 → 0.4.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.
Files changed (2) hide show
  1. package/dist/index.js +52 -47
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,57 +1,62 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{createRequire as p$}from"node:module";var i$=Object.create;var{getPrototypeOf:a$,defineProperty:Dy,getOwnPropertyNames:e$}=Object;var n$=Object.prototype.hasOwnProperty;var o$=(y,$,j)=>{j=y!=null?i$(a$(y)):{};let G=$||!y||!y.__esModule?Dy(j,"default",{value:y,enumerable:!0}):j;for(let P of e$(y))if(!n$.call(G,P))Dy(G,P,{get:()=>y[P],enumerable:!0});return G};var B=(y,$)=>()=>($||y(($={exports:{}}).exports,$),$.exports);var O=p$(import.meta.url);var u=B((yj)=>{class $y extends Error{constructor(y,$,j){super(j);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=y,this.nestedError=void 0}}class ky extends $y{constructor(y){super(1,"commander.invalidArgument",y);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}yj.CommanderError=$y;yj.InvalidArgumentError=ky});var s=B((Rj)=>{var{InvalidArgumentError:Gj}=u();class by{constructor(y,$){switch(this.description=$||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,y[0]){case"<":this.required=!0,this._name=y.slice(1,-1);break;case"[":this.required=!1,this._name=y.slice(1,-1);break;default:this.required=!0,this._name=y;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(y,$){if($===this.defaultValue||!Array.isArray($))return[y];return $.concat(y)}default(y,$){return this.defaultValue=y,this.defaultValueDescription=$,this}argParser(y){return this.parseArg=y,this}choices(y){return this.argChoices=y.slice(),this.parseArg=($,j)=>{if(!this.argChoices.includes($))throw new Gj(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,j);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Pj(y){let $=y.name()+(y.variadic===!0?"...":"");return y.required?"<"+$+">":"["+$+"]"}Rj.Argument=by;Rj.humanReadableArgName=Pj});var jy=B((Ej)=>{var{humanReadableArgName:Uj}=s();class vy{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(y){let $=y.commands.filter((G)=>!G._hidden),j=y._getHelpCommand();if(j&&!j._hidden)$.push(j);if(this.sortSubcommands)$.sort((G,P)=>{return G.name().localeCompare(P.name())});return $}compareOptions(y,$){let j=(G)=>{return G.short?G.short.replace(/^-/,""):G.long.replace(/^--/,"")};return j(y).localeCompare(j($))}visibleOptions(y){let $=y.options.filter((G)=>!G.hidden),j=y._getHelpOption();if(j&&!j.hidden){let G=j.short&&y._findOption(j.short),P=j.long&&y._findOption(j.long);if(!G&&!P)$.push(j);else if(j.long&&!P)$.push(y.createOption(j.long,j.description));else if(j.short&&!G)$.push(y.createOption(j.short,j.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(y){if(!this.showGlobalOptions)return[];let $=[];for(let j=y.parent;j;j=j.parent){let G=j.options.filter((P)=>!P.hidden);$.push(...G)}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleArguments(y){if(y._argsDescription)y.registeredArguments.forEach(($)=>{$.description=$.description||y._argsDescription[$.name()]||""});if(y.registeredArguments.find(($)=>$.description))return y.registeredArguments;return[]}subcommandTerm(y){let $=y.registeredArguments.map((j)=>Uj(j)).join(" ");return y._name+(y._aliases[0]?"|"+y._aliases[0]:"")+(y.options.length?" [options]":"")+($?" "+$:"")}optionTerm(y){return y.flags}argumentTerm(y){return y.name()}longestSubcommandTermLength(y,$){return $.visibleCommands(y).reduce((j,G)=>{return Math.max(j,$.subcommandTerm(G).length)},0)}longestOptionTermLength(y,$){return $.visibleOptions(y).reduce((j,G)=>{return Math.max(j,$.optionTerm(G).length)},0)}longestGlobalOptionTermLength(y,$){return $.visibleGlobalOptions(y).reduce((j,G)=>{return Math.max(j,$.optionTerm(G).length)},0)}longestArgumentTermLength(y,$){return $.visibleArguments(y).reduce((j,G)=>{return Math.max(j,$.argumentTerm(G).length)},0)}commandUsage(y){let $=y._name;if(y._aliases[0])$=$+"|"+y._aliases[0];let j="";for(let G=y.parent;G;G=G.parent)j=G.name()+" "+j;return j+$+" "+y.usage()}commandDescription(y){return y.description()}subcommandDescription(y){return y.summary()||y.description()}optionDescription(y){let $=[];if(y.argChoices)$.push(`choices: ${y.argChoices.map((j)=>JSON.stringify(j)).join(", ")}`);if(y.defaultValue!==void 0){if(y.required||y.optional||y.isBoolean()&&typeof y.defaultValue==="boolean")$.push(`default: ${y.defaultValueDescription||JSON.stringify(y.defaultValue)}`)}if(y.presetArg!==void 0&&y.optional)$.push(`preset: ${JSON.stringify(y.presetArg)}`);if(y.envVar!==void 0)$.push(`env: ${y.envVar}`);if($.length>0)return`${y.description} (${$.join(", ")})`;return y.description}argumentDescription(y){let $=[];if(y.argChoices)$.push(`choices: ${y.argChoices.map((j)=>JSON.stringify(j)).join(", ")}`);if(y.defaultValue!==void 0)$.push(`default: ${y.defaultValueDescription||JSON.stringify(y.defaultValue)}`);if($.length>0){let j=`(${$.join(", ")})`;if(y.description)return`${y.description} ${j}`;return j}return y.description}formatHelp(y,$){let j=$.padWidth(y,$),G=$.helpWidth||80,P=2,R=2;function q(c,H){if(H){let yy=`${c.padEnd(j+2)}${H}`;return $.wrap(yy,G-2,j+2)}return c}function S(c){return c.join(`
4
- `).replace(/^/gm," ".repeat(2))}let U=[`Usage: ${$.commandUsage(y)}`,""],I=$.commandDescription(y);if(I.length>0)U=U.concat([$.wrap(I,G,0),""]);let J=$.visibleArguments(y).map((c)=>{return q($.argumentTerm(c),$.argumentDescription(c))});if(J.length>0)U=U.concat(["Arguments:",S(J),""]);let Z=$.visibleOptions(y).map((c)=>{return q($.optionTerm(c),$.optionDescription(c))});if(Z.length>0)U=U.concat(["Options:",S(Z),""]);if(this.showGlobalOptions){let c=$.visibleGlobalOptions(y).map((H)=>{return q($.optionTerm(H),$.optionDescription(H))});if(c.length>0)U=U.concat(["Global Options:",S(c),""])}let X=$.visibleCommands(y).map((c)=>{return q($.subcommandTerm(c),$.subcommandDescription(c))});if(X.length>0)U=U.concat(["Commands:",S(X),""]);return U.join(`
5
- `)}padWidth(y,$){return Math.max($.longestOptionTermLength(y,$),$.longestGlobalOptionTermLength(y,$),$.longestSubcommandTermLength(y,$),$.longestArgumentTermLength(y,$))}wrap(y,$,j,G=40){let R=new RegExp(`[\\n][${" \\f\\t\\v   -    \uFEFF"}]+`);if(y.match(R))return y;let q=$-j;if(q<G)return y;let S=y.slice(0,j),U=y.slice(j).replace(`\r
3
+ import{createRequire as Q$}from"node:module";var U$=Object.create;var{getPrototypeOf:I$,defineProperty:hc,getOwnPropertyNames:L$}=Object;var S$=Object.prototype.hasOwnProperty;function q$(c){return this[c]}var w$,E$,Y$=(c,y,$)=>{var j=c!=null&&typeof c==="object";if(j){var P=y?w$??=new WeakMap:E$??=new WeakMap,R=P.get(c);if(R)return R}$=c!=null?U$(I$(c)):{};let G=y||!c||!c.__esModule?hc($,"default",{value:c,enumerable:!0}):$;for(let f of L$(c))if(!S$.call(G,f))hc(G,f,{get:q$.bind(c,f),enumerable:!0});if(j)P.set(c,G);return G};var x=(c,y)=>()=>(y||c((y={exports:{}}).exports,y),y.exports);var t=Q$(import.meta.url);var g=x((Z$)=>{class $c extends Error{constructor(c,y,$){super($);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=y,this.exitCode=c,this.nestedError=void 0}}class vc extends $c{constructor(c){super(1,"commander.invalidArgument",c);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Z$.CommanderError=$c;Z$.InvalidArgumentError=vc});var l=x((W$)=>{var{InvalidArgumentError:z$}=g();class bc{constructor(c,y){switch(this.description=y||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,c[0]){case"<":this.required=!0,this._name=c.slice(1,-1);break;case"[":this.required=!1,this._name=c.slice(1,-1);break;default:this.required=!0,this._name=c;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(c,y){if(y===this.defaultValue||!Array.isArray(y))return[c];return y.concat(c)}default(c,y){return this.defaultValue=c,this.defaultValueDescription=y,this}argParser(c){return this.parseArg=c,this}choices(c){return this.argChoices=c.slice(),this.parseArg=(y,$)=>{if(!this.argChoices.includes(y))throw new z$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(y,$);return y},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function X$(c){let y=c.name()+(c.variadic===!0?"...":"");return c.required?"<"+y+">":"["+y+"]"}W$.Argument=bc;W$.humanReadableArgName=X$});var jc=x((M$)=>{var{humanReadableArgName:H$}=l();class uc{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(c){let y=c.commands.filter((j)=>!j._hidden),$=c._getHelpCommand();if($&&!$._hidden)y.push($);if(this.sortSubcommands)y.sort((j,P)=>{return j.name().localeCompare(P.name())});return y}compareOptions(c,y){let $=(j)=>{return j.short?j.short.replace(/^-/,""):j.long.replace(/^--/,"")};return $(c).localeCompare($(y))}visibleOptions(c){let y=c.options.filter((j)=>!j.hidden),$=c._getHelpOption();if($&&!$.hidden){let j=$.short&&c._findOption($.short),P=$.long&&c._findOption($.long);if(!j&&!P)y.push($);else if($.long&&!P)y.push(c.createOption($.long,$.description));else if($.short&&!j)y.push(c.createOption($.short,$.description))}if(this.sortOptions)y.sort(this.compareOptions);return y}visibleGlobalOptions(c){if(!this.showGlobalOptions)return[];let y=[];for(let $=c.parent;$;$=$.parent){let j=$.options.filter((P)=>!P.hidden);y.push(...j)}if(this.sortOptions)y.sort(this.compareOptions);return y}visibleArguments(c){if(c._argsDescription)c.registeredArguments.forEach((y)=>{y.description=y.description||c._argsDescription[y.name()]||""});if(c.registeredArguments.find((y)=>y.description))return c.registeredArguments;return[]}subcommandTerm(c){let y=c.registeredArguments.map(($)=>H$($)).join(" ");return c._name+(c._aliases[0]?"|"+c._aliases[0]:"")+(c.options.length?" [options]":"")+(y?" "+y:"")}optionTerm(c){return c.flags}argumentTerm(c){return c.name()}longestSubcommandTermLength(c,y){return y.visibleCommands(c).reduce(($,j)=>{return Math.max($,y.subcommandTerm(j).length)},0)}longestOptionTermLength(c,y){return y.visibleOptions(c).reduce(($,j)=>{return Math.max($,y.optionTerm(j).length)},0)}longestGlobalOptionTermLength(c,y){return y.visibleGlobalOptions(c).reduce(($,j)=>{return Math.max($,y.optionTerm(j).length)},0)}longestArgumentTermLength(c,y){return y.visibleArguments(c).reduce(($,j)=>{return Math.max($,y.argumentTerm(j).length)},0)}commandUsage(c){let y=c._name;if(c._aliases[0])y=y+"|"+c._aliases[0];let $="";for(let j=c.parent;j;j=j.parent)$=j.name()+" "+$;return $+y+" "+c.usage()}commandDescription(c){return c.description()}subcommandDescription(c){return c.summary()||c.description()}optionDescription(c){let y=[];if(c.argChoices)y.push(`choices: ${c.argChoices.map(($)=>JSON.stringify($)).join(", ")}`);if(c.defaultValue!==void 0){if(c.required||c.optional||c.isBoolean()&&typeof c.defaultValue==="boolean")y.push(`default: ${c.defaultValueDescription||JSON.stringify(c.defaultValue)}`)}if(c.presetArg!==void 0&&c.optional)y.push(`preset: ${JSON.stringify(c.presetArg)}`);if(c.envVar!==void 0)y.push(`env: ${c.envVar}`);if(y.length>0)return`${c.description} (${y.join(", ")})`;return c.description}argumentDescription(c){let y=[];if(c.argChoices)y.push(`choices: ${c.argChoices.map(($)=>JSON.stringify($)).join(", ")}`);if(c.defaultValue!==void 0)y.push(`default: ${c.defaultValueDescription||JSON.stringify(c.defaultValue)}`);if(y.length>0){let $=`(${y.join(", ")})`;if(c.description)return`${c.description} ${$}`;return $}return c.description}formatHelp(c,y){let $=y.padWidth(c,y),j=y.helpWidth||80,P=2,R=2;function G(Q,_){if(_){let yc=`${Q.padEnd($+2)}${_}`;return y.wrap(yc,j-2,$+2)}return Q}function f(Q){return Q.join(`
4
+ `).replace(/^/gm," ".repeat(2))}let U=[`Usage: ${y.commandUsage(c)}`,""],q=y.commandDescription(c);if(q.length>0)U=U.concat([y.wrap(q,j,0),""]);let w=y.visibleArguments(c).map((Q)=>{return G(y.argumentTerm(Q),y.argumentDescription(Q))});if(w.length>0)U=U.concat(["Arguments:",f(w),""]);let Y=y.visibleOptions(c).map((Q)=>{return G(y.optionTerm(Q),y.optionDescription(Q))});if(Y.length>0)U=U.concat(["Options:",f(Y),""]);if(this.showGlobalOptions){let Q=y.visibleGlobalOptions(c).map((_)=>{return G(y.optionTerm(_),y.optionDescription(_))});if(Q.length>0)U=U.concat(["Global Options:",f(Q),""])}let J=y.visibleCommands(c).map((Q)=>{return G(y.subcommandTerm(Q),y.subcommandDescription(Q))});if(J.length>0)U=U.concat(["Commands:",f(J),""]);return U.join(`
5
+ `)}padWidth(c,y){return Math.max(y.longestOptionTermLength(c,y),y.longestGlobalOptionTermLength(c,y),y.longestSubcommandTermLength(c,y),y.longestArgumentTermLength(c,y))}wrap(c,y,$,j=40){let R=new RegExp(`[\\n][${" \\f\\t\\v   -    \uFEFF"}]+`);if(c.match(R))return c;let G=y-$;if(G<j)return c;let f=c.slice(0,$),U=c.slice($).replace(`\r
6
6
  `,`
7
- `),I=" ".repeat(j),Z=`\\s${"​"}`,X=new RegExp(`
8
- |.{1,${q-1}}([${Z}]|$)|[^${Z}]+?([${Z}]|$)`,"g"),c=U.match(X)||[];return S+c.map((H,yy)=>{if(H===`
9
- `)return"";return(yy>0?I:"")+H.trimEnd()}).join(`
10
- `)}}Ej.Help=vy});var Gy=B((Zj)=>{var{InvalidArgumentError:Lj}=u();class hy{constructor(y,$){this.flags=y,this.description=$||"",this.required=y.includes("<"),this.optional=y.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(y),this.mandatory=!1;let j=Jj(y);if(this.short=j.shortFlag,this.long=j.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(y,$){return this.defaultValue=y,this.defaultValueDescription=$,this}preset(y){return this.presetArg=y,this}conflicts(y){return this.conflictsWith=this.conflictsWith.concat(y),this}implies(y){let $=y;if(typeof y==="string")$={[y]:!0};return this.implied=Object.assign(this.implied||{},$),this}env(y){return this.envVar=y,this}argParser(y){return this.parseArg=y,this}makeOptionMandatory(y=!0){return this.mandatory=!!y,this}hideHelp(y=!0){return this.hidden=!!y,this}_concatValue(y,$){if($===this.defaultValue||!Array.isArray($))return[y];return $.concat(y)}choices(y){return this.argChoices=y.slice(),this.parseArg=($,j)=>{if(!this.argChoices.includes($))throw new Lj(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,j);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return Qj(this.name().replace(/^no-/,""))}is(y){return this.short===y||this.long===y}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class Oy{constructor(y){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,y.forEach(($)=>{if($.negate)this.negativeOptions.set($.attributeName(),$);else this.positiveOptions.set($.attributeName(),$)}),this.negativeOptions.forEach(($,j)=>{if(this.positiveOptions.has(j))this.dualOptions.add(j)})}valueFromOption(y,$){let j=$.attributeName();if(!this.dualOptions.has(j))return!0;let G=this.negativeOptions.get(j).presetArg,P=G!==void 0?G:!1;return $.negate===(P===y)}}function Qj(y){return y.split("-").reduce(($,j)=>{return $+j[0].toUpperCase()+j.slice(1)})}function Jj(y){let $,j,G=y.split(/[ |,]+/);if(G.length>1&&!/^[[<]/.test(G[1]))$=G.shift();if(j=G.shift(),!$&&/^-[^-]$/.test(j))$=j,j=void 0;return{shortFlag:$,longFlag:j}}Zj.Option=hy;Zj.DualOptions=Oy});var uy=B((Fj)=>{function wj(y,$){if(Math.abs(y.length-$.length)>3)return Math.max(y.length,$.length);let j=[];for(let G=0;G<=y.length;G++)j[G]=[G];for(let G=0;G<=$.length;G++)j[0][G]=G;for(let G=1;G<=$.length;G++)for(let P=1;P<=y.length;P++){let R=1;if(y[P-1]===$[G-1])R=0;else R=1;if(j[P][G]=Math.min(j[P-1][G]+1,j[P][G-1]+1,j[P-1][G-1]+R),P>1&&G>1&&y[P-1]===$[G-2]&&y[P-2]===$[G-1])j[P][G]=Math.min(j[P][G],j[P-2][G-2]+1)}return j[y.length][$.length]}function Xj(y,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let j=y.startsWith("--");if(j)y=y.slice(2),$=$.map((q)=>q.slice(2));let G=[],P=3,R=0.4;if($.forEach((q)=>{if(q.length<=1)return;let S=wj(y,q),U=Math.max(y.length,q.length);if((U-S)/U>R){if(S<P)P=S,G=[q];else if(S===P)G.push(q)}}),G.sort((q,S)=>q.localeCompare(S)),j)G=G.map((q)=>`--${q}`);if(G.length>1)return`
11
- (Did you mean one of ${G.join(", ")}?)`;if(G.length===1)return`
12
- (Did you mean ${G[0]}?)`;return""}Fj.suggestSimilar=Xj});var ly=B((Kj)=>{var zj=O("node:events").EventEmitter,Py=O("node:child_process"),z=O("node:path"),Ry=O("node:fs"),w=O("node:process"),{Argument:Hj,humanReadableArgName:Wj}=s(),{CommanderError:qy}=u(),{Help:Mj}=jy(),{Option:gy,DualOptions:fj}=Gy(),{suggestSimilar:ty}=uy();class Sy extends zj{constructor(y){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=y||"",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:($)=>w.stdout.write($),writeErr:($)=>w.stderr.write($),getOutHelpWidth:()=>w.stdout.isTTY?w.stdout.columns:void 0,getErrHelpWidth:()=>w.stderr.isTTY?w.stderr.columns:void 0,outputError:($,j)=>j($)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(y){return this._outputConfiguration=y._outputConfiguration,this._helpOption=y._helpOption,this._helpCommand=y._helpCommand,this._helpConfiguration=y._helpConfiguration,this._exitCallback=y._exitCallback,this._storeOptionsAsProperties=y._storeOptionsAsProperties,this._combineFlagAndOptionalValue=y._combineFlagAndOptionalValue,this._allowExcessArguments=y._allowExcessArguments,this._enablePositionalOptions=y._enablePositionalOptions,this._showHelpAfterError=y._showHelpAfterError,this._showSuggestionAfterError=y._showSuggestionAfterError,this}_getCommandAndAncestors(){let y=[];for(let $=this;$;$=$.parent)y.push($);return y}command(y,$,j){let G=$,P=j;if(typeof G==="object"&&G!==null)P=G,G=null;P=P||{};let[,R,q]=y.match(/([^ ]+) *(.*)/),S=this.createCommand(R);if(G)S.description(G),S._executableHandler=!0;if(P.isDefault)this._defaultCommandName=S._name;if(S._hidden=!!(P.noHelp||P.hidden),S._executableFile=P.executableFile||null,q)S.arguments(q);if(this._registerCommand(S),S.parent=this,S.copyInheritedSettings(this),G)return this;return S}createCommand(y){return new Sy(y)}createHelp(){return Object.assign(new Mj,this.configureHelp())}configureHelp(y){if(y===void 0)return this._helpConfiguration;return this._helpConfiguration=y,this}configureOutput(y){if(y===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,y),this}showHelpAfterError(y=!0){if(typeof y!=="string")y=!!y;return this._showHelpAfterError=y,this}showSuggestionAfterError(y=!0){return this._showSuggestionAfterError=!!y,this}addCommand(y,$){if(!y._name)throw Error(`Command passed to .addCommand() must have a name
13
- - specify the name in Command constructor or using .name()`);if($=$||{},$.isDefault)this._defaultCommandName=y._name;if($.noHelp||$.hidden)y._hidden=!0;return this._registerCommand(y),y.parent=this,y._checkForBrokenPassThrough(),this}createArgument(y,$){return new Hj(y,$)}argument(y,$,j,G){let P=this.createArgument(y,$);if(typeof j==="function")P.default(G).argParser(j);else P.default(j);return this.addArgument(P),this}arguments(y){return y.trim().split(/ +/).forEach(($)=>{this.argument($)}),this}addArgument(y){let $=this.registeredArguments.slice(-1)[0];if($&&$.variadic)throw Error(`only the last argument can be variadic '${$.name()}'`);if(y.required&&y.defaultValue!==void 0&&y.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${y.name()}'`);return this.registeredArguments.push(y),this}helpCommand(y,$){if(typeof y==="boolean")return this._addImplicitHelpCommand=y,this;y=y??"help [command]";let[,j,G]=y.match(/([^ ]+) *(.*)/),P=$??"display help for command",R=this.createCommand(j);if(R.helpOption(!1),G)R.arguments(G);if(P)R.description(P);return this._addImplicitHelpCommand=!0,this._helpCommand=R,this}addHelpCommand(y,$){if(typeof y!=="object")return this.helpCommand(y,$),this;return this._addImplicitHelpCommand=!0,this._helpCommand=y,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(y,$){let j=["preSubcommand","preAction","postAction"];if(!j.includes(y))throw Error(`Unexpected value for event passed to hook : '${y}'.
14
- Expecting one of '${j.join("', '")}'`);if(this._lifeCycleHooks[y])this._lifeCycleHooks[y].push($);else this._lifeCycleHooks[y]=[$];return this}exitOverride(y){if(y)this._exitCallback=y;else this._exitCallback=($)=>{if($.code!=="commander.executeSubCommandAsync")throw $};return this}_exit(y,$,j){if(this._exitCallback)this._exitCallback(new qy(y,$,j));w.exit(y)}action(y){let $=(j)=>{let G=this.registeredArguments.length,P=j.slice(0,G);if(this._storeOptionsAsProperties)P[G]=this;else P[G]=this.opts();return P.push(this),y.apply(this,P)};return this._actionHandler=$,this}createOption(y,$){return new gy(y,$)}_callParseArg(y,$,j,G){try{return y.parseArg($,j)}catch(P){if(P.code==="commander.invalidArgument"){let R=`${G} ${P.message}`;this.error(R,{exitCode:P.exitCode,code:P.code})}throw P}}_registerOption(y){let $=y.short&&this._findOption(y.short)||y.long&&this._findOption(y.long);if($){let j=y.long&&this._findOption(y.long)?y.long:y.short;throw Error(`Cannot add option '${y.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${j}'
15
- - already used by option '${$.flags}'`)}this.options.push(y)}_registerCommand(y){let $=(G)=>{return[G.name()].concat(G.aliases())},j=$(y).find((G)=>this._findCommand(G));if(j){let G=$(this._findCommand(j)).join("|"),P=$(y).join("|");throw Error(`cannot add command '${P}' as already have command '${G}'`)}this.commands.push(y)}addOption(y){this._registerOption(y);let $=y.name(),j=y.attributeName();if(y.negate){let P=y.long.replace(/^--no-/,"--");if(!this._findOption(P))this.setOptionValueWithSource(j,y.defaultValue===void 0?!0:y.defaultValue,"default")}else if(y.defaultValue!==void 0)this.setOptionValueWithSource(j,y.defaultValue,"default");let G=(P,R,q)=>{if(P==null&&y.presetArg!==void 0)P=y.presetArg;let S=this.getOptionValue(j);if(P!==null&&y.parseArg)P=this._callParseArg(y,P,S,R);else if(P!==null&&y.variadic)P=y._concatValue(P,S);if(P==null)if(y.negate)P=!1;else if(y.isBoolean()||y.optional)P=!0;else P="";this.setOptionValueWithSource(j,P,q)};if(this.on("option:"+$,(P)=>{let R=`error: option '${y.flags}' argument '${P}' is invalid.`;G(P,R,"cli")}),y.envVar)this.on("optionEnv:"+$,(P)=>{let R=`error: option '${y.flags}' value '${P}' from env '${y.envVar}' is invalid.`;G(P,R,"env")});return this}_optionEx(y,$,j,G,P){if(typeof $==="object"&&$ instanceof gy)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let R=this.createOption($,j);if(R.makeOptionMandatory(!!y.mandatory),typeof G==="function")R.default(P).argParser(G);else if(G instanceof RegExp){let q=G;G=(S,U)=>{let I=q.exec(S);return I?I[0]:U},R.default(P).argParser(G)}else R.default(G);return this.addOption(R)}option(y,$,j,G){return this._optionEx({},y,$,j,G)}requiredOption(y,$,j,G){return this._optionEx({mandatory:!0},y,$,j,G)}combineFlagAndOptionalValue(y=!0){return this._combineFlagAndOptionalValue=!!y,this}allowUnknownOption(y=!0){return this._allowUnknownOption=!!y,this}allowExcessArguments(y=!0){return this._allowExcessArguments=!!y,this}enablePositionalOptions(y=!0){return this._enablePositionalOptions=!!y,this}passThroughOptions(y=!0){return this._passThroughOptions=!!y,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(y=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!y,this}getOptionValue(y){if(this._storeOptionsAsProperties)return this[y];return this._optionValues[y]}setOptionValue(y,$){return this.setOptionValueWithSource(y,$,void 0)}setOptionValueWithSource(y,$,j){if(this._storeOptionsAsProperties)this[y]=$;else this._optionValues[y]=$;return this._optionValueSources[y]=j,this}getOptionValueSource(y){return this._optionValueSources[y]}getOptionValueSourceWithGlobals(y){let $;return this._getCommandAndAncestors().forEach((j)=>{if(j.getOptionValueSource(y)!==void 0)$=j.getOptionValueSource(y)}),$}_prepareUserArgs(y,$){if(y!==void 0&&!Array.isArray(y))throw Error("first parameter to parse must be array or undefined");if($=$||{},y===void 0&&$.from===void 0){if(w.versions?.electron)$.from="electron";let G=w.execArgv??[];if(G.includes("-e")||G.includes("--eval")||G.includes("-p")||G.includes("--print"))$.from="eval"}if(y===void 0)y=w.argv;this.rawArgs=y.slice();let j;switch($.from){case void 0:case"node":this._scriptPath=y[1],j=y.slice(2);break;case"electron":if(w.defaultApp)this._scriptPath=y[1],j=y.slice(2);else j=y.slice(1);break;case"user":j=y.slice(0);break;case"eval":j=y.slice(1);break;default:throw Error(`unexpected parse option { from: '${$.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",j}parse(y,$){let j=this._prepareUserArgs(y,$);return this._parseCommand([],j),this}async parseAsync(y,$){let j=this._prepareUserArgs(y,$);return await this._parseCommand([],j),this}_executeSubCommand(y,$){$=$.slice();let j=!1,G=[".js",".ts",".tsx",".mjs",".cjs"];function P(I,J){let Z=z.resolve(I,J);if(Ry.existsSync(Z))return Z;if(G.includes(z.extname(J)))return;let X=G.find((c)=>Ry.existsSync(`${Z}${c}`));if(X)return`${Z}${X}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let R=y._executableFile||`${this._name}-${y._name}`,q=this._executableDir||"";if(this._scriptPath){let I;try{I=Ry.realpathSync(this._scriptPath)}catch(J){I=this._scriptPath}q=z.resolve(z.dirname(I),q)}if(q){let I=P(q,R);if(!I&&!y._executableFile&&this._scriptPath){let J=z.basename(this._scriptPath,z.extname(this._scriptPath));if(J!==this._name)I=P(q,`${J}-${y._name}`)}R=I||R}j=G.includes(z.extname(R));let S;if(w.platform!=="win32")if(j)$.unshift(R),$=my(w.execArgv).concat($),S=Py.spawn(w.argv[0],$,{stdio:"inherit"});else S=Py.spawn(R,$,{stdio:"inherit"});else $.unshift(R),$=my(w.execArgv).concat($),S=Py.spawn(w.execPath,$,{stdio:"inherit"});if(!S.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((J)=>{w.on(J,()=>{if(S.killed===!1&&S.exitCode===null)S.kill(J)})});let U=this._exitCallback;S.on("close",(I)=>{if(I=I??1,!U)w.exit(I);else U(new qy(I,"commander.executeSubCommandAsync","(close)"))}),S.on("error",(I)=>{if(I.code==="ENOENT"){let J=q?`searched for local subcommand relative to directory '${q}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Z=`'${R}' does not exist
16
- - if '${y._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
7
+ `),q=" ".repeat($),Y=`\\s${"​"}`,J=new RegExp(`
8
+ |.{1,${G-1}}([${Y}]|$)|[^${Y}]+?([${Y}]|$)`,"g"),Q=U.match(J)||[];return f+Q.map((_,yc)=>{if(_===`
9
+ `)return"";return(yc>0?q:"")+_.trimEnd()}).join(`
10
+ `)}}M$.Help=uc});var Pc=x((N$)=>{var{InvalidArgumentError:B$}=g();class Oc{constructor(c,y){this.flags=c,this.description=y||"",this.required=c.includes("<"),this.optional=c.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(c),this.mandatory=!1;let $=x$(c);if(this.short=$.shortFlag,this.long=$.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(c,y){return this.defaultValue=c,this.defaultValueDescription=y,this}preset(c){return this.presetArg=c,this}conflicts(c){return this.conflictsWith=this.conflictsWith.concat(c),this}implies(c){let y=c;if(typeof c==="string")y={[c]:!0};return this.implied=Object.assign(this.implied||{},y),this}env(c){return this.envVar=c,this}argParser(c){return this.parseArg=c,this}makeOptionMandatory(c=!0){return this.mandatory=!!c,this}hideHelp(c=!0){return this.hidden=!!c,this}_concatValue(c,y){if(y===this.defaultValue||!Array.isArray(y))return[c];return y.concat(c)}choices(c){return this.argChoices=c.slice(),this.parseArg=(y,$)=>{if(!this.argChoices.includes(y))throw new B$(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(y,$);return y},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return T$(this.name().replace(/^no-/,""))}is(c){return this.short===c||this.long===c}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class tc{constructor(c){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,c.forEach((y)=>{if(y.negate)this.negativeOptions.set(y.attributeName(),y);else this.positiveOptions.set(y.attributeName(),y)}),this.negativeOptions.forEach((y,$)=>{if(this.positiveOptions.has($))this.dualOptions.add($)})}valueFromOption(c,y){let $=y.attributeName();if(!this.dualOptions.has($))return!0;let j=this.negativeOptions.get($).presetArg,P=j!==void 0?j:!1;return y.negate===(P===c)}}function T$(c){return c.split("-").reduce((y,$)=>{return y+$[0].toUpperCase()+$.slice(1)})}function x$(c){let y,$,j=c.split(/[ |,]+/);if(j.length>1&&!/^[[<]/.test(j[1]))y=j.shift();if($=j.shift(),!y&&/^-[^-]$/.test($))y=$,$=void 0;return{shortFlag:y,longFlag:$}}N$.Option=Oc;N$.DualOptions=tc});var gc=x((h$)=>{function D$(c,y){if(Math.abs(c.length-y.length)>3)return Math.max(c.length,y.length);let $=[];for(let j=0;j<=c.length;j++)$[j]=[j];for(let j=0;j<=y.length;j++)$[0][j]=j;for(let j=1;j<=y.length;j++)for(let P=1;P<=c.length;P++){let R=1;if(c[P-1]===y[j-1])R=0;else R=1;if($[P][j]=Math.min($[P-1][j]+1,$[P][j-1]+1,$[P-1][j-1]+R),P>1&&j>1&&c[P-1]===y[j-2]&&c[P-2]===y[j-1])$[P][j]=Math.min($[P][j],$[P-2][j-2]+1)}return $[c.length][y.length]}function k$(c,y){if(!y||y.length===0)return"";y=Array.from(new Set(y));let $=c.startsWith("--");if($)c=c.slice(2),y=y.map((G)=>G.slice(2));let j=[],P=3,R=0.4;if(y.forEach((G)=>{if(G.length<=1)return;let f=D$(c,G),U=Math.max(c.length,G.length);if((U-f)/U>R){if(f<P)P=f,j=[G];else if(f===P)j.push(G)}}),j.sort((G,f)=>G.localeCompare(f)),$)j=j.map((G)=>`--${G}`);if(j.length>1)return`
11
+ (Did you mean one of ${j.join(", ")}?)`;if(j.length===1)return`
12
+ (Did you mean ${j[0]}?)`;return""}h$.suggestSimilar=k$});var rc=x((s$)=>{var b$=t("node:events").EventEmitter,Rc=t("node:child_process"),X=t("node:path"),Gc=t("node:fs"),Z=t("node:process"),{Argument:u$,humanReadableArgName:O$}=l(),{CommanderError:fc}=g(),{Help:t$}=jc(),{Option:sc,DualOptions:g$}=Pc(),{suggestSimilar:mc}=gc();class Uc extends b${constructor(c){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=c||"",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:(y)=>Z.stdout.write(y),writeErr:(y)=>Z.stderr.write(y),getOutHelpWidth:()=>Z.stdout.isTTY?Z.stdout.columns:void 0,getErrHelpWidth:()=>Z.stderr.isTTY?Z.stderr.columns:void 0,outputError:(y,$)=>$(y)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(c){return this._outputConfiguration=c._outputConfiguration,this._helpOption=c._helpOption,this._helpCommand=c._helpCommand,this._helpConfiguration=c._helpConfiguration,this._exitCallback=c._exitCallback,this._storeOptionsAsProperties=c._storeOptionsAsProperties,this._combineFlagAndOptionalValue=c._combineFlagAndOptionalValue,this._allowExcessArguments=c._allowExcessArguments,this._enablePositionalOptions=c._enablePositionalOptions,this._showHelpAfterError=c._showHelpAfterError,this._showSuggestionAfterError=c._showSuggestionAfterError,this}_getCommandAndAncestors(){let c=[];for(let y=this;y;y=y.parent)c.push(y);return c}command(c,y,$){let j=y,P=$;if(typeof j==="object"&&j!==null)P=j,j=null;P=P||{};let[,R,G]=c.match(/([^ ]+) *(.*)/),f=this.createCommand(R);if(j)f.description(j),f._executableHandler=!0;if(P.isDefault)this._defaultCommandName=f._name;if(f._hidden=!!(P.noHelp||P.hidden),f._executableFile=P.executableFile||null,G)f.arguments(G);if(this._registerCommand(f),f.parent=this,f.copyInheritedSettings(this),j)return this;return f}createCommand(c){return new Uc(c)}createHelp(){return Object.assign(new t$,this.configureHelp())}configureHelp(c){if(c===void 0)return this._helpConfiguration;return this._helpConfiguration=c,this}configureOutput(c){if(c===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,c),this}showHelpAfterError(c=!0){if(typeof c!=="string")c=!!c;return this._showHelpAfterError=c,this}showSuggestionAfterError(c=!0){return this._showSuggestionAfterError=!!c,this}addCommand(c,y){if(!c._name)throw Error(`Command passed to .addCommand() must have a name
13
+ - specify the name in Command constructor or using .name()`);if(y=y||{},y.isDefault)this._defaultCommandName=c._name;if(y.noHelp||y.hidden)c._hidden=!0;return this._registerCommand(c),c.parent=this,c._checkForBrokenPassThrough(),this}createArgument(c,y){return new u$(c,y)}argument(c,y,$,j){let P=this.createArgument(c,y);if(typeof $==="function")P.default(j).argParser($);else P.default($);return this.addArgument(P),this}arguments(c){return c.trim().split(/ +/).forEach((y)=>{this.argument(y)}),this}addArgument(c){let y=this.registeredArguments.slice(-1)[0];if(y&&y.variadic)throw Error(`only the last argument can be variadic '${y.name()}'`);if(c.required&&c.defaultValue!==void 0&&c.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${c.name()}'`);return this.registeredArguments.push(c),this}helpCommand(c,y){if(typeof c==="boolean")return this._addImplicitHelpCommand=c,this;c=c??"help [command]";let[,$,j]=c.match(/([^ ]+) *(.*)/),P=y??"display help for command",R=this.createCommand($);if(R.helpOption(!1),j)R.arguments(j);if(P)R.description(P);return this._addImplicitHelpCommand=!0,this._helpCommand=R,this}addHelpCommand(c,y){if(typeof c!=="object")return this.helpCommand(c,y),this;return this._addImplicitHelpCommand=!0,this._helpCommand=c,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(c,y){let $=["preSubcommand","preAction","postAction"];if(!$.includes(c))throw Error(`Unexpected value for event passed to hook : '${c}'.
14
+ Expecting one of '${$.join("', '")}'`);if(this._lifeCycleHooks[c])this._lifeCycleHooks[c].push(y);else this._lifeCycleHooks[c]=[y];return this}exitOverride(c){if(c)this._exitCallback=c;else this._exitCallback=(y)=>{if(y.code!=="commander.executeSubCommandAsync")throw y};return this}_exit(c,y,$){if(this._exitCallback)this._exitCallback(new fc(c,y,$));Z.exit(c)}action(c){let y=($)=>{let j=this.registeredArguments.length,P=$.slice(0,j);if(this._storeOptionsAsProperties)P[j]=this;else P[j]=this.opts();return P.push(this),c.apply(this,P)};return this._actionHandler=y,this}createOption(c,y){return new sc(c,y)}_callParseArg(c,y,$,j){try{return c.parseArg(y,$)}catch(P){if(P.code==="commander.invalidArgument"){let R=`${j} ${P.message}`;this.error(R,{exitCode:P.exitCode,code:P.code})}throw P}}_registerOption(c){let y=c.short&&this._findOption(c.short)||c.long&&this._findOption(c.long);if(y){let $=c.long&&this._findOption(c.long)?c.long:c.short;throw Error(`Cannot add option '${c.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${$}'
15
+ - already used by option '${y.flags}'`)}this.options.push(c)}_registerCommand(c){let y=(j)=>{return[j.name()].concat(j.aliases())},$=y(c).find((j)=>this._findCommand(j));if($){let j=y(this._findCommand($)).join("|"),P=y(c).join("|");throw Error(`cannot add command '${P}' as already have command '${j}'`)}this.commands.push(c)}addOption(c){this._registerOption(c);let y=c.name(),$=c.attributeName();if(c.negate){let P=c.long.replace(/^--no-/,"--");if(!this._findOption(P))this.setOptionValueWithSource($,c.defaultValue===void 0?!0:c.defaultValue,"default")}else if(c.defaultValue!==void 0)this.setOptionValueWithSource($,c.defaultValue,"default");let j=(P,R,G)=>{if(P==null&&c.presetArg!==void 0)P=c.presetArg;let f=this.getOptionValue($);if(P!==null&&c.parseArg)P=this._callParseArg(c,P,f,R);else if(P!==null&&c.variadic)P=c._concatValue(P,f);if(P==null)if(c.negate)P=!1;else if(c.isBoolean()||c.optional)P=!0;else P="";this.setOptionValueWithSource($,P,G)};if(this.on("option:"+y,(P)=>{let R=`error: option '${c.flags}' argument '${P}' is invalid.`;j(P,R,"cli")}),c.envVar)this.on("optionEnv:"+y,(P)=>{let R=`error: option '${c.flags}' value '${P}' from env '${c.envVar}' is invalid.`;j(P,R,"env")});return this}_optionEx(c,y,$,j,P){if(typeof y==="object"&&y instanceof sc)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let R=this.createOption(y,$);if(R.makeOptionMandatory(!!c.mandatory),typeof j==="function")R.default(P).argParser(j);else if(j instanceof RegExp){let G=j;j=(f,U)=>{let q=G.exec(f);return q?q[0]:U},R.default(P).argParser(j)}else R.default(j);return this.addOption(R)}option(c,y,$,j){return this._optionEx({},c,y,$,j)}requiredOption(c,y,$,j){return this._optionEx({mandatory:!0},c,y,$,j)}combineFlagAndOptionalValue(c=!0){return this._combineFlagAndOptionalValue=!!c,this}allowUnknownOption(c=!0){return this._allowUnknownOption=!!c,this}allowExcessArguments(c=!0){return this._allowExcessArguments=!!c,this}enablePositionalOptions(c=!0){return this._enablePositionalOptions=!!c,this}passThroughOptions(c=!0){return this._passThroughOptions=!!c,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(c=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!c,this}getOptionValue(c){if(this._storeOptionsAsProperties)return this[c];return this._optionValues[c]}setOptionValue(c,y){return this.setOptionValueWithSource(c,y,void 0)}setOptionValueWithSource(c,y,$){if(this._storeOptionsAsProperties)this[c]=y;else this._optionValues[c]=y;return this._optionValueSources[c]=$,this}getOptionValueSource(c){return this._optionValueSources[c]}getOptionValueSourceWithGlobals(c){let y;return this._getCommandAndAncestors().forEach(($)=>{if($.getOptionValueSource(c)!==void 0)y=$.getOptionValueSource(c)}),y}_prepareUserArgs(c,y){if(c!==void 0&&!Array.isArray(c))throw Error("first parameter to parse must be array or undefined");if(y=y||{},c===void 0&&y.from===void 0){if(Z.versions?.electron)y.from="electron";let j=Z.execArgv??[];if(j.includes("-e")||j.includes("--eval")||j.includes("-p")||j.includes("--print"))y.from="eval"}if(c===void 0)c=Z.argv;this.rawArgs=c.slice();let $;switch(y.from){case void 0:case"node":this._scriptPath=c[1],$=c.slice(2);break;case"electron":if(Z.defaultApp)this._scriptPath=c[1],$=c.slice(2);else $=c.slice(1);break;case"user":$=c.slice(0);break;case"eval":$=c.slice(1);break;default:throw Error(`unexpected parse option { from: '${y.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",$}parse(c,y){let $=this._prepareUserArgs(c,y);return this._parseCommand([],$),this}async parseAsync(c,y){let $=this._prepareUserArgs(c,y);return await this._parseCommand([],$),this}_executeSubCommand(c,y){y=y.slice();let $=!1,j=[".js",".ts",".tsx",".mjs",".cjs"];function P(q,w){let Y=X.resolve(q,w);if(Gc.existsSync(Y))return Y;if(j.includes(X.extname(w)))return;let J=j.find((Q)=>Gc.existsSync(`${Y}${Q}`));if(J)return`${Y}${J}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let R=c._executableFile||`${this._name}-${c._name}`,G=this._executableDir||"";if(this._scriptPath){let q;try{q=Gc.realpathSync(this._scriptPath)}catch(w){q=this._scriptPath}G=X.resolve(X.dirname(q),G)}if(G){let q=P(G,R);if(!q&&!c._executableFile&&this._scriptPath){let w=X.basename(this._scriptPath,X.extname(this._scriptPath));if(w!==this._name)q=P(G,`${w}-${c._name}`)}R=q||R}$=j.includes(X.extname(R));let f;if(Z.platform!=="win32")if($)y.unshift(R),y=lc(Z.execArgv).concat(y),f=Rc.spawn(Z.argv[0],y,{stdio:"inherit"});else f=Rc.spawn(R,y,{stdio:"inherit"});else y.unshift(R),y=lc(Z.execArgv).concat(y),f=Rc.spawn(Z.execPath,y,{stdio:"inherit"});if(!f.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((w)=>{Z.on(w,()=>{if(f.killed===!1&&f.exitCode===null)f.kill(w)})});let U=this._exitCallback;f.on("close",(q)=>{if(q=q??1,!U)Z.exit(q);else U(new fc(q,"commander.executeSubCommandAsync","(close)"))}),f.on("error",(q)=>{if(q.code==="ENOENT"){let w=G?`searched for local subcommand relative to directory '${G}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Y=`'${R}' does not exist
16
+ - if '${c._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${J}`;throw Error(Z)}else if(I.code==="EACCES")throw Error(`'${R}' not executable`);if(!U)w.exit(1);else{let J=new qy(1,"commander.executeSubCommandAsync","(error)");J.nestedError=I,U(J)}}),this.runningCommand=S}_dispatchSubcommand(y,$,j){let G=this._findCommand(y);if(!G)this.help({error:!0});let P;return P=this._chainOrCallSubCommandHook(P,G,"preSubcommand"),P=this._chainOrCall(P,()=>{if(G._executableHandler)this._executeSubCommand(G,$.concat(j));else return G._parseCommand($,j)}),P}_dispatchHelpCommand(y){if(!y)this.help();let $=this._findCommand(y);if($&&!$._executableHandler)$.help();return this._dispatchSubcommand(y,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((y,$)=>{if(y.required&&this.args[$]==null)this.missingArgument(y.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let y=(j,G,P)=>{let R=G;if(G!==null&&j.parseArg){let q=`error: command-argument value '${G}' is invalid for argument '${j.name()}'.`;R=this._callParseArg(j,G,P,q)}return R};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((j,G)=>{let P=j.defaultValue;if(j.variadic){if(G<this.args.length){if(P=this.args.slice(G),j.parseArg)P=P.reduce((R,q)=>{return y(j,q,R)},j.defaultValue)}else if(P===void 0)P=[]}else if(G<this.args.length){if(P=this.args[G],j.parseArg)P=y(j,P,j.defaultValue)}$[G]=P}),this.processedArgs=$}_chainOrCall(y,$){if(y&&y.then&&typeof y.then==="function")return y.then(()=>$());return $()}_chainOrCallHooks(y,$){let j=y,G=[];if(this._getCommandAndAncestors().reverse().filter((P)=>P._lifeCycleHooks[$]!==void 0).forEach((P)=>{P._lifeCycleHooks[$].forEach((R)=>{G.push({hookedCommand:P,callback:R})})}),$==="postAction")G.reverse();return G.forEach((P)=>{j=this._chainOrCall(j,()=>{return P.callback(P.hookedCommand,this)})}),j}_chainOrCallSubCommandHook(y,$,j){let G=y;if(this._lifeCycleHooks[j]!==void 0)this._lifeCycleHooks[j].forEach((P)=>{G=this._chainOrCall(G,()=>{return P(this,$)})});return G}_parseCommand(y,$){let j=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),y=y.concat(j.operands),$=j.unknown,this.args=y.concat($),y&&this._findCommand(y[0]))return this._dispatchSubcommand(y[0],y.slice(1),$);if(this._getHelpCommand()&&y[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(y[1]);if(this._defaultCommandName)return this._outputHelpIfRequested($),this._dispatchSubcommand(this._defaultCommandName,y,$);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(j.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let G=()=>{if(j.unknown.length>0)this.unknownOption(j.unknown[0])},P=`command:${this.name()}`;if(this._actionHandler){G(),this._processArguments();let R;if(R=this._chainOrCallHooks(R,"preAction"),R=this._chainOrCall(R,()=>this._actionHandler(this.processedArgs)),this.parent)R=this._chainOrCall(R,()=>{this.parent.emit(P,y,$)});return R=this._chainOrCallHooks(R,"postAction"),R}if(this.parent&&this.parent.listenerCount(P))G(),this._processArguments(),this.parent.emit(P,y,$);else if(y.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",y,$);if(this.listenerCount("command:*"))this.emit("command:*",y,$);else if(this.commands.length)this.unknownCommand();else G(),this._processArguments()}else if(this.commands.length)G(),this.help({error:!0});else G(),this._processArguments()}_findCommand(y){if(!y)return;return this.commands.find(($)=>$._name===y||$._aliases.includes(y))}_findOption(y){return this.options.find(($)=>$.is(y))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((y)=>{y.options.forEach(($)=>{if($.mandatory&&y.getOptionValue($.attributeName())===void 0)y.missingMandatoryOptionValue($)})})}_checkForConflictingLocalOptions(){let y=this.options.filter((j)=>{let G=j.attributeName();if(this.getOptionValue(G)===void 0)return!1;return this.getOptionValueSource(G)!=="default"});y.filter((j)=>j.conflictsWith.length>0).forEach((j)=>{let G=y.find((P)=>j.conflictsWith.includes(P.attributeName()));if(G)this._conflictingOption(j,G)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((y)=>{y._checkForConflictingLocalOptions()})}parseOptions(y){let $=[],j=[],G=$,P=y.slice();function R(S){return S.length>1&&S[0]==="-"}let q=null;while(P.length){let S=P.shift();if(S==="--"){if(G===j)G.push(S);G.push(...P);break}if(q&&!R(S)){this.emit(`option:${q.name()}`,S);continue}if(q=null,R(S)){let U=this._findOption(S);if(U){if(U.required){let I=P.shift();if(I===void 0)this.optionMissingArgument(U);this.emit(`option:${U.name()}`,I)}else if(U.optional){let I=null;if(P.length>0&&!R(P[0]))I=P.shift();this.emit(`option:${U.name()}`,I)}else this.emit(`option:${U.name()}`);q=U.variadic?U:null;continue}}if(S.length>2&&S[0]==="-"&&S[1]!=="-"){let U=this._findOption(`-${S[1]}`);if(U){if(U.required||U.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${U.name()}`,S.slice(2));else this.emit(`option:${U.name()}`),P.unshift(`-${S.slice(2)}`);continue}}if(/^--[^=]+=/.test(S)){let U=S.indexOf("="),I=this._findOption(S.slice(0,U));if(I&&(I.required||I.optional)){this.emit(`option:${I.name()}`,S.slice(U+1));continue}}if(R(S))G=j;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&j.length===0){if(this._findCommand(S)){if($.push(S),P.length>0)j.push(...P);break}else if(this._getHelpCommand()&&S===this._getHelpCommand().name()){if($.push(S),P.length>0)$.push(...P);break}else if(this._defaultCommandName){if(j.push(S),P.length>0)j.push(...P);break}}if(this._passThroughOptions){if(G.push(S),P.length>0)G.push(...P);break}G.push(S)}return{operands:$,unknown:j}}opts(){if(this._storeOptionsAsProperties){let y={},$=this.options.length;for(let j=0;j<$;j++){let G=this.options[j].attributeName();y[G]=G===this._versionOptionName?this._version:this[G]}return y}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((y,$)=>Object.assign(y,$.opts()),{})}error(y,$){if(this._outputConfiguration.outputError(`${y}
18
+ - ${w}`;throw Error(Y)}else if(q.code==="EACCES")throw Error(`'${R}' not executable`);if(!U)Z.exit(1);else{let w=new fc(1,"commander.executeSubCommandAsync","(error)");w.nestedError=q,U(w)}}),this.runningCommand=f}_dispatchSubcommand(c,y,$){let j=this._findCommand(c);if(!j)this.help({error:!0});let P;return P=this._chainOrCallSubCommandHook(P,j,"preSubcommand"),P=this._chainOrCall(P,()=>{if(j._executableHandler)this._executeSubCommand(j,y.concat($));else return j._parseCommand(y,$)}),P}_dispatchHelpCommand(c){if(!c)this.help();let y=this._findCommand(c);if(y&&!y._executableHandler)y.help();return this._dispatchSubcommand(c,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((c,y)=>{if(c.required&&this.args[y]==null)this.missingArgument(c.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let c=($,j,P)=>{let R=j;if(j!==null&&$.parseArg){let G=`error: command-argument value '${j}' is invalid for argument '${$.name()}'.`;R=this._callParseArg($,j,P,G)}return R};this._checkNumberOfArguments();let y=[];this.registeredArguments.forEach(($,j)=>{let P=$.defaultValue;if($.variadic){if(j<this.args.length){if(P=this.args.slice(j),$.parseArg)P=P.reduce((R,G)=>{return c($,G,R)},$.defaultValue)}else if(P===void 0)P=[]}else if(j<this.args.length){if(P=this.args[j],$.parseArg)P=c($,P,$.defaultValue)}y[j]=P}),this.processedArgs=y}_chainOrCall(c,y){if(c&&c.then&&typeof c.then==="function")return c.then(()=>y());return y()}_chainOrCallHooks(c,y){let $=c,j=[];if(this._getCommandAndAncestors().reverse().filter((P)=>P._lifeCycleHooks[y]!==void 0).forEach((P)=>{P._lifeCycleHooks[y].forEach((R)=>{j.push({hookedCommand:P,callback:R})})}),y==="postAction")j.reverse();return j.forEach((P)=>{$=this._chainOrCall($,()=>{return P.callback(P.hookedCommand,this)})}),$}_chainOrCallSubCommandHook(c,y,$){let j=c;if(this._lifeCycleHooks[$]!==void 0)this._lifeCycleHooks[$].forEach((P)=>{j=this._chainOrCall(j,()=>{return P(this,y)})});return j}_parseCommand(c,y){let $=this.parseOptions(y);if(this._parseOptionsEnv(),this._parseOptionsImplied(),c=c.concat($.operands),y=$.unknown,this.args=c.concat(y),c&&this._findCommand(c[0]))return this._dispatchSubcommand(c[0],c.slice(1),y);if(this._getHelpCommand()&&c[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(c[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(y),this._dispatchSubcommand(this._defaultCommandName,c,y);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested($.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let j=()=>{if($.unknown.length>0)this.unknownOption($.unknown[0])},P=`command:${this.name()}`;if(this._actionHandler){j(),this._processArguments();let R;if(R=this._chainOrCallHooks(R,"preAction"),R=this._chainOrCall(R,()=>this._actionHandler(this.processedArgs)),this.parent)R=this._chainOrCall(R,()=>{this.parent.emit(P,c,y)});return R=this._chainOrCallHooks(R,"postAction"),R}if(this.parent&&this.parent.listenerCount(P))j(),this._processArguments(),this.parent.emit(P,c,y);else if(c.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",c,y);if(this.listenerCount("command:*"))this.emit("command:*",c,y);else if(this.commands.length)this.unknownCommand();else j(),this._processArguments()}else if(this.commands.length)j(),this.help({error:!0});else j(),this._processArguments()}_findCommand(c){if(!c)return;return this.commands.find((y)=>y._name===c||y._aliases.includes(c))}_findOption(c){return this.options.find((y)=>y.is(c))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((c)=>{c.options.forEach((y)=>{if(y.mandatory&&c.getOptionValue(y.attributeName())===void 0)c.missingMandatoryOptionValue(y)})})}_checkForConflictingLocalOptions(){let c=this.options.filter(($)=>{let j=$.attributeName();if(this.getOptionValue(j)===void 0)return!1;return this.getOptionValueSource(j)!=="default"});c.filter(($)=>$.conflictsWith.length>0).forEach(($)=>{let j=c.find((P)=>$.conflictsWith.includes(P.attributeName()));if(j)this._conflictingOption($,j)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((c)=>{c._checkForConflictingLocalOptions()})}parseOptions(c){let y=[],$=[],j=y,P=c.slice();function R(f){return f.length>1&&f[0]==="-"}let G=null;while(P.length){let f=P.shift();if(f==="--"){if(j===$)j.push(f);j.push(...P);break}if(G&&!R(f)){this.emit(`option:${G.name()}`,f);continue}if(G=null,R(f)){let U=this._findOption(f);if(U){if(U.required){let q=P.shift();if(q===void 0)this.optionMissingArgument(U);this.emit(`option:${U.name()}`,q)}else if(U.optional){let q=null;if(P.length>0&&!R(P[0]))q=P.shift();this.emit(`option:${U.name()}`,q)}else this.emit(`option:${U.name()}`);G=U.variadic?U:null;continue}}if(f.length>2&&f[0]==="-"&&f[1]!=="-"){let U=this._findOption(`-${f[1]}`);if(U){if(U.required||U.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${U.name()}`,f.slice(2));else this.emit(`option:${U.name()}`),P.unshift(`-${f.slice(2)}`);continue}}if(/^--[^=]+=/.test(f)){let U=f.indexOf("="),q=this._findOption(f.slice(0,U));if(q&&(q.required||q.optional)){this.emit(`option:${q.name()}`,f.slice(U+1));continue}}if(R(f))j=$;if((this._enablePositionalOptions||this._passThroughOptions)&&y.length===0&&$.length===0){if(this._findCommand(f)){if(y.push(f),P.length>0)$.push(...P);break}else if(this._getHelpCommand()&&f===this._getHelpCommand().name()){if(y.push(f),P.length>0)y.push(...P);break}else if(this._defaultCommandName){if($.push(f),P.length>0)$.push(...P);break}}if(this._passThroughOptions){if(j.push(f),P.length>0)j.push(...P);break}j.push(f)}return{operands:y,unknown:$}}opts(){if(this._storeOptionsAsProperties){let c={},y=this.options.length;for(let $=0;$<y;$++){let j=this.options[$].attributeName();c[j]=j===this._versionOptionName?this._version:this[j]}return c}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((c,y)=>Object.assign(c,y.opts()),{})}error(c,y){if(this._outputConfiguration.outputError(`${c}
19
19
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
20
  `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0});let j=$||{},G=j.exitCode||1,P=j.code||"commander.error";this._exit(G,P,y)}_parseOptionsEnv(){this.options.forEach((y)=>{if(y.envVar&&y.envVar in w.env){let $=y.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(y.required||y.optional)this.emit(`optionEnv:${y.name()}`,w.env[y.envVar]);else this.emit(`optionEnv:${y.name()}`)}})}_parseOptionsImplied(){let y=new fj(this.options),$=(j)=>{return this.getOptionValue(j)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(j))};this.options.filter((j)=>j.implied!==void 0&&$(j.attributeName())&&y.valueFromOption(this.getOptionValue(j.attributeName()),j)).forEach((j)=>{Object.keys(j.implied).filter((G)=>!$(G)).forEach((G)=>{this.setOptionValueWithSource(G,j.implied[G],"implied")})})}missingArgument(y){let $=`error: missing required argument '${y}'`;this.error($,{code:"commander.missingArgument"})}optionMissingArgument(y){let $=`error: option '${y.flags}' argument missing`;this.error($,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(y){let $=`error: required option '${y.flags}' not specified`;this.error($,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(y,$){let j=(R)=>{let q=R.attributeName(),S=this.getOptionValue(q),U=this.options.find((J)=>J.negate&&q===J.attributeName()),I=this.options.find((J)=>!J.negate&&q===J.attributeName());if(U&&(U.presetArg===void 0&&S===!1||U.presetArg!==void 0&&S===U.presetArg))return U;return I||R},G=(R)=>{let q=j(R),S=q.attributeName();if(this.getOptionValueSource(S)==="env")return`environment variable '${q.envVar}'`;return`option '${q.flags}'`},P=`error: ${G(y)} cannot be used with ${G($)}`;this.error(P,{code:"commander.conflictingOption"})}unknownOption(y){if(this._allowUnknownOption)return;let $="";if(y.startsWith("--")&&this._showSuggestionAfterError){let G=[],P=this;do{let R=P.createHelp().visibleOptions(P).filter((q)=>q.long).map((q)=>q.long);G=G.concat(R),P=P.parent}while(P&&!P._enablePositionalOptions);$=ty(y,G)}let j=`error: unknown option '${y}'${$}`;this.error(j,{code:"commander.unknownOption"})}_excessArguments(y){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,j=$===1?"":"s",P=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${j} but got ${y.length}.`;this.error(P,{code:"commander.excessArguments"})}unknownCommand(){let y=this.args[0],$="";if(this._showSuggestionAfterError){let G=[];this.createHelp().visibleCommands(this).forEach((P)=>{if(G.push(P.name()),P.alias())G.push(P.alias())}),$=ty(y,G)}let j=`error: unknown command '${y}'${$}`;this.error(j,{code:"commander.unknownCommand"})}version(y,$,j){if(y===void 0)return this._version;this._version=y,$=$||"-V, --version",j=j||"output the version number";let G=this.createOption($,j);return this._versionOptionName=G.attributeName(),this._registerOption(G),this.on("option:"+G.name(),()=>{this._outputConfiguration.writeOut(`${y}
22
- `),this._exit(0,"commander.version",y)}),this}description(y,$){if(y===void 0&&$===void 0)return this._description;if(this._description=y,$)this._argsDescription=$;return this}summary(y){if(y===void 0)return this._summary;return this._summary=y,this}alias(y){if(y===void 0)return this._aliases[0];let $=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)$=this.commands[this.commands.length-1];if(y===$._name)throw Error("Command alias can't be the same as its name");let j=this.parent?._findCommand(y);if(j){let G=[j.name()].concat(j.aliases()).join("|");throw Error(`cannot add alias '${y}' to command '${this.name()}' as already have command '${G}'`)}return $._aliases.push(y),this}aliases(y){if(y===void 0)return this._aliases;return y.forEach(($)=>this.alias($)),this}usage(y){if(y===void 0){if(this._usage)return this._usage;let $=this.registeredArguments.map((j)=>{return Wj(j)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?$:[]).join(" ")}return this._usage=y,this}name(y){if(y===void 0)return this._name;return this._name=y,this}nameFromFilename(y){return this._name=z.basename(y,z.extname(y)),this}executableDir(y){if(y===void 0)return this._executableDir;return this._executableDir=y,this}helpInformation(y){let $=this.createHelp();if($.helpWidth===void 0)$.helpWidth=y&&y.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return $.formatHelp(this,$)}_getHelpContext(y){y=y||{};let $={error:!!y.error},j;if($.error)j=(G)=>this._outputConfiguration.writeErr(G);else j=(G)=>this._outputConfiguration.writeOut(G);return $.write=y.write||j,$.command=this,$}outputHelp(y){let $;if(typeof y==="function")$=y,y=void 0;let j=this._getHelpContext(y);this._getCommandAndAncestors().reverse().forEach((P)=>P.emit("beforeAllHelp",j)),this.emit("beforeHelp",j);let G=this.helpInformation(j);if($){if(G=$(G),typeof G!=="string"&&!Buffer.isBuffer(G))throw Error("outputHelp callback must return a string or a Buffer")}if(j.write(G),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",j),this._getCommandAndAncestors().forEach((P)=>P.emit("afterAllHelp",j))}helpOption(y,$){if(typeof y==="boolean"){if(y)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return y=y??"-h, --help",$=$??"display help for command",this._helpOption=this.createOption(y,$),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(y){return this._helpOption=y,this}help(y){this.outputHelp(y);let $=w.exitCode||0;if($===0&&y&&typeof y!=="function"&&y.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(y,$){let j=["beforeAll","before","after","afterAll"];if(!j.includes(y))throw Error(`Unexpected value for position to addHelpText.
23
- Expecting one of '${j.join("', '")}'`);let G=`${y}Help`;return this.on(G,(P)=>{let R;if(typeof $==="function")R=$({error:P.error,command:P.command});else R=$;if(R)P.write(`${R}
24
- `)}),this}_outputHelpIfRequested(y){let $=this._getHelpOption();if($&&y.find((G)=>$.is(G)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function my(y){return y.map(($)=>{if(!$.startsWith("--inspect"))return $;let j,G="127.0.0.1",P="9229",R;if((R=$.match(/^(--inspect(-brk)?)$/))!==null)j=R[1];else if((R=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(j=R[1],/^\d+$/.test(R[3]))P=R[3];else G=R[3];else if((R=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)j=R[1],G=R[3],P=R[4];if(j&&P!=="0")return`${j}=${G}:${parseInt(P)+1}`;return $})}Kj.Command=Sy});var iy=B((Nj)=>{var{Argument:sy}=s(),{Command:Uy}=ly(),{CommanderError:Bj,InvalidArgumentError:ry}=u(),{Help:Cj}=jy(),{Option:dy}=Gy();Nj.program=new Uy;Nj.createCommand=(y)=>new Uy(y);Nj.createOption=(y,$)=>new dy(y,$);Nj.createArgument=(y,$)=>new sy(y,$);Nj.Command=Uy;Nj.Option=dy;Nj.Argument=sy;Nj.Help=Cj;Nj.CommanderError=Bj;Nj.InvalidArgumentError=ry;Nj.InvalidOptionArgumentError=ry});var ay=o$(iy(),1),{program:F,createCommand:lG,createArgument:sG,createOption:rG,CommanderError:dG,InvalidArgumentError:iG,InvalidOptionArgumentError:aG,Command:eG,Argument:nG,Option:oG,Help:pG}=ay.default;var ey="0.2.0";import{homedir as mj}from"os";import{join as ny}from"path";import{existsSync as Ey,mkdirSync as lj,readFileSync as sj,writeFileSync as rj,unlinkSync as dj}from"fs";function oy(){let y=process.env.ACE_TEST_HOME??mj();return ny(y,".ace")}function Iy(){return ny(oy(),"credentials.json")}var ij=process.env.DEBUG==="true"||process.env.ACE_DEBUG==="true";function D(y,...$){if(ij)console.error(`[ace-cli debug] ${y}`,...$)}function aj(){let y=oy();if(!Ey(y))lj(y,{recursive:!0,mode:448})}function C(){try{let y=Iy();if(!Ey(y))return D("Credentials file does not exist:",y),null;let $=sj(y,"utf-8"),j=JSON.parse($);if(j.expiresAt&&new Date(j.expiresAt)<new Date)return D("Token expired at:",j.expiresAt),null;return j}catch(y){return D("Error reading credentials:",y),null}}function Ly(y){aj();let $=Iy();rj($,JSON.stringify(y,null,2),{mode:384}),D("Credentials saved to:",$)}function Qy(){try{let y=Iy();if(Ey(y))return dj(y),D("Credentials cleared"),!0;return!1}catch(y){return D("Error clearing credentials:",y),!1}}function g(){return C()?.apiUrl??process.env.ACE_API_URL??"https://aceisyourassistant.com"}import Wy from"node:process";import{Buffer as I$}from"node:buffer";import L$ from"node:path";import{fileURLToPath as _G}from"node:url";import{promisify as zG}from"node:util";import Q$ from"node:child_process";import HG,{constants as WG}from"node:fs/promises";import j$ from"node:process";import G$,{constants as jG}from"node:fs/promises";import $$ from"node:process";import yG from"node:os";import $G from"node:fs";import oj from"node:fs";import py from"node:fs";var Jy;function ej(){try{return py.statSync("/.dockerenv"),!0}catch{return!1}}function nj(){try{return py.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Zy(){if(Jy===void 0)Jy=ej()||nj();return Jy}var Yy,pj=()=>{try{return oj.statSync("/run/.containerenv"),!0}catch{return!1}};function k(){if(Yy===void 0)Yy=pj()||Zy();return Yy}var y$=()=>{if($$.platform!=="linux")return!1;if(yG.release().toLowerCase().includes("microsoft")){if(k())return!1;return!0}try{return $G.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!k():!1}catch{return!1}},W=$$.env.__IS_WSL_TEST__?y$:y$();var GG=(()=>{let $;return async function(){if($)return $;let j="/etc/wsl.conf",G=!1;try{await G$.access(j,jG.F_OK),G=!0}catch{}if(!G)return"/mnt/";let P=await G$.readFile(j,{encoding:"utf8"}),R=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(P);if(!R)return"/mnt/";return $=R.groups.mountPoint.trim(),$=$.endsWith("/")?$:`${$}/`,$}})(),PG=async()=>{return`${await GG()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},cy=async()=>{if(W)return PG();return`${j$.env.SYSTEMROOT||j$.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`};function M(y,$,j){let G=(P)=>Object.defineProperty(y,$,{value:P,enumerable:!0,writable:!0});return Object.defineProperty(y,$,{configurable:!0,enumerable:!0,get(){let P=j();return G(P),P},set(P){G(P)}}),y}import{promisify as cG}from"node:util";import zy from"node:process";import{execFile as wG}from"node:child_process";import{promisify as RG}from"node:util";import qG from"node:process";import{execFile as SG}from"node:child_process";var UG=RG(SG);async function wy(){if(qG.platform!=="darwin")throw Error("macOS only");let{stdout:y}=await UG("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),j=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(y)?.groups.id??"com.apple.Safari";if(j==="com.apple.safari")return"com.apple.Safari";return j}import EG from"node:process";import{promisify as IG}from"node:util";import{execFile as LG,execFileSync as CP}from"node:child_process";var QG=IG(LG);async function P$(y,{humanReadableOutput:$=!0,signal:j}={}){if(EG.platform!=="darwin")throw Error("macOS only");let G=$?[]:["-ss"],P={};if(j)P.signal=j;let{stdout:R}=await QG("osascript",["-e",y,G],P);return R.trim()}async function Xy(y){return P$(`tell application "Finder" to set app_path to application file id "${y}" as string
25
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as JG}from"node:util";import{execFile as ZG}from"node:child_process";var YG=JG(ZG),R$={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},kP=new Map(Object.entries(R$));class Fy extends Error{}async function _y(y=YG){let{stdout:$}=await y("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),j=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec($);if(!j)throw new Fy(`Cannot find Windows browser in stdout: ${JSON.stringify($)}`);let{id:G}=j.groups,P=R$[G];if(!P)throw new Fy(`Unknown browser ID: ${G}`);return P}var XG=cG(wG),FG=(y)=>y.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,($)=>$.toUpperCase());async function Hy(){if(zy.platform==="darwin"){let y=await wy();return{name:await Xy(y),id:y}}if(zy.platform==="linux"){let{stdout:y}=await XG("xdg-mime",["query","default","x-scheme-handler/http"]),$=y.trim();return{name:FG($.replace(/.desktop$/,"").replace("-"," ")),id:$}}if(zy.platform==="win32")return _y();throw Error("Only macOS, Linux, and Windows are supported")}var MG=zG(Q$.execFile),My=L$.dirname(_G(import.meta.url)),q$=L$.join(My,"xdg-open"),{platform:b,arch:S$}=Wy;async function fG(){let y=await cy(),$=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,j=I$.from($,"utf16le").toString("base64"),{stdout:G}=await MG(y,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",j],{encoding:"utf8"}),P=G.trim(),R={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return R[P]?{id:R[P]}:{}}var U$=async(y,$)=>{let j;for(let G of y)try{return await $(G)}catch(P){j=P}throw j},r=async(y)=>{if(y={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...y},Array.isArray(y.app))return U$(y.app,(S)=>r({...y,app:S}));let{name:$,arguments:j=[]}=y.app??{};if(j=[...j],Array.isArray($))return U$($,(S)=>r({...y,app:{name:S,arguments:j}}));if($==="browser"||$==="browserPrivate"){let S={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},U={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},I=W?await fG():await Hy();if(I.id in S){let J=S[I.id];if($==="browserPrivate")j.push(U[J]);return r({...y,app:{name:N[J],arguments:j}})}throw Error(`${I.name} is not supported as a default browser`)}let G,P=[],R={};if(b==="darwin"){if(G="open",y.wait)P.push("--wait-apps");if(y.background)P.push("--background");if(y.newInstance)P.push("--new");if($)P.push("-a",$)}else if(b==="win32"||W&&!k()&&!$){if(G=await cy(),P.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),!W)R.windowsVerbatimArguments=!0;let S=["Start"];if(y.wait)S.push("-Wait");if($){if(S.push(`"\`"${$}\`""`),y.target)j.push(y.target)}else if(y.target)S.push(`"${y.target}"`);if(j.length>0)j=j.map((U)=>`"\`"${U}\`""`),S.push("-ArgumentList",j.join(","));y.target=I$.from(S.join(" "),"utf16le").toString("base64")}else{if($)G=$;else{let S=!My||My==="/",U=!1;try{await HG.access(q$,WG.X_OK),U=!0}catch{}G=Wy.versions.electron??(b==="android"||S||!U)?"xdg-open":q$}if(j.length>0)P.push(...j);if(!y.wait)R.stdio="ignore",R.detached=!0}if(b==="darwin"&&j.length>0)P.push("--args",...j);if(y.target)P.push(y.target);let q=Q$.spawn(G,P,R);if(y.wait)return new Promise((S,U)=>{q.once("error",U),q.once("close",(I)=>{if(!y.allowNonzeroExitCode&&I>0){U(Error(`Exited with code ${I}`));return}S(q)})});return q.unref(),q},KG=(y,$)=>{if(typeof y!=="string")throw TypeError("Expected a `target`");return r({...$,target:y})};function E$(y){if(typeof y==="string"||Array.isArray(y))return y;let{[S$]:$}=y;if(!$)throw Error(`${S$} is not supported`);return $}function d({[b]:y},{wsl:$}){if($&&W)return E$($);if(!y)throw Error(`${b} is not supported`);return E$(y)}var N={};M(N,"chrome",()=>d({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));M(N,"brave",()=>d({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));M(N,"firefox",()=>d({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));M(N,"edge",()=>d({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));M(N,"browser",()=>"browser");M(N,"browserPrivate",()=>"browserPrivate");var J$=KG;var TG=2000,BG=600;async function fy(y){let $=y??g();console.log(`Initiating authentication...
26
- `);let j=await fetch(`${$}/api/cli-auth/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!j.ok){let Z=await j.text();throw Error(`Failed to initiate auth: ${Z}`)}let{deviceCode:G,userCode:P,verificationUrl:R,interval:q,expiresIn:S}=await j.json(),U=(q||TG/1000)*1000,I=Math.ceil((S||BG)/(U/1000));console.log("Opening browser to authenticate..."),console.log(""),console.log(` Your code: ${P}`),console.log(""),console.log(` Or visit: ${R}`),console.log(""),await J$(R),console.log("Waiting for authorization...");let J=0;while(J<I){await CG(U),J++;try{let Z=await fetch(`${$}/api/cli-auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:G})});if(!Z.ok){if(Z.status===400)continue;throw Error(`Poll failed: ${await Z.text()}`)}let X=await Z.json();if(X.status==="authorized"&&X.token){let c={apiUrl:$,token:X.token.token,expiresAt:X.token.expiresAt,userId:X.token.userId,userEmail:X.token.userEmail};Ly(c),console.log(""),console.log(`Authenticated as ${X.token.userEmail}`),console.log(""),console.log("You can now use ace commands. Try:"),console.log(" ace orient"),console.log(' ace capture "My new task"');return}if(X.status==="expired")throw Error("Authentication code expired. Please try again.")}catch(Z){if(Z instanceof TypeError)continue;throw Z}}throw Error("Authentication timed out. Please try again.")}function CG(y){return new Promise(($)=>setTimeout($,y))}function Ky(y,$){let j=$?new Date($):new Date,G=y.toLowerCase().trim().replace(/\s+/g,""),P,R=0,q=G.match(/^(\d{1,2}):(\d{2})(?::\d{2})?$/);if(q)P=parseInt(q[1],10),R=parseInt(q[2],10);else{let S=G.match(/^(\d{1,2})(?::(\d{2}))?([ap]m?)$/);if(S){P=parseInt(S[1],10),R=S[2]?parseInt(S[2],10):0;let U=S[3].startsWith("p");if(U&&P!==12)P+=12;else if(!U&&P===12)P=0}else{let U=new Date(y);if(!isNaN(U.getTime()))return U.toISOString();throw Error(`Invalid time format: ${y}. Use "HH:MM", "H:MMam/pm", or ISO format.`)}}if(P<0||P>23)throw Error(`Invalid hours: ${P}. Must be between 0 and 23.`);if(R<0||R>59)throw Error(`Invalid minutes: ${R}. Must be between 0 and 59.`);return j.setHours(P,R,0,0),j.toISOString()}function Z$(y,$){let j=new Date(y);return new Date(j.getTime()+$*60*1000).toISOString()}function V(y){let j=new Date(new Date);if(j.setHours(0,0,0,0),y==="today"){let q=new Date(j);return q.setHours(23,59,59,999),{startDate:j.toISOString(),endDate:q.toISOString()}}if(y==="week"){let q=new Date(j);return q.setDate(q.getDate()+7),q.setHours(23,59,59,999),{startDate:j.toISOString(),endDate:q.toISOString()}}if(!/^\d{4}-\d{2}-\d{2}$/.test(y))throw Error(`Invalid date format: ${y}. Use YYYY-MM-DD format.`);let P=new Date(y);if(isNaN(P.getTime()))throw Error(`Invalid date: ${y}. Use YYYY-MM-DD format.`);P.setHours(0,0,0,0);let R=new Date(P);return R.setHours(23,59,59,999),{startDate:P.toISOString(),endDate:R.toISOString()}}function t(y){return new Date(y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function x(y){return new Date(y).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Y$(y,$,j){if(j)return t(y);let G=new Date(y),P=new Date($);if(G.toDateString()===P.toDateString())return`${x(y)} - ${x($)}`;return`${t(y)} ${x(y)} - ${t($)} ${x($)}`}function m(){return new Date().toISOString().split("T")[0]}function L(){return process.argv.includes("--json")}function Q(y,$){if($?.json||L())console.log(JSON.stringify(y,null,2));else if(typeof y==="string")console.log(y);else console.log(JSON.stringify(y,null,2))}function E(y){if(L())console.log(JSON.stringify({error:y}));else console.error(`Error: ${y}`)}function f(y){let $=[`[${y.id.slice(0,8)}] ${y.name}`];if(y.project_name)$.push(`(${y.project_name})`);if(y.dueDate)$.push(`due: ${y.dueDate}`);if(y.status==="waiting"&&y.waitingFor)$.push(`waiting: ${y.waitingFor}`);return $.join(" ")}function K(y){let $=[`[${y.id.slice(0,8)}] ${y.name}`];if(y.category_name)$.push(`(${y.category_name})`);if(y.status!=="active")$.push(`[${y.status}]`);return $.join(" ")}function _(y,$){if(y.length===0)return $?`${$}: (none)`:"(no actions)";let j=y.map((G)=>` ${f(G)}`);if($)return`${$} (${y.length}):
27
- ${j.join(`
28
- `)}`;return j.join(`
29
- `)}function v(y,$){if(y.length===0)return $?`${$}: (none)`:"(no projects)";let j=y.map((G)=>` ${K(G)}`);if($)return`${$} (${y.length}):
30
- ${j.join(`
31
- `)}`;return j.join(`
32
- `)}function c$(y){let $=[];$.push(`Inbox: ${y.inboxCount} items`);let j=y.domains.map((G)=>` ${G.name}: ${G.active_count}/${G.activeProjectLimit} active`);if($.push(`Capacity:
33
- ${j.join(`
34
- `)}`),y.activeProjects.length>0)$.push(v(y.activeProjects,"Active Projects"));if(y.overdue.length>0)$.push(_(y.overdue,"Overdue"));if(y.dueToday.length>0)$.push(_(y.dueToday,"Due Today"));if(y.waiting.length>0)$.push(_(y.waiting,"Waiting"));return $.join(`
21
+ `),this.outputHelp({error:!0});let $=y||{},j=$.exitCode||1,P=$.code||"commander.error";this._exit(j,P,c)}_parseOptionsEnv(){this.options.forEach((c)=>{if(c.envVar&&c.envVar in Z.env){let y=c.attributeName();if(this.getOptionValue(y)===void 0||["default","config","env"].includes(this.getOptionValueSource(y)))if(c.required||c.optional)this.emit(`optionEnv:${c.name()}`,Z.env[c.envVar]);else this.emit(`optionEnv:${c.name()}`)}})}_parseOptionsImplied(){let c=new g$(this.options),y=($)=>{return this.getOptionValue($)!==void 0&&!["default","implied"].includes(this.getOptionValueSource($))};this.options.filter(($)=>$.implied!==void 0&&y($.attributeName())&&c.valueFromOption(this.getOptionValue($.attributeName()),$)).forEach(($)=>{Object.keys($.implied).filter((j)=>!y(j)).forEach((j)=>{this.setOptionValueWithSource(j,$.implied[j],"implied")})})}missingArgument(c){let y=`error: missing required argument '${c}'`;this.error(y,{code:"commander.missingArgument"})}optionMissingArgument(c){let y=`error: option '${c.flags}' argument missing`;this.error(y,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(c){let y=`error: required option '${c.flags}' not specified`;this.error(y,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(c,y){let $=(R)=>{let G=R.attributeName(),f=this.getOptionValue(G),U=this.options.find((w)=>w.negate&&G===w.attributeName()),q=this.options.find((w)=>!w.negate&&G===w.attributeName());if(U&&(U.presetArg===void 0&&f===!1||U.presetArg!==void 0&&f===U.presetArg))return U;return q||R},j=(R)=>{let G=$(R),f=G.attributeName();if(this.getOptionValueSource(f)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},P=`error: ${j(c)} cannot be used with ${j(y)}`;this.error(P,{code:"commander.conflictingOption"})}unknownOption(c){if(this._allowUnknownOption)return;let y="";if(c.startsWith("--")&&this._showSuggestionAfterError){let j=[],P=this;do{let R=P.createHelp().visibleOptions(P).filter((G)=>G.long).map((G)=>G.long);j=j.concat(R),P=P.parent}while(P&&!P._enablePositionalOptions);y=mc(c,j)}let $=`error: unknown option '${c}'${y}`;this.error($,{code:"commander.unknownOption"})}_excessArguments(c){if(this._allowExcessArguments)return;let y=this.registeredArguments.length,$=y===1?"":"s",P=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${y} argument${$} but got ${c.length}.`;this.error(P,{code:"commander.excessArguments"})}unknownCommand(){let c=this.args[0],y="";if(this._showSuggestionAfterError){let j=[];this.createHelp().visibleCommands(this).forEach((P)=>{if(j.push(P.name()),P.alias())j.push(P.alias())}),y=mc(c,j)}let $=`error: unknown command '${c}'${y}`;this.error($,{code:"commander.unknownCommand"})}version(c,y,$){if(c===void 0)return this._version;this._version=c,y=y||"-V, --version",$=$||"output the version number";let j=this.createOption(y,$);return this._versionOptionName=j.attributeName(),this._registerOption(j),this.on("option:"+j.name(),()=>{this._outputConfiguration.writeOut(`${c}
22
+ `),this._exit(0,"commander.version",c)}),this}description(c,y){if(c===void 0&&y===void 0)return this._description;if(this._description=c,y)this._argsDescription=y;return this}summary(c){if(c===void 0)return this._summary;return this._summary=c,this}alias(c){if(c===void 0)return this._aliases[0];let y=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)y=this.commands[this.commands.length-1];if(c===y._name)throw Error("Command alias can't be the same as its name");let $=this.parent?._findCommand(c);if($){let j=[$.name()].concat($.aliases()).join("|");throw Error(`cannot add alias '${c}' to command '${this.name()}' as already have command '${j}'`)}return y._aliases.push(c),this}aliases(c){if(c===void 0)return this._aliases;return c.forEach((y)=>this.alias(y)),this}usage(c){if(c===void 0){if(this._usage)return this._usage;let y=this.registeredArguments.map(($)=>{return O$($)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?y:[]).join(" ")}return this._usage=c,this}name(c){if(c===void 0)return this._name;return this._name=c,this}nameFromFilename(c){return this._name=X.basename(c,X.extname(c)),this}executableDir(c){if(c===void 0)return this._executableDir;return this._executableDir=c,this}helpInformation(c){let y=this.createHelp();if(y.helpWidth===void 0)y.helpWidth=c&&c.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return y.formatHelp(this,y)}_getHelpContext(c){c=c||{};let y={error:!!c.error},$;if(y.error)$=(j)=>this._outputConfiguration.writeErr(j);else $=(j)=>this._outputConfiguration.writeOut(j);return y.write=c.write||$,y.command=this,y}outputHelp(c){let y;if(typeof c==="function")y=c,c=void 0;let $=this._getHelpContext(c);this._getCommandAndAncestors().reverse().forEach((P)=>P.emit("beforeAllHelp",$)),this.emit("beforeHelp",$);let j=this.helpInformation($);if(y){if(j=y(j),typeof j!=="string"&&!Buffer.isBuffer(j))throw Error("outputHelp callback must return a string or a Buffer")}if($.write(j),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",$),this._getCommandAndAncestors().forEach((P)=>P.emit("afterAllHelp",$))}helpOption(c,y){if(typeof c==="boolean"){if(c)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return c=c??"-h, --help",y=y??"display help for command",this._helpOption=this.createOption(c,y),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(c){return this._helpOption=c,this}help(c){this.outputHelp(c);let y=Z.exitCode||0;if(y===0&&c&&typeof c!=="function"&&c.error)y=1;this._exit(y,"commander.help","(outputHelp)")}addHelpText(c,y){let $=["beforeAll","before","after","afterAll"];if(!$.includes(c))throw Error(`Unexpected value for position to addHelpText.
23
+ Expecting one of '${$.join("', '")}'`);let j=`${c}Help`;return this.on(j,(P)=>{let R;if(typeof y==="function")R=y({error:P.error,command:P.command});else R=y;if(R)P.write(`${R}
24
+ `)}),this}_outputHelpIfRequested(c){let y=this._getHelpOption();if(y&&c.find((j)=>y.is(j)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function lc(c){return c.map((y)=>{if(!y.startsWith("--inspect"))return y;let $,j="127.0.0.1",P="9229",R;if((R=y.match(/^(--inspect(-brk)?)$/))!==null)$=R[1];else if((R=y.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if($=R[1],/^\d+$/.test(R[3]))P=R[3];else j=R[3];else if((R=y.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)$=R[1],j=R[3],P=R[4];if($&&P!=="0")return`${$}=${j}:${parseInt(P)+1}`;return y})}s$.Command=Uc});var ic=x((d$)=>{var{Argument:dc}=l(),{Command:Ic}=rc(),{CommanderError:l$,InvalidArgumentError:ec}=g(),{Help:r$}=jc(),{Option:ac}=Pc();d$.program=new Ic;d$.createCommand=(c)=>new Ic(c);d$.createOption=(c,y)=>new ac(c,y);d$.createArgument=(c,y)=>new dc(c,y);d$.Command=Ic;d$.Option=ac;d$.Argument=dc;d$.Help=r$;d$.CommanderError=l$;d$.InvalidArgumentError=ec;d$.InvalidOptionArgumentError=ec});var nc=Y$(ic(),1),{program:F,createCommand:SP,createArgument:qP,createOption:wP,CommanderError:EP,InvalidArgumentError:YP,InvalidOptionArgumentError:QP,Command:ZP,Argument:JP,Option:FP,Help:zP}=nc.default;var oc="0.4.0";import{homedir as Gj}from"os";import{join as pc}from"path";import{existsSync as Lc,mkdirSync as fj,readFileSync as Uj,writeFileSync as Ij,unlinkSync as Lj}from"fs";function cy(){let c=process.env.ACE_TEST_HOME??Gj();return pc(c,".ace")}function Sc(){return pc(cy(),"credentials.json")}var yy="https://aceisyourassistant.com",Sj=process.env.DEBUG==="true"||process.env.ACE_DEBUG==="true";function N(c,...y){if(Sj)console.error(`[ace-cli debug] ${c}`,...y)}function qj(){let c=cy();if(!Lc(c))fj(c,{recursive:!0,mode:448})}function A(){let c=process.env.ACE_TOKEN;if(c)return N("Using ACE_TOKEN environment variable"),{apiUrl:process.env.ACE_API_URL??yy,token:c,expiresAt:null,userId:"env-token",userEmail:"ACE_TOKEN"};try{let y=Sc();if(!Lc(y))return N("Credentials file does not exist:",y),null;let $=Uj(y,"utf-8"),j=JSON.parse($);if(j.expiresAt&&new Date(j.expiresAt)<new Date)return N("Token expired at:",j.expiresAt),null;return j}catch(y){return N("Error reading credentials:",y),null}}function qc(c){qj();let y=Sc();Ij(y,JSON.stringify(c,null,2),{mode:384}),N("Credentials saved to:",y)}function wc(){try{let c=Sc();if(Lc(c))return Lj(c),N("Credentials cleared"),!0;return!1}catch(c){return N("Error clearing credentials:",c),!1}}function s(){return A()?.apiUrl??process.env.ACE_API_URL??yy}function r(){return!!process.env.ACE_TOKEN}import Kc from"node:process";import{Buffer as wy}from"node:buffer";import Ey from"node:path";import{fileURLToPath as vj}from"node:url";import{promisify as bj}from"node:util";import Yy from"node:child_process";import uj,{constants as Oj}from"node:fs/promises";import Ry from"node:process";import Gy,{constants as Fj}from"node:fs/promises";import Py from"node:process";import Zj from"node:os";import Jj from"node:fs";import Yj from"node:fs";import $y from"node:fs";var Ec;function wj(){try{return $y.statSync("/.dockerenv"),!0}catch{return!1}}function Ej(){try{return $y.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Yc(){if(Ec===void 0)Ec=wj()||Ej();return Ec}var Qc,Qj=()=>{try{return Yj.statSync("/run/.containerenv"),!0}catch{return!1}};function h(){if(Qc===void 0)Qc=Qj()||Yc();return Qc}var jy=()=>{if(Py.platform!=="linux")return!1;if(Zj.release().toLowerCase().includes("microsoft")){if(h())return!1;return!0}try{return Jj.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!h():!1}catch{return!1}},K=Py.env.__IS_WSL_TEST__?jy:jy();var zj=(()=>{let y;return async function(){if(y)return y;let $="/etc/wsl.conf",j=!1;try{await Gy.access($,Fj.F_OK),j=!0}catch{}if(!j)return"/mnt/";let P=await Gy.readFile($,{encoding:"utf8"}),R=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(P);if(!R)return"/mnt/";return y=R.groups.mountPoint.trim(),y=y.endsWith("/")?y:`${y}/`,y}})(),Xj=async()=>{return`${await zj()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},Zc=async()=>{if(K)return Xj();return`${Ry.env.SYSTEMROOT||Ry.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`};function H(c,y,$){let j=(P)=>Object.defineProperty(c,y,{value:P,enumerable:!0,writable:!0});return Object.defineProperty(c,y,{configurable:!0,enumerable:!0,get(){let P=$();return j(P),P},set(P){j(P)}}),c}import{promisify as Vj}from"node:util";import Wc from"node:process";import{execFile as Dj}from"node:child_process";import{promisify as Wj}from"node:util";import _j from"node:process";import{execFile as Kj}from"node:child_process";var Hj=Wj(Kj);async function Jc(){if(_j.platform!=="darwin")throw Error("macOS only");let{stdout:c}=await Hj("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),$=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(c)?.groups.id??"com.apple.Safari";if($==="com.apple.safari")return"com.apple.Safari";return $}import Mj from"node:process";import{promisify as Cj}from"node:util";import{execFile as Bj,execFileSync as iP}from"node:child_process";var Tj=Cj(Bj);async function fy(c,{humanReadableOutput:y=!0,signal:$}={}){if(Mj.platform!=="darwin")throw Error("macOS only");let j=y?[]:["-ss"],P={};if($)P.signal=$;let{stdout:R}=await Tj("osascript",["-e",c,j],P);return R.trim()}async function Fc(c){return fy(`tell application "Finder" to set app_path to application file id "${c}" as string
25
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as xj}from"node:util";import{execFile as Nj}from"node:child_process";var Aj=xj(Nj),Uy={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},$R=new Map(Object.entries(Uy));class zc extends Error{}async function Xc(c=Aj){let{stdout:y}=await c("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),$=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(y);if(!$)throw new zc(`Cannot find Windows browser in stdout: ${JSON.stringify(y)}`);let{id:j}=$.groups,P=Uy[j];if(!P)throw new zc(`Unknown browser ID: ${j}`);return P}var kj=Vj(Dj),hj=(c)=>c.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(y)=>y.toUpperCase());async function _c(){if(Wc.platform==="darwin"){let c=await Jc();return{name:await Fc(c),id:c}}if(Wc.platform==="linux"){let{stdout:c}=await kj("xdg-mime",["query","default","x-scheme-handler/http"]),y=c.trim();return{name:hj(y.replace(/.desktop$/,"").replace("-"," ")),id:y}}if(Wc.platform==="win32")return Xc();throw Error("Only macOS, Linux, and Windows are supported")}var tj=bj(Yy.execFile),Hc=Ey.dirname(vj(import.meta.url)),Iy=Ey.join(Hc,"xdg-open"),{platform:v,arch:Ly}=Kc;async function gj(){let c=await Zc(),y=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,$=wy.from(y,"utf16le").toString("base64"),{stdout:j}=await tj(c,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",$],{encoding:"utf8"}),P=j.trim(),R={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return R[P]?{id:R[P]}:{}}var Sy=async(c,y)=>{let $;for(let j of c)try{return await y(j)}catch(P){$=P}throw $},d=async(c)=>{if(c={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...c},Array.isArray(c.app))return Sy(c.app,(f)=>d({...c,app:f}));let{name:y,arguments:$=[]}=c.app??{};if($=[...$],Array.isArray(y))return Sy(y,(f)=>d({...c,app:{name:f,arguments:$}}));if(y==="browser"||y==="browserPrivate"){let f={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},U={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},q=K?await gj():await _c();if(q.id in f){let w=f[q.id];if(y==="browserPrivate")$.push(U[w]);return d({...c,app:{name:V[w],arguments:$}})}throw Error(`${q.name} is not supported as a default browser`)}let j,P=[],R={};if(v==="darwin"){if(j="open",c.wait)P.push("--wait-apps");if(c.background)P.push("--background");if(c.newInstance)P.push("--new");if(y)P.push("-a",y)}else if(v==="win32"||K&&!h()&&!y){if(j=await Zc(),P.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),!K)R.windowsVerbatimArguments=!0;let f=["Start"];if(c.wait)f.push("-Wait");if(y){if(f.push(`"\`"${y}\`""`),c.target)$.push(c.target)}else if(c.target)f.push(`"${c.target}"`);if($.length>0)$=$.map((U)=>`"\`"${U}\`""`),f.push("-ArgumentList",$.join(","));c.target=wy.from(f.join(" "),"utf16le").toString("base64")}else{if(y)j=y;else{let f=!Hc||Hc==="/",U=!1;try{await uj.access(Iy,Oj.X_OK),U=!0}catch{}j=Kc.versions.electron??(v==="android"||f||!U)?"xdg-open":Iy}if($.length>0)P.push(...$);if(!c.wait)R.stdio="ignore",R.detached=!0}if(v==="darwin"&&$.length>0)P.push("--args",...$);if(c.target)P.push(c.target);let G=Yy.spawn(j,P,R);if(c.wait)return new Promise((f,U)=>{G.once("error",U),G.once("close",(q)=>{if(!c.allowNonzeroExitCode&&q>0){U(Error(`Exited with code ${q}`));return}f(G)})});return G.unref(),G},sj=(c,y)=>{if(typeof c!=="string")throw TypeError("Expected a `target`");return d({...y,target:c})};function qy(c){if(typeof c==="string"||Array.isArray(c))return c;let{[Ly]:y}=c;if(!y)throw Error(`${Ly} is not supported`);return y}function e({[v]:c},{wsl:y}){if(y&&K)return qy(y);if(!c)throw Error(`${v} is not supported`);return qy(c)}var V={};H(V,"chrome",()=>e({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));H(V,"brave",()=>e({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));H(V,"firefox",()=>e({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));H(V,"edge",()=>e({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));H(V,"browser",()=>"browser");H(V,"browserPrivate",()=>"browserPrivate");var Qy=sj;var mj=2000,lj=600;async function Mc(c){let y=c??s();console.log(`Initiating authentication...
26
+ `);let $=await fetch(`${y}/api/cli-auth/initiate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!$.ok){let Y=await $.text();throw Error(`Failed to initiate auth: ${Y}`)}let{deviceCode:j,userCode:P,verificationUrl:R,interval:G,expiresIn:f}=await $.json(),U=(G||mj/1000)*1000,q=Math.ceil((f||lj)/(U/1000));console.log("Opening browser to authenticate..."),console.log(""),console.log(` Your code: ${P}`),console.log(""),console.log(` Or visit: ${R}`),console.log(""),await Qy(R),console.log("Waiting for authorization...");let w=0;while(w<q){await rj(U),w++;try{let Y=await fetch(`${y}/api/cli-auth/poll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:j})});if(!Y.ok){if(Y.status===400)continue;throw Error(`Poll failed: ${await Y.text()}`)}let J=await Y.json();if(J.status==="authorized"&&J.token){let Q={apiUrl:y,token:J.token.token,expiresAt:J.token.expiresAt,userId:J.token.userId,userEmail:J.token.userEmail};qc(Q),console.log(""),console.log(`Authenticated as ${J.token.userEmail}`),console.log(""),console.log("You can now use ace commands. Try:"),console.log(" ace orient"),console.log(' ace capture "My new task"');return}if(J.status==="expired")throw Error("Authentication code expired. Please try again.")}catch(Y){if(Y instanceof TypeError)continue;throw Y}}throw Error("Authentication timed out. Please try again.")}function rj(c){return new Promise((y)=>setTimeout(y,c))}function Cc(c,y){let $=y?new Date(y):new Date,j=c.toLowerCase().trim().replace(/\s+/g,""),P,R=0,G=j.match(/^(\d{1,2}):(\d{2})(?::\d{2})?$/);if(G)P=parseInt(G[1],10),R=parseInt(G[2],10);else{let f=j.match(/^(\d{1,2})(?::(\d{2}))?([ap]m?)$/);if(f){P=parseInt(f[1],10),R=f[2]?parseInt(f[2],10):0;let U=f[3].startsWith("p");if(U&&P!==12)P+=12;else if(!U&&P===12)P=0}else{let U=new Date(c);if(!isNaN(U.getTime()))return U.toISOString();throw Error(`Invalid time format: ${c}. Use "HH:MM", "H:MMam/pm", or ISO format.`)}}if(P<0||P>23)throw Error(`Invalid hours: ${P}. Must be between 0 and 23.`);if(R<0||R>59)throw Error(`Invalid minutes: ${R}. Must be between 0 and 59.`);return $.setHours(P,R,0,0),$.toISOString()}function Zy(c,y){let $=new Date(c);return new Date($.getTime()+y*60*1000).toISOString()}function D(c){let $=new Date(new Date);if($.setHours(0,0,0,0),c==="today"){let G=new Date($);return G.setHours(23,59,59,999),{startDate:$.toISOString(),endDate:G.toISOString()}}if(c==="week"){let G=new Date($);return G.setDate(G.getDate()+7),G.setHours(23,59,59,999),{startDate:$.toISOString(),endDate:G.toISOString()}}if(!/^\d{4}-\d{2}-\d{2}$/.test(c))throw Error(`Invalid date format: ${c}. Use YYYY-MM-DD format.`);let P=new Date(c);if(isNaN(P.getTime()))throw Error(`Invalid date: ${c}. Use YYYY-MM-DD format.`);P.setHours(0,0,0,0);let R=new Date(P);return R.setHours(23,59,59,999),{startDate:P.toISOString(),endDate:R.toISOString()}}function b(c){return new Date(c).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function W(c){return new Date(c).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Jy(c,y,$){if($)return b(c);let j=new Date(c),P=new Date(y);if(j.toDateString()===P.toDateString())return`${W(c)} - ${W(y)}`;return`${b(c)} ${W(c)} - ${b(y)} ${W(y)}`}function M(){return new Date().toISOString().split("T")[0]}function Fy(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function L(){return process.argv.includes("--json")}function S(c,y){if(y?.json||L())console.log(JSON.stringify(c,null,2));else if(typeof c==="string")console.log(c);else console.log(JSON.stringify(c,null,2))}function I(c){if(L())console.log(JSON.stringify({error:c}));else console.error(`Error: ${c}`)}function C(c){let y=[`[${c.id.slice(0,8)}] ${c.name}`];if(c.project_name)y.push(`(${c.project_name})`);if(c.dueDate)y.push(`due: ${c.dueDate}`);if(c.status==="waiting"&&c.waitingFor)y.push(`waiting: ${c.waitingFor}`);return y.join(" ")}function B(c){let y=[`[${c.id.slice(0,8)}] ${c.name}`];if(c.category_name)y.push(`(${c.category_name})`);if(c.status!=="active")y.push(`[${c.status}]`);return y.join(" ")}function z(c,y){if(c.length===0)return y?`${y}: (none)`:"(no actions)";let $=c.map((j)=>` ${C(j)}`);if(y)return`${y} (${c.length}):
27
+ ${$.join(`
28
+ `)}`;return $.join(`
29
+ `)}function u(c,y){if(c.length===0)return y?`${y}: (none)`:"(no projects)";let $=c.map((j)=>` ${B(j)}`);if(y)return`${y} (${c.length}):
30
+ ${$.join(`
31
+ `)}`;return $.join(`
32
+ `)}function zy(c){let y=[];y.push(`Inbox: ${c.inboxCount} items`);let $=c.domains.map((j)=>` ${j.name}: ${j.active_count}/${j.activeProjectLimit} active`);if(y.push(`Capacity:
33
+ ${$.join(`
34
+ `)}`),c.activeProjects.length>0)y.push(u(c.activeProjects,"Active Projects"));if(c.overdue.length>0)y.push(z(c.overdue,"Overdue"));if(c.dueToday.length>0)y.push(z(c.dueToday,"Due Today"));if(c.waiting.length>0)y.push(z(c.waiting,"Waiting"));return y.join(`
35
35
 
36
- `)}function NG(y){let $=[`[${y.id.slice(0,8)}] ${y.name}`];if($.push(`(${y.accountEmail})`),!y.isEnabled)$.push("[disabled]");return $.join(" ")}function w$(y,$){if(y.length===0)return $?`${$}: (none)`:"(no calendars connected)";let j=y.map((G)=>` ${NG(G)}`);if($)return`${$} (${y.length}):
37
- ${j.join(`
38
- `)}`;return j.join(`
39
- `)}function X$(y){let j=[`${Y$(y.startTime,y.endTime,y.isAllDay)} - ${y.summary}`];if(y.location)j.push(`@ ${y.location}`);return j.join(" ")}function Ty(y,$){if(y.length===0)return $?`${$}: (no events)`:"(no events)";let j=new Map;for(let P of y){let R=t(P.startTime),q=j.get(R)||[];q.push(P),j.set(R,q)}let G=[];if($)G.push(`${$} (${y.length}):`);for(let[P,R]of j){G.push(`
40
- ${P}:`);for(let q of R){let U=` ${q.isAllDay?"All day":`${x(q.startTime)} - ${x(q.endTime)}`}: ${q.summary}`;if(q.location)U+=` @ ${q.location}`;G.push(U)}}return G.join(`
41
- `)}function F$(y){let $=y.command("auth").description("Manage authentication");$.command("login").description("Authenticate with Ace").option("--api-url <url>","Ace API URL (default: https://aceisyourassistant.com)").action(async(j)=>{try{await fy(j.apiUrl)}catch(G){E(G instanceof Error?G.message:"Login failed"),process.exit(1)}}),$.command("logout").description("Remove stored credentials").action(()=>{let j=Qy();if(L())Q({success:j});else if(j)console.log("Logged out successfully");else console.log("No credentials to remove")}),$.command("status").description("Show current authentication status").action(()=>{let j=C();if(L())Q({authenticated:!!j,email:j?.userEmail??null,apiUrl:j?.apiUrl??null});else if(j)console.log(`Authenticated as ${j.userEmail}`),console.log(`API URL: ${j.apiUrl}`);else console.log("Not authenticated. Run: ace auth login")}),$.command("whoami").description("Show current user").action(()=>{let j=C();if(L())Q({authenticated:!!j,email:j?.userEmail??null,userId:j?.userId??null});else if(j)console.log(j.userEmail);else console.log("Not authenticated"),process.exit(1)})}class Cy extends Error{status;body;constructor(y,$,j){super(y);this.status=$;this.body=j;this.name="ApiError"}}class By extends Cy{constructor(y="Not authenticated. Run: ace auth login"){super(y,401);this.name="AuthError"}}async function Y(y,$={},j){let G=C();if(!G)throw new By;let R=`${j??G.apiUrl??g()}/api${y}`,q=await fetch(R,{...$,headers:{Authorization:`Bearer ${G.token}`,"Content-Type":"application/json",...$.headers}});if(q.status===401)throw new By("Session expired. Run: ace auth login");if(!q.ok){let S=await q.json().catch(()=>({}));throw new Cy(S.error??`Request failed with status ${q.status}`,q.status,S)}return q.json()}async function _$(){return Y("/dashboard")}async function T(y={}){let $=new URLSearchParams;if(y.status)$.set("status",y.status);if(y.projectId)$.set("project_id",y.projectId);if(y.contextId)$.set("context_id",y.contextId);if(y.search)$.set("search",y.search);if(y.limit)$.set("limit",String(y.limit));if(y.offset)$.set("offset",String(y.offset));if(y.dueBefore)$.set("due_before",y.dueBefore);if(y.dueAfter)$.set("due_after",y.dueAfter);if(y.completedAfter)$.set("completed_after",y.completedAfter);let j=$.toString(),G=j?`/actions?${j}`:"/actions";return(await Y(G)).actions}async function z$(y){return Y(`/actions/${y}`)}async function i(y){return Y("/actions",{method:"POST",body:JSON.stringify(y)})}async function Ny(y,$){return Y(`/actions/${y}`,{method:"PUT",body:JSON.stringify($)})}async function H$(y){return Ny(y,{status:"completed"})}async function W$(y){await Y(`/actions/${y}`,{method:"DELETE"})}async function l(y={}){let $=new URLSearchParams;if(y.status)$.set("status",y.status);if(y.domain)$.set("domain",y.domain);if(y.categoryId)$.set("category_id",y.categoryId);if(y.search)$.set("search",y.search);if(y.dueForReview)$.set("dueForReview","true");if(y.completedAfter)$.set("completed_after",y.completedAfter);let j=$.toString(),G=j?`/projects?${j}`:"/projects";return(await Y(G)).projects}async function M$(y){return Y(`/projects/${y}`)}async function f$(y){return Y("/projects",{method:"POST",body:JSON.stringify(y)})}async function a(y,$){return Y(`/projects/${y}`,{method:"PUT",body:JSON.stringify($)})}async function K$(y){return Y(`/projects/${y}`,{method:"PUT",body:JSON.stringify({action:"review"})})}async function T$(y){await Y(`/projects/${y}`,{method:"DELETE"})}async function B$(){return(await Y("/contexts")).contexts}async function e(y={}){let $=new URLSearchParams;if(y.status)$.set("status",y.status);if(y.domain)$.set("domain",y.domain);if(y.search)$.set("search",y.search);if(y.dueForReview)$.set("dueForReview","true");let j=$.toString(),G=j?`/goals?${j}`:"/goals";return(await Y(G)).goals}async function C$(y,$=!1){let j=$?`/goals/${y}?include=projects`:`/goals/${y}`;return Y(j)}async function N$(y){return Y("/goals",{method:"POST",body:JSON.stringify(y)})}async function n(y,$){return Y(`/goals/${y}`,{method:"PUT",body:JSON.stringify($)})}async function x$(y){return Y(`/goals/${y}`,{method:"PUT",body:JSON.stringify({action:"review"})})}async function V$(y){await Y(`/goals/${y}`,{method:"DELETE"})}async function A$(){return(await Y("/domains")).domains}async function D$(y={}){let $=new URLSearchParams;if(y.source)$.set("source",y.source);if(y.limit)$.set("limit",String(y.limit));let j=$.toString(),G=j?`/activity-log?${j}`:"/activity-log";return(await Y(G)).logs}async function k$(y){return Y("/activity-log",{method:"POST",body:JSON.stringify(y)})}async function xy(){return(await Y("/calendar/calendars")).calendars}async function Vy(y={}){let $=new URLSearchParams;if(y.calendarId)$.set("calendarId",y.calendarId);if(y.startDate)$.set("startDate",y.startDate);if(y.endDate)$.set("endDate",y.endDate);if(y.limit)$.set("limit",String(y.limit));if(y.pageToken)$.set("pageToken",y.pageToken);let j=$.toString(),G=j?`/calendar/events?${j}`:"/calendar/events";return Y(G)}async function b$(y){return(await Y("/calendar/events",{method:"POST",body:JSON.stringify(y)})).event}function v$(y){y.command("capture").description("Quick capture an item to inbox").argument("<text>","The item to capture").option("-n, --notes <notes>","Additional notes").action(async($,j)=>{try{let G=await i({name:$,status:"inbox",notes:j.notes});if(L())Q(G);else console.log(`Captured: ${f(G)}`)}catch(G){E(G instanceof Error?G.message:"Capture failed"),process.exit(1)}})}function h$(y){y.command("orient").description("Daily orientation - see your current state").alias("dashboard").action(async()=>{try{let $=await _$();if(L())Q($);else console.log(c$($))}catch($){E($ instanceof Error?$.message:"Failed to load dashboard"),process.exit(1)}})}function xG(){let y=new Date;return y.setHours(0,0,0,0),y}function o(y){return y.toISOString().split("T")[0]}function h(y){let $=xG();if(y==="overdue")return{dueBefore:o($)};if(y==="today"){let j=new Date($);return j.setDate(j.getDate()+1),{dueAfter:o($),dueBefore:o(j)}}if(y==="week"){let j=new Date($);return j.setDate(j.getDate()+7),{dueBefore:o(j)}}return{}}function O$(y){if(y==="today")return h("today");if(y==="week")return h("week");return{dueBefore:y}}function p(y){let $=new Date;return $.setDate($.getDate()-y),$.toISOString()}function u$(y){let $=y.command("actions").description("Manage actions");$.command("list").description("List actions").option("-s, --status <status>","Filter by status (inbox, active, waiting, someday)").option("-p, --project <id>","Filter by project ID").option("-c, --context <id>","Filter by context ID").option("-q, --search <query>","Search by name").option("-l, --limit <n>","Limit results","50").option("-d, --due <period>","Filter by due date (today, week, or YYYY-MM-DD)").option("--overdue","Show only overdue actions").action(async(j)=>{try{let G,P;if(j.overdue)G=h("overdue").dueBefore;else if(j.due){let q=O$(j.due);G=q.dueBefore,P=q.dueAfter}let R=await T({status:j.status,projectId:j.project,contextId:j.context,search:j.search,limit:parseInt(j.limit),dueBefore:G,dueAfter:P});if(L())Q({actions:R});else{let q=j.status?`${j.status} actions`:"Actions";console.log(_(R,q))}}catch(G){E(G instanceof Error?G.message:"Failed to list actions"),process.exit(1)}}),$.command("inbox").description("List inbox items").action(async()=>{try{let j=await T({status:"inbox"});if(L())Q({actions:j,count:j.length});else console.log(_(j,"Inbox"))}catch(j){E(j instanceof Error?j.message:"Failed to list inbox"),process.exit(1)}}),$.command("due").description("List actions due today").option("-w, --week","Show actions due this week").action(async(j)=>{try{let G=h(j.week?"week":"today"),P=await T({status:"active",dueBefore:G.dueBefore,dueAfter:G.dueAfter});if(L())Q({actions:P,count:P.length});else{let R=j.week?"Due This Week":"Due Today";console.log(_(P,R))}}catch(G){E(G instanceof Error?G.message:"Failed to list due actions"),process.exit(1)}}),$.command("overdue").description("List overdue actions").action(async()=>{try{let j=h("overdue"),G=await T({status:"active",dueBefore:j.dueBefore});if(L())Q({actions:G,count:G.length});else console.log(_(G,"Overdue"))}catch(j){E(j instanceof Error?j.message:"Failed to list overdue actions"),process.exit(1)}}),$.command("waiting").description("List actions waiting on someone/something").action(async()=>{try{let j=await T({status:"waiting"});if(L())Q({actions:j,count:j.length});else console.log(_(j,"Waiting"))}catch(j){E(j instanceof Error?j.message:"Failed to list waiting actions"),process.exit(1)}}),$.command("get <id>").description("Get action details").action(async(j)=>{try{let G=await z$(j);if(L())Q(G);else{if(console.log(f(G)),G.notes)console.log(`
42
- Notes: ${G.notes}`);if(G.contexts.length>0)console.log(`
43
- Contexts: ${G.contexts.map((P)=>P.name).join(", ")}`)}}catch(G){E(G instanceof Error?G.message:"Failed to get action"),process.exit(1)}}),$.command("add <name>").description("Create a new action").option("-s, --status <status>","Initial status (default: inbox)").option("-p, --project <id>","Assign to project").option("-d, --due <date>","Due date (YYYY-MM-DD)").option("-n, --notes <notes>","Additional notes").action(async(j,G)=>{try{let P=await i({name:j,status:G.status??"inbox",projectId:G.project,dueDate:G.due,notes:G.notes});if(L())Q(P);else console.log(`Created: ${f(P)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create action"),process.exit(1)}}),$.command("update <id>").description("Update an action").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-p, --project <id>",'Assign to project (use "none" to unassign)').option("-d, --due <date>",'Due date (YYYY-MM-DD, or "none" to clear)').option("--notes <notes>","Update notes").option("-w, --waiting <reason>","Set waiting reason").action(async(j,G)=>{try{let P={};if(G.name)P.name=G.name;if(G.status)P.status=G.status;if(G.project==="none")P.projectId=null;else if(G.project)P.projectId=G.project;if(G.due==="none")P.dueDate=null;else if(G.due)P.dueDate=G.due;if(G.notes)P.notes=G.notes;if(G.waiting)P.waitingFor=G.waiting,P.status="waiting";let R=await Ny(j,P);if(L())Q(R);else console.log(`Updated: ${f(R)}`)}catch(P){E(P instanceof Error?P.message:"Failed to update action"),process.exit(1)}}),$.command("complete <id>").description("Mark an action as completed").action(async(j)=>{try{let G=await H$(j);if(L())Q(G);else console.log(`Completed: ${f(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to complete action"),process.exit(1)}}),$.command("delete <id>").description("Delete an action").action(async(j)=>{try{if(await W$(j),L())Q({success:!0,id:j});else console.log(`Deleted action ${j}`)}catch(G){E(G instanceof Error?G.message:"Failed to delete action"),process.exit(1)}}),$.command("count").description("Count actions by status").option("-s, --status <status>","Status to count (default: inbox)").action(async(j)=>{try{let G=j.status??"inbox",P=await T({status:G});if(L())Q({status:G,count:P.length});else console.log(`${G}: ${P.length}`)}catch(G){E(G instanceof Error?G.message:"Failed to count actions"),process.exit(1)}}),$.command("completed").description("List recently completed actions").option("-d, --days <n>","Number of days to look back","7").option("-l, --limit <n>","Max items to return","50").action(async(j)=>{try{let G=parseInt(j.days),P=await T({status:"completed",completedAfter:p(G),limit:parseInt(j.limit)});if(L())Q({actions:P,count:P.length,days:G});else console.log(_(P,`Completed (last ${j.days} days)`))}catch(G){E(G instanceof Error?G.message:"Failed to list completed actions"),process.exit(1)}})}function g$(y){let $=y.command("projects").description("Manage projects");$.command("list").description("List projects").option("-s, --status <status>","Filter by status").option("-d, --domain <domain>","Filter by domain (Work, Personal)").option("-c, --category <id>","Filter by category ID").option("-q, --search <query>","Search by name").option("-r, --review","Show only projects due for review").action(async(j)=>{try{let G=await l({status:j.status,domain:j.domain,categoryId:j.category,search:j.search,dueForReview:j.review});if(L())Q({projects:G});else{let P=j.status?`${j.status} projects`:"Projects";console.log(v(G,P))}}catch(G){E(G instanceof Error?G.message:"Failed to list projects"),process.exit(1)}}),$.command("active").description("List active projects").option("-d, --domain <domain>","Filter by domain (Work, Personal)").action(async(j)=>{try{let G=await l({status:"active",domain:j.domain});if(L())Q({projects:G,count:G.length});else console.log(v(G,"Active Projects"))}catch(G){E(G instanceof Error?G.message:"Failed to list active projects"),process.exit(1)}}),$.command("get <id>").description("Get project details").action(async(j)=>{try{let G=await M$(j);if(L())Q(G);else{if(console.log(K(G)),G.theOneThing)console.log(`
44
- The One Thing: ${G.theOneThing}`);if(G.notes)console.log(`
45
- Notes: ${G.notes}`);if(console.log(`
46
- Status: ${G.status}`),G.reviewAfter)console.log(`Review after: ${G.reviewAfter}`)}}catch(G){E(G instanceof Error?G.message:"Failed to get project"),process.exit(1)}}),$.command("add <name>").description("Create a new project").option("-s, --status <status>","Initial status (default: incubating)").option("-c, --category <id>","Assign to category").option("-t, --the-one-thing <text>","Set the one thing").option("-n, --notes <notes>","Additional notes").action(async(j,G)=>{try{let P=await f$({name:j,status:G.status??"incubating",categoryId:G.category,theOneThing:G.theOneThing,notes:G.notes});if(L())Q(P);else console.log(`Created: ${K(P)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create project"),process.exit(1)}}),$.command("update <id>").description("Update a project").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-c, --category <id>",'Assign to category (use "none" to unassign)').option("-t, --the-one-thing <text>","Set the one thing").option("--notes <notes>","Update notes").action(async(j,G)=>{try{let P={};if(G.name)P.name=G.name;if(G.status)P.status=G.status;if(G.category==="none")P.categoryId=null;else if(G.category)P.categoryId=G.category;if(G.theOneThing)P.theOneThing=G.theOneThing;if(G.notes)P.notes=G.notes;let R=await a(j,P);if(L())Q(R);else console.log(`Updated: ${K(R)}`)}catch(P){E(P instanceof Error?P.message:"Failed to update project"),process.exit(1)}}),$.command("activate <id>").description("Set project status to active").action(async(j)=>{try{let G=await a(j,{status:"active"});if(L())Q(G);else console.log(`Activated: ${K(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to activate project"),process.exit(1)}}),$.command("complete <id>").description("Mark a project as completed").action(async(j)=>{try{let G=await a(j,{status:"completed"});if(L())Q(G);else console.log(`Completed: ${K(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to complete project"),process.exit(1)}}),$.command("review").description("List projects due for review").action(async()=>{try{let j=await l({dueForReview:!0});if(L())Q({projects:j,count:j.length});else console.log(v(j,"Projects Due for Review"))}catch(j){E(j instanceof Error?j.message:"Failed to list projects for review"),process.exit(1)}}),$.command("mark-reviewed <id>").description("Mark a project as reviewed (resets review timer)").action(async(j)=>{try{let G=await K$(j);if(L())Q(G);else console.log(`Marked as reviewed: ${K(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to mark project as reviewed"),process.exit(1)}}),$.command("drop <id>").description("Drop a project (soft delete)").action(async(j)=>{try{if(await T$(j),L())Q({success:!0,id:j});else console.log(`Dropped project ${j}`)}catch(G){E(G instanceof Error?G.message:"Failed to drop project"),process.exit(1)}}),$.command("completed").description("List recently completed projects").option("-d, --days <n>","Number of days to look back","7").action(async(j)=>{try{let G=parseInt(j.days),P=await l({status:"completed",completedAfter:p(G)});if(L())Q({projects:P,count:P.length,days:G});else console.log(v(P,`Completed (last ${j.days} days)`))}catch(G){E(G instanceof Error?G.message:"Failed to list completed projects"),process.exit(1)}})}function A(y){let $=y.id.slice(0,8),j=y.domain_name?` (${y.domain_name})`:"";return`[${$}] ${y.name}${j}`}function Ay(y,$){if(y.length===0)return`${$}: (none)`;let j=[`${$} (${y.length}):`],G=y.reduce((P,R)=>{let q=R.domain_name||"Unknown";if(!P[q])P[q]=[];return P[q].push(R),P},{});for(let[P,R]of Object.entries(G)){j.push(`
47
- ${P}:`);for(let q of R){let S=q.status!=="active"?` [${q.status}]`:"";if(j.push(` ${A(q)}${S}`),q.theOneThing)j.push(` Focus: ${q.theOneThing}`);if(q.project_count!==void 0)j.push(` Projects: ${q.project_count}`)}}return j.join(`
48
- `)}function t$(y){let $=y.command("goals").description("Manage goals");$.command("list").description("List goals").option("-s, --status <status>","Filter by status (active, paused, completed, dropped)").option("-d, --domain <domain>","Filter by domain (Work, Personal)").option("-q, --search <query>","Search by name").option("-r, --review","Show only goals due for review").action(async(j)=>{try{let G=await e({status:j.status,domain:j.domain,search:j.search,dueForReview:j.review});if(L())Q({goals:G});else{let P=j.status?`${j.status} goals`:"Goals";console.log(Ay(G,P))}}catch(G){E(G instanceof Error?G.message:"Failed to list goals"),process.exit(1)}}),$.command("active").description("List active goals").option("-d, --domain <domain>","Filter by domain (Work, Personal)").action(async(j)=>{try{let G=await e({status:"active",domain:j.domain});if(L())Q({goals:G,count:G.length});else console.log(Ay(G,"Active Goals"))}catch(G){E(G instanceof Error?G.message:"Failed to list active goals"),process.exit(1)}}),$.command("get <id>").description("Get goal details").option("-p, --projects","Include linked projects").action(async(j,G)=>{try{let P=await C$(j,G.projects);if(L())Q(P);else{if(console.log(A(P)),console.log(`
36
+ `)}function dj(c){let y=[`[${c.id.slice(0,8)}] ${c.name}`];if(y.push(`(${c.accountEmail})`),!c.isEnabled)y.push("[disabled]");return y.join(" ")}function Xy(c,y){if(c.length===0)return y?`${y}: (none)`:"(no calendars connected)";let $=c.map((j)=>` ${dj(j)}`);if(y)return`${y} (${c.length}):
37
+ ${$.join(`
38
+ `)}`;return $.join(`
39
+ `)}function Wy(c){let $=[`${Jy(c.startTime,c.endTime,c.isAllDay)} - ${c.summary}`];if(c.location)$.push(`@ ${c.location}`);return $.join(" ")}function Bc(c,y){if(c.length===0)return y?`${y}: (no events)`:"(no events)";let $=new Map;for(let P of c){let R=b(P.startTime),G=$.get(R)||[];G.push(P),$.set(R,G)}let j=[];if(y)j.push(`${y} (${c.length}):`);for(let[P,R]of $){j.push(`
40
+ ${P}:`);for(let G of R){let U=` ${G.isAllDay?"All day":`${W(G.startTime)} - ${W(G.endTime)}`}: ${G.summary}`;if(G.location)U+=` @ ${G.location}`;j.push(U)}}return j.join(`
41
+ `)}function Tc(c){let y=Math.floor(c/60),$=c%60;if(y===0)return`${$}m`;if($===0)return`${y}h`;return`${y}h ${$}m`}function ej(c,y){let $=new Date(y).getTime()-new Date(c).getTime();return Tc(Math.round($/60000))}function aj(c){let y=[],$=b(c.date+"T12:00:00Z");if(c.freeSlots.length===0)y.push(` ${$}: No availability`);else{y.push(` ${$}: ${Tc(c.totalFreeMinutes)} free`);for(let j of c.freeSlots){let P=ej(j.start,j.end);y.push(` ${W(j.start)} - ${W(j.end)} (${P})`)}}return y.join(`
42
+ `)}function _y(c,y){let $=[],j=c.days.reduce((U,q)=>U+q.totalFreeMinutes,0),{startHour:P,endHour:R}=c.options,G=y||"Availability",f=`${String(P).padStart(2,"0")}:00-${String(R).padStart(2,"0")}:00`;$.push(`${G} (${f}, ${Tc(j)} total free):`);for(let U of c.days)$.push(aj(U));return $.join(`
43
+ `)}function Ky(c){let y=c.command("auth").description("Manage authentication");y.command("login").description("Authenticate with Ace").option("--api-url <url>","Ace API URL (default: https://aceisyourassistant.com)").action(async($)=>{try{await Mc($.apiUrl)}catch(j){I(j instanceof Error?j.message:"Login failed"),process.exit(1)}}),y.command("logout").description("Remove stored credentials").action(()=>{let $=wc();if(L())S({success:$});else if($)console.log("Logged out successfully");else console.log("No credentials to remove")}),y.command("status").description("Show current authentication status").action(()=>{let $=A(),j=r();if(L())S({authenticated:!!$,method:j?"env-token":"stored-credentials",email:$?.userEmail??null,apiUrl:$?.apiUrl??null});else if($&&j)console.log("Authenticated via ACE_TOKEN environment variable"),console.log(`API URL: ${$.apiUrl}`);else if($)console.log(`Authenticated as ${$.userEmail}`),console.log(`API URL: ${$.apiUrl}`);else console.log("Not authenticated. Run: ace auth login")}),y.command("whoami").description("Show current user").action(()=>{let $=A(),j=r();if(L())S({authenticated:!!$,method:j?"env-token":"stored-credentials",email:j?null:$?.userEmail??null,userId:j?null:$?.userId??null});else if($&&j)console.log("Authenticated via ACE_TOKEN (run ace auth login for full user info)");else if($)console.log($.userEmail);else console.log("Not authenticated"),process.exit(1)})}class Nc extends Error{status;body;constructor(c,y,$){super(c);this.status=y;this.body=$;this.name="ApiError"}}class xc extends Nc{constructor(c="Not authenticated. Run: ace auth login"){super(c,401);this.name="AuthError"}}async function E(c,y={},$){let j=A();if(!j)throw new xc;let R=`${$??j.apiUrl??s()}/api${c}`,G=await fetch(R,{...y,headers:{Authorization:`Bearer ${j.token}`,"Content-Type":"application/json",...y.headers}});if(G.status===401)throw new xc("Session expired. Run: ace auth login");if(!G.ok){let f=await G.json().catch(()=>({}));throw new Nc(f.error??`Request failed with status ${G.status}`,G.status,f)}return G.json()}async function Hy(){return E("/dashboard")}async function T(c={}){let y=new URLSearchParams;if(c.status)y.set("status",c.status);if(c.projectId)y.set("project_id",c.projectId);if(c.contextId)y.set("context_id",c.contextId);if(c.search)y.set("search",c.search);if(c.limit)y.set("limit",String(c.limit));if(c.offset)y.set("offset",String(c.offset));if(c.dueBefore)y.set("due_before",c.dueBefore);if(c.dueAfter)y.set("due_after",c.dueAfter);if(c.completedAfter)y.set("completed_after",c.completedAfter);let $=y.toString(),j=$?`/actions?${$}`:"/actions";return(await E(j)).actions}async function My(c){return E(`/actions/${c}`)}async function a(c){return E("/actions",{method:"POST",body:JSON.stringify(c)})}async function Ac(c,y){return E(`/actions/${c}`,{method:"PUT",body:JSON.stringify(y)})}async function Cy(c){return Ac(c,{status:"completed"})}async function By(c){await E(`/actions/${c}`,{method:"DELETE"})}async function m(c={}){let y=new URLSearchParams;if(c.status)y.set("status",c.status);if(c.domain)y.set("domain",c.domain);if(c.categoryId)y.set("category_id",c.categoryId);if(c.search)y.set("search",c.search);if(c.dueForReview)y.set("dueForReview","true");if(c.completedAfter)y.set("completed_after",c.completedAfter);let $=y.toString(),j=$?`/projects?${$}`:"/projects";return(await E(j)).projects}async function Ty(c){return E(`/projects/${c}`)}async function xy(c){return E("/projects",{method:"POST",body:JSON.stringify(c)})}async function i(c,y){return E(`/projects/${c}`,{method:"PUT",body:JSON.stringify(y)})}async function Ny(c){return E(`/projects/${c}`,{method:"PUT",body:JSON.stringify({action:"review"})})}async function Ay(c){await E(`/projects/${c}`,{method:"DELETE"})}async function Vy(){return(await E("/contexts")).contexts}async function n(c={}){let y=new URLSearchParams;if(c.status)y.set("status",c.status);if(c.domain)y.set("domain",c.domain);if(c.search)y.set("search",c.search);if(c.dueForReview)y.set("dueForReview","true");let $=y.toString(),j=$?`/goals?${$}`:"/goals";return(await E(j)).goals}async function Dy(c,y=!1){let $=y?`/goals/${c}?include=projects`:`/goals/${c}`;return E($)}async function ky(c){return E("/goals",{method:"POST",body:JSON.stringify(c)})}async function o(c,y){return E(`/goals/${c}`,{method:"PUT",body:JSON.stringify(y)})}async function hy(c){return E(`/goals/${c}`,{method:"PUT",body:JSON.stringify({action:"review"})})}async function vy(c){await E(`/goals/${c}`,{method:"DELETE"})}async function by(){return(await E("/domains")).domains}async function uy(c={}){let y=new URLSearchParams;if(c.source)y.set("source",c.source);if(c.limit)y.set("limit",String(c.limit));let $=y.toString(),j=$?`/activity-log?${$}`:"/activity-log";return(await E(j)).logs}async function Oy(c){return E("/activity-log",{method:"POST",body:JSON.stringify(c)})}async function Vc(){return(await E("/calendar/calendars")).calendars}async function Dc(c={}){let y=new URLSearchParams;if(c.calendarId)y.set("calendarId",c.calendarId);if(c.startDate)y.set("startDate",c.startDate);if(c.endDate)y.set("endDate",c.endDate);if(c.limit)y.set("limit",String(c.limit));if(c.pageToken)y.set("pageToken",c.pageToken);let $=y.toString(),j=$?`/calendar/events?${$}`:"/calendar/events";return E(j)}async function ty(c){return(await E("/calendar/events",{method:"POST",body:JSON.stringify(c)})).event}async function gy(c={}){let y=new URLSearchParams;if(c.limit)y.set("limit",String(c.limit));if(c.offset)y.set("offset",String(c.offset));let $=y.toString(),j=$?`/updates?${$}`:"/updates";return(await E(j)).updates}async function sy(c={}){return E("/updates",{method:"POST",body:JSON.stringify(c)})}async function my(c){return E(`/updates/${c}`)}async function ly(c={}){let y=new URLSearchParams;if(c.hours)y.set("hours",String(c.hours));if(c.since)y.set("since",c.since);if(c.until)y.set("until",c.until);if(c.statuses)y.set("statuses",c.statuses);let $=y.toString(),j=$?`/linear/issues?${$}`:"/linear/issues";return E(j)}async function ry(){return E("/linear/statuses")}async function dy(c={}){let y=new URLSearchParams;if(c.startDate)y.set("startDate",c.startDate);if(c.endDate)y.set("endDate",c.endDate);if(c.startHour!==void 0)y.set("startHour",String(c.startHour));if(c.endHour!==void 0)y.set("endHour",String(c.endHour));if(c.minSlotMinutes!==void 0)y.set("minSlotMinutes",String(c.minSlotMinutes));if(c.timezone)y.set("timezone",c.timezone);if(c.calendarId)y.set("calendarId",c.calendarId);let $=y.toString(),j=$?`/calendar/availability?${$}`:"/calendar/availability";return E(j)}function ey(c){c.command("capture").description("Quick capture an item to inbox").argument("<text>","The item to capture").option("-n, --notes <notes>","Additional notes").action(async(y,$)=>{try{let j=await a({name:y,status:"inbox",notes:$.notes});if(L())S(j);else console.log(`Captured: ${C(j)}`)}catch(j){I(j instanceof Error?j.message:"Capture failed"),process.exit(1)}})}function ay(c){c.command("orient").description("Daily orientation - see your current state").alias("dashboard").action(async()=>{try{let y=await Hy();if(L())S(y);else console.log(zy(y))}catch(y){I(y instanceof Error?y.message:"Failed to load dashboard"),process.exit(1)}})}function ij(){let c=new Date;return c.setHours(0,0,0,0),c}function p(c){return c.toISOString().split("T")[0]}function O(c){let y=ij();if(c==="overdue")return{dueBefore:p(y)};if(c==="today"){let $=new Date(y);return $.setDate($.getDate()+1),{dueAfter:p(y),dueBefore:p($)}}if(c==="week"){let $=new Date(y);return $.setDate($.getDate()+7),{dueBefore:p($)}}return{}}function iy(c){if(c==="today")return O("today");if(c==="week")return O("week");return{dueBefore:c}}function cc(c){let y=new Date;return y.setDate(y.getDate()-c),y.toISOString()}function ny(c){let y=c.command("actions").description("Manage actions");y.command("list").description("List actions").option("-s, --status <status>","Filter by status (inbox, active, waiting, someday)").option("-p, --project <id>","Filter by project ID").option("-c, --context <id>","Filter by context ID").option("-q, --search <query>","Search by name").option("-l, --limit <n>","Limit results","50").option("-d, --due <period>","Filter by due date (today, week, or YYYY-MM-DD)").option("--overdue","Show only overdue actions").action(async($)=>{try{let j,P;if($.overdue)j=O("overdue").dueBefore;else if($.due){let G=iy($.due);j=G.dueBefore,P=G.dueAfter}let R=await T({status:$.status,projectId:$.project,contextId:$.context,search:$.search,limit:parseInt($.limit),dueBefore:j,dueAfter:P});if(L())S({actions:R});else{let G=$.status?`${$.status} actions`:"Actions";console.log(z(R,G))}}catch(j){I(j instanceof Error?j.message:"Failed to list actions"),process.exit(1)}}),y.command("inbox").description("List inbox items").action(async()=>{try{let $=await T({status:"inbox"});if(L())S({actions:$,count:$.length});else console.log(z($,"Inbox"))}catch($){I($ instanceof Error?$.message:"Failed to list inbox"),process.exit(1)}}),y.command("due").description("List actions due today").option("-w, --week","Show actions due this week").action(async($)=>{try{let j=O($.week?"week":"today"),P=await T({status:"active",dueBefore:j.dueBefore,dueAfter:j.dueAfter});if(L())S({actions:P,count:P.length});else{let R=$.week?"Due This Week":"Due Today";console.log(z(P,R))}}catch(j){I(j instanceof Error?j.message:"Failed to list due actions"),process.exit(1)}}),y.command("overdue").description("List overdue actions").action(async()=>{try{let $=O("overdue"),j=await T({status:"active",dueBefore:$.dueBefore});if(L())S({actions:j,count:j.length});else console.log(z(j,"Overdue"))}catch($){I($ instanceof Error?$.message:"Failed to list overdue actions"),process.exit(1)}}),y.command("waiting").description("List actions waiting on someone/something").action(async()=>{try{let $=await T({status:"waiting"});if(L())S({actions:$,count:$.length});else console.log(z($,"Waiting"))}catch($){I($ instanceof Error?$.message:"Failed to list waiting actions"),process.exit(1)}}),y.command("get <id>").description("Get action details").action(async($)=>{try{let j=await My($);if(L())S(j);else{if(console.log(C(j)),j.notes)console.log(`
44
+ Notes: ${j.notes}`);if(j.contexts.length>0)console.log(`
45
+ Contexts: ${j.contexts.map((P)=>P.name).join(", ")}`)}}catch(j){I(j instanceof Error?j.message:"Failed to get action"),process.exit(1)}}),y.command("add <name>").description("Create a new action").option("-s, --status <status>","Initial status (default: inbox)").option("-p, --project <id>","Assign to project").option("-d, --due <date>","Due date (YYYY-MM-DD)").option("-n, --notes <notes>","Additional notes").action(async($,j)=>{try{let P=await a({name:$,status:j.status??"inbox",projectId:j.project,dueDate:j.due,notes:j.notes});if(L())S(P);else console.log(`Created: ${C(P)}`)}catch(P){I(P instanceof Error?P.message:"Failed to create action"),process.exit(1)}}),y.command("update <id>").description("Update an action").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-p, --project <id>",'Assign to project (use "none" to unassign)').option("-d, --due <date>",'Due date (YYYY-MM-DD, or "none" to clear)').option("--notes <notes>","Update notes").option("-w, --waiting <reason>","Set waiting reason").action(async($,j)=>{try{let P={};if(j.name)P.name=j.name;if(j.status)P.status=j.status;if(j.project==="none")P.projectId=null;else if(j.project)P.projectId=j.project;if(j.due==="none")P.dueDate=null;else if(j.due)P.dueDate=j.due;if(j.notes)P.notes=j.notes;if(j.waiting)P.waitingFor=j.waiting,P.status="waiting";let R=await Ac($,P);if(L())S(R);else console.log(`Updated: ${C(R)}`)}catch(P){I(P instanceof Error?P.message:"Failed to update action"),process.exit(1)}}),y.command("complete <id>").description("Mark an action as completed").action(async($)=>{try{let j=await Cy($);if(L())S(j);else console.log(`Completed: ${C(j)}`)}catch(j){I(j instanceof Error?j.message:"Failed to complete action"),process.exit(1)}}),y.command("delete <id>").description("Delete an action").action(async($)=>{try{if(await By($),L())S({success:!0,id:$});else console.log(`Deleted action ${$}`)}catch(j){I(j instanceof Error?j.message:"Failed to delete action"),process.exit(1)}}),y.command("count").description("Count actions by status").option("-s, --status <status>","Status to count (default: inbox)").action(async($)=>{try{let j=$.status??"inbox",P=await T({status:j});if(L())S({status:j,count:P.length});else console.log(`${j}: ${P.length}`)}catch(j){I(j instanceof Error?j.message:"Failed to count actions"),process.exit(1)}}),y.command("completed").description("List recently completed actions").option("-d, --days <n>","Number of days to look back","7").option("-l, --limit <n>","Max items to return","50").action(async($)=>{try{let j=parseInt($.days),P=await T({status:"completed",completedAfter:cc(j),limit:parseInt($.limit)});if(L())S({actions:P,count:P.length,days:j});else console.log(z(P,`Completed (last ${$.days} days)`))}catch(j){I(j instanceof Error?j.message:"Failed to list completed actions"),process.exit(1)}})}function oy(c){let y=c.command("projects").description("Manage projects");y.command("list").description("List projects").option("-s, --status <status>","Filter by status").option("-d, --domain <domain>","Filter by domain (Work, Personal)").option("-c, --category <id>","Filter by category ID").option("-q, --search <query>","Search by name").option("-r, --review","Show only projects due for review").action(async($)=>{try{let j=await m({status:$.status,domain:$.domain,categoryId:$.category,search:$.search,dueForReview:$.review});if(L())S({projects:j});else{let P=$.status?`${$.status} projects`:"Projects";console.log(u(j,P))}}catch(j){I(j instanceof Error?j.message:"Failed to list projects"),process.exit(1)}}),y.command("active").description("List active projects").option("-d, --domain <domain>","Filter by domain (Work, Personal)").action(async($)=>{try{let j=await m({status:"active",domain:$.domain});if(L())S({projects:j,count:j.length});else console.log(u(j,"Active Projects"))}catch(j){I(j instanceof Error?j.message:"Failed to list active projects"),process.exit(1)}}),y.command("get <id>").description("Get project details").action(async($)=>{try{let j=await Ty($);if(L())S(j);else{if(console.log(B(j)),j.theOneThing)console.log(`
46
+ The One Thing: ${j.theOneThing}`);if(j.notes)console.log(`
47
+ Notes: ${j.notes}`);if(console.log(`
48
+ Status: ${j.status}`),j.reviewAfter)console.log(`Review after: ${j.reviewAfter}`)}}catch(j){I(j instanceof Error?j.message:"Failed to get project"),process.exit(1)}}),y.command("add <name>").description("Create a new project").option("-s, --status <status>","Initial status (default: incubating)").option("-c, --category <id>","Assign to category").option("-t, --the-one-thing <text>","Set the one thing").option("-n, --notes <notes>","Additional notes").action(async($,j)=>{try{let P=await xy({name:$,status:j.status??"incubating",categoryId:j.category,theOneThing:j.theOneThing,notes:j.notes});if(L())S(P);else console.log(`Created: ${B(P)}`)}catch(P){I(P instanceof Error?P.message:"Failed to create project"),process.exit(1)}}),y.command("update <id>").description("Update a project").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-c, --category <id>",'Assign to category (use "none" to unassign)').option("-t, --the-one-thing <text>","Set the one thing").option("--notes <notes>","Update notes").action(async($,j)=>{try{let P={};if(j.name)P.name=j.name;if(j.status)P.status=j.status;if(j.category==="none")P.categoryId=null;else if(j.category)P.categoryId=j.category;if(j.theOneThing)P.theOneThing=j.theOneThing;if(j.notes)P.notes=j.notes;let R=await i($,P);if(L())S(R);else console.log(`Updated: ${B(R)}`)}catch(P){I(P instanceof Error?P.message:"Failed to update project"),process.exit(1)}}),y.command("activate <id>").description("Set project status to active").action(async($)=>{try{let j=await i($,{status:"active"});if(L())S(j);else console.log(`Activated: ${B(j)}`)}catch(j){I(j instanceof Error?j.message:"Failed to activate project"),process.exit(1)}}),y.command("complete <id>").description("Mark a project as completed").action(async($)=>{try{let j=await i($,{status:"completed"});if(L())S(j);else console.log(`Completed: ${B(j)}`)}catch(j){I(j instanceof Error?j.message:"Failed to complete project"),process.exit(1)}}),y.command("review").description("List projects due for review").action(async()=>{try{let $=await m({dueForReview:!0});if(L())S({projects:$,count:$.length});else console.log(u($,"Projects Due for Review"))}catch($){I($ instanceof Error?$.message:"Failed to list projects for review"),process.exit(1)}}),y.command("mark-reviewed <id>").description("Mark a project as reviewed (resets review timer)").action(async($)=>{try{let j=await Ny($);if(L())S(j);else console.log(`Marked as reviewed: ${B(j)}`)}catch(j){I(j instanceof Error?j.message:"Failed to mark project as reviewed"),process.exit(1)}}),y.command("drop <id>").description("Drop a project (soft delete)").action(async($)=>{try{if(await Ay($),L())S({success:!0,id:$});else console.log(`Dropped project ${$}`)}catch(j){I(j instanceof Error?j.message:"Failed to drop project"),process.exit(1)}}),y.command("completed").description("List recently completed projects").option("-d, --days <n>","Number of days to look back","7").action(async($)=>{try{let j=parseInt($.days),P=await m({status:"completed",completedAfter:cc(j)});if(L())S({projects:P,count:P.length,days:j});else console.log(u(P,`Completed (last ${$.days} days)`))}catch(j){I(j instanceof Error?j.message:"Failed to list completed projects"),process.exit(1)}})}function k(c){let y=c.id.slice(0,8),$=c.domain_name?` (${c.domain_name})`:"";return`[${y}] ${c.name}${$}`}function kc(c,y){if(c.length===0)return`${y}: (none)`;let $=[`${y} (${c.length}):`],j=c.reduce((P,R)=>{let G=R.domain_name||"Unknown";if(!P[G])P[G]=[];return P[G].push(R),P},{});for(let[P,R]of Object.entries(j)){$.push(`
49
+ ${P}:`);for(let G of R){let f=G.status!=="active"?` [${G.status}]`:"";if($.push(` ${k(G)}${f}`),G.theOneThing)$.push(` Focus: ${G.theOneThing}`);if(G.project_count!==void 0)$.push(` Projects: ${G.project_count}`)}}return $.join(`
50
+ `)}function py(c){let y=c.command("goals").description("Manage goals");y.command("list").description("List goals").option("-s, --status <status>","Filter by status (active, paused, completed, dropped)").option("-d, --domain <domain>","Filter by domain (Work, Personal)").option("-q, --search <query>","Search by name").option("-r, --review","Show only goals due for review").action(async($)=>{try{let j=await n({status:$.status,domain:$.domain,search:$.search,dueForReview:$.review});if(L())S({goals:j});else{let P=$.status?`${$.status} goals`:"Goals";console.log(kc(j,P))}}catch(j){I(j instanceof Error?j.message:"Failed to list goals"),process.exit(1)}}),y.command("active").description("List active goals").option("-d, --domain <domain>","Filter by domain (Work, Personal)").action(async($)=>{try{let j=await n({status:"active",domain:$.domain});if(L())S({goals:j,count:j.length});else console.log(kc(j,"Active Goals"))}catch(j){I(j instanceof Error?j.message:"Failed to list active goals"),process.exit(1)}}),y.command("get <id>").description("Get goal details").option("-p, --projects","Include linked projects").action(async($,j)=>{try{let P=await Dy($,j.projects);if(L())S(P);else{if(console.log(k(P)),console.log(`
49
51
  Status: ${P.status}`),P.theOneThing)console.log(`Focus: ${P.theOneThing}`);if(P.notes)console.log(`
50
52
  Notes: ${P.notes}`);if(P.reviewAfter)console.log(`
51
53
  Review after: ${P.reviewAfter}`);if(P.projects&&P.projects.length>0){console.log(`
52
- Linked Projects (${P.projects.length}):`);for(let R of P.projects)console.log(` - ${R.name} [${R.status}]`)}}}catch(P){E(P instanceof Error?P.message:"Failed to get goal"),process.exit(1)}}),$.command("add <name>").description("Create a new goal").option("-d, --domain <domain>","Domain (Work or Personal)","Personal").option("-s, --status <status>","Initial status (default: active)").option("-f, --focus <text>","Set the focus/one thing").option("-n, --notes <notes>","Additional notes").action(async(j,G)=>{try{let P=await A$();if(!P||P.length===0)E("No domains found. Please check your Ace configuration."),process.exit(1);let R=P.find((S)=>S.name.toLowerCase()===G.domain.toLowerCase());if(!R){let S=P.map((U)=>U.name).join(", ");E(`Invalid domain: ${G.domain}. Valid options: ${S}`),process.exit(1)}let q=await N$({name:j,domainId:R.id,status:G.status??"active",theOneThing:G.focus,notes:G.notes});if(L())Q(q);else console.log(`Created: ${A(q)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create goal"),process.exit(1)}}),$.command("update <id>").description("Update a goal").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-f, --focus <text>","Update the focus/one thing").option("--notes <notes>","Update notes").action(async(j,G)=>{try{let P={};if(G.name)P.name=G.name;if(G.status)P.status=G.status;if(G.focus)P.theOneThing=G.focus;if(G.notes)P.notes=G.notes;let R=await n(j,P);if(L())Q(R);else console.log(`Updated: ${A(R)}`)}catch(P){E(P instanceof Error?P.message:"Failed to update goal"),process.exit(1)}}),$.command("mark-reviewed <id>").description("Mark a goal as reviewed (resets review timer)").action(async(j)=>{try{let G=await x$(j);if(L())Q(G);else console.log(`Marked as reviewed: ${A(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to mark goal as reviewed"),process.exit(1)}}),$.command("complete <id>").description("Mark a goal as completed").action(async(j)=>{try{let G=await n(j,{status:"completed"});if(L())Q(G);else console.log(`Completed: ${A(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to complete goal"),process.exit(1)}}),$.command("pause <id>").description("Pause a goal").action(async(j)=>{try{let G=await n(j,{status:"paused"});if(L())Q(G);else console.log(`Paused: ${A(G)}`)}catch(G){E(G instanceof Error?G.message:"Failed to pause goal"),process.exit(1)}}),$.command("drop <id>").description("Drop a goal").action(async(j)=>{try{if(await V$(j),L())Q({success:!0,id:j});else console.log(`Dropped goal ${j}`)}catch(G){E(G instanceof Error?G.message:"Failed to drop goal"),process.exit(1)}}),$.command("review").description("List goals due for review").action(async()=>{try{let j=await e({dueForReview:!0});if(L())Q({goals:j,count:j.length});else console.log(Ay(j,"Goals Due for Review"))}catch(j){E(j instanceof Error?j.message:"Failed to list goals for review"),process.exit(1)}})}function VG(y,$){if(y.length===0)return`${$}: (none)`;let j=[`${$} (${y.length}):`],G=y.reduce((P,R)=>{let q=new Date(R.timestamp).toLocaleDateString();if(!P[q])P[q]=[];return P[q].push(R),P},{});for(let[P,R]of Object.entries(G)){j.push(`
53
- ${P}:`);for(let q of R){let S=new Date(q.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});j.push(` ${S} [${q.source}] ${q.summary}`)}}return j.join(`
54
- `)}function m$(y){let $=y.command("activity").description("View and log activity");$.command("list").description("List activity log entries").option("-s, --source <source>","Filter by source (manual, git, calendar, etc.)").option("-l, --limit <n>","Limit results","50").action(async(j)=>{try{let G=await D$({source:j.source,limit:parseInt(j.limit)});if(L())Q({logs:G});else{let P=j.source?`Activity (${j.source})`:"Recent Activity";console.log(VG(G,P))}}catch(G){E(G instanceof Error?G.message:"Failed to list activity"),process.exit(1)}}),$.command("log <summary>").description("Log an activity").option("-s, --source <source>","Activity source","manual").option("-p, --project <id>","Link to project").option("-a, --action <id>","Link to action").action(async(j,G)=>{try{let P=await k$({source:G.source,summary:j,project_id:G.project,action_id:G.action});if(L())Q(P);else if(console.log(`Logged: ${j}`),G.project)console.log(` Linked to project: ${G.project}`)}catch(P){E(P instanceof Error?P.message:"Failed to log activity"),process.exit(1)}})}function l$(y){y.command("contexts").description("Manage contexts").command("list").description("List all contexts").action(async()=>{try{let j=await B$();if(L())Q({contexts:j});else if(j.length===0)console.log("No contexts found");else{console.log("Contexts:");for(let G of j){let P=G.type?` (${G.type})`:"";console.log(` [${G.id.slice(0,8)}] ${G.name}${P}`)}}}catch(j){E(j instanceof Error?j.message:"Failed to list contexts"),process.exit(1)}})}var AG=30,s$=1,r$=250,DG=50;function d$(y){let $=y.command("calendar").description("Manage calendar events");$.command("list").description("List connected calendars").action(async()=>{try{let j=await xy();if(L())Q({calendars:j});else console.log(w$(j,"Connected Calendars"))}catch(j){E(j instanceof Error?j.message:"Failed to list calendars"),process.exit(1)}}),$.command("events").description("List calendar events").option("-c, --calendar <id>","Filter by calendar ID").option("-d, --date <date>","Date to show events for (YYYY-MM-DD, default: today)").option("-w, --week","Show events for the next 7 days").option("--from <date>","Start date for range (YYYY-MM-DD)").option("--to <date>","End date for range (YYYY-MM-DD)").option("-l, --limit <n>","Maximum number of events",String(DG)).option("--page-token <token>","Page token for pagination (requires --calendar)").action(async(j)=>{try{if(j.pageToken&&!j.calendar)E("--page-token requires --calendar to be specified"),process.exit(1);let G,P;if(j.from&&j.to){let S=V(j.from),U=V(j.to);G=S.startDate,P=U.endDate}else if(j.week){let S=V("week");G=S.startDate,P=S.endDate}else if(j.date){let S=V(j.date);G=S.startDate,P=S.endDate}else{let S=V("today");G=S.startDate,P=S.endDate}let R=parseInt(j.limit);if(isNaN(R)||R<s$||R>r$)E(`Invalid limit. Must be between ${s$} and ${r$}.`),process.exit(1);let q=await Vy({calendarId:j.calendar,startDate:G,endDate:P,limit:R,pageToken:j.pageToken});if(L())Q({events:q.events,count:q.events.length,nextPageToken:q.nextPageToken});else{let S="Events";if(j.week)S="Events (next 7 days)";else if(j.date)S=`Events for ${j.date}`;else if(j.from&&j.to)S=`Events from ${j.from} to ${j.to}`;else S=`Events for ${m()}`;if(console.log(Ty(q.events,S)),q.nextPageToken)console.log(`
55
- More events available. Use --page-token ${q.nextPageToken} to see next page.`)}}catch(G){E(G instanceof Error?G.message:"Failed to list events"),process.exit(1)}}),$.command("today").description("List today's calendar events").option("-c, --calendar <id>","Filter by calendar ID").action(async(j)=>{try{let G=V("today"),P=await Vy({calendarId:j.calendar,startDate:G.startDate,endDate:G.endDate});if(L())Q({events:P.events,count:P.events.length,date:m()});else console.log(Ty(P.events,`Today (${m()})`))}catch(G){E(G instanceof Error?G.message:"Failed to list today's events"),process.exit(1)}}),$.command("add <summary>").description("Create a new calendar event").option("-c, --calendar <id>","Calendar ID to create event on").option("-s, --start <time>","Start time (e.g., 14:00, 2pm)","").option("-e, --end <time>","End time (e.g., 15:00, 3pm)").option("--duration <minutes>","Duration in minutes (alternative to --end)",String(AG)).option("-d, --date <date>","Date for the event (YYYY-MM-DD, default: today)").option("-l, --location <location>","Event location").option("--description <text>","Event description").option("--timezone <tz>","Timezone for the event (e.g., America/New_York, default: calendar's timezone)").action(async(j,G)=>{try{if(!G.calendar){let I=(await xy()).filter((J)=>J.isEnabled);if(I.length===0)E("No calendars connected. Connect a calendar via the web app first."),process.exit(1);if(I.length===1)G.calendar=I[0].id;else{let J=I.map((Z)=>` ${Z.id.slice(0,8)} - ${Z.name} (${Z.accountEmail})`).join(`
56
- `);E(`Multiple calendars available. Please specify --calendar <id>:
57
- ${J}`),process.exit(1)}}if(!G.start)E("Start time is required. Use --start <time> (e.g., --start 14:00 or --start 2pm)"),process.exit(1);let P=G.date||m(),R;try{R=Ky(G.start,P)}catch(U){E(U instanceof Error?U.message:"Invalid start time"),process.exit(1)}let q;if(G.end)try{q=Ky(G.end,P)}catch(U){E(U instanceof Error?U.message:"Invalid end time"),process.exit(1)}else{let U=parseInt(G.duration);if(isNaN(U)||U<=0)E("Invalid duration. Must be a positive number of minutes."),process.exit(1);q=Z$(R,U)}let S=await b$({calendarId:G.calendar,summary:j,startTime:R,endTime:q,location:G.location,description:G.description,timeZone:G.timezone});if(L())Q(S);else console.log(`Created: ${X$(S)}`)}catch(P){E(P instanceof Error?P.message:"Failed to create event"),process.exit(1)}})}F.name("ace").description("CLI for Ace productivity assistant").version(ey);F$(F);v$(F);h$(F);u$(F);g$(F);t$(F);m$(F);l$(F);d$(F);F.option("--json","Output in JSON format for AI consumption").option("--api-url <url>","Override API URL");F.parse();
54
+ Linked Projects (${P.projects.length}):`);for(let R of P.projects)console.log(` - ${R.name} [${R.status}]`)}}}catch(P){I(P instanceof Error?P.message:"Failed to get goal"),process.exit(1)}}),y.command("add <name>").description("Create a new goal").option("-d, --domain <domain>","Domain (Work or Personal)","Personal").option("-s, --status <status>","Initial status (default: active)").option("-f, --focus <text>","Set the focus/one thing").option("-n, --notes <notes>","Additional notes").action(async($,j)=>{try{let P=await by();if(!P||P.length===0)I("No domains found. Please check your Ace configuration."),process.exit(1);let R=P.find((f)=>f.name.toLowerCase()===j.domain.toLowerCase());if(!R){let f=P.map((U)=>U.name).join(", ");I(`Invalid domain: ${j.domain}. Valid options: ${f}`),process.exit(1)}let G=await ky({name:$,domainId:R.id,status:j.status??"active",theOneThing:j.focus,notes:j.notes});if(L())S(G);else console.log(`Created: ${k(G)}`)}catch(P){I(P instanceof Error?P.message:"Failed to create goal"),process.exit(1)}}),y.command("update <id>").description("Update a goal").option("-n, --name <name>","New name").option("-s, --status <status>","New status").option("-f, --focus <text>","Update the focus/one thing").option("--notes <notes>","Update notes").action(async($,j)=>{try{let P={};if(j.name)P.name=j.name;if(j.status)P.status=j.status;if(j.focus)P.theOneThing=j.focus;if(j.notes)P.notes=j.notes;let R=await o($,P);if(L())S(R);else console.log(`Updated: ${k(R)}`)}catch(P){I(P instanceof Error?P.message:"Failed to update goal"),process.exit(1)}}),y.command("mark-reviewed <id>").description("Mark a goal as reviewed (resets review timer)").action(async($)=>{try{let j=await hy($);if(L())S(j);else console.log(`Marked as reviewed: ${k(j)}`)}catch(j){I(j instanceof Error?j.message:"Failed to mark goal as reviewed"),process.exit(1)}}),y.command("complete <id>").description("Mark a goal as completed").action(async($)=>{try{let j=await o($,{status:"completed"});if(L())S(j);else console.log(`Completed: ${k(j)}`)}catch(j){I(j instanceof Error?j.message:"Failed to complete goal"),process.exit(1)}}),y.command("pause <id>").description("Pause a goal").action(async($)=>{try{let j=await o($,{status:"paused"});if(L())S(j);else console.log(`Paused: ${k(j)}`)}catch(j){I(j instanceof Error?j.message:"Failed to pause goal"),process.exit(1)}}),y.command("drop <id>").description("Drop a goal").action(async($)=>{try{if(await vy($),L())S({success:!0,id:$});else console.log(`Dropped goal ${$}`)}catch(j){I(j instanceof Error?j.message:"Failed to drop goal"),process.exit(1)}}),y.command("review").description("List goals due for review").action(async()=>{try{let $=await n({dueForReview:!0});if(L())S({goals:$,count:$.length});else console.log(kc($,"Goals Due for Review"))}catch($){I($ instanceof Error?$.message:"Failed to list goals for review"),process.exit(1)}})}function nj(c,y){if(c.length===0)return`${y}: (none)`;let $=[`${y} (${c.length}):`],j=c.reduce((P,R)=>{let G=new Date(R.timestamp).toLocaleDateString();if(!P[G])P[G]=[];return P[G].push(R),P},{});for(let[P,R]of Object.entries(j)){$.push(`
55
+ ${P}:`);for(let G of R){let f=new Date(G.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});$.push(` ${f} [${G.source}] ${G.summary}`)}}return $.join(`
56
+ `)}function c$(c){let y=c.command("activity").description("View and log activity");y.command("list").description("List activity log entries").option("-s, --source <source>","Filter by source (manual, git, calendar, etc.)").option("-l, --limit <n>","Limit results","50").action(async($)=>{try{let j=await uy({source:$.source,limit:parseInt($.limit)});if(L())S({logs:j});else{let P=$.source?`Activity (${$.source})`:"Recent Activity";console.log(nj(j,P))}}catch(j){I(j instanceof Error?j.message:"Failed to list activity"),process.exit(1)}}),y.command("log <summary>").description("Log an activity").option("-s, --source <source>","Activity source","manual").option("-p, --project <id>","Link to project").option("-a, --action <id>","Link to action").action(async($,j)=>{try{let P=await Oy({source:j.source,summary:$,project_id:j.project,action_id:j.action});if(L())S(P);else if(console.log(`Logged: ${$}`),j.project)console.log(` Linked to project: ${j.project}`)}catch(P){I(P instanceof Error?P.message:"Failed to log activity"),process.exit(1)}})}function y$(c){c.command("contexts").description("Manage contexts").command("list").description("List all contexts").action(async()=>{try{let $=await Vy();if(L())S({contexts:$});else if($.length===0)console.log("No contexts found");else{console.log("Contexts:");for(let j of $){let P=j.type?` (${j.type})`:"";console.log(` [${j.id.slice(0,8)}] ${j.name}${P}`)}}}catch($){I($ instanceof Error?$.message:"Failed to list contexts"),process.exit(1)}})}var oj=30,$$=1,j$=250,pj=50;function P$(c){let y=c.command("calendar").description("Manage calendar events");y.command("list").description("List connected calendars").action(async()=>{try{let $=await Vc();if(L())S({calendars:$});else console.log(Xy($,"Connected Calendars"))}catch($){I($ instanceof Error?$.message:"Failed to list calendars"),process.exit(1)}}),y.command("events").description("List calendar events").option("-c, --calendar <id>","Filter by calendar ID").option("-d, --date <date>","Date to show events for (YYYY-MM-DD, default: today)").option("-w, --week","Show events for the next 7 days").option("--from <date>","Start date for range (YYYY-MM-DD)").option("--to <date>","End date for range (YYYY-MM-DD)").option("-l, --limit <n>","Maximum number of events",String(pj)).option("--page-token <token>","Page token for pagination (requires --calendar)").action(async($)=>{try{if($.pageToken&&!$.calendar)I("--page-token requires --calendar to be specified"),process.exit(1);let j,P;if($.from&&$.to){let f=D($.from),U=D($.to);j=f.startDate,P=U.endDate}else if($.week){let f=D("week");j=f.startDate,P=f.endDate}else if($.date){let f=D($.date);j=f.startDate,P=f.endDate}else{let f=D("today");j=f.startDate,P=f.endDate}let R=parseInt($.limit);if(isNaN(R)||R<$$||R>j$)I(`Invalid limit. Must be between ${$$} and ${j$}.`),process.exit(1);let G=await Dc({calendarId:$.calendar,startDate:j,endDate:P,limit:R,pageToken:$.pageToken});if(L())S({events:G.events,count:G.events.length,nextPageToken:G.nextPageToken});else{let f="Events";if($.week)f="Events (next 7 days)";else if($.date)f=`Events for ${$.date}`;else if($.from&&$.to)f=`Events from ${$.from} to ${$.to}`;else f=`Events for ${M()}`;if(console.log(Bc(G.events,f)),G.nextPageToken)console.log(`
57
+ More events available. Use --page-token ${G.nextPageToken} to see next page.`)}}catch(j){I(j instanceof Error?j.message:"Failed to list events"),process.exit(1)}}),y.command("today").description("List today's calendar events").option("-c, --calendar <id>","Filter by calendar ID").action(async($)=>{try{let j=D("today"),P=await Dc({calendarId:$.calendar,startDate:j.startDate,endDate:j.endDate});if(L())S({events:P.events,count:P.events.length,date:M()});else console.log(Bc(P.events,`Today (${M()})`))}catch(j){I(j instanceof Error?j.message:"Failed to list today's events"),process.exit(1)}}),y.command("availability").alias("free").description("Show free time slots across connected calendars").option("-d, --date <date>","Date to check (YYYY-MM-DD, default: today)").option("-w, --week","Show availability for the next 7 days").option("--from <date>","Start date for range (YYYY-MM-DD)").option("--to <date>","End date for range (YYYY-MM-DD)").option("-c, --calendar <id>","Filter by calendar ID").option("--start-hour <hour>","Working day start hour (0-23, default: 9)").option("--end-hour <hour>","Working day end hour (1-24, default: 17)").option("--min-slot <minutes>","Minimum free slot duration in minutes (default: 30)").option("--timezone <tz>","Timezone (default: local timezone)").action(async($)=>{try{let j,P,R=/^\d{4}-\d{2}-\d{2}$/;if($.from&&!R.test($.from))I("Invalid --from date format. Use YYYY-MM-DD."),process.exit(1);if($.to&&!R.test($.to))I("Invalid --to date format. Use YYYY-MM-DD."),process.exit(1);if($.date&&!R.test($.date))I("Invalid --date format. Use YYYY-MM-DD."),process.exit(1);if($.from&&$.to&&$.from>$.to)I("--from date must not be after --to date."),process.exit(1);if($.from&&$.to)j=$.from,P=$.to;else if($.week){j=M();let w=new Date;w.setDate(w.getDate()+6),P=w.toISOString().split("T")[0]}else if($.date)j=$.date,P=$.date;else j=M(),P=j;let G=$.startHour!==void 0?parseInt($.startHour):void 0,f=$.endHour!==void 0?parseInt($.endHour):void 0,U=$.minSlot!==void 0?parseInt($.minSlot):void 0;if(G!==void 0&&(isNaN(G)||G<0||G>23))I("Invalid start-hour. Must be between 0 and 23."),process.exit(1);if(f!==void 0&&(isNaN(f)||f<1||f>24))I("Invalid end-hour. Must be between 1 and 24."),process.exit(1);if(G!==void 0&&f!==void 0&&G>=f)I("start-hour must be less than end-hour."),process.exit(1);if(U!==void 0&&(isNaN(U)||U<0))I("Invalid min-slot. Must be a non-negative number of minutes."),process.exit(1);let q=await dy({startDate:j,endDate:P,startHour:G,endHour:f,minSlotMinutes:U,timezone:$.timezone||Fy(),calendarId:$.calendar});if(L())S(q);else{let w="Availability";if($.week)w="Availability (next 7 days)";else if($.date)w=`Availability for ${$.date}`;else if($.from&&$.to)w=`Availability from ${$.from} to ${$.to}`;else w=`Availability for ${M()}`;console.log(_y(q,w))}}catch(j){I(j instanceof Error?j.message:"Failed to get availability"),process.exit(1)}}),y.command("add <summary>").description("Create a new calendar event").option("-c, --calendar <id>","Calendar ID to create event on").option("-s, --start <time>","Start time (e.g., 14:00, 2pm)","").option("-e, --end <time>","End time (e.g., 15:00, 3pm)").option("--duration <minutes>","Duration in minutes (alternative to --end)",String(oj)).option("-d, --date <date>","Date for the event (YYYY-MM-DD, default: today)").option("-l, --location <location>","Event location").option("--description <text>","Event description").option("--timezone <tz>","Timezone for the event (e.g., America/New_York, default: calendar's timezone)").action(async($,j)=>{try{if(!j.calendar){let q=(await Vc()).filter((w)=>w.isEnabled);if(q.length===0)I("No calendars connected. Connect a calendar via the web app first."),process.exit(1);if(q.length===1)j.calendar=q[0].id;else{let w=q.map((Y)=>` ${Y.id.slice(0,8)} - ${Y.name} (${Y.accountEmail})`).join(`
58
+ `);I(`Multiple calendars available. Please specify --calendar <id>:
59
+ ${w}`),process.exit(1)}}if(!j.start)I("Start time is required. Use --start <time> (e.g., --start 14:00 or --start 2pm)"),process.exit(1);let P=j.date||M(),R;try{R=Cc(j.start,P)}catch(U){I(U instanceof Error?U.message:"Invalid start time"),process.exit(1)}let G;if(j.end)try{G=Cc(j.end,P)}catch(U){I(U instanceof Error?U.message:"Invalid end time"),process.exit(1)}else{let U=parseInt(j.duration);if(isNaN(U)||U<=0)I("Invalid duration. Must be a positive number of minutes."),process.exit(1);G=Zy(R,U)}let f=await ty({calendarId:j.calendar,summary:$,startTime:R,endTime:G,location:j.location,description:j.description,timeZone:j.timezone});if(L())S(f);else console.log(`Created: ${Wy(f)}`)}catch(P){I(P instanceof Error?P.message:"Failed to create event"),process.exit(1)}})}function R$(c){let y=c.command("linear").description("Linear integration commands");y.command("issues").description("List Linear issues for a time period or by workflow status").option("-h, --hours <n>","Hours to look back","24").option("-s, --since <date>","Start date (ISO string)").option("-u, --until <date>","End date (ISO string, defaults to now)").option("--status <names>",'Filter by workflow status names (comma-separated, e.g. "In Progress,Todo")').option("-f, --format <format>","Output format: text, markdown, slack, html","text").action(async($)=>{try{let j=!!$.status,P=await ly({hours:j?void 0:$.hours?parseInt($.hours):void 0,since:j?void 0:$.since,until:j?void 0:$.until,statuses:$.status});if(L())S(P);else{let R=$.format.toLowerCase();switch(R){case"html":console.log(P.formatted.html);break;case"markdown":console.log(P.formatted.markdown);break;case"slack":console.log(P.formatted.slack);break;case"text":default:console.log(P.formatted.text);break}if(R==="text")if(console.log(""),j)console.log(`--- Stats: ${P.stats.totalIssues} issues (${P.stats.completedIssues} completed)`);else console.log(`--- Stats: ${P.stats.totalIssues} issues (${P.stats.completedIssues} completed), ${P.stats.comments} comments, ${P.stats.statusChanges} status changes`)}}catch(j){I(j instanceof Error?j.message:"Failed to fetch Linear issues"),process.exit(1)}}),y.command("statuses").description("List available workflow statuses from linked Linear teams").action(async()=>{try{let $=await ry();if(L())S($);else{if($.teams.length===0){console.log("No linked Linear teams found.");return}for(let j of $.teams){console.log(`${j.teamName} (${j.teamKey})`);for(let P of j.states)console.log(` ${P.name} [${P.type}]`);console.log("")}}}catch($){I($ instanceof Error?$.message:"Failed to fetch Linear statuses"),process.exit(1)}})}function cP(c){let y=new Date(c.periodEnd).toLocaleDateString(),$=c.aceActivityCount+c.githubActivityCount+c.linearActivityCount+c.calendarActivityCount,j=[`[${c.id.slice(0,8)}] ${y}`];if(j.push(`(${$} activities)`),c.categoriesIncluded.length>0)j.push(`- ${c.categoriesIncluded.join(", ")}`);return j.join(" ")}function yP(c,y){if(c.length===0)return`${y}: (none)`;let $=c.map((j)=>` ${cP(j)}`);return`${y} (${c.length}):
60
+ ${$.join(`
61
+ `)}`}function G$(c){let y=c.stats,$=[];if(y.aceItems>0)$.push(`${y.aceItems} ace`);if(y.commits>0)$.push(`${y.commits} commits`);if(y.pullRequests>0)$.push(`${y.pullRequests} PRs`);if(y.issues>0)$.push(`${y.issues} issues`);if(y.linearIssues>0)$.push(`${y.linearIssues} linear`);if(y.calendarEvents>0)$.push(`${y.calendarEvents} meetings`);if(y.slackMessages>0)$.push(`${y.slackMessages} slack`);return["",`--- Period: ${c.periodStart.slice(0,10)} to ${c.periodEnd.slice(0,10)}`,`--- Stats: ${$.join(", ")||"no activity"}`].join(`
62
+ `)}function f$(c){let y=c.command("updates").description("Daily update commands");y.command("list").description("List recent updates").option("-l, --limit <n>","Number of updates to show","10").option("-o, --offset <n>","Skip first N updates","0").action(async($)=>{try{let j=await gy({limit:parseInt($.limit,10),offset:parseInt($.offset,10)});if(L())S({updates:j,count:j.length});else console.log(yP(j,"Recent Updates"))}catch(j){I(j instanceof Error?j.message:"Failed to list updates"),process.exit(1)}}),y.command("generate").description("Generate a new daily update").option("-d, --date <YYYY-MM-DD>","Target date (defaults to today)").option("--days-off <dates>","Comma-separated ISO dates to skip").option("--timezone <tz>","IANA timezone for working day calculation").option("-f, --format <format>","Output format: markdown, slack","markdown").action(async($)=>{try{let j=$.daysOff?$.daysOff.split(",").map((R)=>R.trim()):void 0,P=await sy({targetDate:$.date,daysOff:j,timezone:$.timezone});if(L())S(P);else{if($.format.toLowerCase()==="slack")console.log(P.formatted.slackMrkdwn);else console.log(P.formatted.markdown);console.log(G$(P)),console.log(`--- ID: ${P.id}`)}}catch(j){I(j instanceof Error?j.message:"Failed to generate update"),process.exit(1)}}),y.command("show <id>").description("Show a specific update").option("-f, --format <format>","Output format: markdown, slack","markdown").action(async($,j)=>{try{let P=await my($);if(L())S(P);else{if(j.format.toLowerCase()==="slack")console.log(P.formatted.slackMrkdwn);else console.log(P.formatted.markdown);console.log(G$(P))}}catch(P){I(P instanceof Error?P.message:"Failed to show update"),process.exit(1)}})}F.name("ace").description("CLI for Ace productivity assistant").version(oc);Ky(F);ey(F);ay(F);ny(F);oy(F);py(F);c$(F);y$(F);P$(F);R$(F);f$(F);F.option("--json","Output in JSON format for AI consumption").option("--api-url <url>","Override API URL");F.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ace-assistant-cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "CLI for Ace productivity assistant - bring your own AI",
5
5
  "type": "module",
6
6
  "bin": {