@hagicode/cli 0.1.0-dev.3.1.074a0f9 → 0.1.0-dev.32.1.c8f71ee

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/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-BXoLU5FX.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}
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./chunks/main-DM4Tim9g.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-BXoLU5FX.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/main-DM4Tim9g.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.3.1.074a0f9",
4
- "description": "HagiCode CLI for proposal session management.",
3
+ "version": "0.1.0-dev.32.1.c8f71ee",
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"
@@ -20,12 +20,14 @@
20
20
  ],
21
21
  "packageManager": "npm@10.9.2",
22
22
  "engines": {
23
- "node": ">=20"
23
+ "node": ">=24.0.0"
24
24
  },
25
25
  "scripts": {
26
26
  "clean": "rimraf dist",
27
- "build": "npm run clean && vite build",
27
+ "build": "export NODE_OPTIONS=\"${NODE_OPTIONS:-} --max-old-space-size=8192\"; npm run clean && vite build",
28
28
  "dev": "tsx ./src/cli.ts",
29
+ "generate:grpc": "node ./buildTools/generate-grpc.mjs",
30
+ "generate:grpc:check": "node ./buildTools/generate-grpc.mjs --check",
29
31
  "generate:api": "node ./buildTools/generate-api.cjs",
30
32
  "generate:api:once": "node ./buildTools/generate-api-once.cjs",
31
33
  "pack:check": "node ./scripts/verify-package.mjs",
@@ -33,13 +35,18 @@
33
35
  "publish:verify-release": "node ./scripts/verify-release-version.mjs",
34
36
  "test": "vitest run",
35
37
  "test:watch": "vitest",
36
- "typecheck": "tsc --noEmit -p tsconfig.json"
38
+ "typecheck": "export NODE_OPTIONS=\"${NODE_OPTIONS:-} --max-old-space-size=8192\"; tsc --noEmit -p tsconfig.json"
37
39
  },
38
40
  "keywords": [
39
41
  "hagicode",
42
+ "hagicode-org",
40
43
  "cli",
41
44
  "openspec",
42
- "proposal"
45
+ "proposal",
46
+ "autotask",
47
+ "vault",
48
+ "ai-agent",
49
+ "agentic-coding"
43
50
  ],
44
51
  "author": "HagiCode",
45
52
  "license": "AGPL-3.0-or-later",
@@ -49,15 +56,20 @@
49
56
  "registry": "https://registry.npmjs.org/"
50
57
  },
51
58
  "dependencies": {
59
+ "@bufbuild/protobuf": "2.16.0",
60
+ "@connectrpc/connect": "2.2.0",
61
+ "@connectrpc/connect-node": "2.2.0",
52
62
  "commander": "^14.0.2"
53
63
  },
54
64
  "devDependencies": {
65
+ "@bufbuild/buf": "1.73.0",
66
+ "@bufbuild/protoc-gen-es": "2.16.0",
55
67
  "@types/node": "^25.0.2",
56
68
  "openapi-typescript-codegen": "^0.29.0",
57
69
  "rimraf": "^6.1.2",
58
70
  "tsx": "^4.20.6",
59
- "typescript": "^5.9.3",
71
+ "typescript": "^6.0.3",
60
72
  "vite": "^8.0.3",
61
- "vitest": "^4.1.1"
73
+ "vitest": "^5.0.5"
62
74
  }
63
75
  }
