@hagicode/cli 0.1.0-dev.5.1.b85b83a → 0.1.0-dev.7.1.8b40188
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -1
- package/dist/chunks/main-CILDKeJ3.js +91 -0
- package/dist/cli.js +1 -1
- package/dist/main.js +1 -1
- package/package.json +2 -2
- package/dist/chunks/main-CUEYUrFk.js +0 -75
package/README.md
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@hagicode/cli)
|
|
4
4
|
|
|
5
|
-
`@hagicode/cli` provides the published `hagi` command for project, proposal, chat, and AutoTask management against a HagiCode backend API.
|
|
5
|
+
`@hagicode/cli` provides the published `hagi` command for project, proposal, vault, chat, and AutoTask management against a HagiCode backend API.
|
|
6
|
+
The same repository also carries the canonical embedded Hagi skill under [`skills/`](skills/), so package usage and AI-oriented guidance live in one writable source.
|
|
6
7
|
|
|
7
8
|
## Requirements
|
|
8
9
|
|
|
@@ -43,10 +44,24 @@ The examples below use `hagi ...` after the package is available on your `PATH`.
|
|
|
43
44
|
hagi --help
|
|
44
45
|
hagi project list --json
|
|
45
46
|
hagi proposal list --json
|
|
47
|
+
hagi vault list --json
|
|
46
48
|
hagi chat list --json
|
|
47
49
|
hagi autotask create --title "Auto commit" --project-id <project-id> --prompt-id auto-compose-commit.en-US
|
|
48
50
|
```
|
|
49
51
|
|
|
52
|
+
## Embedded Skills
|
|
53
|
+
|
|
54
|
+
If you are integrating Hagi CLI into an agent workflow, start from the embedded skill package in this repository:
|
|
55
|
+
|
|
56
|
+
- [`skills/README.md`](skills/README.md) - repository-level discovery entrypoint
|
|
57
|
+
- [`skills/hagi/SKILL.md`](skills/hagi/SKILL.md) - canonical Hagi skill contract
|
|
58
|
+
- [`skills/hagi/references/`](skills/hagi/references/) - focused package usage, proposal flow, maintainer, and validation guidance
|
|
59
|
+
|
|
60
|
+
`repos/cli/skills/**` is the canonical writable source for future Hagi skill updates.
|
|
61
|
+
`repos/skills/**` remains a historical/reference-only mirror during this consolidation.
|
|
62
|
+
|
|
63
|
+
Repository-local `npm run dev -- ...` and `node ./dist/cli.js ...` commands stay in the maintainer section below.
|
|
64
|
+
|
|
50
65
|
## Shared Runtime Flags
|
|
51
66
|
|
|
52
67
|
Every command family supports the same global runtime flags:
|
|
@@ -68,6 +83,8 @@ hagi --base-url https://api.example.com --token "$HAGI_TOKEN" project list --jso
|
|
|
68
83
|
hagi
|
|
69
84
|
|-- project list | create | update | delete
|
|
70
85
|
|-- proposal list | create | generate-name | optimize-description | generate | annotate | execute | archive | status | complete | send
|
|
86
|
+
|-- vault list | create | update | delete
|
|
87
|
+
| `-- files list | preview
|
|
71
88
|
|-- chat list | create | archive | delete | send
|
|
72
89
|
`-- autotask create | send
|
|
73
90
|
```
|
|
@@ -175,6 +192,47 @@ The CLI keeps proposal lifecycle actions explicit and non-interactive:
|
|
|
175
192
|
|
|
176
193
|
Each command maps to one backend action. The CLI may suggest a next command, but it never chains later lifecycle APIs automatically.
|
|
177
194
|
|
|
195
|
+
## Vault Commands
|
|
196
|
+
|
|
197
|
+
List registered vaults:
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
hagi vault list
|
|
201
|
+
hagi vault list --json
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Create a vault with typed options:
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
hagi vault create \
|
|
208
|
+
--name "Main Notes" \
|
|
209
|
+
--type obsidian \
|
|
210
|
+
--physical-path /vaults/main \
|
|
211
|
+
--git-url https://github.com/acme/notes.git
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Update only part of a vault record. The CLI resolves the current vault snapshot first so omitted fields are preserved:
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
hagi vault update --id <vault-id> --name "Renamed Vault"
|
|
218
|
+
hagi vault update --id <vault-id> --physical-path /vaults/new-home --git-url https://github.com/acme/notes.git
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Delete a vault and optionally request backend cleanup of local files:
|
|
222
|
+
|
|
223
|
+
```bash
|
|
224
|
+
hagi vault delete --id <vault-id>
|
|
225
|
+
hagi vault delete --id <vault-id> --delete-local-files --json
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Browse vault files and preview supported content:
|
|
229
|
+
|
|
230
|
+
```bash
|
|
231
|
+
hagi vault files list --id <vault-id>
|
|
232
|
+
hagi vault files list --id <vault-id> --path docs --json
|
|
233
|
+
hagi vault files preview --id <vault-id> --path docs/readme.md
|
|
234
|
+
```
|
|
235
|
+
|
|
178
236
|
## Chat Commands
|
|
179
237
|
|
|
180
238
|
List chat sessions:
|
|
@@ -226,6 +284,7 @@ hagi autotask send --session-id <session-id> --content "Retry with a smaller dif
|
|
|
226
284
|
## Maintainer Workflow (`repos/cli` only)
|
|
227
285
|
|
|
228
286
|
Use the commands in this section only when you are editing or validating the CLI source tree inside this repository.
|
|
287
|
+
Package consumers and automation should stay on `npx @hagicode/cli ...` or an installed `hagi ...` unless they are working on `repos/cli` itself.
|
|
229
288
|
|
|
230
289
|
Build the local repository output:
|
|
231
290
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
var Ht=Object.create,gt=Object.defineProperty,Ft=Object.getOwnPropertyDescriptor,qt=Object.getOwnPropertyNames,kt=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty,U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ut=(t,e,u,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(var i=qt(e),r=0,a=i.length,c;r<a;r++)c=i[r],!Rt.call(t,c)&&c!==u&>(t,c,{get:(h=>e[h]).bind(null,c),enumerable:!(o=Ft(e,c))||o.enumerable});return t},Lt=(t,e,u)=>(u=t!=null?Ht(kt(t)):{},Ut(e||!t||!t.__esModule?gt(u,"default",{value:t,enumerable:!0}):u,t));let Gt=require("node:process"),Bt=require("node:fs/promises");var Q=U((t=>{var e=class extends Error{constructor(o,i,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=o,this.nestedError=void 0}},u=class extends e{constructor(o){super(1,"commander.invalidArgument",o),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};t.CommanderError=e,t.InvalidArgumentError=u})),st=U((t=>{var{InvalidArgumentError:e}=Q(),u=class{constructor(i,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(i,r){return r===this.defaultValue||!Array.isArray(r)?[i]:(r.push(i),r)}default(i,r){return this.defaultValue=i,this.defaultValueDescription=r,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(r,a)=>{if(!this.argChoices.includes(r))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,a):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function o(i){const r=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+r+">":"["+r+"]"}t.Argument=u,t.humanReadableArgName=o})),vt=U((t=>{var{humanReadableArgName:e}=st(),u=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(i){this.helpWidth=this.helpWidth??i.helpWidth??80}visibleCommands(i){const r=i.commands.filter(c=>!c._hidden),a=i._getHelpCommand();return a&&!a._hidden&&r.push(a),this.sortSubcommands&&r.sort((c,h)=>c.name().localeCompare(h.name())),r}compareOptions(i,r){const a=c=>c.short?c.short.replace(/^-/,""):c.long.replace(/^--/,"");return a(i).localeCompare(a(r))}visibleOptions(i){const r=i.options.filter(c=>!c.hidden),a=i._getHelpOption();if(a&&!a.hidden){const c=a.short&&i._findOption(a.short),h=a.long&&i._findOption(a.long);!c&&!h?r.push(a):a.long&&!h?r.push(i.createOption(a.long,a.description)):a.short&&!c&&r.push(i.createOption(a.short,a.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const r=[];for(let a=i.parent;a;a=a.parent){const c=a.options.filter(h=>!h.hidden);r.push(...c)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(i){return i._argsDescription&&i.registeredArguments.forEach(r=>{r.description=r.description||i._argsDescription[r.name()]||""}),i.registeredArguments.find(r=>r.description)?i.registeredArguments:[]}subcommandTerm(i){const r=i.registeredArguments.map(a=>e(a)).join(" ");return i._name+(i._aliases[0]?"|"+i._aliases[0]:"")+(i.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(i){return i.flags}argumentTerm(i){return i.name()}longestSubcommandTermLength(i,r){return r.visibleCommands(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(c)))),0)}longestOptionTermLength(i,r){return r.visibleOptions(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleOptionTerm(r.optionTerm(c)))),0)}longestGlobalOptionTermLength(i,r){return r.visibleGlobalOptions(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleOptionTerm(r.optionTerm(c)))),0)}longestArgumentTermLength(i,r){return r.visibleArguments(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(c)))),0)}commandUsage(i){let r=i._name;i._aliases[0]&&(r=r+"|"+i._aliases[0]);let a="";for(let c=i.parent;c;c=c.parent)a=c.name()+" "+a;return a+r+" "+i.usage()}commandDescription(i){return i.description()}subcommandDescription(i){return i.summary()||i.description()}optionDescription(i){const r=[];if(i.argChoices&&r.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&(i.required||i.optional||i.isBoolean()&&typeof i.defaultValue=="boolean")&&r.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),i.presetArg!==void 0&&i.optional&&r.push(`preset: ${JSON.stringify(i.presetArg)}`),i.envVar!==void 0&&r.push(`env: ${i.envVar}`),r.length>0){const a=`(${r.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}argumentDescription(i){const r=[];if(i.argChoices&&r.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&r.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),r.length>0){const a=`(${r.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}formatItemList(i,r,a){return r.length===0?[]:[a.styleTitle(i),...r,""]}groupItems(i,r,a){const c=new Map;return i.forEach(h=>{const O=a(h);c.has(O)||c.set(O,[])}),r.forEach(h=>{const O=a(h);c.has(O)||c.set(O,[]),c.get(O).push(h)}),c}formatHelp(i,r){const a=r.padWidth(i,r),c=r.helpWidth??80;function h(_,j){return r.formatItem(_,a,j,r)}let O=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(i))}`,""];const A=r.commandDescription(i);A.length>0&&(O=O.concat([r.boxWrap(r.styleCommandDescription(A),c),""]));const C=r.visibleArguments(i).map(_=>h(r.styleArgumentTerm(r.argumentTerm(_)),r.styleArgumentDescription(r.argumentDescription(_))));if(O=O.concat(this.formatItemList("Arguments:",C,r)),this.groupItems(i.options,r.visibleOptions(i),_=>_.helpGroupHeading??"Options:").forEach((_,j)=>{const q=_.map(F=>h(r.styleOptionTerm(r.optionTerm(F)),r.styleOptionDescription(r.optionDescription(F))));O=O.concat(this.formatItemList(j,q,r))}),r.showGlobalOptions){const _=r.visibleGlobalOptions(i).map(j=>h(r.styleOptionTerm(r.optionTerm(j)),r.styleOptionDescription(r.optionDescription(j))));O=O.concat(this.formatItemList("Global Options:",_,r))}return this.groupItems(i.commands,r.visibleCommands(i),_=>_.helpGroup()||"Commands:").forEach((_,j)=>{const q=_.map(F=>h(r.styleSubcommandTerm(r.subcommandTerm(F)),r.styleSubcommandDescription(r.subcommandDescription(F))));O=O.concat(this.formatItemList(j,q,r))}),O.join(`
|
|
2
|
+
`)}displayWidth(i){return o(i).length}styleTitle(i){return i}styleUsage(i){return i.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(i){return this.styleDescriptionText(i)}styleOptionDescription(i){return this.styleDescriptionText(i)}styleSubcommandDescription(i){return this.styleDescriptionText(i)}styleArgumentDescription(i){return this.styleDescriptionText(i)}styleDescriptionText(i){return i}styleOptionTerm(i){return this.styleOptionText(i)}styleSubcommandTerm(i){return i.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(i){return this.styleArgumentText(i)}styleOptionText(i){return i}styleArgumentText(i){return i}styleSubcommandText(i){return i}styleCommandText(i){return i}padWidth(i,r){return Math.max(r.longestOptionTermLength(i,r),r.longestGlobalOptionTermLength(i,r),r.longestSubcommandTermLength(i,r),r.longestArgumentTermLength(i,r))}preformatted(i){return/\n[^\S\r\n]/.test(i)}formatItem(i,r,a,c){const O=" ".repeat(2);if(!a)return O+i;const A=i.padEnd(r+i.length-c.displayWidth(i)),C=2,_=(this.helpWidth??80)-r-C-2;let j;return _<this.minWidthToWrap||c.preformatted(a)?j=a:j=c.boxWrap(a,_).replace(/\n/g,`
|
|
3
|
+
`+" ".repeat(r+C)),O+A+" ".repeat(C)+j.replace(/\n/g,`
|
|
4
|
+
${O}`)}boxWrap(i,r){if(r<this.minWidthToWrap)return i;const a=i.split(/\r\n|\n/),c=/[\s]*[^\s]+/g,h=[];return a.forEach(O=>{const A=O.match(c);if(A===null){h.push("");return}let C=[A.shift()],_=this.displayWidth(C[0]);A.forEach(j=>{const q=this.displayWidth(j);if(_+q<=r){C.push(j),_+=q;return}h.push(C.join(""));const F=j.trimStart();C=[F],_=this.displayWidth(F)}),h.push(C.join(""))}),h.join(`
|
|
5
|
+
`)}};function o(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}t.Help=u,t.stripColor=o})),Ot=U((t=>{var{InvalidArgumentError:e}=Q(),u=class{constructor(a,c){this.flags=a,this.description=c||"",this.required=a.includes("<"),this.optional=a.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(a),this.mandatory=!1;const h=r(a);this.short=h.shortFlag,this.long=h.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,this.helpGroupHeading=void 0}default(a,c){return this.defaultValue=a,this.defaultValueDescription=c,this}preset(a){return this.presetArg=a,this}conflicts(a){return this.conflictsWith=this.conflictsWith.concat(a),this}implies(a){let c=a;return typeof a=="string"&&(c={[a]:!0}),this.implied=Object.assign(this.implied||{},c),this}env(a){return this.envVar=a,this}argParser(a){return this.parseArg=a,this}makeOptionMandatory(a=!0){return this.mandatory=!!a,this}hideHelp(a=!0){return this.hidden=!!a,this}_collectValue(a,c){return c===this.defaultValue||!Array.isArray(c)?[a]:(c.push(a),c)}choices(a){return this.argChoices=a.slice(),this.parseArg=(c,h)=>{if(!this.argChoices.includes(c))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(c,h):c},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?i(this.name().replace(/^no-/,"")):i(this.name())}helpGroup(a){return this.helpGroupHeading=a,this}is(a){return this.short===a||this.long===a}isBoolean(){return!this.required&&!this.optional&&!this.negate}},o=class{constructor(a){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,a.forEach(c=>{c.negate?this.negativeOptions.set(c.attributeName(),c):this.positiveOptions.set(c.attributeName(),c)}),this.negativeOptions.forEach((c,h)=>{this.positiveOptions.has(h)&&this.dualOptions.add(h)})}valueFromOption(a,c){const h=c.attributeName();if(!this.dualOptions.has(h))return!0;const O=this.negativeOptions.get(h).presetArg,A=O!==void 0?O:!1;return c.negate===(A===a)}};function i(a){return a.split("-").reduce((c,h)=>c+h[0].toUpperCase()+h.slice(1))}function r(a){let c,h;const O=/^-[^-]$/,A=/^--[^-]/,C=a.split(/[ |,]+/).concat("guard");if(O.test(C[0])&&(c=C.shift()),A.test(C[0])&&(h=C.shift()),!c&&O.test(C[0])&&(c=C.shift()),!c&&A.test(C[0])&&(c=h,h=C.shift()),C[0].startsWith("-")){const _=C[0],j=`option creation failed due to '${_}' in option flags '${a}'`;throw/^-[^-][^-]/.test(_)?new Error(`${j}
|
|
6
|
+
- a short flag is a single dash and a single character
|
|
7
|
+
- either use a single dash and a single character (for a short flag)
|
|
8
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):O.test(_)?new Error(`${j}
|
|
9
|
+
- too many short flags`):A.test(_)?new Error(`${j}
|
|
10
|
+
- too many long flags`):new Error(`${j}
|
|
11
|
+
- unrecognised flag format`)}if(c===void 0&&h===void 0)throw new Error(`option creation failed due to no flags found in '${a}'.`);return{shortFlag:c,longFlag:h}}t.Option=u,t.DualOptions=o})),Wt=U((t=>{var e=3;function u(i,r){if(Math.abs(i.length-r.length)>e)return Math.max(i.length,r.length);const a=[];for(let c=0;c<=i.length;c++)a[c]=[c];for(let c=0;c<=r.length;c++)a[0][c]=c;for(let c=1;c<=r.length;c++)for(let h=1;h<=i.length;h++){let O=1;i[h-1]===r[c-1]?O=0:O=1,a[h][c]=Math.min(a[h-1][c]+1,a[h][c-1]+1,a[h-1][c-1]+O),h>1&&c>1&&i[h-1]===r[c-2]&&i[h-2]===r[c-1]&&(a[h][c]=Math.min(a[h][c],a[h-2][c-2]+1))}return a[i.length][r.length]}function o(i,r){if(!r||r.length===0)return"";r=Array.from(new Set(r));const a=i.startsWith("--");a&&(i=i.slice(2),r=r.map(A=>A.slice(2)));let c=[],h=e;const O=.4;return r.forEach(A=>{if(A.length<=1)return;const C=u(i,A),_=Math.max(i.length,A.length);(_-C)/_>O&&(C<h?(h=C,c=[A]):C===h&&c.push(A))}),c.sort((A,C)=>A.localeCompare(C)),a&&(c=c.map(A=>`--${A}`)),c.length>1?`
|
|
12
|
+
(Did you mean one of ${c.join(", ")}?)`:c.length===1?`
|
|
13
|
+
(Did you mean ${c[0]}?)`:""}t.suggestSimilar=o})),Mt=U((t=>{var e=require("node:events").EventEmitter,u=require("node:child_process"),o=require("node:path"),i=require("node:fs"),r=require("node:process"),{Argument:a,humanReadableArgName:c}=st(),{CommanderError:h}=Q(),{Help:O,stripColor:A}=vt(),{Option:C,DualOptions:_}=Ot(),{suggestSimilar:j}=Wt(),q=class yt extends e{constructor(s){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=s||"",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._savedState=null,this._outputConfiguration={writeOut:n=>r.stdout.write(n),writeErr:n=>r.stderr.write(n),outputError:(n,l)=>l(n),getOutHelpWidth:()=>r.stdout.isTTY?r.stdout.columns:void 0,getErrHelpWidth:()=>r.stderr.isTTY?r.stderr.columns:void 0,getOutHasColors:()=>Z()??(r.stdout.isTTY&&r.stdout.hasColors?.()),getErrHasColors:()=>Z()??(r.stderr.isTTY&&r.stderr.hasColors?.()),stripColor:n=>A(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(s){return this._outputConfiguration=s._outputConfiguration,this._helpOption=s._helpOption,this._helpCommand=s._helpCommand,this._helpConfiguration=s._helpConfiguration,this._exitCallback=s._exitCallback,this._storeOptionsAsProperties=s._storeOptionsAsProperties,this._combineFlagAndOptionalValue=s._combineFlagAndOptionalValue,this._allowExcessArguments=s._allowExcessArguments,this._enablePositionalOptions=s._enablePositionalOptions,this._showHelpAfterError=s._showHelpAfterError,this._showSuggestionAfterError=s._showSuggestionAfterError,this}_getCommandAndAncestors(){const s=[];for(let n=this;n;n=n.parent)s.push(n);return s}command(s,n,l){let d=n,p=l;typeof d=="object"&&d!==null&&(p=d,d=null),p=p||{};const[,m,y]=s.match(/([^ ]+) *(.*)/),S=this.createCommand(m);return d&&(S.description(d),S._executableHandler=!0),p.isDefault&&(this._defaultCommandName=S._name),S._hidden=!!(p.noHelp||p.hidden),S._executableFile=p.executableFile||null,y&&S.arguments(y),this._registerCommand(S),S.parent=this,S.copyInheritedSettings(this),d?this:S}createCommand(s){return new yt(s)}createHelp(){return Object.assign(new O,this.configureHelp())}configureHelp(s){return s===void 0?this._helpConfiguration:(this._helpConfiguration=s,this)}configureOutput(s){return s===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...s},this)}showHelpAfterError(s=!0){return typeof s!="string"&&(s=!!s),this._showHelpAfterError=s,this}showSuggestionAfterError(s=!0){return this._showSuggestionAfterError=!!s,this}addCommand(s,n){if(!s._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
|
+
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=s._name),(n.noHelp||n.hidden)&&(s._hidden=!0),this._registerCommand(s),s.parent=this,s._checkForBrokenPassThrough(),this}createArgument(s,n){return new a(s,n)}argument(s,n,l,d){const p=this.createArgument(s,n);return typeof l=="function"?p.default(d).argParser(l):p.default(l),this.addArgument(p),this}arguments(s){return s.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(s){const n=this.registeredArguments.slice(-1)[0];if(n?.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(s.required&&s.defaultValue!==void 0&&s.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${s.name()}'`);return this.registeredArguments.push(s),this}helpCommand(s,n){if(typeof s=="boolean")return this._addImplicitHelpCommand=s,s&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,l,d]=(s??"help [command]").match(/([^ ]+) *(.*)/),p=n??"display help for command",m=this.createCommand(l);return m.helpOption(!1),d&&m.arguments(d),p&&m.description(p),this._addImplicitHelpCommand=!0,this._helpCommand=m,(s||n)&&this._initCommandGroup(m),this}addHelpCommand(s,n){return typeof s!="object"?(this.helpCommand(s,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=s,this._initCommandGroup(s),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(s,n){const l=["preSubcommand","preAction","postAction"];if(!l.includes(s))throw new Error(`Unexpected value for event passed to hook : '${s}'.
|
|
15
|
+
Expecting one of '${l.join("', '")}'`);return this._lifeCycleHooks[s]?this._lifeCycleHooks[s].push(n):this._lifeCycleHooks[s]=[n],this}exitOverride(s){return s?this._exitCallback=s:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(s,n,l){this._exitCallback&&this._exitCallback(new h(s,n,l)),r.exit(s)}action(s){const n=l=>{const d=this.registeredArguments.length,p=l.slice(0,d);return this._storeOptionsAsProperties?p[d]=this:p[d]=this.opts(),p.push(this),s.apply(this,p)};return this._actionHandler=n,this}createOption(s,n){return new C(s,n)}_callParseArg(s,n,l,d){try{return s.parseArg(n,l)}catch(p){if(p.code==="commander.invalidArgument"){const m=`${d} ${p.message}`;this.error(m,{exitCode:p.exitCode,code:p.code})}throw p}}_registerOption(s){const n=s.short&&this._findOption(s.short)||s.long&&this._findOption(s.long);if(n){const l=s.long&&this._findOption(s.long)?s.long:s.short;throw new Error(`Cannot add option '${s.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${l}'
|
|
16
|
+
- already used by option '${n.flags}'`)}this._initOptionGroup(s),this.options.push(s)}_registerCommand(s){const n=d=>[d.name()].concat(d.aliases()),l=n(s).find(d=>this._findCommand(d));if(l){const d=n(this._findCommand(l)).join("|"),p=n(s).join("|");throw new Error(`cannot add command '${p}' as already have command '${d}'`)}this._initCommandGroup(s),this.commands.push(s)}addOption(s){this._registerOption(s);const n=s.name(),l=s.attributeName();if(s.negate){const p=s.long.replace(/^--no-/,"--");this._findOption(p)||this.setOptionValueWithSource(l,s.defaultValue===void 0?!0:s.defaultValue,"default")}else s.defaultValue!==void 0&&this.setOptionValueWithSource(l,s.defaultValue,"default");const d=(p,m,y)=>{p==null&&s.presetArg!==void 0&&(p=s.presetArg);const S=this.getOptionValue(l);p!==null&&s.parseArg?p=this._callParseArg(s,p,S,m):p!==null&&s.variadic&&(p=s._collectValue(p,S)),p==null&&(s.negate?p=!1:s.isBoolean()||s.optional?p=!0:p=""),this.setOptionValueWithSource(l,p,y)};return this.on("option:"+n,p=>{d(p,`error: option '${s.flags}' argument '${p}' is invalid.`,"cli")}),s.envVar&&this.on("optionEnv:"+n,p=>{d(p,`error: option '${s.flags}' value '${p}' from env '${s.envVar}' is invalid.`,"env")}),this}_optionEx(s,n,l,d,p){if(typeof n=="object"&&n instanceof C)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const m=this.createOption(n,l);if(m.makeOptionMandatory(!!s.mandatory),typeof d=="function")m.default(p).argParser(d);else if(d instanceof RegExp){const y=d;d=(S,x)=>{const f=y.exec(S);return f?f[0]:x},m.default(p).argParser(d)}else m.default(d);return this.addOption(m)}option(s,n,l,d){return this._optionEx({},s,n,l,d)}requiredOption(s,n,l,d){return this._optionEx({mandatory:!0},s,n,l,d)}combineFlagAndOptionalValue(s=!0){return this._combineFlagAndOptionalValue=!!s,this}allowUnknownOption(s=!0){return this._allowUnknownOption=!!s,this}allowExcessArguments(s=!0){return this._allowExcessArguments=!!s,this}enablePositionalOptions(s=!0){return this._enablePositionalOptions=!!s,this}passThroughOptions(s=!0){return this._passThroughOptions=!!s,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(s=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!s,this}getOptionValue(s){return this._storeOptionsAsProperties?this[s]:this._optionValues[s]}setOptionValue(s,n){return this.setOptionValueWithSource(s,n,void 0)}setOptionValueWithSource(s,n,l){return this._storeOptionsAsProperties?this[s]=n:this._optionValues[s]=n,this._optionValueSources[s]=l,this}getOptionValueSource(s){return this._optionValueSources[s]}getOptionValueSourceWithGlobals(s){let n;return this._getCommandAndAncestors().forEach(l=>{l.getOptionValueSource(s)!==void 0&&(n=l.getOptionValueSource(s))}),n}_prepareUserArgs(s,n){if(s!==void 0&&!Array.isArray(s))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},s===void 0&&n.from===void 0){r.versions?.electron&&(n.from="electron");const d=r.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(n.from="eval")}s===void 0&&(s=r.argv),this.rawArgs=s.slice();let l;switch(n.from){case void 0:case"node":this._scriptPath=s[1],l=s.slice(2);break;case"electron":r.defaultApp?(this._scriptPath=s[1],l=s.slice(2)):l=s.slice(1);break;case"user":l=s.slice(0);break;case"eval":l=s.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",l}parse(s,n){this._prepareForParse();const l=this._prepareUserArgs(s,n);return this._parseCommand([],l),this}async parseAsync(s,n){this._prepareForParse();const l=this._prepareUserArgs(s,n);return await this._parseCommand([],l),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
17
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(s,n,l){if(i.existsSync(s))return;const d=`'${s}' does not exist
|
|
18
|
+
- if '${l}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
19
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
20
|
+
- ${n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;throw new Error(d)}_executeSubCommand(s,n){n=n.slice();let l=!1;const d=[".js",".ts",".tsx",".mjs",".cjs"];function p(f,b){const $=o.resolve(f,b);if(i.existsSync($))return $;if(d.includes(o.extname(b)))return;const pt=d.find(Nt=>i.existsSync(`${$}${Nt}`));if(pt)return`${$}${pt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let m=s._executableFile||`${this._name}-${s._name}`,y=this._executableDir||"";if(this._scriptPath){let f;try{f=i.realpathSync(this._scriptPath)}catch{f=this._scriptPath}y=o.resolve(o.dirname(f),y)}if(y){let f=p(y,m);if(!f&&!s._executableFile&&this._scriptPath){const b=o.basename(this._scriptPath,o.extname(this._scriptPath));b!==this._name&&(f=p(y,`${b}-${s._name}`))}m=f||m}l=d.includes(o.extname(m));let S;r.platform!=="win32"?l?(n.unshift(m),n=F(r.execArgv).concat(n),S=u.spawn(r.argv[0],n,{stdio:"inherit"})):S=u.spawn(m,n,{stdio:"inherit"}):(this._checkForMissingExecutable(m,y,s._name),n.unshift(m),n=F(r.execArgv).concat(n),S=u.spawn(r.execPath,n,{stdio:"inherit"})),S.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{r.on(f,()=>{S.killed===!1&&S.exitCode===null&&S.kill(f)})});const x=this._exitCallback;S.on("close",f=>{f=f??1,x?x(new h(f,"commander.executeSubCommandAsync","(close)")):r.exit(f)}),S.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(m,y,s._name);else if(f.code==="EACCES")throw new Error(`'${m}' not executable`);if(!x)r.exit(1);else{const b=new h(1,"commander.executeSubCommandAsync","(error)");b.nestedError=f,x(b)}}),this.runningCommand=S}_dispatchSubcommand(s,n,l){const d=this._findCommand(s);d||this.help({error:!0}),d._prepareForParse();let p;return p=this._chainOrCallSubCommandHook(p,d,"preSubcommand"),p=this._chainOrCall(p,()=>{if(d._executableHandler)this._executeSubCommand(d,n.concat(l));else return d._parseCommand(n,l)}),p}_dispatchHelpCommand(s){s||this.help();const n=this._findCommand(s);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(s,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((s,n)=>{s.required&&this.args[n]==null&&this.missingArgument(s.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const s=(l,d,p)=>{let m=d;if(d!==null&&l.parseArg){const y=`error: command-argument value '${d}' is invalid for argument '${l.name()}'.`;m=this._callParseArg(l,d,p,y)}return m};this._checkNumberOfArguments();const n=[];this.registeredArguments.forEach((l,d)=>{let p=l.defaultValue;l.variadic?d<this.args.length?(p=this.args.slice(d),l.parseArg&&(p=p.reduce((m,y)=>s(l,y,m),l.defaultValue))):p===void 0&&(p=[]):d<this.args.length&&(p=this.args[d],l.parseArg&&(p=s(l,p,l.defaultValue))),n[d]=p}),this.processedArgs=n}_chainOrCall(s,n){return s?.then&&typeof s.then=="function"?s.then(()=>n()):n()}_chainOrCallHooks(s,n){let l=s;const d=[];return this._getCommandAndAncestors().reverse().filter(p=>p._lifeCycleHooks[n]!==void 0).forEach(p=>{p._lifeCycleHooks[n].forEach(m=>{d.push({hookedCommand:p,callback:m})})}),n==="postAction"&&d.reverse(),d.forEach(p=>{l=this._chainOrCall(l,()=>p.callback(p.hookedCommand,this))}),l}_chainOrCallSubCommandHook(s,n,l){let d=s;return this._lifeCycleHooks[l]!==void 0&&this._lifeCycleHooks[l].forEach(p=>{d=this._chainOrCall(d,()=>p(this,n))}),d}_parseCommand(s,n){const l=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),s=s.concat(l.operands),n=l.unknown,this.args=s.concat(n),s&&this._findCommand(s[0]))return this._dispatchSubcommand(s[0],s.slice(1),n);if(this._getHelpCommand()&&s[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(s[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,s,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(l.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const d=()=>{l.unknown.length>0&&this.unknownOption(l.unknown[0])},p=`command:${this.name()}`;if(this._actionHandler){d(),this._processArguments();let m;return m=this._chainOrCallHooks(m,"preAction"),m=this._chainOrCall(m,()=>this._actionHandler(this.processedArgs)),this.parent&&(m=this._chainOrCall(m,()=>{this.parent.emit(p,s,n)})),m=this._chainOrCallHooks(m,"postAction"),m}if(this.parent?.listenerCount(p))d(),this._processArguments(),this.parent.emit(p,s,n);else if(s.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",s,n);this.listenerCount("command:*")?this.emit("command:*",s,n):this.commands.length?this.unknownCommand():(d(),this._processArguments())}else this.commands.length?(d(),this.help({error:!0})):(d(),this._processArguments())}_findCommand(s){if(s)return this.commands.find(n=>n._name===s||n._aliases.includes(s))}_findOption(s){return this.options.find(n=>n.is(s))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(s=>{s.options.forEach(n=>{n.mandatory&&s.getOptionValue(n.attributeName())===void 0&&s.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){const s=this.options.filter(n=>{const l=n.attributeName();return this.getOptionValue(l)===void 0?!1:this.getOptionValueSource(l)!=="default"});s.filter(n=>n.conflictsWith.length>0).forEach(n=>{const l=s.find(d=>n.conflictsWith.includes(d.attributeName()));l&&this._conflictingOption(n,l)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(s=>{s._checkForConflictingLocalOptions()})}parseOptions(s){const n=[],l=[];let d=n;function p(f){return f.length>1&&f[0]==="-"}const m=f=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(f)?!this._getCommandAndAncestors().some(b=>b.options.map($=>$.short).some($=>/^-\d$/.test($))):!1;let y=null,S=null,x=0;for(;x<s.length||S;){const f=S??s[x++];if(S=null,f==="--"){d===l&&d.push(f),d.push(...s.slice(x));break}if(y&&(!p(f)||m(f))){this.emit(`option:${y.name()}`,f);continue}if(y=null,p(f)){const b=this._findOption(f);if(b){if(b.required){const $=s[x++];$===void 0&&this.optionMissingArgument(b),this.emit(`option:${b.name()}`,$)}else if(b.optional){let $=null;x<s.length&&(!p(s[x])||m(s[x]))&&($=s[x++]),this.emit(`option:${b.name()}`,$)}else this.emit(`option:${b.name()}`);y=b.variadic?b:null;continue}}if(f.length>2&&f[0]==="-"&&f[1]!=="-"){const b=this._findOption(`-${f[1]}`);if(b){b.required||b.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${b.name()}`,f.slice(2)):(this.emit(`option:${b.name()}`),S=`-${f.slice(2)}`);continue}}if(/^--[^=]+=/.test(f)){const b=f.indexOf("="),$=this._findOption(f.slice(0,b));if($&&($.required||$.optional)){this.emit(`option:${$.name()}`,f.slice(b+1));continue}}if(d===n&&p(f)&&!(this.commands.length===0&&m(f))&&(d=l),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&l.length===0){if(this._findCommand(f)){n.push(f),l.push(...s.slice(x));break}else if(this._getHelpCommand()&&f===this._getHelpCommand().name()){n.push(f,...s.slice(x));break}else if(this._defaultCommandName){l.push(f,...s.slice(x));break}}if(this._passThroughOptions){d.push(f,...s.slice(x));break}d.push(f)}return{operands:n,unknown:l}}opts(){if(this._storeOptionsAsProperties){const s={},n=this.options.length;for(let l=0;l<n;l++){const d=this.options[l].attributeName();s[d]=d===this._versionOptionName?this._version:this[d]}return s}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((s,n)=>Object.assign(s,n.opts()),{})}error(s,n){this._outputConfiguration.outputError(`${s}
|
|
21
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
22
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
23
|
+
`),this.outputHelp({error:!0}));const l=n||{},d=l.exitCode||1,p=l.code||"commander.error";this._exit(d,p,s)}_parseOptionsEnv(){this.options.forEach(s=>{if(s.envVar&&s.envVar in r.env){const n=s.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(s.required||s.optional?this.emit(`optionEnv:${s.name()}`,r.env[s.envVar]):this.emit(`optionEnv:${s.name()}`))}})}_parseOptionsImplied(){const s=new _(this.options),n=l=>this.getOptionValue(l)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(l));this.options.filter(l=>l.implied!==void 0&&n(l.attributeName())&&s.valueFromOption(this.getOptionValue(l.attributeName()),l)).forEach(l=>{Object.keys(l.implied).filter(d=>!n(d)).forEach(d=>{this.setOptionValueWithSource(d,l.implied[d],"implied")})})}missingArgument(s){const n=`error: missing required argument '${s}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(s){const n=`error: option '${s.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(s){const n=`error: required option '${s.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(s,n){const l=m=>{const y=m.attributeName(),S=this.getOptionValue(y),x=this.options.find(b=>b.negate&&y===b.attributeName()),f=this.options.find(b=>!b.negate&&y===b.attributeName());return x&&(x.presetArg===void 0&&S===!1||x.presetArg!==void 0&&S===x.presetArg)?x:f||m},d=m=>{const y=l(m),S=y.attributeName();return this.getOptionValueSource(S)==="env"?`environment variable '${y.envVar}'`:`option '${y.flags}'`},p=`error: ${d(s)} cannot be used with ${d(n)}`;this.error(p,{code:"commander.conflictingOption"})}unknownOption(s){if(this._allowUnknownOption)return;let n="";if(s.startsWith("--")&&this._showSuggestionAfterError){let d=[],p=this;do{const m=p.createHelp().visibleOptions(p).filter(y=>y.long).map(y=>y.long);d=d.concat(m),p=p.parent}while(p&&!p._enablePositionalOptions);n=j(s,d)}const l=`error: unknown option '${s}'${n}`;this.error(l,{code:"commander.unknownOption"})}_excessArguments(s){if(this._allowExcessArguments)return;const n=this.registeredArguments.length,l=n===1?"":"s",d=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${l} but got ${s.length}.`;this.error(d,{code:"commander.excessArguments"})}unknownCommand(){const s=this.args[0];let n="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(p=>{d.push(p.name()),p.alias()&&d.push(p.alias())}),n=j(s,d)}const l=`error: unknown command '${s}'${n}`;this.error(l,{code:"commander.unknownCommand"})}version(s,n,l){if(s===void 0)return this._version;this._version=s,n=n||"-V, --version",l=l||"output the version number";const d=this.createOption(n,l);return this._versionOptionName=d.attributeName(),this._registerOption(d),this.on("option:"+d.name(),()=>{this._outputConfiguration.writeOut(`${s}
|
|
24
|
+
`),this._exit(0,"commander.version",s)}),this}description(s,n){return s===void 0&&n===void 0?this._description:(this._description=s,n&&(this._argsDescription=n),this)}summary(s){return s===void 0?this._summary:(this._summary=s,this)}alias(s){if(s===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),s===n._name)throw new Error("Command alias can't be the same as its name");const l=this.parent?._findCommand(s);if(l){const d=[l.name()].concat(l.aliases()).join("|");throw new Error(`cannot add alias '${s}' to command '${this.name()}' as already have command '${d}'`)}return n._aliases.push(s),this}aliases(s){return s===void 0?this._aliases:(s.forEach(n=>this.alias(n)),this)}usage(s){if(s===void 0){if(this._usage)return this._usage;const n=this.registeredArguments.map(l=>c(l));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=s,this}name(s){return s===void 0?this._name:(this._name=s,this)}helpGroup(s){return s===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=s,this)}commandsGroup(s){return s===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=s,this)}optionsGroup(s){return s===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=s,this)}_initOptionGroup(s){this._defaultOptionGroup&&!s.helpGroupHeading&&s.helpGroup(this._defaultOptionGroup)}_initCommandGroup(s){this._defaultCommandGroup&&!s.helpGroup()&&s.helpGroup(this._defaultCommandGroup)}nameFromFilename(s){return this._name=o.basename(s,o.extname(s)),this}executableDir(s){return s===void 0?this._executableDir:(this._executableDir=s,this)}helpInformation(s){const n=this.createHelp(),l=this._getOutputContext(s);n.prepareContext({error:l.error,helpWidth:l.helpWidth,outputHasColors:l.hasColors});const d=n.formatHelp(this,n);return l.hasColors?d:this._outputConfiguration.stripColor(d)}_getOutputContext(s){s=s||{};const n=!!s.error;let l,d,p;return n?(l=y=>this._outputConfiguration.writeErr(y),d=this._outputConfiguration.getErrHasColors(),p=this._outputConfiguration.getErrHelpWidth()):(l=y=>this._outputConfiguration.writeOut(y),d=this._outputConfiguration.getOutHasColors(),p=this._outputConfiguration.getOutHelpWidth()),{error:n,write:y=>(d||(y=this._outputConfiguration.stripColor(y)),l(y)),hasColors:d,helpWidth:p}}outputHelp(s){let n;typeof s=="function"&&(n=s,s=void 0);const l=this._getOutputContext(s),d={error:l.error,write:l.write,command:this};this._getCommandAndAncestors().reverse().forEach(m=>m.emit("beforeAllHelp",d)),this.emit("beforeHelp",d);let p=this.helpInformation({error:l.error});if(n&&(p=n(p),typeof p!="string"&&!Buffer.isBuffer(p)))throw new Error("outputHelp callback must return a string or a Buffer");l.write(p),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",d),this._getCommandAndAncestors().forEach(m=>m.emit("afterAllHelp",d))}helpOption(s,n){return typeof s=="boolean"?(s?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(s??"-h, --help",n??"display help for command"),(s||n)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(s){return this._helpOption=s,this._initOptionGroup(s),this}help(s){this.outputHelp(s);let n=Number(r.exitCode??0);n===0&&s&&typeof s!="function"&&s.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(s,n){const l=["beforeAll","before","after","afterAll"];if(!l.includes(s))throw new Error(`Unexpected value for position to addHelpText.
|
|
25
|
+
Expecting one of '${l.join("', '")}'`);const d=`${s}Help`;return this.on(d,p=>{let m;typeof n=="function"?m=n({error:p.error,command:p.command}):m=n,m&&p.write(`${m}
|
|
26
|
+
`)}),this}_outputHelpIfRequested(s){const n=this._getHelpOption();n&&s.find(l=>n.is(l))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function F(Dt){return Dt.map(s=>{if(!s.startsWith("--inspect"))return s;let n,l="127.0.0.1",d="9229",p;return(p=s.match(/^(--inspect(-brk)?)$/))!==null?n=p[1]:(p=s.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=p[1],/^\d+$/.test(p[3])?d=p[3]:l=p[3]):(p=s.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=p[1],l=p[3],d=p[4]),n&&d!=="0"?`${n}=${l}:${parseInt(d)+1}`:s})}function Z(){if(r.env.NO_COLOR||r.env.FORCE_COLOR==="0"||r.env.FORCE_COLOR==="false")return!1;if(r.env.FORCE_COLOR||r.env.CLICOLOR_FORCE!==void 0)return!0}t.Command=q,t.useColor=Z})),Jt=U((t=>{var{Argument:e}=st(),{Command:u}=Mt(),{CommanderError:o,InvalidArgumentError:i}=Q(),{Help:r}=vt(),{Option:a}=Ot();t.program=new u,t.createCommand=c=>new u(c),t.createOption=(c,h)=>new a(c,h),t.createArgument=(c,h)=>new e(c,h),t.Command=u,t.Option=a,t.Argument=e,t.Help=r,t.CommanderError=o,t.InvalidArgumentError=i,t.InvalidOptionArgumentError=i})),zt=Lt(Jt(),1),{program:Oi,createCommand:yi,createArgument:Ci,createOption:Ai,CommanderError:Kt,InvalidArgumentError:_i,InvalidOptionArgumentError:Si,Command:Qt,Argument:bi,Option:k,Help:Ei}=zt.default;function w(t){return`${JSON.stringify(t,null,2)}
|
|
27
|
+
`}var Ct=(function(t){return t.INIT="Init",t.COMPLETED="Completed",t.ARCHIVED="Archived",t.DRAFTING="Drafting",t.EXECUTION_COMPLETED="ExecutionCompleted",t.OPTIMIZING="Optimizing",t.OPENSPECING="Openspecing",t.REVIEWING="Reviewing",t.EXECUTING="Executing",t.ARCHIVING="Archiving",t})({});function At(t){return t.replace(/\s+/g," ").trim()}function Y(t,e){const u=e.map(r=>t.map(a=>At(a.value(r)))),o=t.map((r,a)=>{const c=u.map(h=>h[a].length);return Math.max(r.header.length,...c)}),i=r=>r.map((a,c)=>a.padEnd(o[c])).join(" ").trimEnd();return[i(t.map(r=>r.header)),i(o.map(r=>"-".repeat(r))),...u.map(i)].join(`
|
|
28
|
+
`)}function L(t){const e=t.filter(([,o])=>o!==void 0&&o!==""),u=Math.max(...e.map(([o])=>o.length));return`${e.map(([o,i])=>`${o.padEnd(u)} ${At(i??"")}`).join(`
|
|
29
|
+
`)}
|
|
30
|
+
`}function ht(t){return typeof t=="string"?t.trim():t?.value?.trim()??""}function G(t){return{sessionId:ht(t.sessionId),title:t.title,type:t.type,status:t.status,projectId:ht(t.projectId),proposalName:t.proposalName??void 0,archived:t.status===Ct.ARCHIVED,lastActiveAt:t.lastActiveAt??void 0,enableIndependentWorkspace:t.enableIndependentWorkspace,baseBranch:t.baseBranch??void 0,metadata:t.metadata??void 0,chatExecutorType:t.chatExecutorType??void 0}}function _t(t){return{sessions:t.sessions.map(G)}}function St(t,e){return e.length===0?`No ${t.toLowerCase()} found.
|
|
31
|
+
`:`${t} (${e.length})
|
|
32
|
+
${Y([{header:"Session ID",value:u=>u.sessionId},{header:"Title",value:u=>u.title},{header:"Status",value:u=>u.status},{header:"Project ID",value:u=>u.projectId},{header:"Archived",value:u=>u.archived?"yes":"no"}],e)}
|
|
33
|
+
`}function M(t,e=[]){return L([["sessionId",t.sessionId],["type",t.type],["title",t.title],["status",t.status],["projectId",t.projectId],["proposalName",t.proposalName],["independentWorkspace",String(t.enableIndependentWorkspace)],["baseBranch",t.baseBranch],["chatExecutorType",t.chatExecutorType],["metadata",t.metadata],...e])}function rt(t,e,u,o=[]){return`${t}
|
|
34
|
+
${L([["sessionId",e],["message",u.message],...o])}`}var g={BASE:"",VERSION:"1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};function B(t){const e=t?.trim();return e||void 0}function Yt(t={},e=process.env){return{baseUrl:B(t.baseUrl)??B(e.HAGI_API_BASE_URL)??"http://127.0.0.1:35168",token:B(t.token)??B(e.HAGI_API_TOKEN),lang:B(t.lang)??B(e.HAGI_API_LANG)}}function Xt(t={},e=process.env){const u=Yt(t,e);return g.BASE=u.baseUrl,g.WITH_CREDENTIALS=!1,g.CREDENTIALS="omit",g.TOKEN=u.token,g.HEADERS=u.lang?{"Accept-Language":u.lang}:void 0,u}var it=class extends Error{url;status;statusText;body;request;constructor(t,e,u){super(u),this.name="ApiError",this.url=e.url,this.status=e.status,this.statusText=e.statusText,this.body=e.body,this.request=t}},D={USAGE:2,HTTP_BAD_REQUEST:20,HTTP_UNAUTHORIZED:21,HTTP_FORBIDDEN:23,HTTP_NOT_FOUND:24,HTTP_CONFLICT:29,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},N=class extends Error{constructor(t){super(t),this.name="CliUsageError"}},ot=class extends Error{status;details;constructor(t,e,u){super(e),this.name="CliHttpError",this.status=t,this.details=u}};function Zt(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function z(t,e){const u=Zt(t)?.[e];return typeof u=="string"&&u.trim()?u.trim():void 0}function te(t){return t.includes("fetch failed")||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("Failed to parse URL")}function mt(t){switch(t){case 400:return D.HTTP_BAD_REQUEST;case 401:return D.HTTP_UNAUTHORIZED;case 403:return D.HTTP_FORBIDDEN;case 404:return D.HTTP_NOT_FOUND;case 409:return D.HTTP_CONFLICT;default:return t&&t>=400&&t<500?D.HTTP_CLIENT_ERROR:t&&t>=500?D.HTTP_SERVER_ERROR:D.UNKNOWN}}function ee(t){if(t instanceof N)return{exitCode:D.USAGE,message:t.message};if(t instanceof ot)return{exitCode:mt(t.status),status:t.status,message:t.message,details:t.details};if(t instanceof it){const e=z(t.body,"error")??z(t.body,"message")??t.message;return{exitCode:mt(t.status),status:t.status,message:e,errorCode:z(t.body,"errorCode"),correlationId:z(t.body,"correlationId"),details:t.body}}return t instanceof Error?{exitCode:te(t.message)?D.TRANSPORT:D.UNKNOWN,message:t.message}:{exitCode:D.UNKNOWN,message:String(t)}}function bt(t,e={}){if(e.json)return`${JSON.stringify({error:{message:t.message,status:t.status,exitCode:t.exitCode,errorCode:t.errorCode,correlationId:t.correlationId,details:t.details}},null,2)}
|
|
35
|
+
`;const u=[t.status?`status=${t.status}`:void 0,t.errorCode?`errorCode=${t.errorCode}`:void 0,t.correlationId?`correlationId=${t.correlationId}`:void 0].filter(Boolean),o=u.length>0?` (${u.join(", ")})`:"";return`${t.message}${o}
|
|
36
|
+
`}var ie=class extends Error{constructor(t){super(t),this.name="CancelError"}get isCancelled(){return!0}},se=class{#e;#i;#t;#s;#o;#n;#r;constructor(t){this.#e=!1,this.#i=!1,this.#t=!1,this.#s=[],this.#o=new Promise((e,u)=>{this.#n=e,this.#r=u;const o=a=>{this.#e||this.#i||this.#t||(this.#e=!0,this.#n&&this.#n(a))},i=a=>{this.#e||this.#i||this.#t||(this.#i=!0,this.#r&&this.#r(a))},r=a=>{this.#e||this.#i||this.#t||this.#s.push(a)};return Object.defineProperty(r,"isResolved",{get:()=>this.#e}),Object.defineProperty(r,"isRejected",{get:()=>this.#i}),Object.defineProperty(r,"isCancelled",{get:()=>this.#t}),t(o,i,r)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(t,e){return this.#o.then(t,e)}catch(t){return this.#o.catch(t)}finally(t){return this.#o.finally(t)}cancel(){if(!(this.#e||this.#i||this.#t)){if(this.#t=!0,this.#s.length)try{for(const t of this.#s)t()}catch(t){console.warn("Cancellation threw an error",t);return}this.#s.length=0,this.#r&&this.#r(new ie("Request aborted"))}}get isCancelled(){return this.#t}},nt=t=>t!=null,J=t=>typeof t=="string",tt=t=>J(t)&&t!=="",at=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),Et=t=>t instanceof FormData,re=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},oe=t=>{const e=[],u=(i,r)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(r))}`)},o=(i,r)=>{nt(r)&&(Array.isArray(r)?r.forEach(a=>{o(i,a)}):typeof r=="object"?Object.entries(r).forEach(([a,c])=>{o(`${i}[${a}]`,c)}):u(i,r))};return Object.entries(t).forEach(([i,r])=>{o(i,r)}),e.length>0?`?${e.join("&")}`:""},ne=(t,e)=>{const u=t.ENCODE_PATH||encodeURI,o=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(r,a)=>e.path?.hasOwnProperty(a)?u(String(e.path[a])):r),i=`${t.BASE}${o}`;return e.query?`${i}${oe(e.query)}`:i},ae=t=>{if(t.formData){const e=new FormData,u=(o,i)=>{J(i)||at(i)?e.append(o,i):e.append(o,JSON.stringify(i))};return Object.entries(t.formData).filter(([o,i])=>nt(i)).forEach(([o,i])=>{Array.isArray(i)?i.forEach(r=>u(o,r)):u(o,i)}),e}},K=async(t,e)=>typeof e=="function"?e(t):e,ue=async(t,e)=>{const[u,o,i,r]=await Promise.all([K(e,t.TOKEN),K(e,t.USERNAME),K(e,t.PASSWORD),K(e,t.HEADERS)]),a=Object.entries({Accept:"application/json",...r,...e.headers}).filter(([c,h])=>nt(h)).reduce((c,[h,O])=>({...c,[h]:String(O)}),{});return tt(u)&&(a.Authorization=`Bearer ${u}`),tt(o)&&tt(i)&&(a.Authorization=`Basic ${re(`${o}:${i}`)}`),e.body!==void 0&&(e.mediaType?a["Content-Type"]=e.mediaType:at(e.body)?a["Content-Type"]=e.body.type||"application/octet-stream":J(e.body)?a["Content-Type"]="text/plain":Et(e.body)||(a["Content-Type"]="application/json")),new Headers(a)},ce=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):J(t.body)||at(t.body)||Et(t.body)?t.body:JSON.stringify(t.body)},le=async(t,e,u,o,i,r,a)=>{const c=new AbortController,h={headers:r,body:o??i,method:e.method,signal:c.signal};return t.WITH_CREDENTIALS&&(h.credentials=t.CREDENTIALS),a(()=>c.abort()),await fetch(u,h)},de=(t,e)=>{if(e){const u=t.headers.get(e);if(J(u))return u}},pe=async t=>{if(t.status!==204)try{const e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(u=>e.toLowerCase().startsWith(u))?await t.json():await t.text()}catch(e){console.error(e)}},he=(t,e)=>{const u={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(u)throw new it(t,e,u);if(!e.ok)throw new it(t,e,`Generic Error: status: ${e.status??"unknown"}; status text: ${e.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})()}`)},v=(t,e)=>new se(async(u,o,i)=>{try{const r=ne(t,e),a=ae(e),c=ce(e),h=await ue(t,e);if(!i.isCancelled){const O=await le(t,e,r,c,a,h,i),A=await pe(O),C=de(O,e.responseHeader),_={url:r,ok:O.ok,status:O.status,statusText:O.statusText,body:C??A};he(e,_),u(_.body)}}catch(r){o(r)}}),me=class{static getApiDataAggregation(){return v(g,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},et=class{static postApiProject({requestBody:t}){return v(g,{method:"POST",url:"/api/Project",body:t,mediaType:"application/json"})}static postApiProjectDemo(){return v(g,{method:"POST",url:"/api/Project/demo"})}static putApiProject({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Project/{id}",path:{id:t},body:e,mediaType:"application/json"})}static deleteApiProject({id:t}){return v(g,{method:"DELETE",url:"/api/Project/{id}",path:{id:t}})}static postApiProjectOpenInVscode({id:t,subPath:e}){return v(g,{method:"POST",url:"/api/Project/{id}/open-in-vscode",path:{id:t},query:{subPath:e},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Project not found",500:"Failed to launch VS Code"}})}static getApiProjectMonospecsManagement({id:t}){return v(g,{method:"GET",url:"/api/Project/{id}/monospecs/management",path:{id:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectMonospecsManagement({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Project/{id}/monospecs/management",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiProjectMonospecsInitialize({id:t}){return v(g,{method:"POST",url:"/api/Project/{id}/monospecs/initialize",path:{id:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiProjectDesignMd({id:t,repositoryPath:e}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md",path:{id:t},query:{repositoryPath:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectDesignMd({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Project/{id}/design-md",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static getApiProjectDesignMdSiteIndex({id:t}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md/site-index",path:{id:t},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndexPreview({id:t,slug:e,theme:u="light"}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}/preview",path:{id:t,slug:e},query:{theme:u},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndex1({id:t,slug:e}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}",path:{id:t,slug:e},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectBranchesValidate({id:t,branchName:e,repositoryPath:u}){return v(g,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:t},query:{branchName:e,repositoryPath:u},errors:{400:"Branch name is required",404:"Project not found"}})}static getApiProjectValidatePath({path:t}){return v(g,{method:"GET",url:"/api/Project/validate-path",query:{path:t},errors:{400:"Path parameter is missing or invalid",500:"Internal server error during validation"}})}static postApiProjectScanGitRepos({requestBody:t}){return v(g,{method:"POST",url:"/api/Project/scan-git-repos",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error during scan"}})}static postApiProjectValidateMonospecs({requestBody:t}){return v(g,{method:"POST",url:"/api/Project/validate-monospecs",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error"}})}},H=class{static postApiSessionsAutoTask({requestBody:t}){return v(g,{method:"POST",url:"/api/Sessions/auto-task",body:t,mediaType:"application/json",errors:{400:"Missing required fields or invalid prompt ID",404:"Project not found",500:"Internal server error"}})}static postApiSessionsArchiveChat({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/archive-chat",path:{sessionId:t},errors:{400:"Session is not a chat session",404:"Session not found",500:"Failed to archive chat session"}})}static postApiSessionsChat({requestBody:t}){return v(g,{method:"POST",url:"/api/Sessions/chat",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:t}){return v(g,{method:"POST",url:"/api/Sessions",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:t,activeOnly:e,includeArchived:u,projectId:o,projectIds:i}){return v(g,{method:"GET",url:"/api/Sessions",query:{type:t,activeOnly:e,includeArchived:u,projectId:o,projectIds:i}})}static getApiSessions1({sessionId:t}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}",path:{sessionId:t},errors:{400:"Invalid session ID format",404:"Session not found",500:"Internal server error occurred"}})}static putApiSessions({sessionId:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:t},body:e,mediaType:"application/json"})}static deleteApiSessions({sessionId:t,deleteFiles:e=!1}){return v(g,{method:"DELETE",url:"/api/Sessions/{sessionId}",path:{sessionId:t},query:{deleteFiles:e},errors:{404:"Session not found",500:"Failed to delete session"}})}static getApiSessionsMessages({sessionId:t,page:e=1,pageSize:u=50,historyScope:o,order:i="desc"}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},query:{page:e,pageSize:u,historyScope:o,order:i},errors:{404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsMessages({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},body:e,mediaType:"application/json"})}static postApiSessionsCancel({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/cancel",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to cancel session"}})}static getApiSessionsProcessingStatus({sessionId:t}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}/processing-status",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to get processing status"}})}static deleteApiSessionsQueue({sessionId:t,queueIndex:e}){return v(g,{method:"DELETE",url:"/api/Sessions/{sessionId}/queue/{queueIndex}",path:{sessionId:t,queueIndex:e},errors:{400:"Invalid queue index",404:"Session not found",500:"Failed to cancel message"}})}static postApiSessionsAnnotations({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/annotations",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Invalid request or session is not a proposal session",404:"Session not found",500:"Failed to process annotations"}})}static postApiSessionsOptimizeProposal({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsGenerateProposal({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name not generated",404:"Session not found",500:"Failed to generate proposal"}})}static postApiSessionsArchive({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/archive",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name missing",404:"Session not found",500:"Failed to archive session"}})}static postApiSessionsExecuteProposal({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/execute-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session, not in valid status, or proposal name missing",404:"Session not found",500:"Failed to execute proposal"}})}static postApiSessionsComplete({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/complete",path:{sessionId:t},errors:{400:"Session is not in ExecutionCompleted status",404:"Session not found",500:"Failed to complete session"}})}static postApiSessionsValidateExecute({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-execute",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateStart({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-start",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateArchive({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-archive",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static getApiSessionsOpenspecFile({sessionId:t,relativePath:e}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}/openspec-file",path:{sessionId:t},query:{relativePath:e},errors:{404:"Session not found or file not found",500:"Failed to read file"}})}static postApiSessionsUpdateCessionId({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/update-cession-id",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to update CessionId"}})}static postApiSessionsOpenInVscode({sessionId:t,subPath:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/open-in-vscode",path:{sessionId:t},query:{subPath:e},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Session not found",500:"Failed to launch VS Code"}})}static postApiSessionsCorrectProposalName({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/correct-proposal-name",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Invalid name format or validation failed",404:"Session not found",409:"Name already in use by another session",500:"Internal server error"}})}static deleteApiSessionsWorkspace({sessionId:t}){return v(g,{method:"DELETE",url:"/api/Sessions/{sessionId}/workspace",path:{sessionId:t},errors:{400:"Session does not have an independent workspace",404:"Session not found",500:"Failed to delete workspace"}})}},W=class{static getApiVaults(){return v(g,{method:"GET",url:"/api/vaults"})}static postApiVaults({requestBody:t}){return v(g,{method:"POST",url:"/api/vaults",body:t,mediaType:"application/json",errors:{400:"Bad Request",500:"Internal Server Error"}})}static putApiVaults({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/vaults/{id}",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static deleteApiVaults({id:t,deleteLocalFiles:e=!1}){return v(g,{method:"DELETE",url:"/api/vaults/{id}",path:{id:t},query:{deleteLocalFiles:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFiles({id:t,path:e}){return v(g,{method:"GET",url:"/api/vaults/{id}/files",path:{id:t},query:{path:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFilesContent({id:t,path:e}){return v(g,{method:"GET",url:"/api/vaults/{id}/files/content",path:{id:t},query:{path:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}};function ft(t,e,u){return v(g,{method:"POST",url:`/api/Sessions/{sessionId}/${e}`,path:{sessionId:t},body:u,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}function fe(){return{listSessions:t=>H.getApiSessions(t),getSession:t=>H.getApiSessions1({sessionId:t}),createProposalSession:t=>H.postApiSessions({requestBody:t}),createChatSession:t=>H.postApiSessionsChat({requestBody:t}),createAutoTaskSession:t=>H.postApiSessionsAutoTask({requestBody:t}),updateSession:(t,e)=>H.putApiSessions({sessionId:t,requestBody:e}),deleteSession:(t,e)=>H.deleteApiSessions({sessionId:t,deleteFiles:e}),sendMessage:(t,e)=>H.postApiSessionsMessages({sessionId:t,requestBody:e}),generateProposalName:t=>ft(t,"generate-proposal-name"),optimizeDescription:(t,e)=>ft(t,"optimize-description",e),generateProposal:(t,e)=>H.postApiSessionsGenerateProposal({sessionId:t,requestBody:e}),executeProposal:(t,e)=>H.postApiSessionsExecuteProposal({sessionId:t,requestBody:e}),archiveProposal:(t,e)=>H.postApiSessionsArchive({sessionId:t,requestBody:e}),completeProposal:t=>H.postApiSessionsComplete({sessionId:t}),submitAnnotations:(t,e)=>H.postApiSessionsAnnotations({sessionId:t,requestBody:e}),listProjects:()=>me.getApiDataAggregation(),createProject:t=>et.postApiProject({requestBody:t}),updateProject:(t,e)=>et.putApiProject({id:t,requestBody:e}),deleteProject:t=>et.deleteApiProject({id:t}),listVaults:()=>W.getApiVaults(),createVault:t=>W.postApiVaults({requestBody:t}),updateVault:(t,e)=>W.putApiVaults({id:t,requestBody:e}),deleteVault:(t,e)=>W.deleteApiVaults({id:t,deleteLocalFiles:e}),listVaultFiles:(t,e)=>W.getApiVaultsFiles({id:t,path:e}),previewVaultFile:(t,e)=>W.getApiVaultsFilesContent({id:t,path:e}),archiveChat:t=>H.postApiSessionsArchiveChat({sessionId:t})}}function I(t){const e=t?.trim();return e||void 0}function V(t,e){const u=I(t);if(!u)throw new N(`${e} is required.`);return u}function It(t){const e=t?.map(u=>I(u)).filter(Boolean);return e&&e.length>0?e:void 0}function wt(t=process.env,e={stdout:u=>{process.stdout.write(u)},stderr:u=>{process.stderr.write(u)}}){return{api:fe(),env:t,io:e}}function ge(t){return t.option("--base-url <url>","Backend API base URL. Defaults to HAGI_API_BASE_URL or the local dev URL.").option("--token <token>","Bearer token for backend API calls. Overrides HAGI_API_TOKEN.").option("--lang <lang>","Accept-Language value for backend API calls. Overrides HAGI_API_LANG.")}function P(t){return t.option("--json","Emit deterministic JSON instead of human-readable text.")}function T(t,e){const u=t.optsWithGlobals();return{api:e.api,env:e.env,io:e.io,outputJson:u.json===!0,runtime:Xt({baseUrl:u.baseUrl,token:u.token,lang:u.lang},e.env)}}function ve(t,e){P(t.command("create").description("Create an AutoTask session through the dedicated generated endpoint.")).requiredOption("--title <title>","AutoTask session title.").requiredOption("--project-id <id>","Owning project id.").requiredOption("--prompt-id <id>","Prompt template id.").option("--message <text>","Optional custom message override.").option("--preset-id <id>","Optional preset id.").option("--repository-path <path>","Optional MonoSpecs repository path.").option("--project-ids <ids...>","Optional extra project ids for multi-project flows.").option("--need-push","Request push after commit creation when supported.").option("--target-branch-mode <mode>","Optional target branch mode.").option("--target-branch-name <name>","Optional custom target branch name.").option("--script-key <key>","Optional stable dungeon script key.").option("--hero-id <id>","Optional preferred hero id.").action(async function(o){if(o.targetBranchName&&o.targetBranchMode!=="new-custom")throw new N("--target-branch-name requires --target-branch-mode new-custom.");if(o.targetBranchMode==="new-custom"&&!I(o.targetBranchName))throw new N("--target-branch-name is required when --target-branch-mode is new-custom.");const i=T(this,e),r={title:V(o.title,"--title"),projectId:V(o.projectId,"--project-id"),promptId:V(o.promptId,"--prompt-id"),message:I(o.message),presetId:I(o.presetId),repositoryPath:I(o.repositoryPath),projectIds:It(o.projectIds),needPush:o.needPush?!0:void 0,targetBranchMode:I(o.targetBranchMode),targetBranchName:I(o.targetBranchName),scriptKey:I(o.scriptKey),heroId:I(o.heroId)},a=G(await i.api.createAutoTaskSession(r));if(i.outputJson){i.io.stdout(w({session:a,promptId:r.promptId,requested:r}));return}i.io.stdout(`AutoTask session created
|
|
37
|
+
${M(a,[["promptId",r.promptId],["repositoryPath",r.repositoryPath],["targetBranchMode",r.targetBranchMode],["targetBranchName",r.targetBranchName],["scriptKey",r.scriptKey],["heroId",r.heroId]])}`)})}var X=(function(t){return t.CLAUDE_CODE_CLI="ClaudeCodeCli",t.CODEX_CLI="CodexCli",t.GIT_HUB_COPILOT="GitHubCopilot",t.CODEBUDDY_CLI="CodebuddyCli",t.OPEN_CODE_CLI="OpenCodeCli",t.IFLOW_CLI="IFlowCli",t.HERMES_CLI="HermesCli",t.QODER_CLI="QoderCli",t.KIRO_CLI="KiroCli",t.KIMI_CLI="KimiCli",t.GEMINI_CLI="GeminiCli",t.DEEP_AGENTS_CLI="DeepAgentsCli",t})({}),ut=(function(t){return t.READONLY="Readonly",t.EDIT="Edit",t})({});function Oe(t,e){P(t.command("send").description("Send a follow-up message to an AutoTask session.")).requiredOption("--session-id <id>","AutoTask session id.").requiredOption("--content <text>","Message content.").addOption(new k("--mode <mode>","Message mode override.").choices(Object.values(ut))).addOption(new k("--executor-type <type>","Executor override for this message.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.sendMessage(r,{content:V(o.content,"--content"),mode:o.mode,executorType:o.executorType});if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message,requested:{mode:o.mode,executorType:o.executorType}}));return}i.io.stdout(rt("AutoTask message sent",r,a,[["mode",o.mode],["executorType",o.executorType]]))})}function ye(t,e){const u=t.command("autotask").description("Manage AutoTask sessions.");ve(u,e),Oe(u,e)}function Ce(t,e){P(t.command("archive").description("Archive a chat session through the dedicated chat archive endpoint.")).requiredOption("--session-id <id>","Chat session id to archive.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.archiveChat(r);if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message}));return}i.io.stdout(`Chat archived
|
|
38
|
+
sessionId ${r}
|
|
39
|
+
message ${a.message}
|
|
40
|
+
`)})}function Ae(t,e){P(t.command("create").description("Create a normal chat session.")).requiredOption("--title <title>","Chat session title.").requiredOption("--project-id <id>","Owning project id.").option("--hero-id <id>","Optional bound hero id.").addOption(new k("--executor-type <type>","Optional executor override.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=G(await i.api.createChatSession({title:V(o.title,"--title"),projectId:V(o.projectId,"--project-id"),heroId:I(o.heroId),executorType:o.executorType}));if(i.outputJson){i.io.stdout(w({session:r}));return}i.io.stdout(`Chat session created
|
|
41
|
+
${M(r)}`)})}function _e(t,e){P(t.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.deleteSession(r,!1);if(i.outputJson){i.io.stdout(w({sessionId:r,deleted:!0,message:a.message}));return}i.io.stdout(`Chat deleted
|
|
42
|
+
sessionId ${r}
|
|
43
|
+
message ${a.message}
|
|
44
|
+
`)})}var ct=(function(t){return t.CHAT="Chat",t.PROPOSAL="Proposal",t})({});function Se(t,e){P(t.command("list").description("List normal chat sessions.")).action(async function(o){if(o.projectId&&o.projectIds?.length)throw new N("Use either --project-id or --project-ids, not both.");const i=T(this,e),r=_t(await i.api.listSessions({type:ct.CHAT,projectId:I(o.projectId),projectIds:It(o.projectIds),activeOnly:o.activeOnly?!0:void 0,includeArchived:o.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(St("Chat sessions",r.sessions))}).option("--project-id <id>","Filter chat sessions by a single project id.").option("--project-ids <ids...>","Filter chat sessions by multiple project ids.").option("--active-only","Only return non-archived chat sessions.").option("--include-archived","Include archived chat sessions.")}function be(t,e){P(t.command("send").description("Send a follow-up message to a chat session.")).requiredOption("--session-id <id>","Chat session id.").requiredOption("--content <text>","Message content.").addOption(new k("--mode <mode>","Message mode override.").choices(Object.values(ut))).addOption(new k("--executor-type <type>","Executor override for this message.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.sendMessage(r,{content:V(o.content,"--content"),mode:o.mode,executorType:o.executorType});if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message,requested:{mode:o.mode,executorType:o.executorType}}));return}i.io.stdout(rt("Chat message sent",r,a,[["mode",o.mode],["executorType",o.executorType]]))})}function Ee(t,e){const u=t.command("chat").description("Manage normal chat sessions.");Se(u,e),Ae(u,e),Ce(u,e),_e(u,e),be(u,e)}function R(t){const e=t?.trim();return e||void 0}function lt(t){return{id:R(t.id)??"",name:R(t.name)??"",path:R(t.path)??"",description:R(t.description),isMonoSpecs:t.isMonoSpecs===!0,monoSpecsVersion:R(t.monoSpecsVersion),monoSpecsRepoDirectory:R(t.monoSpecsRepoDirectory),monoSpecsCommitWhenArchive:typeof t.monoSpecsCommitWhenArchive=="boolean"?t.monoSpecsCommitWhenArchive:void 0,hasError:"hasError"in t?t.hasError===!0:!1,error:"error"in t?R(t.error):void 0}}function Pt(t){return{projects:(t??[]).map(lt)}}function Ie(t){return t.length===0?`No projects found.
|
|
45
|
+
`:`Projects (${t.length})
|
|
46
|
+
${Y([{header:"Project ID",value:e=>e.id},{header:"Name",value:e=>e.name},{header:"Path",value:e=>e.path},{header:"MonoSpecs",value:e=>e.isMonoSpecs?"yes":"no"},{header:"Error",value:e=>e.hasError?"yes":"no"}],t)}
|
|
47
|
+
`}function Tt(t,e=[]){return L([["id",t.id],["name",t.name],["path",t.path],["description",t.description],["isMonoSpecs",String(t.isMonoSpecs)],["monoSpecsVersion",t.monoSpecsVersion],["monoSpecsRepoDirectory",t.monoSpecsRepoDirectory],["monoSpecsCommitWhenArchive",typeof t.monoSpecsCommitWhenArchive=="boolean"?String(t.monoSpecsCommitWhenArchive):void 0],["hasError",String(t.hasError)],["error",t.error],...e])}function we(t,e){P(t.command("create").description("Create a project through the generated project client.")).requiredOption("--name <name>","Project display name.").requiredOption("--path <path>","Project root path.").option("--description <text>","Optional project description.").action(async function(o){const i=T(this,e),r=lt(await i.api.createProject({name:V(o.name,"--name"),path:V(o.path,"--path"),description:I(o.description)}));if(i.outputJson){i.io.stdout(w({project:r}));return}i.io.stdout(`Project created
|
|
48
|
+
${Tt(r)}`)})}function Pe(t,e){P(t.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(o){const i=T(this,e),r=o.id.trim();if(await i.api.deleteProject(r),i.outputJson){i.io.stdout(w({projectId:r,deleted:!0}));return}i.io.stdout(`Project deleted
|
|
49
|
+
projectId ${r}
|
|
50
|
+
`)})}function Te(t,e){P(t.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const o=T(this,e),i=Pt((await o.api.listProjects()).projects);if(o.outputJson){o.io.stdout(w(i));return}o.io.stdout(Ie(i.projects))})}function xe(t,e){P(t.command("update").description("Update a project by merging provided fields into the aggregation snapshot.")).requiredOption("--id <id>","Project id to update.").option("--name <name>","Updated project name.").option("--path <path>","Updated project path.").option("--description <text>","Updated project description.").option("--clear-description","Clear the stored description.").action(async function(o){if(!o.name&&!o.path&&!o.description&&!o.clearDescription)throw new N("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(o.description&&o.clearDescription)throw new N("Use either --description or --clear-description, not both.");const i=T(this,e),r=o.id.trim(),a=Pt((await i.api.listProjects()).projects).projects.find(h=>h.id===r);if(!a)throw new ot(404,`Project ${r} was not found in the aggregation snapshot.`);const c=lt(await i.api.updateProject(r,{name:I(o.name)??a.name,path:I(o.path)??a.path,description:o.clearDescription?null:I(o.description)??a.description??null}));if(i.outputJson){i.io.stdout(w({project:c}));return}i.io.stdout(`Project updated
|
|
51
|
+
${Tt(c)}`)})}function je(t,e){const u=t.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");Te(u,e),we(u,e),xe(u,e),Pe(u,e)}async function $e(){const t=[];for await(const e of Gt.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}async function Ve(t){const e=t.trim();if(!e)throw new N("Provide --input <file> or --input - for stdin.");const u=e==="-"?await $e():await(0,Bt.readFile)(e,"utf8");try{return JSON.parse(u)}catch(o){throw new N(`Invalid JSON input from ${e}: ${o instanceof Error?o.message:String(o)}`)}}function De(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw new N("Annotation input must be a JSON object.");const u=e;if(!Array.isArray(u.files))throw new N("Annotation input must include a files array.");const o=typeof u.totalAnnotations=="number"?u.totalAnnotations:u.files.length,i=typeof u.submittedAt=="string"&&u.submittedAt.trim()?u.submittedAt:new Date().toISOString();return{...u,sessionId:t,totalAnnotations:o,submittedAt:i,files:u.files}}function Ne(t,e){P(t.command("annotate").description("Submit proposal annotations from structured JSON input.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=De(r,await Ve(o.input)),c=await i.api.submitAnnotations(r,a);if(i.outputJson){i.io.stdout(w({sessionId:r,message:c.message,annotationCount:c.annotationCount??a.totalAnnotations,fileCount:c.fileCount??a.files.length}));return}i.io.stdout(`Proposal annotations submitted
|
|
52
|
+
sessionId ${r}
|
|
53
|
+
message ${c.message}
|
|
54
|
+
annotationCount ${c.annotationCount??a.totalAnnotations}
|
|
55
|
+
fileCount ${c.fileCount??a.files.length}
|
|
56
|
+
`)})}function He(t,e){P(t.command("archive").description("Archive a proposal session through the explicit archive endpoint.")).requiredOption("--session-id <id>","Proposal session id to archive.").option("--hero-id <id>","Optional hero override for archiving.").action(async function(o){const i=T(this,e),r=G(await i.api.archiveProposal(o.sessionId.trim(),{heroId:I(o.heroId)}));if(i.outputJson){i.io.stdout(w({session:r}));return}i.io.stdout(`Proposal archive started
|
|
57
|
+
${M(r)}`)})}function Fe(t,e){P(t.command("complete").description("Mark a proposal session as completed through the dedicated completion endpoint.")).requiredOption("--session-id <id>","Proposal session id to complete.").action(async function(o){const i=T(this,e),r=G(await i.api.completeProposal(o.sessionId.trim()));if(i.outputJson){i.io.stdout(w({session:r}));return}i.io.stdout(`Proposal completed
|
|
58
|
+
${M(r)}`)})}function qe(t){return G(t)}function ke(t){return _t(t)}function Re(t){return St("Proposal sessions",t)}function Ue(t,e=[]){return M(t,e)}var xt="New Proposal";function Le(t){const e=I(t.title);if(e)return e;if(t.defaultTitle)return xt;throw new N("Provide --title or pass --default-title to use the placeholder proposal title.")}function Ge(t,e){P(t.command("create").description("Create a proposal session only. This command does not trigger later lifecycle APIs.")).requiredOption("--project-id <id>","Project id that owns the new proposal session.").requiredOption("--chief-complaint <text>","Proposal chief complaint to store on the new session.").option("--original-chief-complaint <text>","Optional raw chief complaint text to keep alongside the stitched content.").option("--title <title>","Explicit proposal session title.").option("--default-title",`Mark the title as the placeholder title (${xt}).`).option("--enable-independent-workspace","Request an independent workspace for the proposal session.").option("--base-branch <branch>","Optional base branch for the independent workspace.").action(async function(o){const i=T(this,e),r=Le(o),a=qe(await i.api.createProposalSession({title:r,chiefComplaint:o.chiefComplaint.trim(),originalChiefComplaint:I(o.originalChiefComplaint),type:ct.PROPOSAL,projectId:o.projectId.trim(),enableIndependentWorkspace:o.enableIndependentWorkspace?!0:void 0,baseBranch:I(o.baseBranch),isDefaultTitle:!!o.defaultTitle})),c=`hagi proposal generate-name --session-id ${a.sessionId}`;if(i.outputJson){i.io.stdout(w({session:a,nextCommand:c}));return}i.io.stdout(`Proposal session created
|
|
59
|
+
${Ue(a,[["next",c]])}`)})}function Be(t,e){P(t.command("execute").description("Start proposal execution only. This command maps to the execute-proposal backend action.")).requiredOption("--session-id <id>","Proposal session id to execute.").option("--hero-id <id>","Optional hero override for the execute stage.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=I(o.heroId),c=await i.api.executeProposal(r,{heroId:a});if(i.outputJson){i.io.stdout(w({sessionId:r,message:c.message,requested:{heroId:a}}));return}i.io.stdout(`Proposal execution started
|
|
60
|
+
sessionId ${r}
|
|
61
|
+
message ${c.message}
|
|
62
|
+
`)})}function We(t){if(t.enableExploreMode&&t.disableExploreMode)throw new N("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(t.enableExploreMode)return!0;if(t.disableExploreMode)return!1}function Me(t,e){P(t.command("generate").description("Start proposal generation only. This command does not execute the proposal.")).requiredOption("--session-id <id>","Proposal session id to generate.").option("--enable-explore-mode","Explicitly enable explore mode for proposal generation.").option("--disable-explore-mode","Explicitly disable explore mode for proposal generation.").option("--hero-id <id>","Optional hero override for the generate stage.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=We(o),c=await i.api.generateProposal(r,{enableExploreMode:a,heroId:I(o.heroId)}),h=`hagi proposal execute --session-id ${r}`;if(i.outputJson){i.io.stdout(w({sessionId:r,message:c.message,requested:{enableExploreMode:a,heroId:I(o.heroId)},nextCommand:h}));return}i.io.stdout(`Proposal generation started
|
|
63
|
+
sessionId ${r}
|
|
64
|
+
message ${c.message}
|
|
65
|
+
next Wait for the session to reach Reviewing, then run ${h}
|
|
66
|
+
`)})}function Je(t,e){P(t.command("generate-name").description("Generate a proposal name only. This command maps to the generate-proposal-name backend action.")).requiredOption("--session-id <id>","Proposal session id to update.").action(async function(o){const i=T(this,e),r=await i.api.generateProposalName(o.sessionId.trim()),a=`hagi proposal generate --session-id ${o.sessionId.trim()}`;if(i.outputJson){i.io.stdout(w({sessionId:o.sessionId.trim(),proposalName:r.proposalName,nextCommand:a}));return}i.io.stdout(`Proposal name generated
|
|
67
|
+
sessionId ${o.sessionId.trim()}
|
|
68
|
+
proposalName ${r.proposalName}
|
|
69
|
+
next ${a}
|
|
70
|
+
`)})}function ze(t,e){P(t.command("list").description("List proposal sessions from the backend Sessions API.")).option("--project-id <id>","Filter proposal sessions by a single project id.").option("--project-ids <ids...>","Filter proposal sessions by multiple project ids.").option("--active-only","Only return non-archived proposal sessions.").option("--include-archived","Include archived proposal sessions in the result set.").action(async function(o){if(o.projectId&&o.projectIds?.length)throw new N("Use either --project-id or --project-ids, not both.");const i=T(this,e),r=ke(await i.api.listSessions({type:ct.PROPOSAL,projectId:I(o.projectId),projectIds:o.projectIds?.map(I).filter(Boolean),activeOnly:o.activeOnly?!0:void 0,includeArchived:o.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(Re(r.sessions))})}function Ke(t,e){P(t.command("optimize-description").description("Start asynchronous proposal description optimization only.")).requiredOption("--session-id <id>","Proposal session id to optimize.").requiredOption("--description <text>","Description text to optimize.").option("--optimization-direction <text>","Optional optimization direction for AI guidance.").option("--disable-memory-optimization","Disable long-term memory during optimization.").option("--default-title","Treat the current title as a placeholder title.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.optimizeDescription(r,{description:V(o.description,"--description"),optimizationDirection:I(o.optimizationDirection),enableMemoryOptimization:o.disableMemoryOptimization?!1:void 0,isDefaultTitle:o.defaultTitle?!0:void 0});if(i.outputJson){i.io.stdout(w({sessionId:r,taskId:a.taskId,status:a.status}));return}i.io.stdout(`Proposal description optimization started
|
|
71
|
+
sessionId ${r}
|
|
72
|
+
taskId ${a.taskId??""}
|
|
73
|
+
status ${a.status??""}
|
|
74
|
+
`)})}function Qe(t,e){P(t.command("send").description("Send a follow-up message to a proposal session.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--content <text>","Message content.").addOption(new k("--mode <mode>","Message mode override.").choices(Object.values(ut))).addOption(new k("--executor-type <type>","Executor override for this message.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.sendMessage(r,{content:V(o.content,"--content"),mode:o.mode,executorType:o.executorType});if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message,requested:{mode:o.mode,executorType:o.executorType}}));return}i.io.stdout(rt("Proposal message sent",r,a,[["mode",o.mode],["executorType",o.executorType]]))})}function Ye(t,e){P(t.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new k("--status <status>","Target session status.").choices(Object.values(Ct)).makeOptionMandatory()).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.getSession(r);await i.api.updateSession(r,{title:a.title,description:a.description,status:o.status,metadata:a.metadata});const c=G({...a,status:o.status});if(i.outputJson){i.io.stdout(w({session:c}));return}i.io.stdout(`Proposal status updated
|
|
75
|
+
${M(c)}`)})}function Xe(t,e){const u=t.command("proposal").description("Manage proposal sessions through backend session APIs.");ze(u,e),Ge(u,e),Je(u,e),Ke(u,e),Me(u,e),Ne(u,e),Be(u,e),He(u,e),Ye(u,e),Fe(u,e),Qe(u,e)}function E(t){const e=t?.trim();return e||void 0}function Ze(t){return{severity:E(t.severity)??"",code:E(t.code)??"",message:E(t.message)??"",relativePath:E(t.relativePath)}}function dt(t){return{id:E(t.id)??"",name:E(t.name)??"",type:E(t.type)??"",physicalPath:E(t.physicalPath)??"",gitUrl:E(t.gitUrl),createdAtUtc:E(t.createdAtUtc),updatedAtUtc:E(t.updatedAtUtc),bootstrapDiagnostics:(t.bootstrapDiagnostics??[]).map(Ze)}}function jt(t){return{generatedAtUtc:E(t.generatedAtUtc),vaults:(t.items??[]).map(dt)}}function ti(t){return t.length===0?`No vaults found.
|
|
76
|
+
`:`Vaults (${t.length})
|
|
77
|
+
${Y([{header:"Vault ID",value:e=>e.id},{header:"Type",value:e=>e.type},{header:"Name",value:e=>e.name},{header:"Path",value:e=>e.physicalPath}],t)}
|
|
78
|
+
`}function $t(t,e=[]){return L([["id",t.id],["name",t.name],["type",t.type],["physicalPath",t.physicalPath],["gitUrl",t.gitUrl],["createdAtUtc",t.createdAtUtc],["updatedAtUtc",t.updatedAtUtc],["bootstrapDiagnostics",String(t.bootstrapDiagnostics.length)],...e])}function ei(t){return{relativePath:E(t.relativePath)??"",fileName:E(t.fileName)??"",isDirectory:t.isDirectory===!0,extension:E(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:E(t.lastModifiedUtc),previewSupported:t.previewSupported===!0}}function ii(t){return{vaultId:E(t.id)??"",deleted:t.deleted===!0,deleteLocalFilesRequested:t.deleteLocalFilesRequested===!0,localFilesDeletionStatus:E(t.localFilesDeletionStatus),localFilesDeleted:t.localFilesDeleted===!0}}function si(t){return`Vault deleted
|
|
79
|
+
${L([["vaultId",t.vaultId],["deleted",String(t.deleted)],["deleteLocalFilesRequested",String(t.deleteLocalFilesRequested)],["localFilesDeletionStatus",t.localFilesDeletionStatus],["localFilesDeleted",String(t.localFilesDeleted)]])}`}function ri(t){return{vaultId:E(t.vaultId)??"",vaultName:E(t.vaultName)??"",physicalPath:E(t.physicalPath)??"",status:E(t.status)??"",errorCode:E(t.errorCode),message:E(t.message),isTruncated:t.isTruncated===!0,totalFileCount:typeof t.totalFileCount=="number"?t.totalFileCount:0,items:(t.items??[]).map(ei)}}function oi(t){const e=L([["vaultId",t.vaultId],["vaultName",t.vaultName],["physicalPath",t.physicalPath],["status",t.status],["errorCode",t.errorCode],["message",t.message],["isTruncated",String(t.isTruncated)],["totalFileCount",String(t.totalFileCount)]]);return t.items.length===0?`Vault files
|
|
80
|
+
${e}No files found.
|
|
81
|
+
`:`Vault files
|
|
82
|
+
${e}${Y([{header:"Relative Path",value:u=>u.relativePath},{header:"Directory",value:u=>u.isDirectory?"yes":"no"},{header:"Extension",value:u=>u.extension},{header:"Size",value:u=>String(u.sizeBytes)},{header:"Preview",value:u=>u.previewSupported?"yes":"no"}],t.items)}
|
|
83
|
+
`}function ni(t){return{vaultId:E(t.vaultId)??"",vaultName:E(t.vaultName)??"",physicalPath:E(t.physicalPath)??"",relativePath:E(t.relativePath)??"",fileName:E(t.fileName)??"",extension:E(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:E(t.lastModifiedUtc),status:E(t.status)??"",errorCode:E(t.errorCode),message:E(t.message),previewSupported:t.previewSupported===!0,contentTruncated:t.contentTruncated===!0,content:E(t.content)}}function ai(t){const e=L([["vaultId",t.vaultId],["vaultName",t.vaultName],["physicalPath",t.physicalPath],["relativePath",t.relativePath],["fileName",t.fileName],["extension",t.extension],["sizeBytes",String(t.sizeBytes)],["lastModifiedUtc",t.lastModifiedUtc],["status",t.status],["errorCode",t.errorCode],["message",t.message],["previewSupported",String(t.previewSupported)],["contentTruncated",String(t.contentTruncated)]]);if(!t.content)return`Vault file preview
|
|
84
|
+
${e}`;const u=t.content.endsWith(`
|
|
85
|
+
`)?"":`
|
|
86
|
+
`;return`Vault file preview
|
|
87
|
+
${e}content
|
|
88
|
+
-------
|
|
89
|
+
${t.content}${u}`}function ui(t,e){P(t.command("create").description("Create a vault through the generated vault client.")).requiredOption("--name <name>","Vault display name.").requiredOption("--type <type>","Vault type, such as folder, obsidian, or coderef.").requiredOption("--physical-path <path>","Vault physical path.").option("--git-url <url>","Optional git remote URL for git-backed vaults.").action(async function(o){const i=T(this,e),r=dt(await i.api.createVault({name:V(o.name,"--name"),type:V(o.type,"--type"),physicalPath:V(o.physicalPath,"--physical-path"),gitUrl:I(o.gitUrl)}));if(i.outputJson){i.io.stdout(w({vault:r}));return}i.io.stdout(`Vault created
|
|
90
|
+
${$t(r)}`)})}function ci(t,e){P(t.command("delete").description("Delete a vault by id and optionally request local file cleanup.")).requiredOption("--id <id>","Vault id to delete.").option("--delete-local-files","Request backend deletion of local vault files.").action(async function(o){const i=T(this,e),r=ii(await i.api.deleteVault(V(o.id,"--id"),o.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(si(r))})}function li(t,e){P(t.command("list").description("List files under a registered vault path.")).requiredOption("--id <id>","Vault id to browse.").option("--path <path>","Optional relative path under the vault root.").action(async function(o){const i=T(this,e),r=ri(await i.api.listVaultFiles(V(o.id,"--id"),I(o.path)));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(oi(r))})}function di(t,e){P(t.command("preview").description("Preview supported file content from a registered vault.")).requiredOption("--id <id>","Vault id to browse.").requiredOption("--path <path>","Relative file path to preview.").action(async function(o){const i=T(this,e),r=ni(await i.api.previewVaultFile(V(o.id,"--id"),V(o.path,"--path")));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(ai(r))})}function pi(t,e){P(t.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const o=T(this,e),i=jt(await o.api.listVaults());if(o.outputJson){o.io.stdout(w(i));return}o.io.stdout(ti(i.vaults))})}function hi(t,e){P(t.command("update").description("Update a vault by merging provided fields into the current vault snapshot.")).requiredOption("--id <id>","Vault id to update.").option("--name <name>","Updated vault display name.").option("--type <type>","Updated vault type.").option("--physical-path <path>","Updated vault physical path.").option("--git-url <url>","Updated git remote URL.").action(async function(o){const i=I(o.name),r=I(o.type),a=I(o.physicalPath),c=I(o.gitUrl);if(!i&&!r&&!a&&!c)throw new N("Provide at least one field to update: --name, --type, --physical-path, or --git-url.");const h=T(this,e),O=V(o.id,"--id"),A=jt(await h.api.listVaults()).vaults.find(_=>_.id===O);if(!A)throw new ot(404,`Vault ${O} was not found in the latest vault snapshot.`);const C=dt(await h.api.updateVault(O,{name:i??A.name,type:r??A.type,physicalPath:a??A.physicalPath,gitUrl:c??A.gitUrl??null}));if(h.outputJson){h.io.stdout(w({vault:C}));return}h.io.stdout(`Vault updated
|
|
91
|
+
${$t(C)}`)})}function mi(t,e){const u=t.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");pi(u,e),ui(u,e),hi(u,e),ci(u,e);const o=u.command("files").description("Browse registered vault files and preview supported content.");li(o,e),di(o,e)}function fi(t){return t.includes("--json")}function Vt(t=wt(),e=!1){const u=new Qt;return u.name("hagi").description("HagiCode CLI for project, proposal, vault, chat, and AutoTask management.").showHelpAfterError().exitOverride(),u.configureOutput({writeOut:o=>{t.io.stdout(o)},writeErr:o=>{e||t.io.stderr(o)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),ge(u),je(u,t),Xe(u,t),mi(u,t),Ee(u,t),ye(u,t),u}function gi(t,e,u){return t.exitCode===0||t.code==="commander.helpDisplayed"||t.code==="commander.version"?0:(u&&e.io.stderr(bt({exitCode:D.USAGE,message:t.message},{json:!0})),D.USAGE)}async function vi(t=process.argv,e=wt()){const u=fi(t),o=Vt(e,u);try{return await o.parseAsync([...t]),0}catch(i){if(i instanceof Kt)return gi(i,e,u);const r=ee(i);return e.io.stderr(bt(r,{json:u})),r.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return D}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return Vt}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return vi}});
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./chunks/main-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./chunks/main-CILDKeJ3.js");s.runCli().then(e=>{e!==0&&(process.exitCode=e)}).catch(e=>{const n=e instanceof Error?e.stack??e.message:String(e);process.stderr.write(`${n}
|
|
3
3
|
`),process.exitCode=s.EXIT_CODES.UNKNOWN});
|
package/dist/main.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/main-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/main-CILDKeJ3.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hagicode/cli",
|
|
3
|
-
"version": "0.1.0-dev.
|
|
4
|
-
"description": "HagiCode CLI for project, proposal, chat, and AutoTask management.",
|
|
3
|
+
"version": "0.1.0-dev.7.1.8b40188",
|
|
4
|
+
"description": "HagiCode CLI for project, proposal, vault, chat, and AutoTask management.",
|
|
5
5
|
"homepage": "https://github.com/HagiCode-org/cli#readme",
|
|
6
6
|
"bugs": {
|
|
7
7
|
"url": "https://github.com/HagiCode-org/cli/issues"
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
var xe=Object.create,le=Object.defineProperty,je=Object.getOwnPropertyDescriptor,$e=Object.getOwnPropertyNames,He=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,F=(e,o)=>()=>(o||e((o={exports:{}}).exports,o),o.exports),Ne=(e,o,c,a)=>{if(o&&typeof o=="object"||typeof o=="function")for(var i=$e(o),s=0,n=i.length,u;s<n;s++)u=i[s],!De.call(e,u)&&u!==c&&le(e,u,{get:(h=>o[h]).bind(null,u),enumerable:!(a=je(o,u))||a.enumerable});return e},ke=(e,o,c)=>(c=e!=null?xe(He(e)):{},Ne(o||!e||!e.__esModule?le(c,"default",{value:e,enumerable:!0}):c,e));let Ve=require("node:process"),Re=require("node:fs/promises");var J=F((e=>{var o=class extends Error{constructor(a,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=a,this.nestedError=void 0}},c=class extends o{constructor(a){super(1,"commander.invalidArgument",a),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=o,e.InvalidArgumentError=c})),Z=F((e=>{var{InvalidArgumentError:o}=J(),c=class{constructor(i,s){switch(this.description=s||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(i,s){return s===this.defaultValue||!Array.isArray(s)?[i]:(s.push(i),s)}default(i,s){return this.defaultValue=i,this.defaultValueDescription=s,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(s,n)=>{if(!this.argChoices.includes(s))throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(s,n):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function a(i){const s=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+s+">":"["+s+"]"}e.Argument=c,e.humanReadableArgName=a})),de=F((e=>{var{humanReadableArgName:o}=Z(),c=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(i){this.helpWidth=this.helpWidth??i.helpWidth??80}visibleCommands(i){const s=i.commands.filter(u=>!u._hidden),n=i._getHelpCommand();return n&&!n._hidden&&s.push(n),this.sortSubcommands&&s.sort((u,h)=>u.name().localeCompare(h.name())),s}compareOptions(i,s){const n=u=>u.short?u.short.replace(/^-/,""):u.long.replace(/^--/,"");return n(i).localeCompare(n(s))}visibleOptions(i){const s=i.options.filter(u=>!u.hidden),n=i._getHelpOption();if(n&&!n.hidden){const u=n.short&&i._findOption(n.short),h=n.long&&i._findOption(n.long);!u&&!h?s.push(n):n.long&&!h?s.push(i.createOption(n.long,n.description)):n.short&&!u&&s.push(i.createOption(n.short,n.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const s=[];for(let n=i.parent;n;n=n.parent){const u=n.options.filter(h=>!h.hidden);s.push(...u)}return this.sortOptions&&s.sort(this.compareOptions),s}visibleArguments(i){return i._argsDescription&&i.registeredArguments.forEach(s=>{s.description=s.description||i._argsDescription[s.name()]||""}),i.registeredArguments.find(s=>s.description)?i.registeredArguments:[]}subcommandTerm(i){const s=i.registeredArguments.map(n=>o(n)).join(" ");return i._name+(i._aliases[0]?"|"+i._aliases[0]:"")+(i.options.length?" [options]":"")+(s?" "+s:"")}optionTerm(i){return i.flags}argumentTerm(i){return i.name()}longestSubcommandTermLength(i,s){return s.visibleCommands(i).reduce((n,u)=>Math.max(n,this.displayWidth(s.styleSubcommandTerm(s.subcommandTerm(u)))),0)}longestOptionTermLength(i,s){return s.visibleOptions(i).reduce((n,u)=>Math.max(n,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestGlobalOptionTermLength(i,s){return s.visibleGlobalOptions(i).reduce((n,u)=>Math.max(n,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestArgumentTermLength(i,s){return s.visibleArguments(i).reduce((n,u)=>Math.max(n,this.displayWidth(s.styleArgumentTerm(s.argumentTerm(u)))),0)}commandUsage(i){let s=i._name;i._aliases[0]&&(s=s+"|"+i._aliases[0]);let n="";for(let u=i.parent;u;u=u.parent)n=u.name()+" "+n;return n+s+" "+i.usage()}commandDescription(i){return i.description()}subcommandDescription(i){return i.summary()||i.description()}optionDescription(i){const s=[];if(i.argChoices&&s.push(`choices: ${i.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),i.defaultValue!==void 0&&(i.required||i.optional||i.isBoolean()&&typeof i.defaultValue=="boolean")&&s.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),i.presetArg!==void 0&&i.optional&&s.push(`preset: ${JSON.stringify(i.presetArg)}`),i.envVar!==void 0&&s.push(`env: ${i.envVar}`),s.length>0){const n=`(${s.join(", ")})`;return i.description?`${i.description} ${n}`:n}return i.description}argumentDescription(i){const s=[];if(i.argChoices&&s.push(`choices: ${i.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),i.defaultValue!==void 0&&s.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),s.length>0){const n=`(${s.join(", ")})`;return i.description?`${i.description} ${n}`:n}return i.description}formatItemList(i,s,n){return s.length===0?[]:[n.styleTitle(i),...s,""]}groupItems(i,s,n){const u=new Map;return i.forEach(h=>{const O=n(h);u.has(O)||u.set(O,[])}),s.forEach(h=>{const O=n(h);u.has(O)||u.set(O,[]),u.get(O).push(h)}),u}formatHelp(i,s){const n=s.padWidth(i,s),u=s.helpWidth??80;function h(S,w){return s.formatItem(S,n,w,s)}let O=[`${s.styleTitle("Usage:")} ${s.styleUsage(s.commandUsage(i))}`,""];const b=s.commandDescription(i);b.length>0&&(O=O.concat([s.boxWrap(s.styleCommandDescription(b),u),""]));const y=s.visibleArguments(i).map(S=>h(s.styleArgumentTerm(s.argumentTerm(S)),s.styleArgumentDescription(s.argumentDescription(S))));if(O=O.concat(this.formatItemList("Arguments:",y,s)),this.groupItems(i.options,s.visibleOptions(i),S=>S.helpGroupHeading??"Options:").forEach((S,w)=>{const V=S.map(N=>h(s.styleOptionTerm(s.optionTerm(N)),s.styleOptionDescription(s.optionDescription(N))));O=O.concat(this.formatItemList(w,V,s))}),s.showGlobalOptions){const S=s.visibleGlobalOptions(i).map(w=>h(s.styleOptionTerm(s.optionTerm(w)),s.styleOptionDescription(s.optionDescription(w))));O=O.concat(this.formatItemList("Global Options:",S,s))}return this.groupItems(i.commands,s.visibleCommands(i),S=>S.helpGroup()||"Commands:").forEach((S,w)=>{const V=S.map(N=>h(s.styleSubcommandTerm(s.subcommandTerm(N)),s.styleSubcommandDescription(s.subcommandDescription(N))));O=O.concat(this.formatItemList(w,V,s))}),O.join(`
|
|
2
|
-
`)}displayWidth(i){return a(i).length}styleTitle(i){return i}styleUsage(i){return i.split(" ").map(s=>s==="[options]"?this.styleOptionText(s):s==="[command]"?this.styleSubcommandText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleCommandText(s)).join(" ")}styleCommandDescription(i){return this.styleDescriptionText(i)}styleOptionDescription(i){return this.styleDescriptionText(i)}styleSubcommandDescription(i){return this.styleDescriptionText(i)}styleArgumentDescription(i){return this.styleDescriptionText(i)}styleDescriptionText(i){return i}styleOptionTerm(i){return this.styleOptionText(i)}styleSubcommandTerm(i){return i.split(" ").map(s=>s==="[options]"?this.styleOptionText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleSubcommandText(s)).join(" ")}styleArgumentTerm(i){return this.styleArgumentText(i)}styleOptionText(i){return i}styleArgumentText(i){return i}styleSubcommandText(i){return i}styleCommandText(i){return i}padWidth(i,s){return Math.max(s.longestOptionTermLength(i,s),s.longestGlobalOptionTermLength(i,s),s.longestSubcommandTermLength(i,s),s.longestArgumentTermLength(i,s))}preformatted(i){return/\n[^\S\r\n]/.test(i)}formatItem(i,s,n,u){const O=" ".repeat(2);if(!n)return O+i;const b=i.padEnd(s+i.length-u.displayWidth(i)),y=2,S=(this.helpWidth??80)-s-y-2;let w;return S<this.minWidthToWrap||u.preformatted(n)?w=n:w=u.boxWrap(n,S).replace(/\n/g,`
|
|
3
|
-
`+" ".repeat(s+y)),O+b+" ".repeat(y)+w.replace(/\n/g,`
|
|
4
|
-
${O}`)}boxWrap(i,s){if(s<this.minWidthToWrap)return i;const n=i.split(/\r\n|\n/),u=/[\s]*[^\s]+/g,h=[];return n.forEach(O=>{const b=O.match(u);if(b===null){h.push("");return}let y=[b.shift()],S=this.displayWidth(y[0]);b.forEach(w=>{const V=this.displayWidth(w);if(S+V<=s){y.push(w),S+=V;return}h.push(y.join(""));const N=w.trimStart();y=[N],S=this.displayWidth(N)}),h.push(y.join(""))}),h.join(`
|
|
5
|
-
`)}};function a(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}e.Help=c,e.stripColor=a})),pe=F((e=>{var{InvalidArgumentError:o}=J(),c=class{constructor(n,u){this.flags=n,this.description=u||"",this.required=n.includes("<"),this.optional=n.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(n),this.mandatory=!1;const h=s(n);this.short=h.shortFlag,this.long=h.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,this.helpGroupHeading=void 0}default(n,u){return this.defaultValue=n,this.defaultValueDescription=u,this}preset(n){return this.presetArg=n,this}conflicts(n){return this.conflictsWith=this.conflictsWith.concat(n),this}implies(n){let u=n;return typeof n=="string"&&(u={[n]:!0}),this.implied=Object.assign(this.implied||{},u),this}env(n){return this.envVar=n,this}argParser(n){return this.parseArg=n,this}makeOptionMandatory(n=!0){return this.mandatory=!!n,this}hideHelp(n=!0){return this.hidden=!!n,this}_collectValue(n,u){return u===this.defaultValue||!Array.isArray(u)?[n]:(u.push(n),u)}choices(n){return this.argChoices=n.slice(),this.parseArg=(u,h)=>{if(!this.argChoices.includes(u))throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(u,h):u},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?i(this.name().replace(/^no-/,"")):i(this.name())}helpGroup(n){return this.helpGroupHeading=n,this}is(n){return this.short===n||this.long===n}isBoolean(){return!this.required&&!this.optional&&!this.negate}},a=class{constructor(n){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,n.forEach(u=>{u.negate?this.negativeOptions.set(u.attributeName(),u):this.positiveOptions.set(u.attributeName(),u)}),this.negativeOptions.forEach((u,h)=>{this.positiveOptions.has(h)&&this.dualOptions.add(h)})}valueFromOption(n,u){const h=u.attributeName();if(!this.dualOptions.has(h))return!0;const O=this.negativeOptions.get(h).presetArg,b=O!==void 0?O:!1;return u.negate===(b===n)}};function i(n){return n.split("-").reduce((u,h)=>u+h[0].toUpperCase()+h.slice(1))}function s(n){let u,h;const O=/^-[^-]$/,b=/^--[^-]/,y=n.split(/[ |,]+/).concat("guard");if(O.test(y[0])&&(u=y.shift()),b.test(y[0])&&(h=y.shift()),!u&&O.test(y[0])&&(u=y.shift()),!u&&b.test(y[0])&&(u=h,h=y.shift()),y[0].startsWith("-")){const S=y[0],w=`option creation failed due to '${S}' in option flags '${n}'`;throw/^-[^-][^-]/.test(S)?new Error(`${w}
|
|
6
|
-
- a short flag is a single dash and a single character
|
|
7
|
-
- either use a single dash and a single character (for a short flag)
|
|
8
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):O.test(S)?new Error(`${w}
|
|
9
|
-
- too many short flags`):b.test(S)?new Error(`${w}
|
|
10
|
-
- too many long flags`):new Error(`${w}
|
|
11
|
-
- unrecognised flag format`)}if(u===void 0&&h===void 0)throw new Error(`option creation failed due to no flags found in '${n}'.`);return{shortFlag:u,longFlag:h}}e.Option=c,e.DualOptions=a})),qe=F((e=>{var o=3;function c(i,s){if(Math.abs(i.length-s.length)>o)return Math.max(i.length,s.length);const n=[];for(let u=0;u<=i.length;u++)n[u]=[u];for(let u=0;u<=s.length;u++)n[0][u]=u;for(let u=1;u<=s.length;u++)for(let h=1;h<=i.length;h++){let O=1;i[h-1]===s[u-1]?O=0:O=1,n[h][u]=Math.min(n[h-1][u]+1,n[h][u-1]+1,n[h-1][u-1]+O),h>1&&u>1&&i[h-1]===s[u-2]&&i[h-2]===s[u-1]&&(n[h][u]=Math.min(n[h][u],n[h-2][u-2]+1))}return n[i.length][s.length]}function a(i,s){if(!s||s.length===0)return"";s=Array.from(new Set(s));const n=i.startsWith("--");n&&(i=i.slice(2),s=s.map(b=>b.slice(2)));let u=[],h=o;const O=.4;return s.forEach(b=>{if(b.length<=1)return;const y=c(i,b),S=Math.max(i.length,b.length);(S-y)/S>O&&(y<h?(h=y,u=[b]):y===h&&u.push(b))}),u.sort((b,y)=>b.localeCompare(y)),n&&(u=u.map(b=>`--${b}`)),u.length>1?`
|
|
12
|
-
(Did you mean one of ${u.join(", ")}?)`:u.length===1?`
|
|
13
|
-
(Did you mean ${u[0]}?)`:""}e.suggestSimilar=a})),Fe=F((e=>{var o=require("node:events").EventEmitter,c=require("node:child_process"),a=require("node:path"),i=require("node:fs"),s=require("node:process"),{Argument:n,humanReadableArgName:u}=Z(),{CommanderError:h}=J(),{Help:O,stripColor:b}=de(),{Option:y,DualOptions:S}=pe(),{suggestSimilar:w}=qe(),V=class he extends o{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",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._savedState=null,this._outputConfiguration={writeOut:r=>s.stdout.write(r),writeErr:r=>s.stderr.write(r),outputError:(r,l)=>l(r),getOutHelpWidth:()=>s.stdout.isTTY?s.stdout.columns:void 0,getErrHelpWidth:()=>s.stderr.isTTY?s.stderr.columns:void 0,getOutHasColors:()=>K()??(s.stdout.isTTY&&s.stdout.hasColors?.()),getErrHasColors:()=>K()??(s.stderr.isTTY&&s.stderr.hasColors?.()),stripColor:r=>b(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){const t=[];for(let r=this;r;r=r.parent)t.push(r);return t}command(t,r,l){let d=r,p=l;typeof d=="object"&&d!==null&&(p=d,d=null),p=p||{};const[,m,v]=t.match(/([^ ]+) *(.*)/),C=this.createCommand(m);return d&&(C.description(d),C._executableHandler=!0),p.isDefault&&(this._defaultCommandName=C._name),C._hidden=!!(p.noHelp||p.hidden),C._executableFile=p.executableFile||null,v&&C.arguments(v),this._registerCommand(C),C.parent=this,C.copyInheritedSettings(this),d?this:C}createCommand(t){return new he(t)}createHelp(){return Object.assign(new O,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...t},this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,r){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
|
-
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=t._name),(r.noHelp||r.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,r){return new n(t,r)}argument(t,r,l,d){const p=this.createArgument(t,r);return typeof l=="function"?p.default(d).argParser(l):p.default(l),this.addArgument(p),this}arguments(t){return t.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(t){const r=this.registeredArguments.slice(-1)[0];if(r?.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,r){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,l,d]=(t??"help [command]").match(/([^ ]+) *(.*)/),p=r??"display help for command",m=this.createCommand(l);return m.helpOption(!1),d&&m.arguments(d),p&&m.description(p),this._addImplicitHelpCommand=!0,this._helpCommand=m,(t||r)&&this._initCommandGroup(m),this}addHelpCommand(t,r){return typeof t!="object"?(this.helpCommand(t,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,r){const l=["preSubcommand","preAction","postAction"];if(!l.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
15
|
-
Expecting one of '${l.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(r):this._lifeCycleHooks[t]=[r],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(t,r,l){this._exitCallback&&this._exitCallback(new h(t,r,l)),s.exit(t)}action(t){const r=l=>{const d=this.registeredArguments.length,p=l.slice(0,d);return this._storeOptionsAsProperties?p[d]=this:p[d]=this.opts(),p.push(this),t.apply(this,p)};return this._actionHandler=r,this}createOption(t,r){return new y(t,r)}_callParseArg(t,r,l,d){try{return t.parseArg(r,l)}catch(p){if(p.code==="commander.invalidArgument"){const m=`${d} ${p.message}`;this.error(m,{exitCode:p.exitCode,code:p.code})}throw p}}_registerOption(t){const r=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(r){const l=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${l}'
|
|
16
|
-
- already used by option '${r.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){const r=d=>[d.name()].concat(d.aliases()),l=r(t).find(d=>this._findCommand(d));if(l){const d=r(this._findCommand(l)).join("|"),p=r(t).join("|");throw new Error(`cannot add command '${p}' as already have command '${d}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);const r=t.name(),l=t.attributeName();if(t.negate){const p=t.long.replace(/^--no-/,"--");this._findOption(p)||this.setOptionValueWithSource(l,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(l,t.defaultValue,"default");const d=(p,m,v)=>{p==null&&t.presetArg!==void 0&&(p=t.presetArg);const C=this.getOptionValue(l);p!==null&&t.parseArg?p=this._callParseArg(t,p,C,m):p!==null&&t.variadic&&(p=t._collectValue(p,C)),p==null&&(t.negate?p=!1:t.isBoolean()||t.optional?p=!0:p=""),this.setOptionValueWithSource(l,p,v)};return this.on("option:"+r,p=>{d(p,`error: option '${t.flags}' argument '${p}' is invalid.`,"cli")}),t.envVar&&this.on("optionEnv:"+r,p=>{d(p,`error: option '${t.flags}' value '${p}' from env '${t.envVar}' is invalid.`,"env")}),this}_optionEx(t,r,l,d,p){if(typeof r=="object"&&r instanceof y)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const m=this.createOption(r,l);if(m.makeOptionMandatory(!!t.mandatory),typeof d=="function")m.default(p).argParser(d);else if(d instanceof RegExp){const v=d;d=(C,I)=>{const f=v.exec(C);return f?f[0]:I},m.default(p).argParser(d)}else m.default(d);return this.addOption(m)}option(t,r,l,d){return this._optionEx({},t,r,l,d)}requiredOption(t,r,l,d){return this._optionEx({mandatory:!0},t,r,l,d)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,r){return this.setOptionValueWithSource(t,r,void 0)}setOptionValueWithSource(t,r,l){return this._storeOptionsAsProperties?this[t]=r:this._optionValues[t]=r,this._optionValueSources[t]=l,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let r;return this._getCommandAndAncestors().forEach(l=>{l.getOptionValueSource(t)!==void 0&&(r=l.getOptionValueSource(t))}),r}_prepareUserArgs(t,r){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},t===void 0&&r.from===void 0){s.versions?.electron&&(r.from="electron");const d=s.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(r.from="eval")}t===void 0&&(t=s.argv),this.rawArgs=t.slice();let l;switch(r.from){case void 0:case"node":this._scriptPath=t[1],l=t.slice(2);break;case"electron":s.defaultApp?(this._scriptPath=t[1],l=t.slice(2)):l=t.slice(1);break;case"user":l=t.slice(0);break;case"eval":l=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",l}parse(t,r){this._prepareForParse();const l=this._prepareUserArgs(t,r);return this._parseCommand([],l),this}async parseAsync(t,r){this._prepareForParse();const l=this._prepareUserArgs(t,r);return await this._parseCommand([],l),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
17
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,r,l){if(i.existsSync(t))return;const d=`'${t}' does not exist
|
|
18
|
-
- if '${l}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
19
|
-
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
20
|
-
- ${r?`searched for local subcommand relative to directory '${r}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;throw new Error(d)}_executeSubCommand(t,r){r=r.slice();let l=!1;const d=[".js",".ts",".tsx",".mjs",".cjs"];function p(f,A){const j=a.resolve(f,A);if(i.existsSync(j))return j;if(d.includes(a.extname(A)))return;const ae=d.find(Pe=>i.existsSync(`${j}${Pe}`));if(ae)return`${j}${ae}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let m=t._executableFile||`${this._name}-${t._name}`,v=this._executableDir||"";if(this._scriptPath){let f;try{f=i.realpathSync(this._scriptPath)}catch{f=this._scriptPath}v=a.resolve(a.dirname(f),v)}if(v){let f=p(v,m);if(!f&&!t._executableFile&&this._scriptPath){const A=a.basename(this._scriptPath,a.extname(this._scriptPath));A!==this._name&&(f=p(v,`${A}-${t._name}`))}m=f||m}l=d.includes(a.extname(m));let C;s.platform!=="win32"?l?(r.unshift(m),r=N(s.execArgv).concat(r),C=c.spawn(s.argv[0],r,{stdio:"inherit"})):C=c.spawn(m,r,{stdio:"inherit"}):(this._checkForMissingExecutable(m,v,t._name),r.unshift(m),r=N(s.execArgv).concat(r),C=c.spawn(s.execPath,r,{stdio:"inherit"})),C.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{s.on(f,()=>{C.killed===!1&&C.exitCode===null&&C.kill(f)})});const I=this._exitCallback;C.on("close",f=>{f=f??1,I?I(new h(f,"commander.executeSubCommandAsync","(close)")):s.exit(f)}),C.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(m,v,t._name);else if(f.code==="EACCES")throw new Error(`'${m}' not executable`);if(!I)s.exit(1);else{const A=new h(1,"commander.executeSubCommandAsync","(error)");A.nestedError=f,I(A)}}),this.runningCommand=C}_dispatchSubcommand(t,r,l){const d=this._findCommand(t);d||this.help({error:!0}),d._prepareForParse();let p;return p=this._chainOrCallSubCommandHook(p,d,"preSubcommand"),p=this._chainOrCall(p,()=>{if(d._executableHandler)this._executeSubCommand(d,r.concat(l));else return d._parseCommand(r,l)}),p}_dispatchHelpCommand(t){t||this.help();const r=this._findCommand(t);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,r)=>{t.required&&this.args[r]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const t=(l,d,p)=>{let m=d;if(d!==null&&l.parseArg){const v=`error: command-argument value '${d}' is invalid for argument '${l.name()}'.`;m=this._callParseArg(l,d,p,v)}return m};this._checkNumberOfArguments();const r=[];this.registeredArguments.forEach((l,d)=>{let p=l.defaultValue;l.variadic?d<this.args.length?(p=this.args.slice(d),l.parseArg&&(p=p.reduce((m,v)=>t(l,v,m),l.defaultValue))):p===void 0&&(p=[]):d<this.args.length&&(p=this.args[d],l.parseArg&&(p=t(l,p,l.defaultValue))),r[d]=p}),this.processedArgs=r}_chainOrCall(t,r){return t?.then&&typeof t.then=="function"?t.then(()=>r()):r()}_chainOrCallHooks(t,r){let l=t;const d=[];return this._getCommandAndAncestors().reverse().filter(p=>p._lifeCycleHooks[r]!==void 0).forEach(p=>{p._lifeCycleHooks[r].forEach(m=>{d.push({hookedCommand:p,callback:m})})}),r==="postAction"&&d.reverse(),d.forEach(p=>{l=this._chainOrCall(l,()=>p.callback(p.hookedCommand,this))}),l}_chainOrCallSubCommandHook(t,r,l){let d=t;return this._lifeCycleHooks[l]!==void 0&&this._lifeCycleHooks[l].forEach(p=>{d=this._chainOrCall(d,()=>p(this,r))}),d}_parseCommand(t,r){const l=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(l.operands),r=l.unknown,this.args=t.concat(r),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),r);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,t,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(l.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const d=()=>{l.unknown.length>0&&this.unknownOption(l.unknown[0])},p=`command:${this.name()}`;if(this._actionHandler){d(),this._processArguments();let m;return m=this._chainOrCallHooks(m,"preAction"),m=this._chainOrCall(m,()=>this._actionHandler(this.processedArgs)),this.parent&&(m=this._chainOrCall(m,()=>{this.parent.emit(p,t,r)})),m=this._chainOrCallHooks(m,"postAction"),m}if(this.parent?.listenerCount(p))d(),this._processArguments(),this.parent.emit(p,t,r);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,r);this.listenerCount("command:*")?this.emit("command:*",t,r):this.commands.length?this.unknownCommand():(d(),this._processArguments())}else this.commands.length?(d(),this.help({error:!0})):(d(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(r=>r._name===t||r._aliases.includes(t))}_findOption(t){return this.options.find(r=>r.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(r=>{r.mandatory&&t.getOptionValue(r.attributeName())===void 0&&t.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){const t=this.options.filter(r=>{const l=r.attributeName();return this.getOptionValue(l)===void 0?!1:this.getOptionValueSource(l)!=="default"});t.filter(r=>r.conflictsWith.length>0).forEach(r=>{const l=t.find(d=>r.conflictsWith.includes(d.attributeName()));l&&this._conflictingOption(r,l)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){const r=[],l=[];let d=r;function p(f){return f.length>1&&f[0]==="-"}const m=f=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(f)?!this._getCommandAndAncestors().some(A=>A.options.map(j=>j.short).some(j=>/^-\d$/.test(j))):!1;let v=null,C=null,I=0;for(;I<t.length||C;){const f=C??t[I++];if(C=null,f==="--"){d===l&&d.push(f),d.push(...t.slice(I));break}if(v&&(!p(f)||m(f))){this.emit(`option:${v.name()}`,f);continue}if(v=null,p(f)){const A=this._findOption(f);if(A){if(A.required){const j=t[I++];j===void 0&&this.optionMissingArgument(A),this.emit(`option:${A.name()}`,j)}else if(A.optional){let j=null;I<t.length&&(!p(t[I])||m(t[I]))&&(j=t[I++]),this.emit(`option:${A.name()}`,j)}else this.emit(`option:${A.name()}`);v=A.variadic?A:null;continue}}if(f.length>2&&f[0]==="-"&&f[1]!=="-"){const A=this._findOption(`-${f[1]}`);if(A){A.required||A.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${A.name()}`,f.slice(2)):(this.emit(`option:${A.name()}`),C=`-${f.slice(2)}`);continue}}if(/^--[^=]+=/.test(f)){const A=f.indexOf("="),j=this._findOption(f.slice(0,A));if(j&&(j.required||j.optional)){this.emit(`option:${j.name()}`,f.slice(A+1));continue}}if(d===r&&p(f)&&!(this.commands.length===0&&m(f))&&(d=l),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&l.length===0){if(this._findCommand(f)){r.push(f),l.push(...t.slice(I));break}else if(this._getHelpCommand()&&f===this._getHelpCommand().name()){r.push(f,...t.slice(I));break}else if(this._defaultCommandName){l.push(f,...t.slice(I));break}}if(this._passThroughOptions){d.push(f,...t.slice(I));break}d.push(f)}return{operands:r,unknown:l}}opts(){if(this._storeOptionsAsProperties){const t={},r=this.options.length;for(let l=0;l<r;l++){const d=this.options[l].attributeName();t[d]=d===this._versionOptionName?this._version:this[d]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,r)=>Object.assign(t,r.opts()),{})}error(t,r){this._outputConfiguration.outputError(`${t}
|
|
21
|
-
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
22
|
-
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
23
|
-
`),this.outputHelp({error:!0}));const l=r||{},d=l.exitCode||1,p=l.code||"commander.error";this._exit(d,p,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in s.env){const r=t.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,s.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){const t=new S(this.options),r=l=>this.getOptionValue(l)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(l));this.options.filter(l=>l.implied!==void 0&&r(l.attributeName())&&t.valueFromOption(this.getOptionValue(l.attributeName()),l)).forEach(l=>{Object.keys(l.implied).filter(d=>!r(d)).forEach(d=>{this.setOptionValueWithSource(d,l.implied[d],"implied")})})}missingArgument(t){const r=`error: missing required argument '${t}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(t){const r=`error: option '${t.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const r=`error: required option '${t.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,r){const l=m=>{const v=m.attributeName(),C=this.getOptionValue(v),I=this.options.find(A=>A.negate&&v===A.attributeName()),f=this.options.find(A=>!A.negate&&v===A.attributeName());return I&&(I.presetArg===void 0&&C===!1||I.presetArg!==void 0&&C===I.presetArg)?I:f||m},d=m=>{const v=l(m),C=v.attributeName();return this.getOptionValueSource(C)==="env"?`environment variable '${v.envVar}'`:`option '${v.flags}'`},p=`error: ${d(t)} cannot be used with ${d(r)}`;this.error(p,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let r="";if(t.startsWith("--")&&this._showSuggestionAfterError){let d=[],p=this;do{const m=p.createHelp().visibleOptions(p).filter(v=>v.long).map(v=>v.long);d=d.concat(m),p=p.parent}while(p&&!p._enablePositionalOptions);r=w(t,d)}const l=`error: unknown option '${t}'${r}`;this.error(l,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const r=this.registeredArguments.length,l=r===1?"":"s",d=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${l} but got ${t.length}.`;this.error(d,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let r="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(p=>{d.push(p.name()),p.alias()&&d.push(p.alias())}),r=w(t,d)}const l=`error: unknown command '${t}'${r}`;this.error(l,{code:"commander.unknownCommand"})}version(t,r,l){if(t===void 0)return this._version;this._version=t,r=r||"-V, --version",l=l||"output the version number";const d=this.createOption(r,l);return this._versionOptionName=d.attributeName(),this._registerOption(d),this.on("option:"+d.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
24
|
-
`),this._exit(0,"commander.version",t)}),this}description(t,r){return t===void 0&&r===void 0?this._description:(this._description=t,r&&(this._argsDescription=r),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),t===r._name)throw new Error("Command alias can't be the same as its name");const l=this.parent?._findCommand(t);if(l){const d=[l.name()].concat(l.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${d}'`)}return r._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(r=>this.alias(r)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;const r=this.registeredArguments.map(l=>u(l));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=a.basename(t,a.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){const r=this.createHelp(),l=this._getOutputContext(t);r.prepareContext({error:l.error,helpWidth:l.helpWidth,outputHasColors:l.hasColors});const d=r.formatHelp(this,r);return l.hasColors?d:this._outputConfiguration.stripColor(d)}_getOutputContext(t){t=t||{};const r=!!t.error;let l,d,p;return r?(l=v=>this._outputConfiguration.writeErr(v),d=this._outputConfiguration.getErrHasColors(),p=this._outputConfiguration.getErrHelpWidth()):(l=v=>this._outputConfiguration.writeOut(v),d=this._outputConfiguration.getOutHasColors(),p=this._outputConfiguration.getOutHelpWidth()),{error:r,write:v=>(d||(v=this._outputConfiguration.stripColor(v)),l(v)),hasColors:d,helpWidth:p}}outputHelp(t){let r;typeof t=="function"&&(r=t,t=void 0);const l=this._getOutputContext(t),d={error:l.error,write:l.write,command:this};this._getCommandAndAncestors().reverse().forEach(m=>m.emit("beforeAllHelp",d)),this.emit("beforeHelp",d);let p=this.helpInformation({error:l.error});if(r&&(p=r(p),typeof p!="string"&&!Buffer.isBuffer(p)))throw new Error("outputHelp callback must return a string or a Buffer");l.write(p),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",d),this._getCommandAndAncestors().forEach(m=>m.emit("afterAllHelp",d))}helpOption(t,r){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",r??"display help for command"),(t||r)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let r=Number(s.exitCode??0);r===0&&t&&typeof t!="function"&&t.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(t,r){const l=["beforeAll","before","after","afterAll"];if(!l.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
25
|
-
Expecting one of '${l.join("', '")}'`);const d=`${t}Help`;return this.on(d,p=>{let m;typeof r=="function"?m=r({error:p.error,command:p.command}):m=r,m&&p.write(`${m}
|
|
26
|
-
`)}),this}_outputHelpIfRequested(t){const r=this._getHelpOption();r&&t.find(l=>r.is(l))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function N(Te){return Te.map(t=>{if(!t.startsWith("--inspect"))return t;let r,l="127.0.0.1",d="9229",p;return(p=t.match(/^(--inspect(-brk)?)$/))!==null?r=p[1]:(p=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=p[1],/^\d+$/.test(p[3])?d=p[3]:l=p[3]):(p=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=p[1],l=p[3],d=p[4]),r&&d!=="0"?`${r}=${l}:${parseInt(d)+1}`:t})}function K(){if(s.env.NO_COLOR||s.env.FORCE_COLOR==="0"||s.env.FORCE_COLOR==="false")return!1;if(s.env.FORCE_COLOR||s.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=V,e.useColor=K})),Ge=F((e=>{var{Argument:o}=Z(),{Command:c}=Fe(),{CommanderError:a,InvalidArgumentError:i}=J(),{Help:s}=de(),{Option:n}=pe();e.program=new c,e.createCommand=u=>new c(u),e.createOption=(u,h)=>new n(u,h),e.createArgument=(u,h)=>new o(u,h),e.Command=c,e.Option=n,e.Argument=o,e.Help=s,e.CommanderError=a,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i})),Le=ke(Ge(),1),{program:Qt,createCommand:Yt,createArgument:Xt,createOption:Zt,CommanderError:We,InvalidArgumentError:ei,InvalidOptionArgumentError:ti,Command:Ue,Argument:ii,Option:R,Help:si}=Le.default;function T(e){return`${JSON.stringify(e,null,2)}
|
|
27
|
-
`}var me=(function(e){return e.INIT="Init",e.COMPLETED="Completed",e.ARCHIVED="Archived",e.DRAFTING="Drafting",e.EXECUTION_COMPLETED="ExecutionCompleted",e.OPTIMIZING="Optimizing",e.OPENSPECING="Openspecing",e.REVIEWING="Reviewing",e.EXECUTING="Executing",e.ARCHIVING="Archiving",e})({});function fe(e){return e.replace(/\s+/g," ").trim()}function ge(e,o){const c=o.map(s=>e.map(n=>fe(n.value(s)))),a=e.map((s,n)=>{const u=c.map(h=>h[n].length);return Math.max(s.header.length,...u)}),i=s=>s.map((n,u)=>n.padEnd(a[u])).join(" ").trimEnd();return[i(e.map(s=>s.header)),i(a.map(s=>"-".repeat(s))),...c.map(i)].join(`
|
|
28
|
-
`)}function ee(e){const o=e.filter(([,a])=>a!==void 0&&a!==""),c=Math.max(...o.map(([a])=>a.length));return`${o.map(([a,i])=>`${a.padEnd(c)} ${fe(i??"")}`).join(`
|
|
29
|
-
`)}
|
|
30
|
-
`}function ce(e){return typeof e=="string"?e.trim():e?.value?.trim()??""}function G(e){return{sessionId:ce(e.sessionId),title:e.title,type:e.type,status:e.status,projectId:ce(e.projectId),proposalName:e.proposalName??void 0,archived:e.status===me.ARCHIVED,lastActiveAt:e.lastActiveAt??void 0,enableIndependentWorkspace:e.enableIndependentWorkspace,baseBranch:e.baseBranch??void 0,metadata:e.metadata??void 0,chatExecutorType:e.chatExecutorType??void 0}}function Oe(e){return{sessions:e.sessions.map(G)}}function _e(e,o){return o.length===0?`No ${e.toLowerCase()} found.
|
|
31
|
-
`:`${e} (${o.length})
|
|
32
|
-
${ge([{header:"Session ID",value:c=>c.sessionId},{header:"Title",value:c=>c.title},{header:"Status",value:c=>c.status},{header:"Project ID",value:c=>c.projectId},{header:"Archived",value:c=>c.archived?"yes":"no"}],o)}
|
|
33
|
-
`}function W(e,o=[]){return ee([["sessionId",e.sessionId],["type",e.type],["title",e.title],["status",e.status],["projectId",e.projectId],["proposalName",e.proposalName],["independentWorkspace",String(e.enableIndependentWorkspace)],["baseBranch",e.baseBranch],["chatExecutorType",e.chatExecutorType],["metadata",e.metadata],...o])}function te(e,o,c,a=[]){return`${e}
|
|
34
|
-
${ee([["sessionId",o],["message",c.message],...a])}`}var g={BASE:"",VERSION:"1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};function L(e){const o=e?.trim();return o||void 0}function Me(e={},o=process.env){return{baseUrl:L(e.baseUrl)??L(o.HAGI_API_BASE_URL)??"http://127.0.0.1:35168",token:L(e.token)??L(o.HAGI_API_TOKEN),lang:L(e.lang)??L(o.HAGI_API_LANG)}}function Be(e={},o=process.env){const c=Me(e,o);return g.BASE=c.baseUrl,g.WITH_CREDENTIALS=!1,g.CREDENTIALS="omit",g.TOKEN=c.token,g.HEADERS=c.lang?{"Accept-Language":c.lang}:void 0,c}var X=class extends Error{url;status;statusText;body;request;constructor(e,o,c){super(c),this.name="ApiError",this.url=o.url,this.status=o.status,this.statusText=o.statusText,this.body=o.body,this.request=e}},H={USAGE:2,HTTP_BAD_REQUEST:20,HTTP_UNAUTHORIZED:21,HTTP_FORBIDDEN:23,HTTP_NOT_FOUND:24,HTTP_CONFLICT:29,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},D=class extends Error{constructor(e){super(e),this.name="CliUsageError"}},ve=class extends Error{status;details;constructor(e,o,c){super(o),this.name="CliHttpError",this.status=e,this.details=c}};function Je(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function M(e,o){const c=Je(e)?.[o];return typeof c=="string"&&c.trim()?c.trim():void 0}function ze(e){return e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ENOTFOUND")||e.includes("Failed to parse URL")}function ue(e){switch(e){case 400:return H.HTTP_BAD_REQUEST;case 401:return H.HTTP_UNAUTHORIZED;case 403:return H.HTTP_FORBIDDEN;case 404:return H.HTTP_NOT_FOUND;case 409:return H.HTTP_CONFLICT;default:return e&&e>=400&&e<500?H.HTTP_CLIENT_ERROR:e&&e>=500?H.HTTP_SERVER_ERROR:H.UNKNOWN}}function Ke(e){if(e instanceof D)return{exitCode:H.USAGE,message:e.message};if(e instanceof ve)return{exitCode:ue(e.status),status:e.status,message:e.message,details:e.details};if(e instanceof X){const o=M(e.body,"error")??M(e.body,"message")??e.message;return{exitCode:ue(e.status),status:e.status,message:o,errorCode:M(e.body,"errorCode"),correlationId:M(e.body,"correlationId"),details:e.body}}return e instanceof Error?{exitCode:ze(e.message)?H.TRANSPORT:H.UNKNOWN,message:e.message}:{exitCode:H.UNKNOWN,message:String(e)}}function Ce(e,o={}){if(o.json)return`${JSON.stringify({error:{message:e.message,status:e.status,exitCode:e.exitCode,errorCode:e.errorCode,correlationId:e.correlationId,details:e.details}},null,2)}
|
|
35
|
-
`;const c=[e.status?`status=${e.status}`:void 0,e.errorCode?`errorCode=${e.errorCode}`:void 0,e.correlationId?`correlationId=${e.correlationId}`:void 0].filter(Boolean),a=c.length>0?` (${c.join(", ")})`:"";return`${e.message}${a}
|
|
36
|
-
`}var Qe=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Ye=class{#t;#i;#e;#s;#r;#n;#o;constructor(e){this.#t=!1,this.#i=!1,this.#e=!1,this.#s=[],this.#r=new Promise((o,c)=>{this.#n=o,this.#o=c;const a=n=>{this.#t||this.#i||this.#e||(this.#t=!0,this.#n&&this.#n(n))},i=n=>{this.#t||this.#i||this.#e||(this.#i=!0,this.#o&&this.#o(n))},s=n=>{this.#t||this.#i||this.#e||this.#s.push(n)};return Object.defineProperty(s,"isResolved",{get:()=>this.#t}),Object.defineProperty(s,"isRejected",{get:()=>this.#i}),Object.defineProperty(s,"isCancelled",{get:()=>this.#e}),e(a,i,s)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,o){return this.#r.then(e,o)}catch(e){return this.#r.catch(e)}finally(e){return this.#r.finally(e)}cancel(){if(!(this.#t||this.#i||this.#e)){if(this.#e=!0,this.#s.length)try{for(const e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new Qe("Request aborted"))}}get isCancelled(){return this.#e}},ie=e=>e!=null,U=e=>typeof e=="string",Q=e=>U(e)&&e!=="",se=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Ae=e=>e instanceof FormData,Xe=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Ze=e=>{const o=[],c=(i,s)=>{o.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},a=(i,s)=>{ie(s)&&(Array.isArray(s)?s.forEach(n=>{a(i,n)}):typeof s=="object"?Object.entries(s).forEach(([n,u])=>{a(`${i}[${n}]`,u)}):c(i,s))};return Object.entries(e).forEach(([i,s])=>{a(i,s)}),o.length>0?`?${o.join("&")}`:""},et=(e,o)=>{const c=e.ENCODE_PATH||encodeURI,a=o.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(s,n)=>o.path?.hasOwnProperty(n)?c(String(o.path[n])):s),i=`${e.BASE}${a}`;return o.query?`${i}${Ze(o.query)}`:i},tt=e=>{if(e.formData){const o=new FormData,c=(a,i)=>{U(i)||se(i)?o.append(a,i):o.append(a,JSON.stringify(i))};return Object.entries(e.formData).filter(([a,i])=>ie(i)).forEach(([a,i])=>{Array.isArray(i)?i.forEach(s=>c(a,s)):c(a,i)}),o}},B=async(e,o)=>typeof o=="function"?o(e):o,it=async(e,o)=>{const[c,a,i,s]=await Promise.all([B(o,e.TOKEN),B(o,e.USERNAME),B(o,e.PASSWORD),B(o,e.HEADERS)]),n=Object.entries({Accept:"application/json",...s,...o.headers}).filter(([u,h])=>ie(h)).reduce((u,[h,O])=>({...u,[h]:String(O)}),{});return Q(c)&&(n.Authorization=`Bearer ${c}`),Q(a)&&Q(i)&&(n.Authorization=`Basic ${Xe(`${a}:${i}`)}`),o.body!==void 0&&(o.mediaType?n["Content-Type"]=o.mediaType:se(o.body)?n["Content-Type"]=o.body.type||"application/octet-stream":U(o.body)?n["Content-Type"]="text/plain":Ae(o.body)||(n["Content-Type"]="application/json")),new Headers(n)},st=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):U(e.body)||se(e.body)||Ae(e.body)?e.body:JSON.stringify(e.body)},ot=async(e,o,c,a,i,s,n)=>{const u=new AbortController,h={headers:s,body:a??i,method:o.method,signal:u.signal};return e.WITH_CREDENTIALS&&(h.credentials=e.CREDENTIALS),n(()=>u.abort()),await fetch(c,h)},rt=(e,o)=>{if(o){const c=e.headers.get(o);if(U(c))return c}},nt=async e=>{if(e.status!==204)try{const o=e.headers.get("Content-Type");if(o)return["application/json","application/problem+json"].some(c=>o.toLowerCase().startsWith(c))?await e.json():await e.text()}catch(o){console.error(o)}},at=(e,o)=>{const c={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[o.status];if(c)throw new X(e,o,c);if(!o.ok)throw new X(e,o,`Generic Error: status: ${o.status??"unknown"}; status text: ${o.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(o.body,null,2)}catch{return}})()}`)},_=(e,o)=>new Ye(async(c,a,i)=>{try{const s=et(e,o),n=tt(o),u=st(o),h=await it(e,o);if(!i.isCancelled){const O=await ot(e,o,s,u,n,h,i),b=await nt(O),y=rt(O,o.responseHeader),S={url:s,ok:O.ok,status:O.status,statusText:O.statusText,body:y??b};at(o,S),c(S.body)}}catch(s){a(s)}}),ct=class{static getApiDataAggregation(){return _(g,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},Y=class{static postApiProject({requestBody:e}){return _(g,{method:"POST",url:"/api/Project",body:e,mediaType:"application/json"})}static postApiProjectDemo(){return _(g,{method:"POST",url:"/api/Project/demo"})}static putApiProject({id:e,requestBody:o}){return _(g,{method:"PUT",url:"/api/Project/{id}",path:{id:e},body:o,mediaType:"application/json"})}static deleteApiProject({id:e}){return _(g,{method:"DELETE",url:"/api/Project/{id}",path:{id:e}})}static postApiProjectOpenInVscode({id:e,subPath:o}){return _(g,{method:"POST",url:"/api/Project/{id}/open-in-vscode",path:{id:e},query:{subPath:o},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Project not found",500:"Failed to launch VS Code"}})}static getApiProjectMonospecsManagement({id:e}){return _(g,{method:"GET",url:"/api/Project/{id}/monospecs/management",path:{id:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectMonospecsManagement({id:e,requestBody:o}){return _(g,{method:"PUT",url:"/api/Project/{id}/monospecs/management",path:{id:e},body:o,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiProjectBranchesValidate({id:e,branchName:o,repositoryPath:c}){return _(g,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:e},query:{branchName:o,repositoryPath:c},errors:{400:"Branch name is required",404:"Project not found"}})}static getApiProjectValidatePath({path:e}){return _(g,{method:"GET",url:"/api/Project/validate-path",query:{path:e},errors:{400:"Path parameter is missing or invalid",500:"Internal server error during validation"}})}static postApiProjectScanGitRepos({requestBody:e}){return _(g,{method:"POST",url:"/api/Project/scan-git-repos",body:e,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error during scan"}})}static postApiProjectValidateMonospecs({requestBody:e}){return _(g,{method:"POST",url:"/api/Project/validate-monospecs",body:e,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error"}})}static getApiProjectKnowledgeOverview({id:e}){return _(g,{method:"GET",url:"/api/Project/{id}/knowledge/overview",path:{id:e},errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static getApiProjectKnowledgeGraph({id:e}){return _(g,{method:"GET",url:"/api/Project/{id}/knowledge/graph",path:{id:e},errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static postApiProjectKnowledgeMemoriesAccept({id:e,memoryId:o}){return _(g,{method:"POST",url:"/api/Project/{id}/knowledge/memories/{memoryId}/accept",path:{id:e,memoryId:o},errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static postApiProjectKnowledgeMemoriesRestoreCandidate({id:e,memoryId:o}){return _(g,{method:"POST",url:"/api/Project/{id}/knowledge/memories/{memoryId}/restore-candidate",path:{id:e,memoryId:o},errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static deleteApiProjectKnowledgeMemories({id:e,memoryId:o}){return _(g,{method:"DELETE",url:"/api/Project/{id}/knowledge/memories/{memoryId}",path:{id:e,memoryId:o},errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}},$=class{static postApiSessionsAutoTask({requestBody:e}){return _(g,{method:"POST",url:"/api/Sessions/auto-task",body:e,mediaType:"application/json",errors:{400:"Missing required fields or invalid prompt ID",404:"Project not found",500:"Internal server error"}})}static postApiSessionsArchiveChat({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/archive-chat",path:{sessionId:e},errors:{400:"Session is not a chat session",404:"Session not found",500:"Failed to archive chat session"}})}static postApiSessionsChat({requestBody:e}){return _(g,{method:"POST",url:"/api/Sessions/chat",body:e,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:e}){return _(g,{method:"POST",url:"/api/Sessions",body:e,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:e,activeOnly:o,includeArchived:c,projectId:a,projectIds:i}){return _(g,{method:"GET",url:"/api/Sessions",query:{type:e,activeOnly:o,includeArchived:c,projectId:a,projectIds:i}})}static getApiSessions1({sessionId:e}){return _(g,{method:"GET",url:"/api/Sessions/{sessionId}",path:{sessionId:e},errors:{400:"Invalid session ID format",404:"Session not found",500:"Internal server error occurred"}})}static putApiSessions({sessionId:e,requestBody:o}){return _(g,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:e},body:o,mediaType:"application/json"})}static deleteApiSessions({sessionId:e,deleteFiles:o=!1}){return _(g,{method:"DELETE",url:"/api/Sessions/{sessionId}",path:{sessionId:e},query:{deleteFiles:o},errors:{404:"Session not found",500:"Failed to delete session"}})}static postApiSessionsCancel({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/cancel",path:{sessionId:e},errors:{404:"Session not found",500:"Failed to cancel session"}})}static getApiSessionsProcessingStatus({sessionId:e}){return _(g,{method:"GET",url:"/api/Sessions/{sessionId}/processing-status",path:{sessionId:e},errors:{404:"Session not found",500:"Failed to get processing status"}})}static deleteApiSessionsQueue({sessionId:e,queueIndex:o}){return _(g,{method:"DELETE",url:"/api/Sessions/{sessionId}/queue/{queueIndex}",path:{sessionId:e,queueIndex:o},errors:{400:"Invalid queue index",404:"Session not found",500:"Failed to cancel message"}})}static postApiSessionsMessages({sessionId:e,requestBody:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:e},body:o,mediaType:"application/json"})}static postApiSessionsAnnotations({sessionId:e,requestBody:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/annotations",path:{sessionId:e},body:o,mediaType:"application/json",errors:{400:"Invalid request or session is not a proposal session",404:"Session not found",500:"Failed to process annotations"}})}static postApiSessionsGenerateProposalName({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal-name",path:{sessionId:e},errors:{400:"Session is not a proposal session or proposal name already exists",404:"Session not found",409:"Proposal name already exists for this session",500:"Failed to generate proposal name"}})}static postApiSessionsOptimizeDescription({sessionId:e,requestBody:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-description",path:{sessionId:e},body:o,mediaType:"application/json",errors:{400:"Invalid request or empty description",404:"Session not found",500:"Failed to start optimization task"}})}static postApiSessionsOptimizeTitle({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-title",path:{sessionId:e},errors:{400:"Invalid request or session has no description",404:"Session not found",500:"Failed to optimize title"}})}static postApiSessionsGenerateProposal({sessionId:e,requestBody:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal",path:{sessionId:e},body:o,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name not generated",404:"Session not found",500:"Failed to generate proposal"}})}static postApiSessionsArchive({sessionId:e,requestBody:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/archive",path:{sessionId:e},body:o,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name missing",404:"Session not found",500:"Failed to archive session"}})}static postApiSessionsExecuteProposal({sessionId:e,requestBody:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/execute-proposal",path:{sessionId:e},body:o,mediaType:"application/json",errors:{400:"Session is not a proposal session, not in valid status, or proposal name missing",404:"Session not found",500:"Failed to execute proposal"}})}static postApiSessionsComplete({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/complete",path:{sessionId:e},errors:{400:"Session is not in ExecutionCompleted status",404:"Session not found",500:"Failed to complete session"}})}static postApiSessionsValidateExecute({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-execute",path:{sessionId:e},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateStart({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-start",path:{sessionId:e},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateArchive({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-archive",path:{sessionId:e},errors:{404:"Session not found",500:"Failed to validate session"}})}static getApiSessionsOpenspecFile({sessionId:e,relativePath:o}){return _(g,{method:"GET",url:"/api/Sessions/{sessionId}/openspec-file",path:{sessionId:e},query:{relativePath:o},errors:{404:"Session not found or file not found",500:"Failed to read file"}})}static postApiSessionsUpdateCessionId({sessionId:e}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/update-cession-id",path:{sessionId:e},errors:{404:"Session not found",500:"Failed to update CessionId"}})}static postApiSessionsOpenInVscode({sessionId:e,subPath:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/open-in-vscode",path:{sessionId:e},query:{subPath:o},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Session not found",500:"Failed to launch VS Code"}})}static postApiSessionsCorrectProposalName({sessionId:e,requestBody:o}){return _(g,{method:"POST",url:"/api/Sessions/{sessionId}/correct-proposal-name",path:{sessionId:e},body:o,mediaType:"application/json",errors:{400:"Invalid name format or validation failed",404:"Session not found",409:"Name already in use by another session",500:"Internal server error"}})}static deleteApiSessionsWorkspace({sessionId:e}){return _(g,{method:"DELETE",url:"/api/Sessions/{sessionId}/workspace",path:{sessionId:e},errors:{400:"Session does not have an independent workspace",404:"Session not found",500:"Failed to delete workspace"}})}};function ut(){return{listSessions:e=>$.getApiSessions(e),getSession:e=>$.getApiSessions1({sessionId:e}),createProposalSession:e=>$.postApiSessions({requestBody:e}),createChatSession:e=>$.postApiSessionsChat({requestBody:e}),createAutoTaskSession:e=>$.postApiSessionsAutoTask({requestBody:e}),updateSession:(e,o)=>$.putApiSessions({sessionId:e,requestBody:o}),deleteSession:(e,o)=>$.deleteApiSessions({sessionId:e,deleteFiles:o}),sendMessage:(e,o)=>$.postApiSessionsMessages({sessionId:e,requestBody:o}),generateProposalName:e=>$.postApiSessionsGenerateProposalName({sessionId:e}),optimizeDescription:(e,o)=>$.postApiSessionsOptimizeDescription({sessionId:e,requestBody:o}),generateProposal:(e,o)=>$.postApiSessionsGenerateProposal({sessionId:e,requestBody:o}),executeProposal:(e,o)=>$.postApiSessionsExecuteProposal({sessionId:e,requestBody:o}),archiveProposal:(e,o)=>$.postApiSessionsArchive({sessionId:e,requestBody:o}),completeProposal:e=>$.postApiSessionsComplete({sessionId:e}),submitAnnotations:(e,o)=>$.postApiSessionsAnnotations({sessionId:e,requestBody:o}),listProjects:()=>ct.getApiDataAggregation(),createProject:e=>Y.postApiProject({requestBody:e}),updateProject:(e,o)=>Y.putApiProject({id:e,requestBody:o}),deleteProject:e=>Y.deleteApiProject({id:e}),archiveChat:e=>$.postApiSessionsArchiveChat({sessionId:e})}}function E(e){const o=e?.trim();return o||void 0}function k(e,o){const c=E(e);if(!c)throw new D(`${o} is required.`);return c}function ye(e){const o=e?.map(c=>E(c)).filter(Boolean);return o&&o.length>0?o:void 0}function Se(e=process.env,o={stdout:c=>{process.stdout.write(c)},stderr:c=>{process.stderr.write(c)}}){return{api:ut(),env:e,io:o}}function lt(e){return e.option("--base-url <url>","Backend API base URL. Defaults to HAGI_API_BASE_URL or the local dev URL.").option("--token <token>","Bearer token for backend API calls. Overrides HAGI_API_TOKEN.").option("--lang <lang>","Accept-Language value for backend API calls. Overrides HAGI_API_LANG.")}function P(e){return e.option("--json","Emit deterministic JSON instead of human-readable text.")}function x(e,o){const c=e.optsWithGlobals();return{api:o.api,env:o.env,io:o.io,outputJson:c.json===!0,runtime:Be({baseUrl:c.baseUrl,token:c.token,lang:c.lang},o.env)}}function dt(e,o){P(e.command("create").description("Create an AutoTask session through the dedicated generated endpoint.")).requiredOption("--title <title>","AutoTask session title.").requiredOption("--project-id <id>","Owning project id.").requiredOption("--prompt-id <id>","Prompt template id.").option("--message <text>","Optional custom message override.").option("--preset-id <id>","Optional preset id.").option("--repository-path <path>","Optional MonoSpecs repository path.").option("--project-ids <ids...>","Optional extra project ids for multi-project flows.").option("--need-push","Request push after commit creation when supported.").option("--target-branch-mode <mode>","Optional target branch mode.").option("--target-branch-name <name>","Optional custom target branch name.").option("--script-key <key>","Optional stable dungeon script key.").option("--hero-id <id>","Optional preferred hero id.").action(async function(a){if(a.targetBranchName&&a.targetBranchMode!=="new-custom")throw new D("--target-branch-name requires --target-branch-mode new-custom.");if(a.targetBranchMode==="new-custom"&&!E(a.targetBranchName))throw new D("--target-branch-name is required when --target-branch-mode is new-custom.");const i=x(this,o),s={title:k(a.title,"--title"),projectId:k(a.projectId,"--project-id"),promptId:k(a.promptId,"--prompt-id"),message:E(a.message),presetId:E(a.presetId),repositoryPath:E(a.repositoryPath),projectIds:ye(a.projectIds),needPush:a.needPush?!0:void 0,targetBranchMode:E(a.targetBranchMode),targetBranchName:E(a.targetBranchName),scriptKey:E(a.scriptKey),heroId:E(a.heroId)},n=G(await i.api.createAutoTaskSession(s));if(i.outputJson){i.io.stdout(T({session:n,promptId:s.promptId,requested:s}));return}i.io.stdout(`AutoTask session created
|
|
37
|
-
${W(n,[["promptId",s.promptId],["repositoryPath",s.repositoryPath],["targetBranchMode",s.targetBranchMode],["targetBranchName",s.targetBranchName],["scriptKey",s.scriptKey],["heroId",s.heroId]])}`)})}var z=(function(e){return e.CLAUDE_CODE_CLI="ClaudeCodeCli",e.CODEX_CLI="CodexCli",e.GIT_HUB_COPILOT="GitHubCopilot",e.CODEBUDDY_CLI="CodebuddyCli",e.OPEN_CODE_CLI="OpenCodeCli",e.IFLOW_CLI="IFlowCli",e.HERMES_CLI="HermesCli",e.QODER_CLI="QoderCli",e.KIRO_CLI="KiroCli",e.KIMI_CLI="KimiCli",e.GEMINI_CLI="GeminiCli",e})({}),oe=(function(e){return e.READONLY="Readonly",e.EDIT="Edit",e})({});function pt(e,o){P(e.command("send").description("Send a follow-up message to an AutoTask session.")).requiredOption("--session-id <id>","AutoTask session id.").requiredOption("--content <text>","Message content.").addOption(new R("--mode <mode>","Message mode override.").choices(Object.values(oe))).addOption(new R("--executor-type <type>","Executor override for this message.").choices(Object.values(z))).action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=await i.api.sendMessage(s,{content:k(a.content,"--content"),mode:a.mode,executorType:a.executorType});if(i.outputJson){i.io.stdout(T({sessionId:s,message:n.message,requested:{mode:a.mode,executorType:a.executorType}}));return}i.io.stdout(te("AutoTask message sent",s,n,[["mode",a.mode],["executorType",a.executorType]]))})}function ht(e,o){const c=e.command("autotask").description("Manage AutoTask sessions.");dt(c,o),pt(c,o)}function mt(e,o){P(e.command("archive").description("Archive a chat session through the dedicated chat archive endpoint.")).requiredOption("--session-id <id>","Chat session id to archive.").action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=await i.api.archiveChat(s);if(i.outputJson){i.io.stdout(T({sessionId:s,message:n.message}));return}i.io.stdout(`Chat archived
|
|
38
|
-
sessionId ${s}
|
|
39
|
-
message ${n.message}
|
|
40
|
-
`)})}function ft(e,o){P(e.command("create").description("Create a normal chat session.")).requiredOption("--title <title>","Chat session title.").requiredOption("--project-id <id>","Owning project id.").option("--hero-id <id>","Optional bound hero id.").addOption(new R("--executor-type <type>","Optional executor override.").choices(Object.values(z))).action(async function(a){const i=x(this,o),s=G(await i.api.createChatSession({title:k(a.title,"--title"),projectId:k(a.projectId,"--project-id"),heroId:E(a.heroId),executorType:a.executorType}));if(i.outputJson){i.io.stdout(T({session:s}));return}i.io.stdout(`Chat session created
|
|
41
|
-
${W(s)}`)})}function gt(e,o){P(e.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=await i.api.deleteSession(s,!1);if(i.outputJson){i.io.stdout(T({sessionId:s,deleted:!0,message:n.message}));return}i.io.stdout(`Chat deleted
|
|
42
|
-
sessionId ${s}
|
|
43
|
-
message ${n.message}
|
|
44
|
-
`)})}var re=(function(e){return e.CHAT="Chat",e.PROPOSAL="Proposal",e})({});function Ot(e,o){P(e.command("list").description("List normal chat sessions.")).action(async function(a){if(a.projectId&&a.projectIds?.length)throw new D("Use either --project-id or --project-ids, not both.");const i=x(this,o),s=Oe(await i.api.listSessions({type:re.CHAT,projectId:E(a.projectId),projectIds:ye(a.projectIds),activeOnly:a.activeOnly?!0:void 0,includeArchived:a.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(T(s));return}i.io.stdout(_e("Chat sessions",s.sessions))}).option("--project-id <id>","Filter chat sessions by a single project id.").option("--project-ids <ids...>","Filter chat sessions by multiple project ids.").option("--active-only","Only return non-archived chat sessions.").option("--include-archived","Include archived chat sessions.")}function _t(e,o){P(e.command("send").description("Send a follow-up message to a chat session.")).requiredOption("--session-id <id>","Chat session id.").requiredOption("--content <text>","Message content.").addOption(new R("--mode <mode>","Message mode override.").choices(Object.values(oe))).addOption(new R("--executor-type <type>","Executor override for this message.").choices(Object.values(z))).action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=await i.api.sendMessage(s,{content:k(a.content,"--content"),mode:a.mode,executorType:a.executorType});if(i.outputJson){i.io.stdout(T({sessionId:s,message:n.message,requested:{mode:a.mode,executorType:a.executorType}}));return}i.io.stdout(te("Chat message sent",s,n,[["mode",a.mode],["executorType",a.executorType]]))})}function vt(e,o){const c=e.command("chat").description("Manage normal chat sessions.");Ot(c,o),ft(c,o),mt(c,o),gt(c,o),_t(c,o)}function q(e){const o=e?.trim();return o||void 0}function ne(e){return{id:q(e.id)??"",name:q(e.name)??"",path:q(e.path)??"",description:q(e.description),isMonoSpecs:e.isMonoSpecs===!0,monoSpecsVersion:q(e.monoSpecsVersion),monoSpecsRepoDirectory:q(e.monoSpecsRepoDirectory),monoSpecsCommitWhenArchive:typeof e.monoSpecsCommitWhenArchive=="boolean"?e.monoSpecsCommitWhenArchive:void 0,hasError:"hasError"in e?e.hasError===!0:!1,error:"error"in e?q(e.error):void 0}}function be(e){return{projects:(e??[]).map(ne)}}function Ct(e){return e.length===0?`No projects found.
|
|
45
|
-
`:`Projects (${e.length})
|
|
46
|
-
${ge([{header:"Project ID",value:o=>o.id},{header:"Name",value:o=>o.name},{header:"Path",value:o=>o.path},{header:"MonoSpecs",value:o=>o.isMonoSpecs?"yes":"no"},{header:"Error",value:o=>o.hasError?"yes":"no"}],e)}
|
|
47
|
-
`}function Ee(e,o=[]){return ee([["id",e.id],["name",e.name],["path",e.path],["description",e.description],["isMonoSpecs",String(e.isMonoSpecs)],["monoSpecsVersion",e.monoSpecsVersion],["monoSpecsRepoDirectory",e.monoSpecsRepoDirectory],["monoSpecsCommitWhenArchive",typeof e.monoSpecsCommitWhenArchive=="boolean"?String(e.monoSpecsCommitWhenArchive):void 0],["hasError",String(e.hasError)],["error",e.error],...o])}function At(e,o){P(e.command("create").description("Create a project through the generated project client.")).requiredOption("--name <name>","Project display name.").requiredOption("--path <path>","Project root path.").option("--description <text>","Optional project description.").action(async function(a){const i=x(this,o),s=ne(await i.api.createProject({name:k(a.name,"--name"),path:k(a.path,"--path"),description:E(a.description)}));if(i.outputJson){i.io.stdout(T({project:s}));return}i.io.stdout(`Project created
|
|
48
|
-
${Ee(s)}`)})}function yt(e,o){P(e.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(a){const i=x(this,o),s=a.id.trim();if(await i.api.deleteProject(s),i.outputJson){i.io.stdout(T({projectId:s,deleted:!0}));return}i.io.stdout(`Project deleted
|
|
49
|
-
projectId ${s}
|
|
50
|
-
`)})}function St(e,o){P(e.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const a=x(this,o),i=be((await a.api.listProjects()).projects);if(a.outputJson){a.io.stdout(T(i));return}a.io.stdout(Ct(i.projects))})}function bt(e,o){P(e.command("update").description("Update a project by merging provided fields into the aggregation snapshot.")).requiredOption("--id <id>","Project id to update.").option("--name <name>","Updated project name.").option("--path <path>","Updated project path.").option("--description <text>","Updated project description.").option("--clear-description","Clear the stored description.").action(async function(a){if(!a.name&&!a.path&&!a.description&&!a.clearDescription)throw new D("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(a.description&&a.clearDescription)throw new D("Use either --description or --clear-description, not both.");const i=x(this,o),s=a.id.trim(),n=be((await i.api.listProjects()).projects).projects.find(h=>h.id===s);if(!n)throw new ve(404,`Project ${s} was not found in the aggregation snapshot.`);const u=ne(await i.api.updateProject(s,{name:E(a.name)??n.name,path:E(a.path)??n.path,description:a.clearDescription?null:E(a.description)??n.description??null}));if(i.outputJson){i.io.stdout(T({project:u}));return}i.io.stdout(`Project updated
|
|
51
|
-
${Ee(u)}`)})}function Et(e,o){const c=e.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");St(c,o),At(c,o),bt(c,o),yt(c,o)}async function It(){const e=[];for await(const o of Ve.stdin)e.push(typeof o=="string"?Buffer.from(o):o);return Buffer.concat(e).toString("utf8")}async function wt(e){const o=e.trim();if(!o)throw new D("Provide --input <file> or --input - for stdin.");const c=o==="-"?await It():await(0,Re.readFile)(o,"utf8");try{return JSON.parse(c)}catch(a){throw new D(`Invalid JSON input from ${o}: ${a instanceof Error?a.message:String(a)}`)}}function Tt(e,o){if(!o||typeof o!="object"||Array.isArray(o))throw new D("Annotation input must be a JSON object.");const c=o;if(!Array.isArray(c.files))throw new D("Annotation input must include a files array.");const a=typeof c.totalAnnotations=="number"?c.totalAnnotations:c.files.length,i=typeof c.submittedAt=="string"&&c.submittedAt.trim()?c.submittedAt:new Date().toISOString();return{...c,sessionId:e,totalAnnotations:a,submittedAt:i,files:c.files}}function Pt(e,o){P(e.command("annotate").description("Submit proposal annotations from structured JSON input.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=Tt(s,await wt(a.input)),u=await i.api.submitAnnotations(s,n);if(i.outputJson){i.io.stdout(T({sessionId:s,message:u.message,annotationCount:u.annotationCount??n.totalAnnotations,fileCount:u.fileCount??n.files.length}));return}i.io.stdout(`Proposal annotations submitted
|
|
52
|
-
sessionId ${s}
|
|
53
|
-
message ${u.message}
|
|
54
|
-
annotationCount ${u.annotationCount??n.totalAnnotations}
|
|
55
|
-
fileCount ${u.fileCount??n.files.length}
|
|
56
|
-
`)})}function xt(e,o){P(e.command("archive").description("Archive a proposal session through the explicit archive endpoint.")).requiredOption("--session-id <id>","Proposal session id to archive.").option("--hero-id <id>","Optional hero override for archiving.").action(async function(a){const i=x(this,o),s=G(await i.api.archiveProposal(a.sessionId.trim(),{heroId:E(a.heroId)}));if(i.outputJson){i.io.stdout(T({session:s}));return}i.io.stdout(`Proposal archive started
|
|
57
|
-
${W(s)}`)})}function jt(e,o){P(e.command("complete").description("Mark a proposal session as completed through the dedicated completion endpoint.")).requiredOption("--session-id <id>","Proposal session id to complete.").action(async function(a){const i=x(this,o),s=G(await i.api.completeProposal(a.sessionId.trim()));if(i.outputJson){i.io.stdout(T({session:s}));return}i.io.stdout(`Proposal completed
|
|
58
|
-
${W(s)}`)})}function $t(e){return G(e)}function Ht(e){return Oe(e)}function Dt(e){return _e("Proposal sessions",e)}function Nt(e,o=[]){return W(e,o)}var Ie="New Proposal";function kt(e){const o=E(e.title);if(o)return o;if(e.defaultTitle)return Ie;throw new D("Provide --title or pass --default-title to use the placeholder proposal title.")}function Vt(e,o){P(e.command("create").description("Create a proposal session only. This command does not trigger later lifecycle APIs.")).requiredOption("--project-id <id>","Project id that owns the new proposal session.").requiredOption("--chief-complaint <text>","Proposal chief complaint to store on the new session.").option("--original-chief-complaint <text>","Optional raw chief complaint text to keep alongside the stitched content.").option("--title <title>","Explicit proposal session title.").option("--default-title",`Mark the title as the placeholder title (${Ie}).`).option("--enable-independent-workspace","Request an independent workspace for the proposal session.").option("--base-branch <branch>","Optional base branch for the independent workspace.").action(async function(a){const i=x(this,o),s=kt(a),n=$t(await i.api.createProposalSession({title:s,chiefComplaint:a.chiefComplaint.trim(),originalChiefComplaint:E(a.originalChiefComplaint),type:re.PROPOSAL,projectId:a.projectId.trim(),enableIndependentWorkspace:a.enableIndependentWorkspace?!0:void 0,baseBranch:E(a.baseBranch),isDefaultTitle:!!a.defaultTitle})),u=`hagi proposal generate-name --session-id ${n.sessionId}`;if(i.outputJson){i.io.stdout(T({session:n,nextCommand:u}));return}i.io.stdout(`Proposal session created
|
|
59
|
-
${Nt(n,[["next",u]])}`)})}function Rt(e,o){P(e.command("execute").description("Start proposal execution only. This command maps to the execute-proposal backend action.")).requiredOption("--session-id <id>","Proposal session id to execute.").option("--hero-id <id>","Optional hero override for the execute stage.").action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=E(a.heroId),u=await i.api.executeProposal(s,{heroId:n});if(i.outputJson){i.io.stdout(T({sessionId:s,message:u.message,requested:{heroId:n}}));return}i.io.stdout(`Proposal execution started
|
|
60
|
-
sessionId ${s}
|
|
61
|
-
message ${u.message}
|
|
62
|
-
`)})}function qt(e){if(e.enableExploreMode&&e.disableExploreMode)throw new D("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(e.enableExploreMode)return!0;if(e.disableExploreMode)return!1}function Ft(e,o){P(e.command("generate").description("Start proposal generation only. This command does not execute the proposal.")).requiredOption("--session-id <id>","Proposal session id to generate.").option("--enable-explore-mode","Explicitly enable explore mode for proposal generation.").option("--disable-explore-mode","Explicitly disable explore mode for proposal generation.").option("--hero-id <id>","Optional hero override for the generate stage.").action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=qt(a),u=await i.api.generateProposal(s,{enableExploreMode:n,heroId:E(a.heroId)}),h=`hagi proposal execute --session-id ${s}`;if(i.outputJson){i.io.stdout(T({sessionId:s,message:u.message,requested:{enableExploreMode:n,heroId:E(a.heroId)},nextCommand:h}));return}i.io.stdout(`Proposal generation started
|
|
63
|
-
sessionId ${s}
|
|
64
|
-
message ${u.message}
|
|
65
|
-
next Wait for the session to reach Reviewing, then run ${h}
|
|
66
|
-
`)})}function Gt(e,o){P(e.command("generate-name").description("Generate a proposal name only. This command maps to the generate-proposal-name backend action.")).requiredOption("--session-id <id>","Proposal session id to update.").action(async function(a){const i=x(this,o),s=await i.api.generateProposalName(a.sessionId.trim()),n=`hagi proposal generate --session-id ${a.sessionId.trim()}`;if(i.outputJson){i.io.stdout(T({sessionId:a.sessionId.trim(),proposalName:s.proposalName,nextCommand:n}));return}i.io.stdout(`Proposal name generated
|
|
67
|
-
sessionId ${a.sessionId.trim()}
|
|
68
|
-
proposalName ${s.proposalName}
|
|
69
|
-
next ${n}
|
|
70
|
-
`)})}function Lt(e,o){P(e.command("list").description("List proposal sessions from the backend Sessions API.")).option("--project-id <id>","Filter proposal sessions by a single project id.").option("--project-ids <ids...>","Filter proposal sessions by multiple project ids.").option("--active-only","Only return non-archived proposal sessions.").option("--include-archived","Include archived proposal sessions in the result set.").action(async function(a){if(a.projectId&&a.projectIds?.length)throw new D("Use either --project-id or --project-ids, not both.");const i=x(this,o),s=Ht(await i.api.listSessions({type:re.PROPOSAL,projectId:E(a.projectId),projectIds:a.projectIds?.map(E).filter(Boolean),activeOnly:a.activeOnly?!0:void 0,includeArchived:a.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(T(s));return}i.io.stdout(Dt(s.sessions))})}function Wt(e,o){P(e.command("optimize-description").description("Start asynchronous proposal description optimization only.")).requiredOption("--session-id <id>","Proposal session id to optimize.").requiredOption("--description <text>","Description text to optimize.").option("--optimization-direction <text>","Optional optimization direction for AI guidance.").option("--disable-memory-optimization","Disable long-term memory during optimization.").option("--default-title","Treat the current title as a placeholder title.").action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=await i.api.optimizeDescription(s,{description:k(a.description,"--description"),optimizationDirection:E(a.optimizationDirection),enableMemoryOptimization:a.disableMemoryOptimization?!1:void 0,isDefaultTitle:a.defaultTitle?!0:void 0});if(i.outputJson){i.io.stdout(T({sessionId:s,taskId:n.taskId,status:n.status}));return}i.io.stdout(`Proposal description optimization started
|
|
71
|
-
sessionId ${s}
|
|
72
|
-
taskId ${n.taskId??""}
|
|
73
|
-
status ${n.status??""}
|
|
74
|
-
`)})}function Ut(e,o){P(e.command("send").description("Send a follow-up message to a proposal session.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--content <text>","Message content.").addOption(new R("--mode <mode>","Message mode override.").choices(Object.values(oe))).addOption(new R("--executor-type <type>","Executor override for this message.").choices(Object.values(z))).action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=await i.api.sendMessage(s,{content:k(a.content,"--content"),mode:a.mode,executorType:a.executorType});if(i.outputJson){i.io.stdout(T({sessionId:s,message:n.message,requested:{mode:a.mode,executorType:a.executorType}}));return}i.io.stdout(te("Proposal message sent",s,n,[["mode",a.mode],["executorType",a.executorType]]))})}function Mt(e,o){P(e.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new R("--status <status>","Target session status.").choices(Object.values(me)).makeOptionMandatory()).action(async function(a){const i=x(this,o),s=a.sessionId.trim(),n=await i.api.getSession(s);await i.api.updateSession(s,{title:n.title,description:n.description,status:a.status,metadata:n.metadata});const u=G({...n,status:a.status});if(i.outputJson){i.io.stdout(T({session:u}));return}i.io.stdout(`Proposal status updated
|
|
75
|
-
${W(u)}`)})}function Bt(e,o){const c=e.command("proposal").description("Manage proposal sessions through backend session APIs.");Lt(c,o),Vt(c,o),Gt(c,o),Wt(c,o),Ft(c,o),Pt(c,o),Rt(c,o),xt(c,o),Mt(c,o),jt(c,o),Ut(c,o)}function Jt(e){return e.includes("--json")}function we(e=Se(),o=!1){const c=new Ue;return c.name("hagi").description("HagiCode CLI for project, proposal, chat, and AutoTask management.").showHelpAfterError().exitOverride(),c.configureOutput({writeOut:a=>{e.io.stdout(a)},writeErr:a=>{o||e.io.stderr(a)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),lt(c),Et(c,e),Bt(c,e),vt(c,e),ht(c,e),c}function zt(e,o,c){return e.exitCode===0||e.code==="commander.helpDisplayed"||e.code==="commander.version"?0:(c&&o.io.stderr(Ce({exitCode:H.USAGE,message:e.message},{json:!0})),H.USAGE)}async function Kt(e=process.argv,o=Se()){const c=Jt(e),a=we(o,c);try{return await a.parseAsync([...e]),0}catch(i){if(i instanceof We)return zt(i,o,c);const s=Ke(i);return o.io.stderr(Ce(s,{json:c})),s.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return H}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return we}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return Kt}});
|