@@ -1,47 +0,0 @@
1
- var ce=Object.create,X=Object.defineProperty,pe=Object.getOwnPropertyDescriptor,de=Object.getOwnPropertyNames,me=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty,H=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports),ge=(t,n,c,p)=>{if(n&&typeof n=="object"||typeof n=="function")for(var s=de(n),i=0,o=s.length,l;i<o;i++)l=s[i],!fe.call(t,l)&&l!==c&&X(t,l,{get:(d=>n[d]).bind(null,l),enumerable:!(p=pe(n,l))||p.enumerable});return t},_e=(t,n,c)=>(c=t!=null?ce(me(t)):{},ge(n||!t||!t.__esModule?X(c,"default",{value:t,enumerable:!0}):c,t)),W=H((t=>{var n=class extends Error{constructor(p,s,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=s,this.exitCode=p,this.nestedError=void 0}},c=class extends n{constructor(p){super(1,"commander.invalidArgument",p),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};t.CommanderError=n,t.InvalidArgumentError=c})),M=H((t=>{var{InvalidArgumentError:n}=W(),c=class{constructor(s,i){switch(this.description=i||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,s[0]){case"<":this.required=!0,this._name=s.slice(1,-1);break;case"[":this.required=!1,this._name=s.slice(1,-1);break;default:this.required=!0,this._name=s;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(s,i){return i===this.defaultValue||!Array.isArray(i)?[s]:(i.push(s),i)}default(s,i){return this.defaultValue=s,this.defaultValueDescription=i,this}argParser(s){return this.parseArg=s,this}choices(s){return this.argChoices=s.slice(),this.parseArg=(i,o)=>{if(!this.argChoices.includes(i))throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(i,o):i},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function p(s){const i=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+i+">":"["+i+"]"}t.Argument=c,t.humanReadableArgName=p})),Y=H((t=>{var{humanReadableArgName:n}=M(),c=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(s){this.helpWidth=this.helpWidth??s.helpWidth??80}visibleCommands(s){const i=s.commands.filter(l=>!l._hidden),o=s._getHelpCommand();return o&&!o._hidden&&i.push(o),this.sortSubcommands&&i.sort((l,d)=>l.name().localeCompare(d.name())),i}compareOptions(s,i){const o=l=>l.short?l.short.replace(/^-/,""):l.long.replace(/^--/,"");return o(s).localeCompare(o(i))}visibleOptions(s){const i=s.options.filter(l=>!l.hidden),o=s._getHelpOption();if(o&&!o.hidden){const l=o.short&&s._findOption(o.short),d=o.long&&s._findOption(o.long);!l&&!d?i.push(o):o.long&&!d?i.push(s.createOption(o.long,o.description)):o.short&&!l&&i.push(s.createOption(o.short,o.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(s){if(!this.showGlobalOptions)return[];const i=[];for(let o=s.parent;o;o=o.parent){const l=o.options.filter(d=>!d.hidden);i.push(...l)}return this.sortOptions&&i.sort(this.compareOptions),i}visibleArguments(s){return s._argsDescription&&s.registeredArguments.forEach(i=>{i.description=i.description||s._argsDescription[i.name()]||""}),s.registeredArguments.find(i=>i.description)?s.registeredArguments:[]}subcommandTerm(s){const i=s.registeredArguments.map(o=>n(o)).join(" ");return s._name+(s._aliases[0]?"|"+s._aliases[0]:"")+(s.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(s){return s.flags}argumentTerm(s){return s.name()}longestSubcommandTermLength(s,i){return i.visibleCommands(s).reduce((o,l)=>Math.max(o,this.displayWidth(i.styleSubcommandTerm(i.subcommandTerm(l)))),0)}longestOptionTermLength(s,i){return i.visibleOptions(s).reduce((o,l)=>Math.max(o,this.displayWidth(i.styleOptionTerm(i.optionTerm(l)))),0)}longestGlobalOptionTermLength(s,i){return i.visibleGlobalOptions(s).reduce((o,l)=>Math.max(o,this.displayWidth(i.styleOptionTerm(i.optionTerm(l)))),0)}longestArgumentTermLength(s,i){return i.visibleArguments(s).reduce((o,l)=>Math.max(o,this.displayWidth(i.styleArgumentTerm(i.argumentTerm(l)))),0)}commandUsage(s){let i=s._name;s._aliases[0]&&(i=i+"|"+s._aliases[0]);let o="";for(let l=s.parent;l;l=l.parent)o=l.name()+" "+o;return o+i+" "+s.usage()}commandDescription(s){return s.description()}subcommandDescription(s){return s.summary()||s.description()}optionDescription(s){const i=[];if(s.argChoices&&i.push(`choices: ${s.argChoices.map(o=>JSON.stringify(o)).join(", ")}`),s.defaultValue!==void 0&&(s.required||s.optional||s.isBoolean()&&typeof s.defaultValue=="boolean")&&i.push(`default: ${s.defaultValueDescription||JSON.stringify(s.defaultValue)}`),s.presetArg!==void 0&&s.optional&&i.push(`preset: ${JSON.stringify(s.presetArg)}`),s.envVar!==void 0&&i.push(`env: ${s.envVar}`),i.length>0){const o=`(${i.join(", ")})`;return s.description?`${s.description} ${o}`:o}return s.description}argumentDescription(s){const i=[];if(s.argChoices&&i.push(`choices: ${s.argChoices.map(o=>JSON.stringify(o)).join(", ")}`),s.defaultValue!==void 0&&i.push(`default: ${s.defaultValueDescription||JSON.stringify(s.defaultValue)}`),i.length>0){const o=`(${i.join(", ")})`;return s.description?`${s.description} ${o}`:o}return s.description}formatItemList(s,i,o){return i.length===0?[]:[o.styleTitle(s),...i,""]}groupItems(s,i,o){const l=new Map;return s.forEach(d=>{const g=o(d);l.has(g)||l.set(g,[])}),i.forEach(d=>{const g=o(d);l.has(g)||l.set(g,[]),l.get(g).push(d)}),l}formatHelp(s,i){const o=i.padWidth(s,i),l=i.helpWidth??80;function d(A,I){return i.formatItem(A,o,I,i)}let g=[`${i.styleTitle("Usage:")} ${i.styleUsage(i.commandUsage(s))}`,""];const E=i.commandDescription(s);E.length>0&&(g=g.concat([i.boxWrap(i.styleCommandDescription(E),l),""]));const C=i.visibleArguments(s).map(A=>d(i.styleArgumentTerm(i.argumentTerm(A)),i.styleArgumentDescription(i.argumentDescription(A))));if(g=g.concat(this.formatItemList("Arguments:",C,i)),this.groupItems(s.options,i.visibleOptions(s),A=>A.helpGroupHeading??"Options:").forEach((A,I)=>{const P=A.map(x=>d(i.styleOptionTerm(i.optionTerm(x)),i.styleOptionDescription(i.optionDescription(x))));g=g.concat(this.formatItemList(I,P,i))}),i.showGlobalOptions){const A=i.visibleGlobalOptions(s).map(I=>d(i.styleOptionTerm(i.optionTerm(I)),i.styleOptionDescription(i.optionDescription(I))));g=g.concat(this.formatItemList("Global Options:",A,i))}return this.groupItems(s.commands,i.visibleCommands(s),A=>A.helpGroup()||"Commands:").forEach((A,I)=>{const P=A.map(x=>d(i.styleSubcommandTerm(i.subcommandTerm(x)),i.styleSubcommandDescription(i.subcommandDescription(x))));g=g.concat(this.formatItemList(I,P,i))}),g.join(`
2
- `)}displayWidth(s){return p(s).length}styleTitle(s){return s}styleUsage(s){return s.split(" ").map(i=>i==="[options]"?this.styleOptionText(i):i==="[command]"?this.styleSubcommandText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleCommandText(i)).join(" ")}styleCommandDescription(s){return this.styleDescriptionText(s)}styleOptionDescription(s){return this.styleDescriptionText(s)}styleSubcommandDescription(s){return this.styleDescriptionText(s)}styleArgumentDescription(s){return this.styleDescriptionText(s)}styleDescriptionText(s){return s}styleOptionTerm(s){return this.styleOptionText(s)}styleSubcommandTerm(s){return s.split(" ").map(i=>i==="[options]"?this.styleOptionText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleSubcommandText(i)).join(" ")}styleArgumentTerm(s){return this.styleArgumentText(s)}styleOptionText(s){return s}styleArgumentText(s){return s}styleSubcommandText(s){return s}styleCommandText(s){return s}padWidth(s,i){return Math.max(i.longestOptionTermLength(s,i),i.longestGlobalOptionTermLength(s,i),i.longestSubcommandTermLength(s,i),i.longestArgumentTermLength(s,i))}preformatted(s){return/\n[^\S\r\n]/.test(s)}formatItem(s,i,o,l){const g=" ".repeat(2);if(!o)return g+s;const E=s.padEnd(i+s.length-l.displayWidth(s)),C=2,A=(this.helpWidth??80)-i-C-2;let I;return A<this.minWidthToWrap||l.preformatted(o)?I=o:I=l.boxWrap(o,A).replace(/\n/g,`
3
- `+" ".repeat(i+C)),g+E+" ".repeat(C)+I.replace(/\n/g,`
4
- ${g}`)}boxWrap(s,i){if(i<this.minWidthToWrap)return s;const o=s.split(/\r\n|\n/),l=/[\s]*[^\s]+/g,d=[];return o.forEach(g=>{const E=g.match(l);if(E===null){d.push("");return}let C=[E.shift()],A=this.displayWidth(C[0]);E.forEach(I=>{const P=this.displayWidth(I);if(A+P<=i){C.push(I),A+=P;return}d.push(C.join(""));const x=I.trimStart();C=[x],A=this.displayWidth(x)}),d.push(C.join(""))}),d.join(`
5
- `)}};function p(s){return s.replace(/\x1b\[\d*(;\d*)*m/g,"")}t.Help=c,t.stripColor=p})),Z=H((t=>{var{InvalidArgumentError:n}=W(),c=class{constructor(o,l){this.flags=o,this.description=l||"",this.required=o.includes("<"),this.optional=o.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(o),this.mandatory=!1;const d=i(o);this.short=d.shortFlag,this.long=d.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(o,l){return this.defaultValue=o,this.defaultValueDescription=l,this}preset(o){return this.presetArg=o,this}conflicts(o){return this.conflictsWith=this.conflictsWith.concat(o),this}implies(o){let l=o;return typeof o=="string"&&(l={[o]:!0}),this.implied=Object.assign(this.implied||{},l),this}env(o){return this.envVar=o,this}argParser(o){return this.parseArg=o,this}makeOptionMandatory(o=!0){return this.mandatory=!!o,this}hideHelp(o=!0){return this.hidden=!!o,this}_collectValue(o,l){return l===this.defaultValue||!Array.isArray(l)?[o]:(l.push(o),l)}choices(o){return this.argChoices=o.slice(),this.parseArg=(l,d)=>{if(!this.argChoices.includes(l))throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(l,d):l},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?s(this.name().replace(/^no-/,"")):s(this.name())}helpGroup(o){return this.helpGroupHeading=o,this}is(o){return this.short===o||this.long===o}isBoolean(){return!this.required&&!this.optional&&!this.negate}},p=class{constructor(o){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,o.forEach(l=>{l.negate?this.negativeOptions.set(l.attributeName(),l):this.positiveOptions.set(l.attributeName(),l)}),this.negativeOptions.forEach((l,d)=>{this.positiveOptions.has(d)&&this.dualOptions.add(d)})}valueFromOption(o,l){const d=l.attributeName();if(!this.dualOptions.has(d))return!0;const g=this.negativeOptions.get(d).presetArg,E=g!==void 0?g:!1;return l.negate===(E===o)}};function s(o){return o.split("-").reduce((l,d)=>l+d[0].toUpperCase()+d.slice(1))}function i(o){let l,d;const g=/^-[^-]$/,E=/^--[^-]/,C=o.split(/[ |,]+/).concat("guard");if(g.test(C[0])&&(l=C.shift()),E.test(C[0])&&(d=C.shift()),!l&&g.test(C[0])&&(l=C.shift()),!l&&E.test(C[0])&&(l=d,d=C.shift()),C[0].startsWith("-")){const A=C[0],I=`option creation failed due to '${A}' in option flags '${o}'`;throw/^-[^-][^-]/.test(A)?new Error(`${I}
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')`):g.test(A)?new Error(`${I}
9
- - too many short flags`):E.test(A)?new Error(`${I}
10
- - too many long flags`):new Error(`${I}
11
- - unrecognised flag format`)}if(l===void 0&&d===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return{shortFlag:l,longFlag:d}}t.Option=c,t.DualOptions=p})),Oe=H((t=>{var n=3;function c(s,i){if(Math.abs(s.length-i.length)>n)return Math.max(s.length,i.length);const o=[];for(let l=0;l<=s.length;l++)o[l]=[l];for(let l=0;l<=i.length;l++)o[0][l]=l;for(let l=1;l<=i.length;l++)for(let d=1;d<=s.length;d++){let g=1;s[d-1]===i[l-1]?g=0:g=1,o[d][l]=Math.min(o[d-1][l]+1,o[d][l-1]+1,o[d-1][l-1]+g),d>1&&l>1&&s[d-1]===i[l-2]&&s[d-2]===i[l-1]&&(o[d][l]=Math.min(o[d][l],o[d-2][l-2]+1))}return o[s.length][i.length]}function p(s,i){if(!i||i.length===0)return"";i=Array.from(new Set(i));const o=s.startsWith("--");o&&(s=s.slice(2),i=i.map(E=>E.slice(2)));let l=[],d=n;const g=.4;return i.forEach(E=>{if(E.length<=1)return;const C=c(s,E),A=Math.max(s.length,E.length);(A-C)/A>g&&(C<d?(d=C,l=[E]):C===d&&l.push(E))}),l.sort((E,C)=>E.localeCompare(C)),o&&(l=l.map(E=>`--${E}`)),l.length>1?`
12
- (Did you mean one of ${l.join(", ")}?)`:l.length===1?`
13
- (Did you mean ${l[0]}?)`:""}t.suggestSimilar=p})),ve=H((t=>{var n=require("node:events").EventEmitter,c=require("node:child_process"),p=require("node:path"),s=require("node:fs"),i=require("node:process"),{Argument:o,humanReadableArgName:l}=M(),{CommanderError:d}=W(),{Help:g,stripColor:E}=Y(),{Option:C,DualOptions:A}=Z(),{suggestSimilar:I}=Oe(),P=class ee extends n{constructor(e){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=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:r=>i.stdout.write(r),writeErr:r=>i.stderr.write(r),outputError:(r,a)=>a(r),getOutHelpWidth:()=>i.stdout.isTTY?i.stdout.columns:void 0,getErrHelpWidth:()=>i.stderr.isTTY?i.stderr.columns:void 0,getOutHasColors:()=>L()??(i.stdout.isTTY&&i.stdout.hasColors?.()),getErrHasColors:()=>L()??(i.stderr.isTTY&&i.stderr.hasColors?.()),stripColor:r=>E(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(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){const e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,a){let u=r,h=a;typeof u=="object"&&u!==null&&(h=u,u=null),h=h||{};const[,m,_]=e.match(/([^ ]+) *(.*)/),O=this.createCommand(m);return u&&(O.description(u),O._executableHandler=!0),h.isDefault&&(this._defaultCommandName=O._name),O._hidden=!!(h.noHelp||h.hidden),O._executableFile=h.executableFile||null,_&&O.arguments(_),this._registerCommand(O),O.parent=this,O.copyInheritedSettings(this),u?this:O}createCommand(e){return new ee(e)}createHelp(){return Object.assign(new g,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...e},this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._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=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new o(e,r)}argument(e,r,a,u){const h=this.createArgument(e,r);return typeof a=="function"?h.default(u).argParser(a):h.default(a),this.addArgument(h),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){const r=this.registeredArguments.slice(-1)[0];if(r?.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,e&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,a,u]=(e??"help [command]").match(/([^ ]+) *(.*)/),h=r??"display help for command",m=this.createCommand(a);return m.helpOption(!1),u&&m.arguments(u),h&&m.description(h),this._addImplicitHelpCommand=!0,this._helpCommand=m,(e||r)&&this._initCommandGroup(m),this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this._initCommandGroup(e),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){const a=["preSubcommand","preAction","postAction"];if(!a.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
15
- Expecting one of '${a.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,a){this._exitCallback&&this._exitCallback(new d(e,r,a)),i.exit(e)}action(e){const r=a=>{const u=this.registeredArguments.length,h=a.slice(0,u);return this._storeOptionsAsProperties?h[u]=this:h[u]=this.opts(),h.push(this),e.apply(this,h)};return this._actionHandler=r,this}createOption(e,r){return new C(e,r)}_callParseArg(e,r,a,u){try{return e.parseArg(r,a)}catch(h){if(h.code==="commander.invalidArgument"){const m=`${u} ${h.message}`;this.error(m,{exitCode:h.exitCode,code:h.code})}throw h}}_registerOption(e){const r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){const a=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${a}'
16
- - already used by option '${r.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){const r=u=>[u.name()].concat(u.aliases()),a=r(e).find(u=>this._findCommand(u));if(a){const u=r(this._findCommand(a)).join("|"),h=r(e).join("|");throw new Error(`cannot add command '${h}' as already have command '${u}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);const r=e.name(),a=e.attributeName();if(e.negate){const h=e.long.replace(/^--no-/,"--");this._findOption(h)||this.setOptionValueWithSource(a,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(a,e.defaultValue,"default");const u=(h,m,_)=>{h==null&&e.presetArg!==void 0&&(h=e.presetArg);const O=this.getOptionValue(a);h!==null&&e.parseArg?h=this._callParseArg(e,h,O,m):h!==null&&e.variadic&&(h=e._collectValue(h,O)),h==null&&(e.negate?h=!1:e.isBoolean()||e.optional?h=!0:h=""),this.setOptionValueWithSource(a,h,_)};return this.on("option:"+r,h=>{u(h,`error: option '${e.flags}' argument '${h}' is invalid.`,"cli")}),e.envVar&&this.on("optionEnv:"+r,h=>{u(h,`error: option '${e.flags}' value '${h}' from env '${e.envVar}' is invalid.`,"env")}),this}_optionEx(e,r,a,u,h){if(typeof r=="object"&&r instanceof C)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const m=this.createOption(r,a);if(m.makeOptionMandatory(!!e.mandatory),typeof u=="function")m.default(h).argParser(u);else if(u instanceof RegExp){const _=u;u=(O,S)=>{const f=_.exec(O);return f?f[0]:S},m.default(h).argParser(u)}else m.default(u);return this.addOption(m)}option(e,r,a,u){return this._optionEx({},e,r,a,u)}requiredOption(e,r,a,u){return this._optionEx({mandatory:!0},e,r,a,u)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,a){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=a,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(a=>{a.getOptionValueSource(e)!==void 0&&(r=a.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){i.versions?.electron&&(r.from="electron");const u=i.execArgv??[];(u.includes("-e")||u.includes("--eval")||u.includes("-p")||u.includes("--print"))&&(r.from="eval")}e===void 0&&(e=i.argv),this.rawArgs=e.slice();let a;switch(r.from){case void 0:case"node":this._scriptPath=e[1],a=e.slice(2);break;case"electron":i.defaultApp?(this._scriptPath=e[1],a=e.slice(2)):a=e.slice(1);break;case"user":a=e.slice(0);break;case"eval":a=e.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",a}parse(e,r){this._prepareForParse();const a=this._prepareUserArgs(e,r);return this._parseCommand([],a),this}async parseAsync(e,r){this._prepareForParse();const a=this._prepareUserArgs(e,r);return await this._parseCommand([],a),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(e,r,a){if(s.existsSync(e))return;const u=`'${e}' does not exist
18
- - if '${a}' 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(u)}_executeSubCommand(e,r){r=r.slice();let a=!1;const u=[".js",".ts",".tsx",".mjs",".cjs"];function h(f,v){const T=p.resolve(f,v);if(s.existsSync(T))return T;if(u.includes(p.extname(v)))return;const K=u.find(he=>s.existsSync(`${T}${he}`));if(K)return`${T}${K}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let m=e._executableFile||`${this._name}-${e._name}`,_=this._executableDir||"";if(this._scriptPath){let f;try{f=s.realpathSync(this._scriptPath)}catch{f=this._scriptPath}_=p.resolve(p.dirname(f),_)}if(_){let f=h(_,m);if(!f&&!e._executableFile&&this._scriptPath){const v=p.basename(this._scriptPath,p.extname(this._scriptPath));v!==this._name&&(f=h(_,`${v}-${e._name}`))}m=f||m}a=u.includes(p.extname(m));let O;i.platform!=="win32"?a?(r.unshift(m),r=x(i.execArgv).concat(r),O=c.spawn(i.argv[0],r,{stdio:"inherit"})):O=c.spawn(m,r,{stdio:"inherit"}):(this._checkForMissingExecutable(m,_,e._name),r.unshift(m),r=x(i.execArgv).concat(r),O=c.spawn(i.execPath,r,{stdio:"inherit"})),O.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{i.on(f,()=>{O.killed===!1&&O.exitCode===null&&O.kill(f)})});const S=this._exitCallback;O.on("close",f=>{f=f??1,S?S(new d(f,"commander.executeSubCommandAsync","(close)")):i.exit(f)}),O.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(m,_,e._name);else if(f.code==="EACCES")throw new Error(`'${m}' not executable`);if(!S)i.exit(1);else{const v=new d(1,"commander.executeSubCommandAsync","(error)");v.nestedError=f,S(v)}}),this.runningCommand=O}_dispatchSubcommand(e,r,a){const u=this._findCommand(e);u||this.help({error:!0}),u._prepareForParse();let h;return h=this._chainOrCallSubCommandHook(h,u,"preSubcommand"),h=this._chainOrCall(h,()=>{if(u._executableHandler)this._executeSubCommand(u,r.concat(a));else return u._parseCommand(r,a)}),h}_dispatchHelpCommand(e){e||this.help();const r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const e=(a,u,h)=>{let m=u;if(u!==null&&a.parseArg){const _=`error: command-argument value '${u}' is invalid for argument '${a.name()}'.`;m=this._callParseArg(a,u,h,_)}return m};this._checkNumberOfArguments();const r=[];this.registeredArguments.forEach((a,u)=>{let h=a.defaultValue;a.variadic?u<this.args.length?(h=this.args.slice(u),a.parseArg&&(h=h.reduce((m,_)=>e(a,_,m),a.defaultValue))):h===void 0&&(h=[]):u<this.args.length&&(h=this.args[u],a.parseArg&&(h=e(a,h,a.defaultValue))),r[u]=h}),this.processedArgs=r}_chainOrCall(e,r){return e?.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let a=e;const u=[];return this._getCommandAndAncestors().reverse().filter(h=>h._lifeCycleHooks[r]!==void 0).forEach(h=>{h._lifeCycleHooks[r].forEach(m=>{u.push({hookedCommand:h,callback:m})})}),r==="postAction"&&u.reverse(),u.forEach(h=>{a=this._chainOrCall(a,()=>h.callback(h.hookedCommand,this))}),a}_chainOrCallSubCommandHook(e,r,a){let u=e;return this._lifeCycleHooks[a]!==void 0&&this._lifeCycleHooks[a].forEach(h=>{u=this._chainOrCall(u,()=>h(this,r))}),u}_parseCommand(e,r){const a=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(a.operands),r=a.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(a.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const u=()=>{a.unknown.length>0&&this.unknownOption(a.unknown[0])},h=`command:${this.name()}`;if(this._actionHandler){u(),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(h,e,r)})),m=this._chainOrCallHooks(m,"postAction"),m}if(this.parent?.listenerCount(h))u(),this._processArguments(),this.parent.emit(h,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(u(),this._processArguments())}else this.commands.length?(u(),this.help({error:!0})):(u(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){const e=this.options.filter(r=>{const a=r.attributeName();return this.getOptionValue(a)===void 0?!1:this.getOptionValueSource(a)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{const a=e.find(u=>r.conflictsWith.includes(u.attributeName()));a&&this._conflictingOption(r,a)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){const r=[],a=[];let u=r;function h(f){return f.length>1&&f[0]==="-"}const m=f=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(f)?!this._getCommandAndAncestors().some(v=>v.options.map(T=>T.short).some(T=>/^-\d$/.test(T))):!1;let _=null,O=null,S=0;for(;S<e.length||O;){const f=O??e[S++];if(O=null,f==="--"){u===a&&u.push(f),u.push(...e.slice(S));break}if(_&&(!h(f)||m(f))){this.emit(`option:${_.name()}`,f);continue}if(_=null,h(f)){const v=this._findOption(f);if(v){if(v.required){const T=e[S++];T===void 0&&this.optionMissingArgument(v),this.emit(`option:${v.name()}`,T)}else if(v.optional){let T=null;S<e.length&&(!h(e[S])||m(e[S]))&&(T=e[S++]),this.emit(`option:${v.name()}`,T)}else this.emit(`option:${v.name()}`);_=v.variadic?v:null;continue}}if(f.length>2&&f[0]==="-"&&f[1]!=="-"){const v=this._findOption(`-${f[1]}`);if(v){v.required||v.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${v.name()}`,f.slice(2)):(this.emit(`option:${v.name()}`),O=`-${f.slice(2)}`);continue}}if(/^--[^=]+=/.test(f)){const v=f.indexOf("="),T=this._findOption(f.slice(0,v));if(T&&(T.required||T.optional)){this.emit(`option:${T.name()}`,f.slice(v+1));continue}}if(u===r&&h(f)&&!(this.commands.length===0&&m(f))&&(u=a),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&a.length===0){if(this._findCommand(f)){r.push(f),a.push(...e.slice(S));break}else if(this._getHelpCommand()&&f===this._getHelpCommand().name()){r.push(f,...e.slice(S));break}else if(this._defaultCommandName){a.push(f,...e.slice(S));break}}if(this._passThroughOptions){u.push(f,...e.slice(S));break}u.push(f)}return{operands:r,unknown:a}}opts(){if(this._storeOptionsAsProperties){const e={},r=this.options.length;for(let a=0;a<r;a++){const u=this.options[a].attributeName();e[u]=u===this._versionOptionName?this._version:this[u]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
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 a=r||{},u=a.exitCode||1,h=a.code||"commander.error";this._exit(u,h,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in i.env){const r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,i.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){const e=new A(this.options),r=a=>this.getOptionValue(a)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(a));this.options.filter(a=>a.implied!==void 0&&r(a.attributeName())&&e.valueFromOption(this.getOptionValue(a.attributeName()),a)).forEach(a=>{Object.keys(a.implied).filter(u=>!r(u)).forEach(u=>{this.setOptionValueWithSource(u,a.implied[u],"implied")})})}missingArgument(e){const r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){const r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){const r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){const a=m=>{const _=m.attributeName(),O=this.getOptionValue(_),S=this.options.find(v=>v.negate&&_===v.attributeName()),f=this.options.find(v=>!v.negate&&_===v.attributeName());return S&&(S.presetArg===void 0&&O===!1||S.presetArg!==void 0&&O===S.presetArg)?S:f||m},u=m=>{const _=a(m),O=_.attributeName();return this.getOptionValueSource(O)==="env"?`environment variable '${_.envVar}'`:`option '${_.flags}'`},h=`error: ${u(e)} cannot be used with ${u(r)}`;this.error(h,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let u=[],h=this;do{const m=h.createHelp().visibleOptions(h).filter(_=>_.long).map(_=>_.long);u=u.concat(m),h=h.parent}while(h&&!h._enablePositionalOptions);r=I(e,u)}const a=`error: unknown option '${e}'${r}`;this.error(a,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;const r=this.registeredArguments.length,a=r===1?"":"s",u=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${a} but got ${e.length}.`;this.error(u,{code:"commander.excessArguments"})}unknownCommand(){const e=this.args[0];let r="";if(this._showSuggestionAfterError){const u=[];this.createHelp().visibleCommands(this).forEach(h=>{u.push(h.name()),h.alias()&&u.push(h.alias())}),r=I(e,u)}const a=`error: unknown command '${e}'${r}`;this.error(a,{code:"commander.unknownCommand"})}version(e,r,a){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",a=a||"output the version number";const u=this.createOption(r,a);return this._versionOptionName=u.attributeName(),this._registerOption(u),this.on("option:"+u.name(),()=>{this._outputConfiguration.writeOut(`${e}
24
- `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===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]),e===r._name)throw new Error("Command alias can't be the same as its name");const a=this.parent?._findCommand(e);if(a){const u=[a.name()].concat(a.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${u}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;const r=this.registeredArguments.map(a=>l(a));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=p.basename(e,p.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){const r=this.createHelp(),a=this._getOutputContext(e);r.prepareContext({error:a.error,helpWidth:a.helpWidth,outputHasColors:a.hasColors});const u=r.formatHelp(this,r);return a.hasColors?u:this._outputConfiguration.stripColor(u)}_getOutputContext(e){e=e||{};const r=!!e.error;let a,u,h;return r?(a=_=>this._outputConfiguration.writeErr(_),u=this._outputConfiguration.getErrHasColors(),h=this._outputConfiguration.getErrHelpWidth()):(a=_=>this._outputConfiguration.writeOut(_),u=this._outputConfiguration.getOutHasColors(),h=this._outputConfiguration.getOutHelpWidth()),{error:r,write:_=>(u||(_=this._outputConfiguration.stripColor(_)),a(_)),hasColors:u,helpWidth:h}}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);const a=this._getOutputContext(e),u={error:a.error,write:a.write,command:this};this._getCommandAndAncestors().reverse().forEach(m=>m.emit("beforeAllHelp",u)),this.emit("beforeHelp",u);let h=this.helpInformation({error:a.error});if(r&&(h=r(h),typeof h!="string"&&!Buffer.isBuffer(h)))throw new Error("outputHelp callback must return a string or a Buffer");a.write(h),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",u),this._getCommandAndAncestors().forEach(m=>m.emit("afterAllHelp",u))}helpOption(e,r){return typeof e=="boolean"?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??"-h, --help",r??"display help for command"),(e||r)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let r=Number(i.exitCode??0);r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){const a=["beforeAll","before","after","afterAll"];if(!a.includes(e))throw new Error(`Unexpected value for position to addHelpText.
25
- Expecting one of '${a.join("', '")}'`);const u=`${e}Help`;return this.on(u,h=>{let m;typeof r=="function"?m=r({error:h.error,command:h.command}):m=r,m&&h.write(`${m}
26
- `)}),this}_outputHelpIfRequested(e){const r=this._getHelpOption();r&&e.find(a=>r.is(a))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function x(ue){return ue.map(e=>{if(!e.startsWith("--inspect"))return e;let r,a="127.0.0.1",u="9229",h;return(h=e.match(/^(--inspect(-brk)?)$/))!==null?r=h[1]:(h=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=h[1],/^\d+$/.test(h[3])?u=h[3]:a=h[3]):(h=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=h[1],a=h[3],u=h[4]),r&&u!=="0"?`${r}=${a}:${parseInt(u)+1}`:e})}function L(){if(i.env.NO_COLOR||i.env.FORCE_COLOR==="0"||i.env.FORCE_COLOR==="false")return!1;if(i.env.FORCE_COLOR||i.env.CLICOLOR_FORCE!==void 0)return!0}t.Command=P,t.useColor=L})),Ce=H((t=>{var{Argument:n}=M(),{Command:c}=ve(),{CommanderError:p,InvalidArgumentError:s}=W(),{Help:i}=Y(),{Option:o}=Z();t.program=new c,t.createCommand=l=>new c(l),t.createOption=(l,d)=>new o(l,d),t.createArgument=(l,d)=>new n(l,d),t.Command=c,t.Option=o,t.Argument=n,t.Help=i,t.CommanderError=p,t.InvalidArgumentError=s,t.InvalidOptionArgumentError=s})),Ae=_e(Ce(),1),{program:at,createCommand:lt,createArgument:ut,createOption:ht,CommanderError:be,InvalidArgumentError:ct,InvalidOptionArgumentError:pt,Command:Ee,Argument:dt,Option:mt,Help:ft}=Ae.default;function V(t){return`${JSON.stringify(t,null,2)}
27
- `}var ye=(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 te(t){return t.replace(/\s+/g," ").trim()}function Se(t,n){const c=n.map(i=>t.map(o=>te(o.value(i)))),p=t.map((i,o)=>{const l=c.map(d=>d[o].length);return Math.max(i.header.length,...l)}),s=i=>i.map((o,l)=>o.padEnd(p[l])).join(" ").trimEnd();return[s(t.map(i=>i.header)),s(p.map(i=>"-".repeat(i))),...c.map(s)].join(`
28
- `)}function Ie(t){const n=t.filter(([,p])=>p!==void 0&&p!==""),c=Math.max(...n.map(([p])=>p.length));return`${n.map(([p,s])=>`${p.padEnd(c)} ${te(s??"")}`).join(`
29
- `)}
30
- `}function Q(t){return t?.value?.trim()??""}function ie(t){return{sessionId:Q(t.sessionId),title:t.title,type:t.type,status:t.status,projectId:Q(t.projectId),proposalName:t.proposalName??void 0,archived:t.status===ye.ARCHIVED,lastActiveAt:t.lastActiveAt??void 0,enableIndependentWorkspace:t.enableIndependentWorkspace,baseBranch:t.baseBranch??void 0}}function Te(t){return{sessions:t.sessions.map(ie)}}function we(t){return t.length===0?`No proposal sessions found.
31
- `:`Proposal sessions (${t.length})
32
- ${Se([{header:"Session ID",value:n=>n.sessionId},{header:"Title",value:n=>n.title},{header:"Status",value:n=>n.status},{header:"Project ID",value:n=>n.projectId},{header:"Archived",value:n=>n.archived?"yes":"no"}],t)}
33
- `}function xe(t,n=[]){return Ie([["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],...n])}var b={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 N(t){const n=t?.trim();return n||void 0}function Pe(t={},n=process.env){return{baseUrl:N(t.baseUrl)??N(n.HAGI_API_BASE_URL)??"http://127.0.0.1:35168",token:N(t.token)??N(n.HAGI_API_TOKEN),lang:N(t.lang)??N(n.HAGI_API_LANG)}}function $e(t={},n=process.env){const c=Pe(t,n);return b.BASE=c.baseUrl,b.WITH_CREDENTIALS=!1,b.CREDENTIALS="omit",b.TOKEN=c.token,b.HEADERS=c.lang?{"Accept-Language":c.lang}:void 0,c}var B=class extends Error{url;status;statusText;body;request;constructor(t,n,c){super(c),this.name="ApiError",this.url=n.url,this.status=n.status,this.statusText=n.statusText,this.body=n.body,this.request=t}},He=class extends Error{constructor(t){super(t),this.name="CancelError"}get isCancelled(){return!0}},Ne=class{#t;#i;#e;#s;#n;#o;#r;constructor(t){this.#t=!1,this.#i=!1,this.#e=!1,this.#s=[],this.#n=new Promise((n,c)=>{this.#o=n,this.#r=c;const p=o=>{this.#t||this.#i||this.#e||(this.#t=!0,this.#o&&this.#o(o))},s=o=>{this.#t||this.#i||this.#e||(this.#i=!0,this.#r&&this.#r(o))},i=o=>{this.#t||this.#i||this.#e||this.#s.push(o)};return Object.defineProperty(i,"isResolved",{get:()=>this.#t}),Object.defineProperty(i,"isRejected",{get:()=>this.#i}),Object.defineProperty(i,"isCancelled",{get:()=>this.#e}),t(p,s,i)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(t,n){return this.#n.then(t,n)}catch(t){return this.#n.catch(t)}finally(t){return this.#n.finally(t)}cancel(){if(!(this.#t||this.#i||this.#e)){if(this.#e=!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 He("Request aborted"))}}get isCancelled(){return this.#e}},J=t=>t!=null,k=t=>typeof t=="string",U=t=>k(t)&&t!=="",z=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]),se=t=>t instanceof FormData,je=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ve=t=>{const n=[],c=(s,i)=>{n.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(i))}`)},p=(s,i)=>{J(i)&&(Array.isArray(i)?i.forEach(o=>{p(s,o)}):typeof i=="object"?Object.entries(i).forEach(([o,l])=>{p(`${s}[${o}]`,l)}):c(s,i))};return Object.entries(t).forEach(([s,i])=>{p(s,i)}),n.length>0?`?${n.join("&")}`:""},ke=(t,n)=>{const c=t.ENCODE_PATH||encodeURI,p=n.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(i,o)=>n.path?.hasOwnProperty(o)?c(String(n.path[o])):i),s=`${t.BASE}${p}`;return n.query?`${s}${Ve(n.query)}`:s},De=t=>{if(t.formData){const n=new FormData,c=(p,s)=>{k(s)||z(s)?n.append(p,s):n.append(p,JSON.stringify(s))};return Object.entries(t.formData).filter(([p,s])=>J(s)).forEach(([p,s])=>{Array.isArray(s)?s.forEach(i=>c(p,i)):c(p,s)}),n}},R=async(t,n)=>typeof n=="function"?n(t):n,Fe=async(t,n)=>{const[c,p,s,i]=await Promise.all([R(n,t.TOKEN),R(n,t.USERNAME),R(n,t.PASSWORD),R(n,t.HEADERS)]),o=Object.entries({Accept:"application/json",...i,...n.headers}).filter(([l,d])=>J(d)).reduce((l,[d,g])=>({...l,[d]:String(g)}),{});return U(c)&&(o.Authorization=`Bearer ${c}`),U(p)&&U(s)&&(o.Authorization=`Basic ${je(`${p}:${s}`)}`),n.body!==void 0&&(n.mediaType?o["Content-Type"]=n.mediaType:z(n.body)?o["Content-Type"]=n.body.type||"application/octet-stream":k(n.body)?o["Content-Type"]="text/plain":se(n.body)||(o["Content-Type"]="application/json")),new Headers(o)},Re=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):k(t.body)||z(t.body)||se(t.body)?t.body:JSON.stringify(t.body)},Ge=async(t,n,c,p,s,i,o)=>{const l=new AbortController,d={headers:i,body:p??s,method:n.method,signal:l.signal};return t.WITH_CREDENTIALS&&(d.credentials=t.CREDENTIALS),o(()=>l.abort()),await fetch(c,d)},We=(t,n)=>{if(n){const c=t.headers.get(n);if(k(c))return c}},qe=async t=>{if(t.status!==204)try{const n=t.headers.get("Content-Type");if(n)return["application/json","application/problem+json"].some(c=>n.toLowerCase().startsWith(c))?await t.json():await t.text()}catch(n){console.error(n)}},Le=(t,n)=>{const c={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[n.status];if(c)throw new B(t,n,c);if(!n.ok)throw new B(t,n,`Generic Error: status: ${n.status??"unknown"}; status text: ${n.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(n.body,null,2)}catch{return}})()}`)},y=(t,n)=>new Ne(async(c,p,s)=>{try{const i=ke(t,n),o=De(n),l=Re(n),d=await Fe(t,n);if(!s.isCancelled){const g=await Ge(t,n,i,l,o,d,s),E=await qe(g),C=We(g,n.responseHeader),A={url:i,ok:g.ok,status:g.status,statusText:g.statusText,body:C??E};Le(n,A),c(A.body)}}catch(i){p(i)}}),j=class{static postApiSessionsAutoTask({requestBody:t}){return y(b,{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 y(b,{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 y(b,{method:"POST",url:"/api/Sessions/chat",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:t}){return y(b,{method:"POST",url:"/api/Sessions",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:t,activeOnly:n,includeArchived:c,projectId:p,projectIds:s}){return y(b,{method:"GET",url:"/api/Sessions",query:{type:t,activeOnly:n,includeArchived:c,projectId:p,projectIds:s}})}static getApiSessions1({sessionId:t}){return y(b,{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:n}){return y(b,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:t},body:n,mediaType:"application/json"})}static deleteApiSessions({sessionId:t,deleteFiles:n=!1}){return y(b,{method:"DELETE",url:"/api/Sessions/{sessionId}",path:{sessionId:t},query:{deleteFiles:n},errors:{404:"Session not found",500:"Failed to delete session"}})}static postApiSessionsCancel({sessionId:t}){return y(b,{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 y(b,{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:n}){return y(b,{method:"DELETE",url:"/api/Sessions/{sessionId}/queue/{queueIndex}",path:{sessionId:t,queueIndex:n},errors:{400:"Invalid queue index",404:"Session not found",500:"Failed to cancel message"}})}static postApiSessionsMessages({sessionId:t,requestBody:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},body:n,mediaType:"application/json"})}static postApiSessionsAnnotations({sessionId:t,requestBody:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/annotations",path:{sessionId:t},body:n,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:t}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal-name",path:{sessionId:t},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:t,requestBody:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-description",path:{sessionId:t},body:n,mediaType:"application/json",errors:{400:"Invalid request or empty description",404:"Session not found",500:"Failed to start optimization task"}})}static postApiSessionsOptimizeTitle({sessionId:t}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-title",path:{sessionId:t},errors:{400:"Invalid request or session has no description",404:"Session not found",500:"Failed to optimize title"}})}static postApiSessionsGenerateProposal({sessionId:t,requestBody:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal",path:{sessionId:t},body:n,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:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/archive",path:{sessionId:t},body:n,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:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/execute-proposal",path:{sessionId:t},body:n,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 y(b,{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 y(b,{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 y(b,{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 y(b,{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:n}){return y(b,{method:"GET",url:"/api/Sessions/{sessionId}/openspec-file",path:{sessionId:t},query:{relativePath:n},errors:{404:"Session not found or file not found",500:"Failed to read file"}})}static postApiSessionsUpdateCessionId({sessionId:t}){return y(b,{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:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/open-in-vscode",path:{sessionId:t},query:{subPath:n},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:n}){return y(b,{method:"POST",url:"/api/Sessions/{sessionId}/correct-proposal-name",path:{sessionId:t},body:n,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 y(b,{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"}})}};function Ue(){return{listSessions:t=>j.getApiSessions(t),createSession:t=>j.postApiSessions({requestBody:t}),generateProposalName:t=>j.postApiSessionsGenerateProposalName({sessionId:t}),generateProposal:(t,n)=>j.postApiSessionsGenerateProposal({sessionId:t,requestBody:n}),executeProposal:(t,n)=>j.postApiSessionsExecuteProposal({sessionId:t,requestBody:n})}}function $(t){const n=t?.trim();return n||void 0}function re(t=process.env,n={stdout:c=>{process.stdout.write(c)},stderr:c=>{process.stderr.write(c)}}){return{api:Ue(),env:t,io:n}}function Be(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 D(t){return t.option("--json","Emit deterministic JSON instead of human-readable text.")}function F(t,n){const c=t.optsWithGlobals();return{api:n.api,env:n.env,io:n.io,outputJson:c.json===!0,runtime:$e({baseUrl:c.baseUrl,token:c.token,lang:c.lang},n.env)}}var w={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},q=class extends Error{constructor(t){super(t),this.name="CliUsageError"}};function Me(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function G(t,n){const c=Me(t)?.[n];return typeof c=="string"&&c.trim()?c.trim():void 0}function Je(t){return t.includes("fetch failed")||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("Failed to parse URL")}function ze(t){switch(t){case 400:return w.HTTP_BAD_REQUEST;case 401:return w.HTTP_UNAUTHORIZED;case 403:return w.HTTP_FORBIDDEN;case 404:return w.HTTP_NOT_FOUND;case 409:return w.HTTP_CONFLICT;default:return t&&t>=400&&t<500?w.HTTP_CLIENT_ERROR:t&&t>=500?w.HTTP_SERVER_ERROR:w.UNKNOWN}}function Ke(t){if(t instanceof q)return{exitCode:w.USAGE,message:t.message};if(t instanceof B){const n=G(t.body,"error")??G(t.body,"message")??t.message;return{exitCode:ze(t.status),status:t.status,message:n,errorCode:G(t.body,"errorCode"),correlationId:G(t.body,"correlationId"),details:t.body}}return t instanceof Error?{exitCode:Je(t.message)?w.TRANSPORT:w.UNKNOWN,message:t.message}:{exitCode:w.UNKNOWN,message:String(t)}}function ne(t,n={}){if(n.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)}
34
- `;const c=[t.status?`status=${t.status}`:void 0,t.errorCode?`errorCode=${t.errorCode}`:void 0,t.correlationId?`correlationId=${t.correlationId}`:void 0].filter(Boolean),p=c.length>0?` (${c.join(", ")})`:"";return`${t.message}${p}
35
- `}var oe=(function(t){return t.CHAT="Chat",t.PROPOSAL="Proposal",t})({}),ae="New Proposal";function Qe(t){const n=$(t.title);if(n)return n;if(t.defaultTitle)return ae;throw new q("Provide --title or pass --default-title to use the placeholder proposal title.")}function Xe(t,n){D(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 (${ae}).`).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(p){const s=F(this,n),i=Qe(p),o=ie(await s.api.createSession({title:i,chiefComplaint:p.chiefComplaint.trim(),originalChiefComplaint:$(p.originalChiefComplaint),type:oe.PROPOSAL,projectId:p.projectId.trim(),enableIndependentWorkspace:p.enableIndependentWorkspace?!0:void 0,baseBranch:$(p.baseBranch),isDefaultTitle:!!p.defaultTitle})),l=`hagi proposal generate-name --session-id ${o.sessionId}`;if(s.outputJson){s.io.stdout(V({session:o,nextCommand:l}));return}s.io.stdout(`Proposal session created
36
- ${xe(o,[["next",l]])}`)})}function Ye(t,n){D(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(p){const s=F(this,n),i=p.sessionId.trim(),o=$(p.heroId),l=await s.api.executeProposal(i,{heroId:o});if(s.outputJson){s.io.stdout(V({sessionId:i,message:l.message,requested:{heroId:o}}));return}s.io.stdout(`Proposal execution started
37
- sessionId ${i}
38
- message ${l.message}
39
- `)})}function Ze(t){if(t.enableExploreMode&&t.disableExploreMode)throw new q("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(t.enableExploreMode)return!0;if(t.disableExploreMode)return!1}function et(t,n){D(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(p){const s=F(this,n),i=p.sessionId.trim(),o=Ze(p),l=await s.api.generateProposal(i,{enableExploreMode:o,heroId:$(p.heroId)}),d=`hagi proposal execute --session-id ${i}`;if(s.outputJson){s.io.stdout(V({sessionId:i,message:l.message,requested:{enableExploreMode:o,heroId:$(p.heroId)},nextCommand:d}));return}s.io.stdout(`Proposal generation started
40
- sessionId ${i}
41
- message ${l.message}
42
- next Wait for the session to reach Reviewing, then run ${d}
43
- `)})}function tt(t,n){D(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(p){const s=F(this,n),i=await s.api.generateProposalName(p.sessionId.trim()),o=`hagi proposal generate --session-id ${p.sessionId.trim()}`;if(s.outputJson){s.io.stdout(V({sessionId:p.sessionId.trim(),proposalName:i.proposalName,nextCommand:o}));return}s.io.stdout(`Proposal name generated
44
- sessionId ${p.sessionId.trim()}
45
- proposalName ${i.proposalName}
46
- next ${o}
47
- `)})}function it(t,n){D(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(p){if(p.projectId&&p.projectIds?.length)throw new q("Use either --project-id or --project-ids, not both.");const s=F(this,n),i=Te(await s.api.listSessions({type:oe.PROPOSAL,projectId:$(p.projectId),projectIds:p.projectIds?.map($).filter(Boolean),activeOnly:p.activeOnly?!0:void 0,includeArchived:p.includeArchived?!0:void 0}));if(s.outputJson){s.io.stdout(V(i));return}s.io.stdout(we(i.sessions))})}function st(t,n){const c=t.command("proposal").description("Manage proposal sessions through backend session APIs.");it(c,n),Xe(c,n),tt(c,n),et(c,n),Ye(c,n)}function rt(t){return t.includes("--json")}function le(t=re(),n=!1){const c=new Ee;return c.name("hagi").description("HagiCode CLI for proposal session management.").showHelpAfterError().exitOverride(),c.configureOutput({writeOut:p=>{t.io.stdout(p)},writeErr:p=>{n||t.io.stderr(p)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),Be(c),st(c,t),c}function nt(t,n,c){return t.exitCode===0||t.code==="commander.helpDisplayed"||t.code==="commander.version"?0:(c&&n.io.stderr(ne({exitCode:w.USAGE,message:t.message},{json:!0})),w.USAGE)}async function ot(t=process.argv,n=re()){const c=rt(t),p=le(n,c);try{return await p.parseAsync([...t]),0}catch(s){if(s instanceof be)return nt(s,n,c);const i=Ke(s);return n.io.stderr(ne(i,{json:c})),i.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return w}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return le}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return ot}});