@hagicode/cli 0.1.0-dev.28.1.71f1989 → 0.1.0-dev.29.1.2b7f294

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 CHANGED
@@ -5,7 +5,7 @@
5
5
  [![license](https://img.shields.io/npm/l/%40hagicode%2Fcli?color=ffd43b)](https://www.npmjs.com/package/@hagicode/cli)
6
6
  [![Node.js](https://img.shields.io/badge/node-%3E%3D24.0.0-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
7
7
 
8
- `@hagicode/cli` provides the published `hagi` command, which lets you drive a HagiCode backend from a terminal, scripts, or an AI agent without opening the app. Manage projects, proposals (generate, execute, archive, and send), vaults and their files, chat sessions, AutoTasks, scheduled plans, and skills (local list, enable, disable and uninstall, gallery search and install, and trusted providers). Every command supports a shared `--json` output for scripting, and an embedded Hagi skill under [`skills/`](skills/) guides agent workflows.
8
+ `@hagicode/cli` provides the published `hagi` command, which lets you drive a HagiCode backend from a terminal, scripts, or an AI agent without opening the app. Manage projects, proposals (generate, execute, archive, and send), vaults and their files, chat sessions, HagiTasks, scheduled plans, and skills (local list, enable, disable and uninstall, gallery search and install, and trusted providers). Every command supports a shared `--json` output for scripting, and an embedded Hagi skill under [`skills/`](skills/) guides agent workflows.
9
9
 
10
10
  ## Requirements
11
11
 
@@ -47,7 +47,8 @@ hagi project list --json
47
47
  hagi proposal list --json
48
48
  hagi vault list --json
49
49
  hagi chat list --json
50
- hagi autotask create --title "Auto commit" --project-id <project-id> --prompt-id auto-compose-commit.en-US
50
+ hagi hagitask list
51
+ hagi hagitask create --title "Auto commit" --project-id <project-id> --prompt-id auto-compose-commit.en-US
51
52
  ```
52
53
 
53
54
  ## Embedded Skills
@@ -112,7 +113,7 @@ hagi
112
113
  |-- vault list | create | update | delete
113
114
  | `-- files list | preview
114
115
  |-- chat list | create | archive | delete | send
115
- |-- autotask create | send
116
+ |-- hagitask list | schema | create | send
116
117
  |-- plan list | get | create | update | enable | disable | delete | run
117
118
  `-- skills local list | enable | disable | uninstall
118
119
  gallery search | detail | install
@@ -310,31 +311,59 @@ hagi chat archive --session-id "$CHAT_ID"
310
311
  hagi chat delete --session-id "$CHAT_ID"
311
312
  ```
312
313
 
313
- ## AutoTask Commands
314
+ ## HagiTask Commands
314
315
 
315
- Create an AutoTask session with package-first automation flags. The new id is read from `session.sessionId`:
316
+ A HagiTask is a preset task with a structured input. Read its schema first, write the input from the schema, then create the session. `hagitask list` shows the active tasks:
316
317
 
317
318
  ```bash
318
- AUTOTASK_ID=$(hagi autotask create \
319
+ hagi hagitask list
320
+ hagi hagitask list --json
321
+ ```
322
+
323
+ `hagitask schema` shows one task's target scope, commands, parameters, requirements and scenes. Each required parameter is marked `yes`. The `--json` output adds the input JSON Schema and an example request body:
324
+
325
+ ```bash
326
+ hagi hagitask schema --task-id compose-commit
327
+ hagi hagitask schema --task-id compose-commit --json
328
+ ```
329
+
330
+ Write the input file. Its keys are the parameter keys the schema lists under `inputs`, plus the `targets` and `targetScopes` keys when the schema's scope lists targets. For example, `input.json` for a task with one required input:
331
+
332
+ ```json
333
+ {
334
+ "inputs": {
335
+ "commitScope": "cli"
336
+ }
337
+ }
338
+ ```
339
+
340
+ Create the session from that task and input. The new id is read from `session.sessionId`:
341
+
342
+ ```bash
343
+ HAGITASK_ID=$(hagi hagitask create \
319
344
  --title "Auto compose commit" \
320
345
  --project-id "$PROJECT_ID" \
321
- --prompt-id auto-compose-commit.en-US \
346
+ --task-id compose-commit \
347
+ --input input.json \
322
348
  --repository-path repos/cli \
323
349
  --need-push \
324
350
  --target-branch-mode new-custom \
325
351
  --target-branch-name feature/cli-completion \
326
- --script-key autotask.auto-compose-commit \
327
352
  --json | json_field '.session.sessionId')
328
353
  ```
329
354
 
330
- The backend must have a hero available for the prompt's script. Without one, `autotask create` fails with a 400 whose error is `no-executable-hero`.
355
+ Use `--prompt-id` instead of `--task-id` for a prompt template with no structured input. `--input` needs `--task-id`. Input is read from a file, or from stdin with `--input -`. The CLI only checks that the input is a JSON object. The backend checks the keys and values. It rejects a key that the schema does not list, and a missing required value. Its error is printed unchanged, and no session is reported as created. `--hero-selection-mode` takes `first` (the default) or `random`.
331
356
 
332
- Send a follow-up message to the AutoTask session:
357
+ The backend must have a hero available for the task's script. Without one, `hagitask create` fails with a 400 whose error is `no-executable-hero`.
358
+
359
+ Send a follow-up message to the HagiTask session:
333
360
 
334
361
  ```bash
335
- hagi autotask send --session-id "$AUTOTASK_ID" --content "Retry with a smaller diff"
362
+ hagi hagitask send --session-id "$HAGITASK_ID" --content "Retry with a smaller diff"
336
363
  ```
337
364
 
365
+ **Migration from AutoTask:** `hagi hagitask create` and `hagi hagitask send` replace `hagi autotask create` and `hagi autotask send`. There is no `autotask` alias, so an `autotask` command now fails as an unknown command. Read the task schema with `hagitask schema` to find the input keys that replace the old flags.
366
+
338
367
  ## Plan Commands
339
368
 
340
369
  A scheduled plan saves a proposal or HagiTask input with a schedule and an agent pool. The backend runs it on that schedule. `plan list` and `plan get` show the plans that exist:
@@ -0,0 +1,138 @@
1
+ var ut=Object.create,$e=Object.defineProperty,dt=Object.getOwnPropertyDescriptor,ct=Object.getOwnPropertyNames,pt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty,Q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),mt=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=ct(t),s=0,a=i.length,u;s<a;s++)u=i[s],!ht.call(e,u)&&u!==o&&$e(e,u,{get:(h=>t[h]).bind(null,u),enumerable:!(r=dt(t,u))||r.enumerable});return e},ft=(e,t,o)=>(o=e!=null?ut(pt(e)):{},mt(t||!e||!e.__esModule?$e(o,"default",{value:e,enumerable:!0}):o,e));let we=require("node:path"),gt=require("node:fs"),vt=require("node:os"),yt=require("node:fs/promises");var ue=Q((e=>{var t=class extends Error{constructor(r,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=r,this.nestedError=void 0}},o=class extends t{constructor(r){super(1,"commander.invalidArgument",r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};e.CommanderError=t,e.InvalidArgumentError=o})),ve=Q((e=>{var{InvalidArgumentError:t}=ue(),o=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,a)=>{if(!this.argChoices.includes(s))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(s,a):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(i){const s=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+s+">":"["+s+"]"}e.Argument=o,e.humanReadableArgName=r})),Ne=Q((e=>{var{humanReadableArgName:t}=ve(),o=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),a=i._getHelpCommand();return a&&!a._hidden&&s.push(a),this.sortSubcommands&&s.sort((u,h)=>u.name().localeCompare(h.name())),s}compareOptions(i,s){const a=u=>u.short?u.short.replace(/^-/,""):u.long.replace(/^--/,"");return a(i).localeCompare(a(s))}visibleOptions(i){const s=i.options.filter(u=>!u.hidden),a=i._getHelpOption();if(a&&!a.hidden){const u=a.short&&i._findOption(a.short),h=a.long&&i._findOption(a.long);!u&&!h?s.push(a):a.long&&!h?s.push(i.createOption(a.long,a.description)):a.short&&!u&&s.push(i.createOption(a.short,a.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const s=[];for(let a=i.parent;a;a=a.parent){const u=a.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(a=>t(a)).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((a,u)=>Math.max(a,this.displayWidth(s.styleSubcommandTerm(s.subcommandTerm(u)))),0)}longestOptionTermLength(i,s){return s.visibleOptions(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestGlobalOptionTermLength(i,s){return s.visibleGlobalOptions(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestArgumentTermLength(i,s){return s.visibleArguments(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleArgumentTerm(s.argumentTerm(u)))),0)}commandUsage(i){let s=i._name;i._aliases[0]&&(s=s+"|"+i._aliases[0]);let a="";for(let u=i.parent;u;u=u.parent)a=u.name()+" "+a;return a+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(a=>JSON.stringify(a)).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 a=`(${s.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}argumentDescription(i){const s=[];if(i.argChoices&&s.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&s.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),s.length>0){const a=`(${s.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}formatItemList(i,s,a){return s.length===0?[]:[a.styleTitle(i),...s,""]}groupItems(i,s,a){const u=new Map;return i.forEach(h=>{const m=a(h);u.has(m)||u.set(m,[])}),s.forEach(h=>{const m=a(h);u.has(m)||u.set(m,[]),u.get(m).push(h)}),u}formatHelp(i,s){const a=s.padWidth(i,s),u=s.helpWidth??80;function h(w,N){return s.formatItem(w,a,N,s)}let m=[`${s.styleTitle("Usage:")} ${s.styleUsage(s.commandUsage(i))}`,""];const P=s.commandDescription(i);P.length>0&&(m=m.concat([s.boxWrap(s.styleCommandDescription(P),u),""]));const _=s.visibleArguments(i).map(w=>h(s.styleArgumentTerm(s.argumentTerm(w)),s.styleArgumentDescription(s.argumentDescription(w))));if(m=m.concat(this.formatItemList("Arguments:",_,s)),this.groupItems(i.options,s.visibleOptions(i),w=>w.helpGroupHeading??"Options:").forEach((w,N)=>{const M=w.map(L=>h(s.styleOptionTerm(s.optionTerm(L)),s.styleOptionDescription(s.optionDescription(L))));m=m.concat(this.formatItemList(N,M,s))}),s.showGlobalOptions){const w=s.visibleGlobalOptions(i).map(N=>h(s.styleOptionTerm(s.optionTerm(N)),s.styleOptionDescription(s.optionDescription(N))));m=m.concat(this.formatItemList("Global Options:",w,s))}return this.groupItems(i.commands,s.visibleCommands(i),w=>w.helpGroup()||"Commands:").forEach((w,N)=>{const M=w.map(L=>h(s.styleSubcommandTerm(s.subcommandTerm(L)),s.styleSubcommandDescription(s.subcommandDescription(L))));m=m.concat(this.formatItemList(N,M,s))}),m.join(`
2
+ `)}displayWidth(i){return r(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,a,u){const m=" ".repeat(2);if(!a)return m+i;const P=i.padEnd(s+i.length-u.displayWidth(i)),_=2,w=(this.helpWidth??80)-s-_-2;let N;return w<this.minWidthToWrap||u.preformatted(a)?N=a:N=u.boxWrap(a,w).replace(/\n/g,`
3
+ `+" ".repeat(s+_)),m+P+" ".repeat(_)+N.replace(/\n/g,`
4
+ ${m}`)}boxWrap(i,s){if(s<this.minWidthToWrap)return i;const a=i.split(/\r\n|\n/),u=/[\s]*[^\s]+/g,h=[];return a.forEach(m=>{const P=m.match(u);if(P===null){h.push("");return}let _=[P.shift()],w=this.displayWidth(_[0]);P.forEach(N=>{const M=this.displayWidth(N);if(w+M<=s){_.push(N),w+=M;return}h.push(_.join(""));const L=N.trimStart();_=[L],w=this.displayWidth(L)}),h.push(_.join(""))}),h.join(`
5
+ `)}};function r(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}e.Help=o,e.stripColor=r})),He=Q((e=>{var{InvalidArgumentError:t}=ue(),o=class{constructor(a,u){this.flags=a,this.description=u||"",this.required=a.includes("<"),this.optional=a.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(a),this.mandatory=!1;const h=s(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,u){return this.defaultValue=a,this.defaultValueDescription=u,this}preset(a){return this.presetArg=a,this}conflicts(a){return this.conflictsWith=this.conflictsWith.concat(a),this}implies(a){let u=a;return typeof a=="string"&&(u={[a]:!0}),this.implied=Object.assign(this.implied||{},u),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,u){return u===this.defaultValue||!Array.isArray(u)?[a]:(u.push(a),u)}choices(a){return this.argChoices=a.slice(),this.parseArg=(u,h)=>{if(!this.argChoices.includes(u))throw new t(`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(a){return this.helpGroupHeading=a,this}is(a){return this.short===a||this.long===a}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(a){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,a.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(a,u){const h=u.attributeName();if(!this.dualOptions.has(h))return!0;const m=this.negativeOptions.get(h).presetArg,P=m!==void 0?m:!1;return u.negate===(P===a)}};function i(a){return a.split("-").reduce((u,h)=>u+h[0].toUpperCase()+h.slice(1))}function s(a){let u,h;const m=/^-[^-]$/,P=/^--[^-]/,_=a.split(/[ |,]+/).concat("guard");if(m.test(_[0])&&(u=_.shift()),P.test(_[0])&&(h=_.shift()),!u&&m.test(_[0])&&(u=_.shift()),!u&&P.test(_[0])&&(u=h,h=_.shift()),_[0].startsWith("-")){const w=_[0],N=`option creation failed due to '${w}' in option flags '${a}'`;throw/^-[^-][^-]/.test(w)?new Error(`${N}
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')`):m.test(w)?new Error(`${N}
9
+ - too many short flags`):P.test(w)?new Error(`${N}
10
+ - too many long flags`):new Error(`${N}
11
+ - unrecognised flag format`)}if(u===void 0&&h===void 0)throw new Error(`option creation failed due to no flags found in '${a}'.`);return{shortFlag:u,longFlag:h}}e.Option=o,e.DualOptions=r})),St=Q((e=>{var t=3;function o(i,s){if(Math.abs(i.length-s.length)>t)return Math.max(i.length,s.length);const a=[];for(let u=0;u<=i.length;u++)a[u]=[u];for(let u=0;u<=s.length;u++)a[0][u]=u;for(let u=1;u<=s.length;u++)for(let h=1;h<=i.length;h++){let m=1;i[h-1]===s[u-1]?m=0:m=1,a[h][u]=Math.min(a[h-1][u]+1,a[h][u-1]+1,a[h-1][u-1]+m),h>1&&u>1&&i[h-1]===s[u-2]&&i[h-2]===s[u-1]&&(a[h][u]=Math.min(a[h][u],a[h-2][u-2]+1))}return a[i.length][s.length]}function r(i,s){if(!s||s.length===0)return"";s=Array.from(new Set(s));const a=i.startsWith("--");a&&(i=i.slice(2),s=s.map(P=>P.slice(2)));let u=[],h=t;const m=.4;return s.forEach(P=>{if(P.length<=1)return;const _=o(i,P),w=Math.max(i.length,P.length);(w-_)/w>m&&(_<h?(h=_,u=[P]):_===h&&u.push(P))}),u.sort((P,_)=>P.localeCompare(_)),a&&(u=u.map(P=>`--${P}`)),u.length>1?`
12
+ (Did you mean one of ${u.join(", ")}?)`:u.length===1?`
13
+ (Did you mean ${u[0]}?)`:""}e.suggestSimilar=r})),Ot=Q((e=>{var t=require("node:events").EventEmitter,o=require("node:child_process"),r=require("node:path"),i=require("node:fs"),s=require("node:process"),{Argument:a,humanReadableArgName:u}=ve(),{CommanderError:h}=ue(),{Help:m,stripColor:P}=Ne(),{Option:_,DualOptions:w}=He(),{suggestSimilar:N}=St(),M=class De extends t{constructor(n){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=n||"",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:l=>s.stdout.write(l),writeErr:l=>s.stderr.write(l),outputError:(l,d)=>d(l),getOutHelpWidth:()=>s.stdout.isTTY?s.stdout.columns:void 0,getErrHelpWidth:()=>s.stderr.isTTY?s.stderr.columns:void 0,getOutHasColors:()=>pe()??(s.stdout.isTTY&&s.stdout.hasColors?.()),getErrHasColors:()=>pe()??(s.stderr.isTTY&&s.stderr.hasColors?.()),stripColor:l=>P(l)},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(n){return this._outputConfiguration=n._outputConfiguration,this._helpOption=n._helpOption,this._helpCommand=n._helpCommand,this._helpConfiguration=n._helpConfiguration,this._exitCallback=n._exitCallback,this._storeOptionsAsProperties=n._storeOptionsAsProperties,this._combineFlagAndOptionalValue=n._combineFlagAndOptionalValue,this._allowExcessArguments=n._allowExcessArguments,this._enablePositionalOptions=n._enablePositionalOptions,this._showHelpAfterError=n._showHelpAfterError,this._showSuggestionAfterError=n._showSuggestionAfterError,this}_getCommandAndAncestors(){const n=[];for(let l=this;l;l=l.parent)n.push(l);return n}command(n,l,d){let c=l,p=d;typeof c=="object"&&c!==null&&(p=c,c=null),p=p||{};const[,v,C]=n.match(/([^ ]+) *(.*)/),T=this.createCommand(v);return c&&(T.description(c),T._executableHandler=!0),p.isDefault&&(this._defaultCommandName=T._name),T._hidden=!!(p.noHelp||p.hidden),T._executableFile=p.executableFile||null,C&&T.arguments(C),this._registerCommand(T),T.parent=this,T.copyInheritedSettings(this),c?this:T}createCommand(n){return new De(n)}createHelp(){return Object.assign(new m,this.configureHelp())}configureHelp(n){return n===void 0?this._helpConfiguration:(this._helpConfiguration=n,this)}configureOutput(n){return n===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...n},this)}showHelpAfterError(n=!0){return typeof n!="string"&&(n=!!n),this._showHelpAfterError=n,this}showSuggestionAfterError(n=!0){return this._showSuggestionAfterError=!!n,this}addCommand(n,l){if(!n._name)throw new Error(`Command passed to .addCommand() must have a name
14
+ - specify the name in Command constructor or using .name()`);return l=l||{},l.isDefault&&(this._defaultCommandName=n._name),(l.noHelp||l.hidden)&&(n._hidden=!0),this._registerCommand(n),n.parent=this,n._checkForBrokenPassThrough(),this}createArgument(n,l){return new a(n,l)}argument(n,l,d,c){const p=this.createArgument(n,l);return typeof d=="function"?p.default(c).argParser(d):p.default(d),this.addArgument(p),this}arguments(n){return n.trim().split(/ +/).forEach(l=>{this.argument(l)}),this}addArgument(n){const l=this.registeredArguments.slice(-1)[0];if(l?.variadic)throw new Error(`only the last argument can be variadic '${l.name()}'`);if(n.required&&n.defaultValue!==void 0&&n.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${n.name()}'`);return this.registeredArguments.push(n),this}helpCommand(n,l){if(typeof n=="boolean")return this._addImplicitHelpCommand=n,n&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,d,c]=(n??"help [command]").match(/([^ ]+) *(.*)/),p=l??"display help for command",v=this.createCommand(d);return v.helpOption(!1),c&&v.arguments(c),p&&v.description(p),this._addImplicitHelpCommand=!0,this._helpCommand=v,(n||l)&&this._initCommandGroup(v),this}addHelpCommand(n,l){return typeof n!="object"?(this.helpCommand(n,l),this):(this._addImplicitHelpCommand=!0,this._helpCommand=n,this._initCommandGroup(n),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(n,l){const d=["preSubcommand","preAction","postAction"];if(!d.includes(n))throw new Error(`Unexpected value for event passed to hook : '${n}'.
15
+ Expecting one of '${d.join("', '")}'`);return this._lifeCycleHooks[n]?this._lifeCycleHooks[n].push(l):this._lifeCycleHooks[n]=[l],this}exitOverride(n){return n?this._exitCallback=n:this._exitCallback=l=>{if(l.code!=="commander.executeSubCommandAsync")throw l},this}_exit(n,l,d){this._exitCallback&&this._exitCallback(new h(n,l,d)),s.exit(n)}action(n){const l=d=>{const c=this.registeredArguments.length,p=d.slice(0,c);return this._storeOptionsAsProperties?p[c]=this:p[c]=this.opts(),p.push(this),n.apply(this,p)};return this._actionHandler=l,this}createOption(n,l){return new _(n,l)}_callParseArg(n,l,d,c){try{return n.parseArg(l,d)}catch(p){if(p.code==="commander.invalidArgument"){const v=`${c} ${p.message}`;this.error(v,{exitCode:p.exitCode,code:p.code})}throw p}}_registerOption(n){const l=n.short&&this._findOption(n.short)||n.long&&this._findOption(n.long);if(l){const d=n.long&&this._findOption(n.long)?n.long:n.short;throw new Error(`Cannot add option '${n.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${d}'
16
+ - already used by option '${l.flags}'`)}this._initOptionGroup(n),this.options.push(n)}_registerCommand(n){const l=c=>[c.name()].concat(c.aliases()),d=l(n).find(c=>this._findCommand(c));if(d){const c=l(this._findCommand(d)).join("|"),p=l(n).join("|");throw new Error(`cannot add command '${p}' as already have command '${c}'`)}this._initCommandGroup(n),this.commands.push(n)}addOption(n){this._registerOption(n);const l=n.name(),d=n.attributeName();if(n.negate){const p=n.long.replace(/^--no-/,"--");this._findOption(p)||this.setOptionValueWithSource(d,n.defaultValue===void 0?!0:n.defaultValue,"default")}else n.defaultValue!==void 0&&this.setOptionValueWithSource(d,n.defaultValue,"default");const c=(p,v,C)=>{p==null&&n.presetArg!==void 0&&(p=n.presetArg);const T=this.getOptionValue(d);p!==null&&n.parseArg?p=this._callParseArg(n,p,T,v):p!==null&&n.variadic&&(p=n._collectValue(p,T)),p==null&&(n.negate?p=!1:n.isBoolean()||n.optional?p=!0:p=""),this.setOptionValueWithSource(d,p,C)};return this.on("option:"+l,p=>{c(p,`error: option '${n.flags}' argument '${p}' is invalid.`,"cli")}),n.envVar&&this.on("optionEnv:"+l,p=>{c(p,`error: option '${n.flags}' value '${p}' from env '${n.envVar}' is invalid.`,"env")}),this}_optionEx(n,l,d,c,p){if(typeof l=="object"&&l instanceof _)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const v=this.createOption(l,d);if(v.makeOptionMandatory(!!n.mandatory),typeof c=="function")v.default(p).argParser(c);else if(c instanceof RegExp){const C=c;c=(T,$)=>{const y=C.exec(T);return y?y[0]:$},v.default(p).argParser(c)}else v.default(c);return this.addOption(v)}option(n,l,d,c){return this._optionEx({},n,l,d,c)}requiredOption(n,l,d,c){return this._optionEx({mandatory:!0},n,l,d,c)}combineFlagAndOptionalValue(n=!0){return this._combineFlagAndOptionalValue=!!n,this}allowUnknownOption(n=!0){return this._allowUnknownOption=!!n,this}allowExcessArguments(n=!0){return this._allowExcessArguments=!!n,this}enablePositionalOptions(n=!0){return this._enablePositionalOptions=!!n,this}passThroughOptions(n=!0){return this._passThroughOptions=!!n,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(n=!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=!!n,this}getOptionValue(n){return this._storeOptionsAsProperties?this[n]:this._optionValues[n]}setOptionValue(n,l){return this.setOptionValueWithSource(n,l,void 0)}setOptionValueWithSource(n,l,d){return this._storeOptionsAsProperties?this[n]=l:this._optionValues[n]=l,this._optionValueSources[n]=d,this}getOptionValueSource(n){return this._optionValueSources[n]}getOptionValueSourceWithGlobals(n){let l;return this._getCommandAndAncestors().forEach(d=>{d.getOptionValueSource(n)!==void 0&&(l=d.getOptionValueSource(n))}),l}_prepareUserArgs(n,l){if(n!==void 0&&!Array.isArray(n))throw new Error("first parameter to parse must be array or undefined");if(l=l||{},n===void 0&&l.from===void 0){s.versions?.electron&&(l.from="electron");const c=s.execArgv??[];(c.includes("-e")||c.includes("--eval")||c.includes("-p")||c.includes("--print"))&&(l.from="eval")}n===void 0&&(n=s.argv),this.rawArgs=n.slice();let d;switch(l.from){case void 0:case"node":this._scriptPath=n[1],d=n.slice(2);break;case"electron":s.defaultApp?(this._scriptPath=n[1],d=n.slice(2)):d=n.slice(1);break;case"user":d=n.slice(0);break;case"eval":d=n.slice(1);break;default:throw new Error(`unexpected parse option { from: '${l.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",d}parse(n,l){this._prepareForParse();const d=this._prepareUserArgs(n,l);return this._parseCommand([],d),this}async parseAsync(n,l){this._prepareForParse();const d=this._prepareUserArgs(n,l);return await this._parseCommand([],d),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(n,l,d){if(i.existsSync(n))return;const c=`'${n}' does not exist
18
+ - if '${d}' 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
+ - ${l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;throw new Error(c)}_executeSubCommand(n,l){l=l.slice();let d=!1;const c=[".js",".ts",".tsx",".mjs",".cjs"];function p(y,I){const H=r.resolve(y,I);if(i.existsSync(H))return H;if(c.includes(r.extname(I)))return;const _e=c.find(lt=>i.existsSync(`${H}${lt}`));if(_e)return`${H}${_e}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let v=n._executableFile||`${this._name}-${n._name}`,C=this._executableDir||"";if(this._scriptPath){let y;try{y=i.realpathSync(this._scriptPath)}catch{y=this._scriptPath}C=r.resolve(r.dirname(y),C)}if(C){let y=p(C,v);if(!y&&!n._executableFile&&this._scriptPath){const I=r.basename(this._scriptPath,r.extname(this._scriptPath));I!==this._name&&(y=p(C,`${I}-${n._name}`))}v=y||v}d=c.includes(r.extname(v));let T;s.platform!=="win32"?d?(l.unshift(v),l=L(s.execArgv).concat(l),T=o.spawn(s.argv[0],l,{stdio:"inherit"})):T=o.spawn(v,l,{stdio:"inherit"}):(this._checkForMissingExecutable(v,C,n._name),l.unshift(v),l=L(s.execArgv).concat(l),T=o.spawn(s.execPath,l,{stdio:"inherit"})),T.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(y=>{s.on(y,()=>{T.killed===!1&&T.exitCode===null&&T.kill(y)})});const $=this._exitCallback;T.on("close",y=>{y=y??1,$?$(new h(y,"commander.executeSubCommandAsync","(close)")):s.exit(y)}),T.on("error",y=>{if(y.code==="ENOENT")this._checkForMissingExecutable(v,C,n._name);else if(y.code==="EACCES")throw new Error(`'${v}' not executable`);if(!$)s.exit(1);else{const I=new h(1,"commander.executeSubCommandAsync","(error)");I.nestedError=y,$(I)}}),this.runningCommand=T}_dispatchSubcommand(n,l,d){const c=this._findCommand(n);c||this.help({error:!0}),c._prepareForParse();let p;return p=this._chainOrCallSubCommandHook(p,c,"preSubcommand"),p=this._chainOrCall(p,()=>{if(c._executableHandler)this._executeSubCommand(c,l.concat(d));else return c._parseCommand(l,d)}),p}_dispatchHelpCommand(n){n||this.help();const l=this._findCommand(n);return l&&!l._executableHandler&&l.help(),this._dispatchSubcommand(n,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((n,l)=>{n.required&&this.args[l]==null&&this.missingArgument(n.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const n=(d,c,p)=>{let v=c;if(c!==null&&d.parseArg){const C=`error: command-argument value '${c}' is invalid for argument '${d.name()}'.`;v=this._callParseArg(d,c,p,C)}return v};this._checkNumberOfArguments();const l=[];this.registeredArguments.forEach((d,c)=>{let p=d.defaultValue;d.variadic?c<this.args.length?(p=this.args.slice(c),d.parseArg&&(p=p.reduce((v,C)=>n(d,C,v),d.defaultValue))):p===void 0&&(p=[]):c<this.args.length&&(p=this.args[c],d.parseArg&&(p=n(d,p,d.defaultValue))),l[c]=p}),this.processedArgs=l}_chainOrCall(n,l){return n?.then&&typeof n.then=="function"?n.then(()=>l()):l()}_chainOrCallHooks(n,l){let d=n;const c=[];return this._getCommandAndAncestors().reverse().filter(p=>p._lifeCycleHooks[l]!==void 0).forEach(p=>{p._lifeCycleHooks[l].forEach(v=>{c.push({hookedCommand:p,callback:v})})}),l==="postAction"&&c.reverse(),c.forEach(p=>{d=this._chainOrCall(d,()=>p.callback(p.hookedCommand,this))}),d}_chainOrCallSubCommandHook(n,l,d){let c=n;return this._lifeCycleHooks[d]!==void 0&&this._lifeCycleHooks[d].forEach(p=>{c=this._chainOrCall(c,()=>p(this,l))}),c}_parseCommand(n,l){const d=this.parseOptions(l);if(this._parseOptionsEnv(),this._parseOptionsImplied(),n=n.concat(d.operands),l=d.unknown,this.args=n.concat(l),n&&this._findCommand(n[0]))return this._dispatchSubcommand(n[0],n.slice(1),l);if(this._getHelpCommand()&&n[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(n[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(l),this._dispatchSubcommand(this._defaultCommandName,n,l);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(d.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const c=()=>{d.unknown.length>0&&this.unknownOption(d.unknown[0])},p=`command:${this.name()}`;if(this._actionHandler){c(),this._processArguments();let v;return v=this._chainOrCallHooks(v,"preAction"),v=this._chainOrCall(v,()=>this._actionHandler(this.processedArgs)),this.parent&&(v=this._chainOrCall(v,()=>{this.parent.emit(p,n,l)})),v=this._chainOrCallHooks(v,"postAction"),v}if(this.parent?.listenerCount(p))c(),this._processArguments(),this.parent.emit(p,n,l);else if(n.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",n,l);this.listenerCount("command:*")?this.emit("command:*",n,l):this.commands.length?this.unknownCommand():(c(),this._processArguments())}else this.commands.length?(c(),this.help({error:!0})):(c(),this._processArguments())}_findCommand(n){if(n)return this.commands.find(l=>l._name===n||l._aliases.includes(n))}_findOption(n){return this.options.find(l=>l.is(n))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(n=>{n.options.forEach(l=>{l.mandatory&&n.getOptionValue(l.attributeName())===void 0&&n.missingMandatoryOptionValue(l)})})}_checkForConflictingLocalOptions(){const n=this.options.filter(l=>{const d=l.attributeName();return this.getOptionValue(d)===void 0?!1:this.getOptionValueSource(d)!=="default"});n.filter(l=>l.conflictsWith.length>0).forEach(l=>{const d=n.find(c=>l.conflictsWith.includes(c.attributeName()));d&&this._conflictingOption(l,d)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(n=>{n._checkForConflictingLocalOptions()})}parseOptions(n){const l=[],d=[];let c=l;function p(y){return y.length>1&&y[0]==="-"}const v=y=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(y)?!this._getCommandAndAncestors().some(I=>I.options.map(H=>H.short).some(H=>/^-\d$/.test(H))):!1;let C=null,T=null,$=0;for(;$<n.length||T;){const y=T??n[$++];if(T=null,y==="--"){c===d&&c.push(y),c.push(...n.slice($));break}if(C&&(!p(y)||v(y))){this.emit(`option:${C.name()}`,y);continue}if(C=null,p(y)){const I=this._findOption(y);if(I){if(I.required){const H=n[$++];H===void 0&&this.optionMissingArgument(I),this.emit(`option:${I.name()}`,H)}else if(I.optional){let H=null;$<n.length&&(!p(n[$])||v(n[$]))&&(H=n[$++]),this.emit(`option:${I.name()}`,H)}else this.emit(`option:${I.name()}`);C=I.variadic?I:null;continue}}if(y.length>2&&y[0]==="-"&&y[1]!=="-"){const I=this._findOption(`-${y[1]}`);if(I){I.required||I.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${I.name()}`,y.slice(2)):(this.emit(`option:${I.name()}`),T=`-${y.slice(2)}`);continue}}if(/^--[^=]+=/.test(y)){const I=y.indexOf("="),H=this._findOption(y.slice(0,I));if(H&&(H.required||H.optional)){this.emit(`option:${H.name()}`,y.slice(I+1));continue}}if(c===l&&p(y)&&!(this.commands.length===0&&v(y))&&(c=d),(this._enablePositionalOptions||this._passThroughOptions)&&l.length===0&&d.length===0){if(this._findCommand(y)){l.push(y),d.push(...n.slice($));break}else if(this._getHelpCommand()&&y===this._getHelpCommand().name()){l.push(y,...n.slice($));break}else if(this._defaultCommandName){d.push(y,...n.slice($));break}}if(this._passThroughOptions){c.push(y,...n.slice($));break}c.push(y)}return{operands:l,unknown:d}}opts(){if(this._storeOptionsAsProperties){const n={},l=this.options.length;for(let d=0;d<l;d++){const c=this.options[d].attributeName();n[c]=c===this._versionOptionName?this._version:this[c]}return n}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((n,l)=>Object.assign(n,l.opts()),{})}error(n,l){this._outputConfiguration.outputError(`${n}
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 d=l||{},c=d.exitCode||1,p=d.code||"commander.error";this._exit(c,p,n)}_parseOptionsEnv(){this.options.forEach(n=>{if(n.envVar&&n.envVar in s.env){const l=n.attributeName();(this.getOptionValue(l)===void 0||["default","config","env"].includes(this.getOptionValueSource(l)))&&(n.required||n.optional?this.emit(`optionEnv:${n.name()}`,s.env[n.envVar]):this.emit(`optionEnv:${n.name()}`))}})}_parseOptionsImplied(){const n=new w(this.options),l=d=>this.getOptionValue(d)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(d));this.options.filter(d=>d.implied!==void 0&&l(d.attributeName())&&n.valueFromOption(this.getOptionValue(d.attributeName()),d)).forEach(d=>{Object.keys(d.implied).filter(c=>!l(c)).forEach(c=>{this.setOptionValueWithSource(c,d.implied[c],"implied")})})}missingArgument(n){const l=`error: missing required argument '${n}'`;this.error(l,{code:"commander.missingArgument"})}optionMissingArgument(n){const l=`error: option '${n.flags}' argument missing`;this.error(l,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(n){const l=`error: required option '${n.flags}' not specified`;this.error(l,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(n,l){const d=v=>{const C=v.attributeName(),T=this.getOptionValue(C),$=this.options.find(I=>I.negate&&C===I.attributeName()),y=this.options.find(I=>!I.negate&&C===I.attributeName());return $&&($.presetArg===void 0&&T===!1||$.presetArg!==void 0&&T===$.presetArg)?$:y||v},c=v=>{const C=d(v),T=C.attributeName();return this.getOptionValueSource(T)==="env"?`environment variable '${C.envVar}'`:`option '${C.flags}'`},p=`error: ${c(n)} cannot be used with ${c(l)}`;this.error(p,{code:"commander.conflictingOption"})}unknownOption(n){if(this._allowUnknownOption)return;let l="";if(n.startsWith("--")&&this._showSuggestionAfterError){let c=[],p=this;do{const v=p.createHelp().visibleOptions(p).filter(C=>C.long).map(C=>C.long);c=c.concat(v),p=p.parent}while(p&&!p._enablePositionalOptions);l=N(n,c)}const d=`error: unknown option '${n}'${l}`;this.error(d,{code:"commander.unknownOption"})}_excessArguments(n){if(this._allowExcessArguments)return;const l=this.registeredArguments.length,d=l===1?"":"s",c=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${l} argument${d} but got ${n.length}.`;this.error(c,{code:"commander.excessArguments"})}unknownCommand(){const n=this.args[0];let l="";if(this._showSuggestionAfterError){const c=[];this.createHelp().visibleCommands(this).forEach(p=>{c.push(p.name()),p.alias()&&c.push(p.alias())}),l=N(n,c)}const d=`error: unknown command '${n}'${l}`;this.error(d,{code:"commander.unknownCommand"})}version(n,l,d){if(n===void 0)return this._version;this._version=n,l=l||"-V, --version",d=d||"output the version number";const c=this.createOption(l,d);return this._versionOptionName=c.attributeName(),this._registerOption(c),this.on("option:"+c.name(),()=>{this._outputConfiguration.writeOut(`${n}
24
+ `),this._exit(0,"commander.version",n)}),this}description(n,l){return n===void 0&&l===void 0?this._description:(this._description=n,l&&(this._argsDescription=l),this)}summary(n){return n===void 0?this._summary:(this._summary=n,this)}alias(n){if(n===void 0)return this._aliases[0];let l=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(l=this.commands[this.commands.length-1]),n===l._name)throw new Error("Command alias can't be the same as its name");const d=this.parent?._findCommand(n);if(d){const c=[d.name()].concat(d.aliases()).join("|");throw new Error(`cannot add alias '${n}' to command '${this.name()}' as already have command '${c}'`)}return l._aliases.push(n),this}aliases(n){return n===void 0?this._aliases:(n.forEach(l=>this.alias(l)),this)}usage(n){if(n===void 0){if(this._usage)return this._usage;const l=this.registeredArguments.map(d=>u(d));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?l:[]).join(" ")}return this._usage=n,this}name(n){return n===void 0?this._name:(this._name=n,this)}helpGroup(n){return n===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=n,this)}commandsGroup(n){return n===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=n,this)}optionsGroup(n){return n===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=n,this)}_initOptionGroup(n){this._defaultOptionGroup&&!n.helpGroupHeading&&n.helpGroup(this._defaultOptionGroup)}_initCommandGroup(n){this._defaultCommandGroup&&!n.helpGroup()&&n.helpGroup(this._defaultCommandGroup)}nameFromFilename(n){return this._name=r.basename(n,r.extname(n)),this}executableDir(n){return n===void 0?this._executableDir:(this._executableDir=n,this)}helpInformation(n){const l=this.createHelp(),d=this._getOutputContext(n);l.prepareContext({error:d.error,helpWidth:d.helpWidth,outputHasColors:d.hasColors});const c=l.formatHelp(this,l);return d.hasColors?c:this._outputConfiguration.stripColor(c)}_getOutputContext(n){n=n||{};const l=!!n.error;let d,c,p;return l?(d=C=>this._outputConfiguration.writeErr(C),c=this._outputConfiguration.getErrHasColors(),p=this._outputConfiguration.getErrHelpWidth()):(d=C=>this._outputConfiguration.writeOut(C),c=this._outputConfiguration.getOutHasColors(),p=this._outputConfiguration.getOutHelpWidth()),{error:l,write:C=>(c||(C=this._outputConfiguration.stripColor(C)),d(C)),hasColors:c,helpWidth:p}}outputHelp(n){let l;typeof n=="function"&&(l=n,n=void 0);const d=this._getOutputContext(n),c={error:d.error,write:d.write,command:this};this._getCommandAndAncestors().reverse().forEach(v=>v.emit("beforeAllHelp",c)),this.emit("beforeHelp",c);let p=this.helpInformation({error:d.error});if(l&&(p=l(p),typeof p!="string"&&!Buffer.isBuffer(p)))throw new Error("outputHelp callback must return a string or a Buffer");d.write(p),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",c),this._getCommandAndAncestors().forEach(v=>v.emit("afterAllHelp",c))}helpOption(n,l){return typeof n=="boolean"?(n?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(n??"-h, --help",l??"display help for command"),(n||l)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(n){return this._helpOption=n,this._initOptionGroup(n),this}help(n){this.outputHelp(n);let l=Number(s.exitCode??0);l===0&&n&&typeof n!="function"&&n.error&&(l=1),this._exit(l,"commander.help","(outputHelp)")}addHelpText(n,l){const d=["beforeAll","before","after","afterAll"];if(!d.includes(n))throw new Error(`Unexpected value for position to addHelpText.
25
+ Expecting one of '${d.join("', '")}'`);const c=`${n}Help`;return this.on(c,p=>{let v;typeof l=="function"?v=l({error:p.error,command:p.command}):v=l,v&&p.write(`${v}
26
+ `)}),this}_outputHelpIfRequested(n){const l=this._getHelpOption();l&&n.find(d=>l.is(d))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function L(at){return at.map(n=>{if(!n.startsWith("--inspect"))return n;let l,d="127.0.0.1",c="9229",p;return(p=n.match(/^(--inspect(-brk)?)$/))!==null?l=p[1]:(p=n.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(l=p[1],/^\d+$/.test(p[3])?c=p[3]:d=p[3]):(p=n.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(l=p[1],d=p[3],c=p[4]),l&&c!=="0"?`${l}=${d}:${parseInt(c)+1}`:n})}function pe(){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=M,e.useColor=pe})),At=Q((e=>{var{Argument:t}=ve(),{Command:o}=Ot(),{CommanderError:r,InvalidArgumentError:i}=ue(),{Help:s}=Ne(),{Option:a}=He();e.program=new o,e.createCommand=u=>new o(u),e.createOption=(u,h)=>new a(u,h),e.createArgument=(u,h)=>new t(u,h),e.Command=o,e.Option=a,e.Argument=t,e.Help=s,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i})),bt=ft(At(),1),{program:Ws,createCommand:Js,createArgument:zs,createOption:Ks,CommanderError:Ct,InvalidArgumentError:Xs,InvalidOptionArgumentError:Qs,Command:Pt,Argument:Ys,Option:W,Help:Zs}=bt.default;function S(e){return`${JSON.stringify(e,null,2)}
27
+ `}var f={BASE:"",VERSION:"1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0},re=class extends Error{url;status;statusText;body;request;constructor(e,t,o){super(o),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},V={USAGE:2,HTTP_BAD_REQUEST:20,HTTP_UNAUTHORIZED:21,HTTP_FORBIDDEN:23,HTTP_NOT_FOUND:24,HTTP_CONFLICT:29,OPERATION_FAILED:30,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},x=class extends Error{constructor(e){super(e),this.name="CliUsageError"}},Ve=class extends Error{constructor(e){super(e),this.name="CliOperationFailedError"}},te=class extends Error{status;details;constructor(e,t,o){super(t),this.name="CliHttpError",this.status=e,this.details=o}};function Re(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ee(e,t){const o=Re(e)?.[t];return typeof o=="string"&&o.trim()?o.trim():void 0}function _t(e){return e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ENOTFOUND")||e.includes("Failed to parse URL")}function Te(e){switch(e){case 400:return V.HTTP_BAD_REQUEST;case 401:return V.HTTP_UNAUTHORIZED;case 403:return V.HTTP_FORBIDDEN;case 404:return V.HTTP_NOT_FOUND;case 409:return V.HTTP_CONFLICT;default:return e&&e>=400&&e<500?V.HTTP_CLIENT_ERROR:e&&e>=500?V.HTTP_SERVER_ERROR:V.UNKNOWN}}function wt(e,t={}){if(e instanceof x)return{exitCode:V.USAGE,message:e.message};if(e instanceof Ve)return{exitCode:V.OPERATION_FAILED,message:e.message};if(e instanceof te)return{exitCode:Te(e.status),status:e.status,message:e.message,details:e.details};if(e instanceof re){const o=ee(e.body,"error")??ee(e.body,"message")??e.message;return{exitCode:Te(e.status),status:e.status,message:o,errorCode:ee(e.body,"errorCode"),correlationId:ee(e.body,"correlationId"),details:e.body}}if(e instanceof Error){if(!_t(e.message))return{exitCode:V.UNKNOWN,message:e.message};const o=t.baseUrl??"the configured backend";return{exitCode:V.TRANSPORT,message:e.message.includes("Failed to parse URL")?`Invalid HagiCode backend base URL: ${o}`:`Cannot reach HagiCode backend at ${o}. Check that the backend is running and the base URL is correct.`}}return{exitCode:V.UNKNOWN,message:String(e)}}function Tt(e){const t=Re(e)?.errors;return Array.isArray(t)?t.flatMap(o=>{const r=ee(o,"field"),i=ee(o,"message");return r&&i?[` - ${r}: ${i}`]:[]}):[]}function qe(e,t={}){if(t.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)}
28
+ `;const o=[e.status?`status=${e.status}`:void 0,e.errorCode?`errorCode=${e.errorCode}`:void 0,e.correlationId?`correlationId=${e.correlationId}`:void 0].filter(Boolean),r=o.length>0?` (${o.join(", ")})`:"";return[`${e.message}${r}`,...Tt(e.details)].join(`
29
+ `)+`
30
+ `}function Et(e){return`cli/${e??"unknown"}`}var It=Et("0.1.0-dev.29.1.2b7f294"),kt="--base-url",xt="HAGI_API_BASE_URL";function B(e){const t=e?.trim();return t||void 0}function Fe(e=process.env){return(0,we.join)(B(e.XDG_CONFIG_HOME)??(0,we.join)((0,vt.homedir)(),".config"),"hagi","config.json")}function jt(e=process.env){const t=Fe(e);let o;try{o=(0,gt.readFileSync)(t,"utf8")}catch(s){if(s.code==="ENOENT")return;throw new x(`Cannot read CLI config file ${t}: ${s instanceof Error?s.message:String(s)}`)}let r;try{r=JSON.parse(o)}catch{throw new x(`CLI config file ${t} is not valid JSON.`)}const i=r&&typeof r=="object"&&!Array.isArray(r)?r.baseUrl:void 0;return typeof i=="string"?B(i):void 0}function $t(e={},t=process.env){const o=B(e.baseUrl)??B(t.HAGI_API_BASE_URL)??jt(t);if(!o)throw new x(`No backend base URL is configured. Set ${kt} <url>, the ${xt} environment variable, or "baseUrl" in ${Fe(t)}.`);return{baseUrl:o,token:B(e.token)??B(t.HAGI_API_TOKEN),lang:B(e.lang)??B(t.HAGI_API_LANG)}}function Nt(e={},t=process.env){const o=$t(e,t);return f.BASE=o.baseUrl,f.WITH_CREDENTIALS=!1,f.CREDENTIALS="omit",f.TOKEN=o.token,f.HEADERS={"X-Hagi-Client":It,...o.lang?{"Accept-Language":o.lang}:{}},o}function Ht(){return B(f.BASE)}var Dt=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Vt=class{#t;#i;#e;#s;#o;#r;#n;constructor(e){this.#t=!1,this.#i=!1,this.#e=!1,this.#s=[],this.#o=new Promise((t,o)=>{this.#r=t,this.#n=o;const r=a=>{this.#t||this.#i||this.#e||(this.#t=!0,this.#r&&this.#r(a))},i=a=>{this.#t||this.#i||this.#e||(this.#i=!0,this.#n&&this.#n(a))},s=a=>{this.#t||this.#i||this.#e||this.#s.push(a)};return Object.defineProperty(s,"isResolved",{get:()=>this.#t}),Object.defineProperty(s,"isRejected",{get:()=>this.#i}),Object.defineProperty(s,"isCancelled",{get:()=>this.#e}),e(r,i,s)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#o.then(e,t)}catch(e){return this.#o.catch(e)}finally(e){return this.#o.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.#n&&this.#n(new Dt("Request aborted"))}}get isCancelled(){return this.#e}},ye=e=>e!=null,ie=e=>typeof e=="string",he=e=>ie(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]),Le=e=>e instanceof FormData,Rt=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},qt=e=>{const t=[],o=(i,s)=>{t.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},r=(i,s)=>{ye(s)&&(Array.isArray(s)?s.forEach(a=>{r(i,a)}):typeof s=="object"?Object.entries(s).forEach(([a,u])=>{r(`${i}[${a}]`,u)}):o(i,s))};return Object.entries(e).forEach(([i,s])=>{r(i,s)}),t.length>0?`?${t.join("&")}`:""},Ft=(e,t)=>{const o=e.ENCODE_PATH||encodeURI,r=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(s,a)=>t.path?.hasOwnProperty(a)?o(String(t.path[a])):s),i=`${e.BASE}${r}`;return t.query?`${i}${qt(t.query)}`:i},Lt=e=>{if(e.formData){const t=new FormData,o=(r,i)=>{ie(i)||Se(i)?t.append(r,i):t.append(r,JSON.stringify(i))};return Object.entries(e.formData).filter(([r,i])=>ye(i)).forEach(([r,i])=>{Array.isArray(i)?i.forEach(s=>o(r,s)):o(r,i)}),t}},ne=async(e,t)=>typeof t=="function"?t(e):t,Gt=async(e,t)=>{const[o,r,i,s]=await Promise.all([ne(t,e.TOKEN),ne(t,e.USERNAME),ne(t,e.PASSWORD),ne(t,e.HEADERS)]),a=Object.entries({Accept:"application/json",...s,...t.headers}).filter(([u,h])=>ye(h)).reduce((u,[h,m])=>({...u,[h]:String(m)}),{});return he(o)&&(a.Authorization=`Bearer ${o}`),he(r)&&he(i)&&(a.Authorization=`Basic ${Rt(`${r}:${i}`)}`),t.body!==void 0&&(t.mediaType?a["Content-Type"]=t.mediaType:Se(t.body)?a["Content-Type"]=t.body.type||"application/octet-stream":ie(t.body)?a["Content-Type"]="text/plain":Le(t.body)||(a["Content-Type"]="application/json")),new Headers(a)},Ut=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):ie(e.body)||Se(e.body)||Le(e.body)?e.body:JSON.stringify(e.body)},Bt=async(e,t,o,r,i,s,a)=>{const u=new AbortController,h={headers:s,body:r??i,method:t.method,signal:u.signal};return e.WITH_CREDENTIALS&&(h.credentials=e.CREDENTIALS),a(()=>u.abort()),await fetch(o,h)},Mt=(e,t)=>{if(t){const o=e.headers.get(t);if(ie(o))return o}},Wt=async e=>{if(e.status!==204)try{const t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(o=>t.toLowerCase().startsWith(o))?await e.json():await e.text()}catch(t){console.error(t)}},Jt=(e,t)=>{const o={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(o)throw new re(e,t,o);if(!t.ok)throw new re(e,t,`Generic Error: status: ${t.status??"unknown"}; status text: ${t.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})()}`)},g=(e,t)=>new Vt(async(o,r,i)=>{try{const s=Ft(e,t),a=Lt(t),u=Ut(t),h=await Gt(e,t);if(!i.isCancelled){const m=await Bt(e,t,s,u,a,h,i),P=await Wt(m),_=Mt(m,t.responseHeader),w={url:s,ok:m.ok,status:m.status,statusText:m.statusText,body:_??P};Jt(t,w),o(w.body)}}catch(s){r(s)}}),zt=class{static getApiDataAggregation(){return g(f,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},Ee=class{static getApiPresetTasksSchemas(){return g(f,{method:"GET",url:"/api/preset-tasks/schemas",errors:{500:"Internal Server Error"}})}static getApiPresetTasksSchema({presetTaskId:e}){return g(f,{method:"GET",url:"/api/preset-tasks/{presetTaskId}/schema",path:{presetTaskId:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}},me=class{static postApiProject({requestBody:e}){return g(f,{method:"POST",url:"/api/Project",body:e,mediaType:"application/json"})}static postApiProjectDemo(){return g(f,{method:"POST",url:"/api/Project/demo"})}static putApiProject({id:e,requestBody:t}){return g(f,{method:"PUT",url:"/api/Project/{id}",path:{id:e},body:t,mediaType:"application/json"})}static deleteApiProject({id:e}){return g(f,{method:"DELETE",url:"/api/Project/{id}",path:{id:e}})}static postApiProjectOpenInVscode({id:e,subPath:t}){return g(f,{method:"POST",url:"/api/Project/{id}/open-in-vscode",path:{id:e},query:{subPath:t},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(f,{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:t}){return g(f,{method:"PUT",url:"/api/Project/{id}/monospecs/management",path:{id:e},body:t,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiProjectMonospecsInitialize({id:e}){return g(f,{method:"POST",url:"/api/Project/{id}/monospecs/initialize",path:{id:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiProjectDesignMd({id:e,repositoryPath:t}){return g(f,{method:"GET",url:"/api/Project/{id}/design-md",path:{id:e},query:{repositoryPath:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectDesignMd({id:e,requestBody:t}){return g(f,{method:"PUT",url:"/api/Project/{id}/design-md",path:{id:e},body:t,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static getApiProjectDesignMdSiteIndex({id:e}){return g(f,{method:"GET",url:"/api/Project/{id}/design-md/site-index",path:{id:e},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndexPreview({id:e,slug:t,theme:o="light"}){return g(f,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}/preview",path:{id:e,slug:t},query:{theme:o},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndex1({id:e,slug:t}){return g(f,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}",path:{id:e,slug:t},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectBranchesValidate({id:e,branchName:t,repositoryPath:o}){return g(f,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:e},query:{branchName:t,repositoryPath:o},errors:{400:"Branch name is required",404:"Project not found"}})}static getApiProjectValidatePath({path:e}){return g(f,{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(f,{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(f,{method:"POST",url:"/api/Project/validate-monospecs",body:e,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error"}})}},z=class{static getApiScheduledPlans(){return g(f,{method:"GET",url:"/api/ScheduledPlans"})}static postApiScheduledPlans({requestBody:e}){return g(f,{method:"POST",url:"/api/ScheduledPlans",body:e,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiScheduledPlans1({id:e}){return g(f,{method:"GET",url:"/api/ScheduledPlans/{id}",path:{id:e},errors:{404:"Not Found"}})}static putApiScheduledPlans({id:e,requestBody:t}){return g(f,{method:"PUT",url:"/api/ScheduledPlans/{id}",path:{id:e},body:t,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found"}})}static deleteApiScheduledPlans({id:e}){return g(f,{method:"DELETE",url:"/api/ScheduledPlans/{id}",path:{id:e},errors:{404:"Not Found"}})}static postApiScheduledPlansRun({id:e}){return g(f,{method:"POST",url:"/api/ScheduledPlans/{id}/run",path:{id:e},errors:{400:"Bad Request",404:"Not Found"}})}static postApiScheduledPlansStart({id:e}){return g(f,{method:"POST",url:"/api/ScheduledPlans/{id}/start",path:{id:e},errors:{404:"Not Found",503:"Service Unavailable"}})}},R=class{static postApiSessionsHagitask({requestBody:e}){return g(f,{method:"POST",url:"/api/Sessions/hagitask",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(f,{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(f,{method:"POST",url:"/api/Sessions/chat",body:e,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:e}){return g(f,{method:"POST",url:"/api/Sessions",body:e,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:e,activeOnly:t,includeArchived:o,projectId:r,projectIds:i}){return g(f,{method:"GET",url:"/api/Sessions",query:{type:e,activeOnly:t,includeArchived:o,projectId:r,projectIds:i}})}static getApiSessions1({sessionId:e}){return g(f,{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:t}){return g(f,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:e},body:t,mediaType:"application/json"})}static deleteApiSessions({sessionId:e,deleteFiles:t=!1}){return g(f,{method:"DELETE",url:"/api/Sessions/{sessionId}",path:{sessionId:e},query:{deleteFiles:t},errors:{404:"Session not found",500:"Failed to delete session"}})}static getApiSessionsMessages({sessionId:e,page:t=1,pageSize:o=50,historyScope:r,order:i="desc"}){return g(f,{method:"GET",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:e},query:{page:t,pageSize:o,historyScope:r,order:i},errors:{404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsMessages({sessionId:e,requestBody:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:e},body:t,mediaType:"application/json"})}static postApiSessionsCancel({sessionId:e}){return g(f,{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(f,{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:t}){return g(f,{method:"DELETE",url:"/api/Sessions/{sessionId}/queue/{queueIndex}",path:{sessionId:e,queueIndex:t},errors:{400:"Invalid queue index",404:"Session not found",500:"Failed to cancel message"}})}static postApiSessionsAnnotations({sessionId:e,requestBody:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/annotations",path:{sessionId:e},body:t,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:e,requestBody:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-proposal",path:{sessionId:e},body:t,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsGenerateProposal({sessionId:e,requestBody:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal",path:{sessionId:e},body:t,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:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/archive",path:{sessionId:e},body:t,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:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/execute-proposal",path:{sessionId:e},body:t,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(f,{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(f,{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(f,{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(f,{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:t}){return g(f,{method:"GET",url:"/api/Sessions/{sessionId}/openspec-file",path:{sessionId:e},query:{relativePath:t},errors:{404:"Session not found or file not found",500:"Failed to read file"}})}static postApiSessionsUpdateCessionId({sessionId:e}){return g(f,{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:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/open-in-vscode",path:{sessionId:e},query:{subPath:t},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:t}){return g(f,{method:"POST",url:"/api/Sessions/{sessionId}/correct-proposal-name",path:{sessionId:e},body:t,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(f,{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"}})}},U=class{static getApiSkillsLocal(){return g(f,{method:"GET",url:"/api/skills/local"})}static postApiSkillsLocalUninstall({requestBody:e}){return g(f,{method:"POST",url:"/api/skills/local/uninstall",body:e,mediaType:"application/json"})}static postApiSkillsLocalBuiltInAvailability({requestBody:e}){return g(f,{method:"POST",url:"/api/skills/local/built-in/availability",body:e,mediaType:"application/json"})}static getApiSkillsGallery({query:e}){return g(f,{method:"GET",url:"/api/skills/gallery",query:{query:e}})}static getApiSkillsGalleryDetail({id:e,source:t}){return g(f,{method:"GET",url:"/api/skills/gallery/detail",query:{id:e,source:t}})}static getApiSkillsGalleryInstallContext({id:e,source:t}){return g(f,{method:"GET",url:"/api/skills/gallery/install-context",query:{id:e,source:t}})}static getApiSkillsProvidersTrusted(){return g(f,{method:"GET",url:"/api/skills/providers/trusted"})}static postApiSkillsProvidersTrusted({requestBody:e}){return g(f,{method:"POST",url:"/api/skills/providers/trusted",body:e,mediaType:"application/json"})}static deleteApiSkillsProvidersTrusted({requestBody:e}){return g(f,{method:"DELETE",url:"/api/skills/providers/trusted",body:e,mediaType:"application/json"})}static postApiSkillsProvidersTrustedReset(){return g(f,{method:"POST",url:"/api/skills/providers/trusted/reset"})}static postApiSkillsGalleryInstall({requestBody:e}){return g(f,{method:"POST",url:"/api/skills/gallery/install",body:e,mediaType:"application/json"})}static getApiSkillsGalleryInstallStream({id:e,source:t,skillSlug:o,version:r}){return g(f,{method:"GET",url:"/api/skills/gallery/install/stream",query:{id:e,source:t,skillSlug:o,version:r}})}},Z=class{static getApiVaults(){return g(f,{method:"GET",url:"/api/vaults"})}static postApiVaults({requestBody:e}){return g(f,{method:"POST",url:"/api/vaults",body:e,mediaType:"application/json",errors:{400:"Bad Request",500:"Internal Server Error"}})}static putApiVaults({id:e,requestBody:t}){return g(f,{method:"PUT",url:"/api/vaults/{id}",path:{id:e},body:t,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static deleteApiVaults({id:e,deleteLocalFiles:t=!1}){return g(f,{method:"DELETE",url:"/api/vaults/{id}",path:{id:e},query:{deleteLocalFiles:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFiles({id:e,path:t}){return g(f,{method:"GET",url:"/api/vaults/{id}/files",path:{id:e},query:{path:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFilesContent({id:e,path:t}){return g(f,{method:"GET",url:"/api/vaults/{id}/files/content",path:{id:e},query:{path:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}};function Kt(){return{listSessions:e=>R.getApiSessions(e),getSession:e=>R.getApiSessions1({sessionId:e}),createProposalSession:e=>R.postApiSessions({requestBody:e}),createChatSession:e=>R.postApiSessionsChat({requestBody:e}),createHagiTaskSession:e=>R.postApiSessionsHagitask({requestBody:e}),listHagiTaskSchemas:()=>Ee.getApiPresetTasksSchemas(),getHagiTaskSchema:e=>Ee.getApiPresetTasksSchema({presetTaskId:e}),updateSession:(e,t)=>R.putApiSessions({sessionId:e,requestBody:t}),deleteSession:(e,t)=>R.deleteApiSessions({sessionId:e,deleteFiles:t}),sendMessage:(e,t)=>R.postApiSessionsMessages({sessionId:e,requestBody:t}),optimizeProposal:(e,t)=>R.postApiSessionsOptimizeProposal({sessionId:e,requestBody:t}),generateProposal:(e,t)=>R.postApiSessionsGenerateProposal({sessionId:e,requestBody:t}),executeProposal:(e,t)=>R.postApiSessionsExecuteProposal({sessionId:e,requestBody:t}),archiveProposal:(e,t)=>R.postApiSessionsArchive({sessionId:e,requestBody:t}),completeProposal:e=>R.postApiSessionsComplete({sessionId:e}),submitAnnotations:(e,t)=>R.postApiSessionsAnnotations({sessionId:e,requestBody:t}),listProjects:()=>zt.getApiDataAggregation(),createProject:e=>me.postApiProject({requestBody:e}),updateProject:(e,t)=>me.putApiProject({id:e,requestBody:t}),deleteProject:e=>me.deleteApiProject({id:e}),listPlans:()=>z.getApiScheduledPlans(),getPlan:e=>z.getApiScheduledPlans1({id:e}),createPlan:e=>z.postApiScheduledPlans({requestBody:e}),updatePlan:(e,t)=>z.putApiScheduledPlans({id:e,requestBody:t}),deletePlan:e=>z.deleteApiScheduledPlans({id:e}),runPlan:e=>z.postApiScheduledPlansRun({id:e}),startPlan:e=>z.postApiScheduledPlansStart({id:e}),listVaults:()=>Z.getApiVaults(),createVault:e=>Z.postApiVaults({requestBody:e}),updateVault:(e,t)=>Z.putApiVaults({id:e,requestBody:t}),deleteVault:(e,t)=>Z.deleteApiVaults({id:e,deleteLocalFiles:t}),listVaultFiles:(e,t)=>Z.getApiVaultsFiles({id:e,path:t}),previewVaultFile:(e,t)=>Z.getApiVaultsFilesContent({id:e,path:t}),archiveChat:e=>R.postApiSessionsArchiveChat({sessionId:e}),listLocalSkills:()=>U.getApiSkillsLocal(),uninstallLocalSkill:e=>U.postApiSkillsLocalUninstall({requestBody:e}),setBuiltInSkillAvailability:e=>U.postApiSkillsLocalBuiltInAvailability({requestBody:e}),searchSkillGallery:e=>U.getApiSkillsGallery({query:e}),getSkillGalleryDetail:(e,t)=>U.getApiSkillsGalleryDetail({id:e,source:t}),installGallerySkill:e=>U.postApiSkillsGalleryInstall({requestBody:e}),listTrustedSkillProviders:()=>U.getApiSkillsProvidersTrusted(),upsertTrustedSkillProvider:e=>U.postApiSkillsProvidersTrusted({requestBody:e}),deleteTrustedSkillProvider:e=>U.deleteApiSkillsProvidersTrusted({requestBody:e}),resetTrustedSkillProviders:()=>U.postApiSkillsProvidersTrustedReset()}}function O(e){const t=e?.trim();return t||void 0}function E(e,t){const o=O(e);if(!o)throw new x(`${t} is required.`);return o}function fe(e){const t=e?.map(o=>O(o)).filter(Boolean);return t&&t.length>0?t:void 0}function Ge(e=process.env,t={stdout:o=>{process.stdout.write(o)},stderr:o=>{process.stderr.write(o)}}){return{api:Kt(),env:e,io:t}}function Xt(e){return e.option("--base-url <url>",'Backend API base URL. Overrides HAGI_API_BASE_URL and the "baseUrl" config file entry.').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 A(e){return e.option("--json","Emit deterministic JSON instead of human-readable text.")}function b(e,t){const o=e.optsWithGlobals();return{api:t.api,env:t.env,io:t.io,outputJson:o.json===!0,runtime:Nt({baseUrl:o.baseUrl,token:o.token,lang:o.lang},t.env)}}function Qt(e,t){A(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(r){const i=b(this,t),s=r.sessionId.trim(),a=await i.api.archiveChat(s);if(i.outputJson){i.io.stdout(S({sessionId:s,message:a.message}));return}i.io.stdout(`Chat archived
31
+ sessionId ${s}
32
+ message ${a.message}
33
+ `)})}var Ue=(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 Be(e){return e.replace(/\s+/g," ").trim()}function F(e,t){const o=t.map(s=>e.map(a=>Be(a.value(s)))),r=e.map((s,a)=>{const u=o.map(h=>h[a].length);return Math.max(s.header.length,...u)}),i=s=>s.map((a,u)=>a.padEnd(r[u])).join(" ").trimEnd();return[i(e.map(s=>s.header)),i(r.map(s=>"-".repeat(s))),...o.map(i)].join(`
34
+ `)}function D(e){const t=e.filter(([,r])=>r!==void 0&&r!==""),o=Math.max(...t.map(([r])=>r.length));return`${t.map(([r,i])=>`${r.padEnd(o)} ${Be(i??"")}`).join(`
35
+ `)}
36
+ `}function Ie(e){return typeof e=="string"?e.trim():e?.value?.trim()??""}function J(e){return{sessionId:Ie(e.sessionId),title:e.title,type:e.type,status:e.status,projectId:Ie(e.projectId),proposalName:e.proposalName??void 0,archived:e.status===Ue.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 Me(e){return{sessions:e.sessions.map(J)}}function We(e,t){return t.length===0?`No ${e.toLowerCase()} found.
37
+ `:`${e} (${t.length})
38
+ ${F([{header:"Session ID",value:o=>o.sessionId},{header:"Title",value:o=>o.title},{header:"Status",value:o=>o.status},{header:"Project ID",value:o=>o.projectId},{header:"Archived",value:o=>o.archived?"yes":"no"}],t)}
39
+ `}function Y(e,t=[]){return D([["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],...t])}function Oe(e,t,o,r=[]){return`${e}
40
+ ${D([["sessionId",t],["message",o.message],...r])}`}var de=(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.DEEP_AGENTS_CLI="DeepAgentsCli",e})({});function Yt(e,t){A(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 W("--executor-type <type>","Optional executor override.").choices(Object.values(de))).action(async function(r){const i=b(this,t),s=J(await i.api.createChatSession({title:E(r.title,"--title"),projectId:E(r.projectId,"--project-id"),heroId:O(r.heroId),executorType:r.executorType}));if(i.outputJson){i.io.stdout(S({session:s}));return}i.io.stdout(`Chat session created
41
+ ${Y(s)}`)})}function Zt(e,t){A(e.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(r){const i=b(this,t),s=r.sessionId.trim(),a=await i.api.deleteSession(s,!1);if(i.outputJson){i.io.stdout(S({sessionId:s,deleted:!0,message:a.message}));return}i.io.stdout(`Chat deleted
42
+ sessionId ${s}
43
+ message ${a.message}
44
+ `)})}var Ae=(function(e){return e.CHAT="Chat",e.PROPOSAL="Proposal",e})({});function ei(e,t){A(e.command("list").description("List normal chat sessions.")).action(async function(r){if(r.projectId&&r.projectIds?.length)throw new x("Use either --project-id or --project-ids, not both.");const i=b(this,t),s=Me(await i.api.listSessions({type:Ae.CHAT,projectId:O(r.projectId),projectIds:fe(r.projectIds),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout(We("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.")}var be=(function(e){return e.READONLY="Readonly",e.EDIT="Edit",e})({});function ti(e,t){A(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 W("--mode <mode>","Message mode override.").choices(Object.values(be))).addOption(new W("--executor-type <type>","Executor override for this message.").choices(Object.values(de))).action(async function(r){const i=b(this,t),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:E(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(S({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(Oe("Chat message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function ii(e,t){const o=e.command("chat").description("Manage normal chat sessions.");ei(o,t),Yt(o,t),Qt(o,t),Zt(o,t),ti(o,t)}async function si(){const e=[];for await(const t of process.stdin)e.push(typeof t=="string"?Buffer.from(t):t);return Buffer.concat(e).toString("utf8")}async function ce(e){const t=e.trim();if(!t)throw new x("Provide --input <file> or --input - for stdin.");const o=t==="-"?await si():await(0,yt.readFile)(t,"utf8");try{return JSON.parse(o)}catch(r){throw new x(`Invalid JSON input from ${t}: ${r instanceof Error?r.message:String(r)}`)}}var ni=["first","random"];async function oi(e){let t;try{t=await ce(e)}catch(o){throw o instanceof x?o:new x(`Cannot read HagiTask input from ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new x(`HagiTask input from ${e} must be a JSON object.`);return t}function ri(e,t,o){if(!t&&!o)throw new x("Provide --task-id or --prompt-id.");if(e.input!==void 0&&!t)throw new x("--input requires --task-id.");if(e.targetBranchName&&e.targetBranchMode!=="new-custom")throw new x("--target-branch-name requires --target-branch-mode new-custom.");if(e.targetBranchMode==="new-custom"&&!O(e.targetBranchName))throw new x("--target-branch-name is required when --target-branch-mode is new-custom.");const r=O(e.heroSelectionMode);if(r&&!ni.includes(r))throw new x("--hero-selection-mode must be first or random.")}function ai(e,t){A(e.command("create").description("Create a HagiTask session. Read the task schema first with `hagitask schema --task-id <id>`, then pass the input JSON with --input.")).requiredOption("--title <title>","HagiTask session title.").requiredOption("--project-id <id>","Owning project id.").option("--task-id <id>","HagiTask id from `hagitask list`. Required with --input.").option("--prompt-id <id>","Prompt template id, for example auto-compose-commit.en-US. Used when there is no --task-id.").option("--input <file|->","Structured task input: a JSON object file, or - to read it from stdin. Needs --task-id.").option("--message <text>","Optional message that overrides the prompt template.").option("--locale <locale>","Locale for the HagiTask prompt, for example en-US.").option("--repository-path <path>","Optional MonoSpecs sub-repository path, for example repos/cli.").option("--target-type <type>","Explicit target type: repository or vault.").option("--vault-id <id>","Registered vault id for vault-targeted execution.").option("--output-vault-id <id>","Output vault id for research-investigation tasks.").option("--reference-vault-id <ids...>","Reference vault ids the session may read.").option("--editable-vault-id <ids...>","Vault ids the session may edit.").option("--hero-id <id>","Preferred hero id. Takes precedence over --hero-selection-mode.").option("--hero-selection-mode <mode>","Hero choice when --hero-id is not given: first (default) or random.").option("--need-push","Request a push after commit creation when supported.").option("--pull-rebase","Run git pull --rebase before pushing, when push is requested.").option("--target-branch-mode <mode>","Optional target branch mode, for example current or new-custom.").option("--target-branch-name <name>","Custom target branch name. Requires --target-branch-mode new-custom.").option("--script-key <key>","Optional stable scenario script key.").action(async function(r){const i=O(r.taskId),s=O(r.promptId);ri(r,i,s);const a=r.input!==void 0?await oi(E(r.input,"--input")):void 0,u=b(this,t),h={title:E(r.title,"--title"),projectId:E(r.projectId,"--project-id"),promptId:s,presetTaskId:i,presetTaskLocale:O(r.locale),presetTaskInput:a,message:O(r.message),repositoryPath:O(r.repositoryPath),targetType:O(r.targetType),vaultId:O(r.vaultId),outputVaultId:O(r.outputVaultId),referenceVaultIds:fe(r.referenceVaultId),editableVaultIds:fe(r.editableVaultId),heroId:O(r.heroId),heroSelectionMode:O(r.heroSelectionMode),needPush:r.needPush?!0:void 0,pullRebaseBeforePush:r.pullRebase?!0:void 0,targetBranchMode:O(r.targetBranchMode),targetBranchName:O(r.targetBranchName),scriptKey:O(r.scriptKey)},m=J(await u.api.createHagiTaskSession(h));if(u.outputJson){u.io.stdout(S({session:m,presetTaskId:h.presetTaskId??null,promptId:h.promptId??null,requested:h}));return}u.io.stdout(`HagiTask session created
45
+ ${Y(m,[["presetTaskId",h.presetTaskId??void 0],["presetTaskLocale",h.presetTaskLocale??void 0],["promptId",h.promptId??void 0],["repositoryPath",h.repositoryPath??void 0],["targetBranchMode",h.targetBranchMode??void 0],["targetBranchName",h.targetBranchName??void 0],["scriptKey",h.scriptKey??void 0],["heroId",h.heroId??void 0],["heroSelectionMode",h.heroSelectionMode??void 0]])}`)})}var j="-";function ke(e){return e?"yes":"no"}function xe(e){return e&&e.length>0?e.join(", "):j}function ae(e){if(Array.isArray(e))return e.map(t=>ae(t));if(e&&typeof e=="object"){const t=e;return Object.fromEntries(Object.keys(t).sort().map(o=>[o,ae(t[o])]))}return e}function Je(e){return[...e].sort((t,o)=>{const r=t.id??"",i=o.id??"";return r<i?-1:r>i?1:0})}function li(e){return ae({tasks:Je(e)})}function ui(e){if(e.length===0)return`No HagiTask is available.
46
+ `;const t=Je(e);return`HagiTasks (${t.length})
47
+ ${F([{header:"ID",value:o=>o.id??j},{header:"Version",value:o=>o.version??j},{header:"Title",value:o=>o.title??j},{header:"Description",value:o=>o.description??j}],t)}
48
+ `}function di(e){const t=[];e.origin==="derived"&&t.push(e.producer?`derived by ${e.producer}`:"derived");for(const o of e.aliases??[])o.key&&t.push(`alias ${o.key} (deprecated)`);return e.options&&e.options.length>0&&t.push(`options: ${e.options.map(o=>o.value??"").join(", ")}`),t.length>0?t.join("; "):j}function ci(e){const t=e.id??j,o=[];o.push(D([["id",e.id??void 0],["title",e.title??void 0],["version",e.version??void 0],["locale",e.locale??void 0],["description",e.description??void 0]]));const r=e.scope?.targets??[];o.push(`Target scope (default ${e.scope?.defaultTargetType??j})${r.length===0?`
49
+ None.
50
+ `:`
51
+ ${F([{header:"ID",value:m=>m.id??j},{header:"Kind",value:m=>m.kind??j},{header:"Selection",value:m=>m.selectionMode??j},{header:"Required",value:m=>ke(m.required)},{header:"Access",value:m=>xe(m.allowedAccessTypes)},{header:"Input key",value:m=>m.requestKey??j},{header:"Scope key",value:m=>m.scopeRequestKey??j}],r)}
52
+ `}`);const i=e.commands?.commands??[];o.push(`Commands${i.length===0?`
53
+ None.
54
+ `:`
55
+ ${F([{header:"ID",value:m=>m.id??j},{header:"Group",value:m=>m.groupId??j},{header:"Label",value:m=>m.label??j},{header:"URL",value:m=>m.url??j}],i)}
56
+ `}`);const s=e.parameters??[];o.push(`Parameters${s.length===0?`
57
+ None.
58
+ `:`
59
+ ${F([{header:"Key",value:m=>m.key??j},{header:"Required",value:m=>ke(m.required)},{header:"Origin",value:m=>m.origin??j},{header:"Type",value:m=>m.valueType??j},{header:"Label",value:m=>m.label??j},{header:"Notes",value:di}],s)}
60
+ `}`);const a=e.requirements??[];o.push(`Requirements${a.length===0?`
61
+ None.
62
+ `:`
63
+ ${a.map(m=>`- ${m.type??j}: ${m.name??xe(m.names)}`).join(`
64
+ `)}
65
+ `}`);const u=e.scenes?.registrations??[];o.push(`Scenes${u.length===0?`
66
+ None.
67
+ `:`
68
+ ${u.map(m=>`- ${m.sceneKey??j}: ${m.title??j}`).join(`
69
+ `)}
70
+ `}`);const h=e.request;return o.push(D([["endpoint",h?`${h.method??j} ${h.path??j}`:void 0],["presetTaskIdField",h?.presetTaskIdField??void 0],["localeField",h?.localeField??void 0],["requiredFields",h?.requiredFields&&h.requiredFields.length>0?h.requiredFields.join(", "):void 0]])),o.push(`Example
71
+ hagi hagitask schema --task-id ${t} --json # full input JSON Schema and example body
72
+ hagi hagitask create --title "<title>" --project-id <project-id> --task-id ${t} --input input.json
73
+ `),o.join(`
74
+ `)}function pi(e){return ae(e)}function hi(e,t){A(e.command("list").description("List the active HagiTasks with their id, version, title and description.")).action(async function(){const r=b(this,t),i=await r.api.listHagiTaskSchemas();if(r.outputJson){r.io.stdout(S(li(i)));return}r.io.stdout(ui(i))})}function mi(e,t){const o=e&&typeof e=="object"?e[t]:void 0;return typeof o=="string"&&o.trim()?o.trim():void 0}function fi(e){const t=e&&typeof e=="object"?e.diagnostics:void 0;return Array.isArray(t)?t:[]}async function gi(e,t){try{return await e.getHagiTaskSchema(t)}catch(o){if(o instanceof re&&o.status===404){const r=fi(o.body);if(r.length>0){const i=r.map(s=>{const a=s.path?` (${s.path})`:"";return` - ${s.code??"diagnostic"}: ${s.message??""}${a}`});throw new te(404,[mi(o.body,"error")??`HagiTask ${t} is not available.`,...i].join(`
75
+ `),o.body)}}throw o}}function vi(e,t){A(e.command("schema").description("Show the creation schema of one HagiTask: scope, commands, parameters, requirements, scenes and an example. --json prints the full schema, including the input JSON Schema.")).requiredOption("--task-id <id>","HagiTask id to read.").action(async function(r){const i=E(r.taskId,"--task-id"),s=b(this,t),a=await gi(s.api,i);if(s.outputJson){s.io.stdout(S(pi(a)));return}s.io.stdout(ci(a))})}function yi(e,t){A(e.command("send").description("Send a follow-up message to a HagiTask session.")).requiredOption("--session-id <id>","HagiTask session id.").requiredOption("--content <text>","Message content.").addOption(new W("--mode <mode>","Message mode override.").choices(Object.values(be))).addOption(new W("--executor-type <type>","Executor override for this message.").choices(Object.values(de))).action(async function(r){const i=b(this,t),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:E(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(S({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(Oe("HagiTask message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Si(e,t){const o=e.command("hagitask").description("Manage HagiTask sessions: list tasks, read a task schema, create a session from it, and send follow-up messages.");hi(o,t),vi(o,t),ai(o,t),yi(o,t)}function G(e){const t=e?.trim();return t||void 0}function ze(e){if(!e)return"";const t=G(e.mode);if(t==="once")return["once",G(e.runAt)].filter(Boolean).join(" ");const o=G(e.repeat?.rule)??t??"";return[o,o==="weekly"?(e.repeat?.weekdays??[]).map(r=>r.trim().slice(0,3).toLowerCase()).join(","):void 0,G(e.timeOfDay),G(e.timeZone)].filter(Boolean).join(" ")}function K(e){return{id:G(e.id)??"",type:G(e.type)??"",name:G(e.name)??"",enabled:e.enabled===!0,state:G(e.state)??"",nextRunAt:G(e.nextRunAt)??null,schedule:e.schedule,agentPool:e.agentPool,payload:e.payload}}function Oi(e){return{plans:e.map(K)}}function Ai(e){return e.length===0?`No scheduled plans found.
76
+ `:`Plans (${e.length})
77
+ ${F([{header:"ID",value:t=>t.id},{header:"Type",value:t=>t.type},{header:"Name",value:t=>t.name},{header:"Enabled",value:t=>t.enabled?"yes":"no"},{header:"State",value:t=>t.state},{header:"Next Run",value:t=>t.nextRunAt??"-"},{header:"Schedule",value:t=>ze(t.schedule)}],e)}
78
+ `}function se(e){return D([["id",e.id],["type",e.type],["name",e.name],["enabled",e.enabled?"yes":"no"],["state",e.state],["nextRun",e.nextRunAt??"-"],["schedule",ze(e.schedule)]])}function bi(e){return{planId:e,deleted:!0}}function Ci(e){return`Plan deleted
79
+ ${D([["planId",e.planId],["deleted",String(e.deleted)]])}`}function Pi(e){return{planId:G(e.planId)??"",accepted:!0}}function _i(e){return`Plan run accepted
80
+ ${D([["planId",e.planId],["accepted",String(e.accepted)]])}`}var wi=["id","createdAt","updatedAt","state","nextRunAt"];async function Ke(e){let t;try{t=await ce(e)}catch(o){throw o instanceof x?o:new x(`Cannot read plan input from ${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new x(`Plan input from ${e} must be a JSON object.`);return t}function le(e){const t={...e};for(const o of wi)delete t[o];return t}function Ti(e){return{strategy:"random",agents:[{heroId:e}]}}function Xe(e){return{...e.name!==void 0?{name:e.name}:{},...e.heroId!==void 0?{agentPool:Ti(e.heroId)}:{},...e.enabled!==void 0?{enabled:e.enabled}:{}}}function Qe(e,t){return{...le(e),...le(t)}}function Ei(e,t){A(e.command("create").description("Create a scheduled plan from a JSON document. Plans are enabled unless --disabled or the document says otherwise.")).requiredOption("--input <file|->","Plan JSON file path, or - to read from stdin.").option("--name <name>","Plan name. Overrides the document name.").option("--hero-id <id>","Hero for a single-agent pool. Replaces the document agent pool.").option("--disabled","Create the plan disabled. Overrides the document enabled value.").action(async function(r){const i=b(this,t),s=le(await Ke(r.input)),a=K(await i.api.createPlan({enabled:!0,...s,...Xe({name:O(r.name),heroId:O(r.heroId),enabled:r.disabled?!1:void 0})}));if(i.outputJson){i.io.stdout(S({plan:a}));return}i.io.stdout(`Plan created
81
+ ${se(a)}`)})}function Ii(e,t){A(e.command("delete").description("Delete a scheduled plan by id.")).requiredOption("--id <id>","Plan id to delete.").action(async function(r){const i=b(this,t),s=E(r.id,"--id");await i.api.deletePlan(s);const a=bi(s);if(i.outputJson){i.io.stdout(S(a));return}i.io.stdout(Ci(a))})}async function Ye(e,t,o){const r=await e.api.getPlan(t);return K(r).enabled===o?{view:K(r),changed:!1}:{view:K(await e.api.updatePlan(t,Qe(r,{enabled:o}))),changed:!0}}function ki(e,t){A(e.command("disable").description("Disable a scheduled plan. Nothing is sent when it is already disabled.")).requiredOption("--id <id>","Plan id to disable.").action(async function(r){const i=b(this,t),{view:s,changed:a}=await Ye(i,E(r.id,"--id"),!1);if(i.outputJson){i.io.stdout(S({plan:s,changed:a}));return}i.io.stdout(`${a?"Plan disabled":"Plan was already disabled"}
82
+ ${se(s)}`)})}function xi(e,t){A(e.command("enable").description("Enable a scheduled plan. Nothing is sent when it is already enabled.")).requiredOption("--id <id>","Plan id to enable.").action(async function(r){const i=b(this,t),{view:s,changed:a}=await Ye(i,E(r.id,"--id"),!0);if(i.outputJson){i.io.stdout(S({plan:s,changed:a}));return}i.io.stdout(`${a?"Plan enabled":"Plan was already enabled"}
83
+ ${se(s)}`)})}function ji(e,t){A(e.command("get").description("Show one scheduled plan, including its schedule, agent pool and payload in --json mode.")).requiredOption("--id <id>","Plan id to read.").action(async function(r){const i=b(this,t),s=K(await i.api.getPlan(E(r.id,"--id")));if(i.outputJson){i.io.stdout(S({plan:s}));return}i.io.stdout(se(s))})}function $i(e,t){A(e.command("list").description("List scheduled plans with their state, next run time and schedule.")).action(async function(){const r=b(this,t),i=Oi(await r.api.listPlans());if(r.outputJson){r.io.stdout(S(i));return}r.io.stdout(Ai(i.plans))})}function Ni(e,t){A(e.command("run").description("Run a scheduled plan now from its stored inputs. The schedule is not changed.")).requiredOption("--id <id>","Plan id to run.").option("--background","Start the run and print the accepted plan id without waiting for the session.").action(async function(r){const i=b(this,t),s=E(r.id,"--id");if(r.background){const u=Pi(await i.api.startPlan(s));if(i.outputJson){i.io.stdout(S(u));return}i.io.stdout(_i(u));return}const a=J(await i.api.runPlan(s));if(i.outputJson){i.io.stdout(S({session:a}));return}i.io.stdout(`Plan run created a session
84
+ ${Y(a)}`)})}function Hi(e,t){A(e.command("update").description("Update a scheduled plan. The current plan is read first and only the given fields change.")).requiredOption("--id <id>","Plan id to update.").option("--input <file|->","JSON document whose top-level fields replace the same fields of the plan.").option("--name <name>","Updated plan name.").option("--hero-id <id>","Hero for a single-agent pool. Replaces the agent pool.").option("--enabled","Enable the plan.").option("--disabled","Disable the plan.").action(async function(r){const i=E(r.id,"--id"),s=O(r.input),a=O(r.name),u=O(r.heroId);if(r.enabled&&r.disabled)throw new x("Pass either --enabled or --disabled, not both.");const h=r.enabled?!0:r.disabled?!1:void 0;if(!s&&!a&&!u&&h===void 0)throw new x("Provide at least one change: --input, --name, --enabled, --disabled, or --hero-id.");const m=s?le(await Ke(s)):{},P=b(this,t),_=await P.api.getPlan(i),w=K(await P.api.updatePlan(i,Qe(_,{...m,...Xe({name:a,heroId:u,enabled:h})})));if(P.outputJson){P.io.stdout(S({plan:w}));return}P.io.stdout(`Plan updated
85
+ ${se(w)}`)})}function Di(e,t){const o=e.command("plan").description("Manage scheduled plans: saved proposal or HagiTask inputs that run on a schedule.");$i(o,t),ji(o,t),Ei(o,t),Hi(o,t),xi(o,t),ki(o,t),Ii(o,t),Ni(o,t)}function q(e){const t=e?.trim();return t||void 0}function Ce(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 Ze(e){return{projects:(e??[]).map(Ce)}}function Vi(e){return e.length===0?`No projects found.
86
+ `:`Projects (${e.length})
87
+ ${F([{header:"Project ID",value:t=>t.id},{header:"Name",value:t=>t.name},{header:"Path",value:t=>t.path},{header:"MonoSpecs",value:t=>t.isMonoSpecs?"yes":"no"},{header:"Error",value:t=>t.hasError?"yes":"no"}],e)}
88
+ `}function et(e,t=[]){return D([["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],...t])}function Ri(e){return{projectId:q(e.id)??"",name:q(e.name)??"",isMonoSpecs:e.isMonoSpecs===!0,hasError:e.hasError===!0,error:q(e.error),repositories:(e.repositories??[]).map(t=>({name:q(t.name),path:t.path??void 0,displayName:q(t.displayName),type:q(t.type),branch:q(t.branch),isValidGitRepo:typeof t.isValidGitRepo=="boolean"?t.isValidGitRepo:void 0}))}}function qi(e){return`${D([["projectId",e.projectId],["name",e.name],["isMonoSpecs",String(e.isMonoSpecs)],["hasError",String(e.hasError)],["error",e.error??(e.hasError?"The project failed to load; its repository list may be incomplete.":void 0)]])}
89
+ ${e.repositories.length===0?`This project lists no repositories.
90
+ `:`${F([{header:"Name",value:t=>t.name??""},{header:"Path",value:t=>t.path??""},{header:"Display name",value:t=>t.displayName??""},{header:"Type",value:t=>t.type??""},{header:"Branch",value:t=>t.branch??""}],e.repositories)}
91
+ `}`}function Fi(e,t){A(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(r){const i=b(this,t),s=Ce(await i.api.createProject({name:E(r.name,"--name"),path:E(r.path,"--path"),description:O(r.description)}));if(i.outputJson){i.io.stdout(S({project:s}));return}i.io.stdout(`Project created
92
+ ${et(s)}`)})}function Li(e,t){A(e.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(r){const i=b(this,t),s=r.id.trim();if(await i.api.deleteProject(s),i.outputJson){i.io.stdout(S({projectId:s,deleted:!0}));return}i.io.stdout(`Project deleted
93
+ projectId ${s}
94
+ `)})}function Gi(e,t){A(e.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const r=b(this,t),i=Ze((await r.api.listProjects()).projects);if(r.outputJson){r.io.stdout(S(i));return}r.io.stdout(Vi(i.projects))})}function Ui(e,t){A(e.command("repositories").description("List the repositories of one project from the aggregation snapshot.")).requiredOption("--id <id>","Project id whose repositories to list.").action(async function(r){const i=b(this,t),s=r.id.trim(),a=((await i.api.listProjects()).projects??[]).find(h=>h.id===s);if(!a)throw new te(404,`Project ${s} was not found in the aggregation snapshot.`);const u=Ri(a);if(i.outputJson){i.io.stdout(S(u));return}i.io.stdout(qi(u))})}function Bi(e,t){A(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(r){if(!r.name&&!r.path&&!r.description&&!r.clearDescription)throw new x("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(r.description&&r.clearDescription)throw new x("Use either --description or --clear-description, not both.");const i=b(this,t),s=r.id.trim(),a=Ze((await i.api.listProjects()).projects).projects.find(h=>h.id===s);if(!a)throw new te(404,`Project ${s} was not found in the aggregation snapshot.`);const u=Ce(await i.api.updateProject(s,{name:O(r.name)??a.name,path:O(r.path)??a.path,description:r.clearDescription?null:O(r.description)??a.description??null}));if(i.outputJson){i.io.stdout(S({project:u}));return}i.io.stdout(`Project updated
95
+ ${et(u)}`)})}function Mi(e,t){const o=e.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");Gi(o,t),Ui(o,t),Fi(o,t),Bi(o,t),Li(o,t)}function Wi(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new x("Annotation input must be a JSON object.");const o=t;if(!Array.isArray(o.files))throw new x("Annotation input must include a files array.");const r=typeof o.totalAnnotations=="number"?o.totalAnnotations:o.files.length,i=typeof o.submittedAt=="string"&&o.submittedAt.trim()?o.submittedAt:new Date().toISOString();return{...o,sessionId:e,totalAnnotations:r,submittedAt:i,files:o.files}}function Ji(e,t){A(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(r){const i=b(this,t),s=r.sessionId.trim(),a=Wi(s,await ce(r.input)),u=await i.api.submitAnnotations(s,a);if(i.outputJson){i.io.stdout(S({sessionId:s,message:u.message,annotationCount:u.annotationCount??a.totalAnnotations,fileCount:u.fileCount??a.files.length}));return}i.io.stdout(`Proposal annotations submitted
96
+ sessionId ${s}
97
+ message ${u.message}
98
+ annotationCount ${u.annotationCount??a.totalAnnotations}
99
+ fileCount ${u.fileCount??a.files.length}
100
+ `)})}function zi(e,t){A(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(r){const i=b(this,t),s=J(await i.api.archiveProposal(r.sessionId.trim(),{heroId:O(r.heroId)}));if(i.outputJson){i.io.stdout(S({session:s}));return}i.io.stdout(`Proposal archive started
101
+ ${Y(s)}`)})}function Ki(e,t){A(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(r){const i=b(this,t),s=J(await i.api.completeProposal(r.sessionId.trim()));if(i.outputJson){i.io.stdout(S({session:s}));return}i.io.stdout(`Proposal completed
102
+ ${Y(s)}`)})}function Xi(e){return J(e)}function Qi(e){return Me(e)}function Yi(e){return We("Proposal sessions",e)}function Zi(e,t=[]){return Y(e,t)}var tt="New Proposal";function es(e){const t=O(e.title);if(t)return t;if(e.defaultTitle)return tt;throw new x("Provide --title or pass --default-title to use the placeholder proposal title.")}function ts(e,t){A(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 (${tt}).`).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(r){const i=b(this,t),s=es(r),a=Xi(await i.api.createProposalSession({title:s,chiefComplaint:r.chiefComplaint.trim(),originalChiefComplaint:O(r.originalChiefComplaint),type:Ae.PROPOSAL,projectId:r.projectId.trim(),enableIndependentWorkspace:r.enableIndependentWorkspace?!0:void 0,baseBranch:O(r.baseBranch),isDefaultTitle:!!r.defaultTitle})),u=`hagi proposal optimize-description --session-id ${a.sessionId} --description "<description>"`;if(i.outputJson){i.io.stdout(S({session:a,nextCommand:u}));return}i.io.stdout(`Proposal session created
103
+ ${Zi(a,[["next",u]])}`)})}function is(e,t){A(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(r){const i=b(this,t),s=r.sessionId.trim(),a=O(r.heroId),u=await i.api.executeProposal(s,{heroId:a});if(i.outputJson){i.io.stdout(S({sessionId:s,message:u.message,requested:{heroId:a}}));return}i.io.stdout(`Proposal execution started
104
+ sessionId ${s}
105
+ message ${u.message}
106
+ `)})}var ge=["zh-CN","zh-Hant","en-US","ja-JP","ko-KR","de-DE","fr-FR","es-ES","pt-BR","ru-RU"];function ss(e){if(e.enableExploreMode&&e.disableExploreMode)throw new x("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(e.enableExploreMode)return!0;if(e.disableExploreMode)return!1}function ns(e){const t=e.trim();if(!ge.includes(t))throw new x(`--proposal-content-language must be one of: ${ge.join(", ")}.`);return t}function os(e,t){A(e.command("generate").description("Start proposal generation only. This command does not execute the proposal.")).requiredOption("--session-id <id>","Proposal session id to generate.").requiredOption("--proposal-content-language <language>",`Language of the generated proposal content (${ge.join(", ")}).`).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(r){const i=b(this,t),s=r.sessionId.trim(),a=ss(r),u=ns(r.proposalContentLanguage),h=await i.api.generateProposal(s,{enableExploreMode:a,heroId:O(r.heroId),proposalContentLanguage:u}),m=`hagi proposal execute --session-id ${s}`;if(i.outputJson){i.io.stdout(S({sessionId:s,message:h.message,requested:{enableExploreMode:a,heroId:O(r.heroId),proposalContentLanguage:u},nextCommand:m}));return}i.io.stdout(`Proposal generation started
107
+ sessionId ${s}
108
+ message ${h.message}
109
+ next Wait for the session to reach Reviewing, then run ${m}
110
+ `)})}function rs(e,t){A(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(r){if(r.projectId&&r.projectIds?.length)throw new x("Use either --project-id or --project-ids, not both.");const i=b(this,t),s=Qi(await i.api.listSessions({type:Ae.PROPOSAL,projectId:O(r.projectId),projectIds:r.projectIds?.map(O).filter(Boolean),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout(Yi(s.sessions))})}function as(e,t){const o=t.summary,r=t.result,i=r?.validation?.isValid===!0,s=o?.appliedTitle||r?.optimizedTitle||"",a=o?.appliedProposalName||r?.optimizedProposalName||"",u=r?.validation?.diagnostics??[],h=[i?"Proposal optimized":"Proposal optimization returned diagnostics",`sessionId ${e}`,`title ${s}`,`proposalName ${a}`,`valid ${i?"yes":"no"}`];for(const m of u)h.push(`diagnostic ${m.code??"UNKNOWN"}: ${m.message??""}`.trimEnd());return i&&h.push(`next hagi proposal generate --session-id ${e}`),`${h.join(`
111
+ `)}
112
+ `}function ls(e,t){A(e.command("optimize-description").description("Optimize the proposal description, title, and name in one backend step.")).requiredOption("--session-id <id>","Proposal session id to optimize.").requiredOption("--description <text>","Description text to optimize.").option("--title <title>","Current title snapshot. The session title is used when omitted.").option("--default-title","Treat the current title as the placeholder title.").option("--optimization-direction <text>","Optional optimization direction for AI guidance.").option("--original-chief-complaint <text>","Optional original chief complaint to keep as context.").action(async function(r){const i=b(this,t),s=E(r.sessionId,"--session-id"),a=await i.api.optimizeProposal(s,{description:E(r.description,"--description"),title:O(r.title),isDefaultTitle:r.defaultTitle?!0:void 0,optimizationDirection:O(r.optimizationDirection),originalChiefComplaint:O(r.originalChiefComplaint)});if(i.outputJson){i.io.stdout(S({sessionId:s,...a}));return}i.io.stdout(as(s,a))})}function us(e,t){A(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 W("--mode <mode>","Message mode override.").choices(Object.values(be))).addOption(new W("--executor-type <type>","Executor override for this message.").choices(Object.values(de))).action(async function(r){const i=b(this,t),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:E(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(S({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(Oe("Proposal message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function ds(e,t){A(e.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new W("--status <status>","Target session status.").choices(Object.values(Ue)).makeOptionMandatory()).action(async function(r){const i=b(this,t),s=r.sessionId.trim(),a=await i.api.getSession(s);await i.api.updateSession(s,{title:a.title,description:a.description,status:r.status,metadata:a.metadata});const u=J({...a,status:r.status});if(i.outputJson){i.io.stdout(S({session:u}));return}i.io.stdout(`Proposal status updated
113
+ ${Y(u)}`)})}function cs(e,t){const o=e.command("proposal").description("Manage proposal sessions through backend session APIs.");rs(o,t),ts(o,t),ls(o,t),os(o,t),Ji(o,t),is(o,t),zi(o,t),ds(o,t),Ki(o,t),us(o,t)}function X(e){return e?"yes":"no"}function ps(e){return e&&e.length>0?e.join(", "):"-"}function it(e){return e.origin??"user"}function st(e){return it(e)==="built-in"}function hs(e){return st(e)?X(e.builtIn?.enabled):"-"}function ms(e){return(st(e)?e.builtIn?.version:e.managedInstallMetadata?.version)??"-"}function fs(e){const t=e.items??[];return t.length===0?`No local skills installed.
114
+ `:`Local skills (${t.length})
115
+ ${F([{header:"Name",value:o=>o.name??"-"},{header:"Origin",value:it},{header:"Enabled",value:hs},{header:"Version",value:ms},{header:"Scope",value:o=>o.scope??"-"},{header:"Agents",value:o=>ps(o.agents)},{header:"Path",value:o=>o.path??"-"}],t)}
116
+ `}function gs(e){return D([["skillName",e.skillName??void 0],["status",e.status??void 0],["message",e.userMessage??void 0],["diagnostic",e.diagnosticMessage??void 0]])}function vs(e){return D([["skillName",e.slug??void 0],["enabled",X(e.enabled)],["message",e.userMessage??void 0],["diagnostic",e.diagnosticMessage??void 0]])}function ys(e){const t=e.items??[];return t.length===0?`No gallery skills found.
117
+ `:`Gallery skills (${t.length})
118
+ ${F([{header:"ID",value:o=>o.id??"-"},{header:"Source",value:o=>o.source??"-"},{header:"Installs",value:o=>String(o.installs??0)},{header:"Trusted",value:o=>X(o.isTrustedSource)}],t)}
119
+ `}function Ss(e){const t=e.trustedProvider;return D([["id",e.id??void 0],["source",e.source??void 0],["skillSlug",e.skillSlug??void 0],["installable",X(e.isInstallable)],["description",e.description??void 0],["repository",e.repositoryFullName??e.repositoryName??void 0],["repositoryUrl",e.repositoryUrl??void 0],["defaultBranch",e.repositoryDefaultBranch??void 0],["trustedSource",X(e.isTrustedSource)],["trustedProvider",t?`${t.displayName??t.providerId??"-"}`:void 0],["installReference",e.installReference??void 0],["installCommand",e.installCommandPreview??void 0],["installVersion",e.installVersion??void 0],["installHint",e.installHint??void 0]])}function Os(e){return D([["installReference",e.installReference??void 0],["normalizedSkillKey",e.normalizedSkillKey??void 0],["version",e.version??void 0],["status",e.status??void 0],["message",e.userMessage??void 0],["diagnostic",e.diagnosticMessage??void 0],["commandPreview",e.commandPreview??void 0]])}function oe(e){const t=e.items??[];return t.length===0?`No trusted providers (directory version ${e.version??0}).
120
+ `:`Trusted providers (${t.length}, directory version ${e.version??0})
121
+ ${F([{header:"Provider ID",value:o=>o.providerId??"-"},{header:"Name",value:o=>o.displayName??"-"},{header:"Enabled",value:o=>X(o.isEnabled)},{header:"Preset",value:o=>X(o.isPreset)},{header:"Rules",value:o=>String(o.ruleCount??0)}],t)}
122
+ `}function As(e,t){const o=e.command("gallery").description("Search the skill gallery, read skill details, and start managed installs.");A(o.command("search").description("Search the skill gallery by keyword.")).option("--query <query>","Keyword to search for. Omit to list the gallery.").action(async function(i){const s=b(this,t),a=await s.api.searchSkillGallery(O(i.query));if(s.outputJson){s.io.stdout(S(a));return}s.io.stdout(ys(a))}),A(o.command("detail").description("Show one gallery skill with installability, trust, and repository details.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").action(async function(i){const s=b(this,t),a=await s.api.getSkillGalleryDetail(E(i.id,"--id"),E(i.source,"--source"));if(s.outputJson){s.io.stdout(S(a));return}s.io.stdout(Ss(a))}),A(o.command("install").description("Start a managed install of one gallery skill.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").requiredOption("--skill-slug <slug>","Skill slug inside the source repository.").option("--version <version>","Optional version token to install.").action(async function(i){const s=b(this,t),a=await s.api.installGallerySkill({id:E(i.id,"--id"),source:E(i.source,"--source"),skillSlug:E(i.skillSlug,"--skill-slug"),version:O(i.version)});if(s.outputJson){s.io.stdout(S(a));return}s.io.stdout(Os(a))})}var bs="The change applies to agent runs that start afterwards; a run already in progress keeps its skills.";function je(e,t,o){const r=o?"enable":"disable";A(e.command(r).description(`${o?"Turn on":"Turn off"} one built-in skill by name. ${bs}`)).requiredOption("--skill-name <name>",`Built-in skill name to ${r}.`).action(async function(s){const a=b(this,t),u=await a.api.setBuiltInSkillAvailability({slug:E(s.skillName,"--skill-name"),enabled:o});if(a.outputJson?a.io.stdout(S(u)):a.io.stdout(vs(u)),!u.succeeded)throw new Ve(u.userMessage??`The built-in skill availability was not changed for ${u.slug??s.skillName}.`)})}function Cs(e,t){const o=e.command("local").description("List, enable or disable built-in skills, and uninstall user-installed local skills.");A(o.command("list").description("List installed local skills with their managed install metadata.")).action(async function(){const i=b(this,t),s=await i.api.listLocalSkills();if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout(fs(s))}),je(o,t,!0),je(o,t,!1),A(o.command("uninstall").description("Uninstall one user-installed local skill by name. Built-in skills cannot be uninstalled; use `skills local disable --skill-name <name>` to stop one from loading.")).requiredOption("--skill-name <name>","Local skill name to uninstall.").action(async function(i){const s=b(this,t),a=await s.api.uninstallLocalSkill({skillName:E(i.skillName,"--skill-name")});if(s.outputJson){s.io.stdout(S(a));return}s.io.stdout(gs(a))})}async function Ps(e,t){const o=await ce(e);if(!o||typeof o!="object"||Array.isArray(o))throw new x(`${t} must be a JSON object.`);return o}function _s(e,t){const o=e.command("trusted").description("Manage the trusted skill provider directory.");A(o.command("list").description("List trusted skill providers.")).action(async function(){const i=b(this,t),s=await i.api.listTrustedSkillProviders();if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout(oe(s))}),A(o.command("upsert").description("Create or update a trusted provider from a JSON document.")).requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(i){const s=b(this,t),a=await Ps(E(i.input,"--input"),"Trusted provider input"),u=await s.api.upsertTrustedSkillProvider(a);if(s.outputJson){s.io.stdout(S(u));return}s.io.stdout(oe(u))}),A(o.command("delete").description("Delete one trusted provider by id.")).requiredOption("--provider-id <id>","Trusted provider id to delete.").action(async function(i){const s=b(this,t),a={providerId:E(i.providerId,"--provider-id")},u=await s.api.deleteTrustedSkillProvider(a);if(s.outputJson){s.io.stdout(S(u));return}s.io.stdout(oe(u))}),A(o.command("reset").description("Reset trusted providers to the backend defaults.")).action(async function(){const i=b(this,t),s=await i.api.resetTrustedSkillProviders();if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout(oe(s))})}function ws(e,t){const o=e.command("skills").description("Manage local skills, the skill gallery, and trusted providers.");Cs(o,t),As(o,t),_s(o,t)}function k(e){const t=e?.trim();return t||void 0}function Ts(e){return{severity:k(e.severity)??"",code:k(e.code)??"",message:k(e.message)??"",relativePath:k(e.relativePath)}}function Pe(e){return{id:k(e.id)??"",name:k(e.name)??"",type:k(e.type)??"",physicalPath:k(e.physicalPath)??"",gitUrl:k(e.gitUrl),createdAtUtc:k(e.createdAtUtc),updatedAtUtc:k(e.updatedAtUtc),bootstrapDiagnostics:(e.bootstrapDiagnostics??[]).map(Ts)}}function nt(e){return{generatedAtUtc:k(e.generatedAtUtc),vaults:(e.items??[]).map(Pe)}}function Es(e){return e.length===0?`No vaults found.
123
+ `:`Vaults (${e.length})
124
+ ${F([{header:"Vault ID",value:t=>t.id},{header:"Type",value:t=>t.type},{header:"Name",value:t=>t.name},{header:"Path",value:t=>t.physicalPath}],e)}
125
+ `}function ot(e,t=[]){return D([["id",e.id],["name",e.name],["type",e.type],["physicalPath",e.physicalPath],["gitUrl",e.gitUrl],["createdAtUtc",e.createdAtUtc],["updatedAtUtc",e.updatedAtUtc],["bootstrapDiagnostics",String(e.bootstrapDiagnostics.length)],...t])}function Is(e){return{relativePath:k(e.relativePath)??"",fileName:k(e.fileName)??"",isDirectory:e.isDirectory===!0,extension:k(e.extension)??"",sizeBytes:typeof e.sizeBytes=="number"?e.sizeBytes:0,lastModifiedUtc:k(e.lastModifiedUtc),previewSupported:e.previewSupported===!0}}function ks(e){return{vaultId:k(e.id)??"",deleted:e.deleted===!0,deleteLocalFilesRequested:e.deleteLocalFilesRequested===!0,localFilesDeletionStatus:k(e.localFilesDeletionStatus),localFilesDeleted:e.localFilesDeleted===!0}}function xs(e){return`Vault deleted
126
+ ${D([["vaultId",e.vaultId],["deleted",String(e.deleted)],["deleteLocalFilesRequested",String(e.deleteLocalFilesRequested)],["localFilesDeletionStatus",e.localFilesDeletionStatus],["localFilesDeleted",String(e.localFilesDeleted)]])}`}function js(e){return{vaultId:k(e.vaultId)??"",vaultName:k(e.vaultName)??"",physicalPath:k(e.physicalPath)??"",status:k(e.status)??"",errorCode:k(e.errorCode),message:k(e.message),isTruncated:e.isTruncated===!0,totalFileCount:typeof e.totalFileCount=="number"?e.totalFileCount:0,items:(e.items??[]).map(Is)}}function $s(e){const t=D([["vaultId",e.vaultId],["vaultName",e.vaultName],["physicalPath",e.physicalPath],["status",e.status],["errorCode",e.errorCode],["message",e.message],["isTruncated",String(e.isTruncated)],["totalFileCount",String(e.totalFileCount)]]);return e.items.length===0?`Vault files
127
+ ${t}No files found.
128
+ `:`Vault files
129
+ ${t}${F([{header:"Relative Path",value:o=>o.relativePath},{header:"Directory",value:o=>o.isDirectory?"yes":"no"},{header:"Extension",value:o=>o.extension},{header:"Size",value:o=>String(o.sizeBytes)},{header:"Preview",value:o=>o.previewSupported?"yes":"no"}],e.items)}
130
+ `}function Ns(e){return{vaultId:k(e.vaultId)??"",vaultName:k(e.vaultName)??"",physicalPath:k(e.physicalPath)??"",relativePath:k(e.relativePath)??"",fileName:k(e.fileName)??"",extension:k(e.extension)??"",sizeBytes:typeof e.sizeBytes=="number"?e.sizeBytes:0,lastModifiedUtc:k(e.lastModifiedUtc),status:k(e.status)??"",errorCode:k(e.errorCode),message:k(e.message),previewSupported:e.previewSupported===!0,contentTruncated:e.contentTruncated===!0,content:k(e.content)}}function Hs(e){const t=D([["vaultId",e.vaultId],["vaultName",e.vaultName],["physicalPath",e.physicalPath],["relativePath",e.relativePath],["fileName",e.fileName],["extension",e.extension],["sizeBytes",String(e.sizeBytes)],["lastModifiedUtc",e.lastModifiedUtc],["status",e.status],["errorCode",e.errorCode],["message",e.message],["previewSupported",String(e.previewSupported)],["contentTruncated",String(e.contentTruncated)]]);if(!e.content)return`Vault file preview
131
+ ${t}`;const o=e.content.endsWith(`
132
+ `)?"":`
133
+ `;return`Vault file preview
134
+ ${t}content
135
+ -------
136
+ ${e.content}${o}`}function Ds(e,t){A(e.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(r){const i=b(this,t),s=Pe(await i.api.createVault({name:E(r.name,"--name"),type:E(r.type,"--type"),physicalPath:E(r.physicalPath,"--physical-path"),gitUrl:O(r.gitUrl)}));if(i.outputJson){i.io.stdout(S({vault:s}));return}i.io.stdout(`Vault created
137
+ ${ot(s)}`)})}function Vs(e,t){A(e.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(r){const i=b(this,t),s=ks(await i.api.deleteVault(E(r.id,"--id"),r.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout(xs(s))})}function Rs(e,t){A(e.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(r){const i=b(this,t),s=js(await i.api.listVaultFiles(E(r.id,"--id"),O(r.path)));if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout($s(s))})}function qs(e,t){A(e.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(r){const i=b(this,t),s=Ns(await i.api.previewVaultFile(E(r.id,"--id"),E(r.path,"--path")));if(i.outputJson){i.io.stdout(S(s));return}i.io.stdout(Hs(s))})}function Fs(e,t){A(e.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const r=b(this,t),i=nt(await r.api.listVaults());if(r.outputJson){r.io.stdout(S(i));return}r.io.stdout(Es(i.vaults))})}function Ls(e,t){A(e.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(r){const i=O(r.name),s=O(r.type),a=O(r.physicalPath),u=O(r.gitUrl);if(!i&&!s&&!a&&!u)throw new x("Provide at least one field to update: --name, --type, --physical-path, or --git-url.");const h=b(this,t),m=E(r.id,"--id"),P=nt(await h.api.listVaults()).vaults.find(w=>w.id===m);if(!P)throw new te(404,`Vault ${m} was not found in the latest vault snapshot.`);const _=Pe(await h.api.updateVault(m,{name:i??P.name,type:s??P.type,physicalPath:a??P.physicalPath,gitUrl:u??P.gitUrl??null}));if(h.outputJson){h.io.stdout(S({vault:_}));return}h.io.stdout(`Vault updated
138
+ ${ot(_)}`)})}function Gs(e,t){const o=e.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");Fs(o,t),Ds(o,t),Ls(o,t),Vs(o,t);const r=o.command("files").description("Browse registered vault files and preview supported content.");Rs(r,t),qs(r,t)}function Us(e){return e.includes("--json")}function rt(e=Ge(),t=!1){const o=new Pt;return o.name("hagi").description("HagiCode CLI for project, proposal, vault, chat, HagiTask, and scheduled plan management.").showHelpAfterError().exitOverride(),o.configureOutput({writeOut:r=>{e.io.stdout(r)},writeErr:r=>{t||e.io.stderr(r)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),Xt(o),Mi(o,e),cs(o,e),Gs(o,e),ii(o,e),Si(o,e),Di(o,e),ws(o,e),o}function Bs(e,t,o){return e.exitCode===0||e.code==="commander.helpDisplayed"||e.code==="commander.version"?0:(o&&t.io.stderr(qe({exitCode:V.USAGE,message:e.message},{json:!0})),V.USAGE)}async function Ms(e=process.argv,t=Ge()){const o=Us(e),r=rt(t,o);try{return await r.parseAsync([...e]),0}catch(i){if(i instanceof Ct)return Bs(i,t,o);const s=wt(i,{baseUrl:Ht()});return t.io.stderr(qe(s,{json:o})),s.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return V}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return rt}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return Ms}});
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-KH2FkAFy.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-BCYk7a3O.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-KH2FkAFy.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/main-BCYk7a3O.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hagicode/cli",
3
- "version": "0.1.0-dev.28.1.71f1989",
3
+ "version": "0.1.0-dev.29.1.2b7f294",
4
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": {
@@ -1,108 +0,0 @@
1
- var se=Object.create,Et=Object.defineProperty,oe=Object.getOwnPropertyDescriptor,ne=Object.getOwnPropertyNames,re=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty,X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),le=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(var i=ne(e),s=0,a=i.length,u;s<a;s++)u=i[s],!ae.call(t,u)&&u!==n&&Et(t,u,{get:(h=>e[h]).bind(null,u),enumerable:!(r=oe(e,u))||r.enumerable});return t},ue=(t,e,n)=>(n=t!=null?se(re(t)):{},le(e||!t||!t.__esModule?Et(n,"default",{value:t,enumerable:!0}):n,t));let Ct=require("node:path"),de=require("node:fs"),ce=require("node:os"),pe=require("node:fs/promises");var nt=X((t=>{var e=class extends Error{constructor(r,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=r,this.nestedError=void 0}},n=class extends e{constructor(r){super(1,"commander.invalidArgument",r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};t.CommanderError=e,t.InvalidArgumentError=n})),ht=X((t=>{var{InvalidArgumentError:e}=nt(),n=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,a)=>{if(!this.argChoices.includes(s))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(s,a):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(i){const s=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+s+">":"["+s+"]"}t.Argument=n,t.humanReadableArgName=r})),It=X((t=>{var{humanReadableArgName:e}=ht(),n=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),a=i._getHelpCommand();return a&&!a._hidden&&s.push(a),this.sortSubcommands&&s.sort((u,h)=>u.name().localeCompare(h.name())),s}compareOptions(i,s){const a=u=>u.short?u.short.replace(/^-/,""):u.long.replace(/^--/,"");return a(i).localeCompare(a(s))}visibleOptions(i){const s=i.options.filter(u=>!u.hidden),a=i._getHelpOption();if(a&&!a.hidden){const u=a.short&&i._findOption(a.short),h=a.long&&i._findOption(a.long);!u&&!h?s.push(a):a.long&&!h?s.push(i.createOption(a.long,a.description)):a.short&&!u&&s.push(i.createOption(a.short,a.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const s=[];for(let a=i.parent;a;a=a.parent){const u=a.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(a=>e(a)).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((a,u)=>Math.max(a,this.displayWidth(s.styleSubcommandTerm(s.subcommandTerm(u)))),0)}longestOptionTermLength(i,s){return s.visibleOptions(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestGlobalOptionTermLength(i,s){return s.visibleGlobalOptions(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestArgumentTermLength(i,s){return s.visibleArguments(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleArgumentTerm(s.argumentTerm(u)))),0)}commandUsage(i){let s=i._name;i._aliases[0]&&(s=s+"|"+i._aliases[0]);let a="";for(let u=i.parent;u;u=u.parent)a=u.name()+" "+a;return a+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(a=>JSON.stringify(a)).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 a=`(${s.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}argumentDescription(i){const s=[];if(i.argChoices&&s.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&s.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),s.length>0){const a=`(${s.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}formatItemList(i,s,a){return s.length===0?[]:[a.styleTitle(i),...s,""]}groupItems(i,s,a){const u=new Map;return i.forEach(h=>{const v=a(h);u.has(v)||u.set(v,[])}),s.forEach(h=>{const v=a(h);u.has(v)||u.set(v,[]),u.get(v).push(h)}),u}formatHelp(i,s){const a=s.padWidth(i,s),u=s.helpWidth??80;function h(w,$){return s.formatItem(w,a,$,s)}let v=[`${s.styleTitle("Usage:")} ${s.styleUsage(s.commandUsage(i))}`,""];const _=s.commandDescription(i);_.length>0&&(v=v.concat([s.boxWrap(s.styleCommandDescription(_),u),""]));const P=s.visibleArguments(i).map(w=>h(s.styleArgumentTerm(s.argumentTerm(w)),s.styleArgumentDescription(s.argumentDescription(w))));if(v=v.concat(this.formatItemList("Arguments:",P,s)),this.groupItems(i.options,s.visibleOptions(i),w=>w.helpGroupHeading??"Options:").forEach((w,$)=>{const B=w.map(q=>h(s.styleOptionTerm(s.optionTerm(q)),s.styleOptionDescription(s.optionDescription(q))));v=v.concat(this.formatItemList($,B,s))}),s.showGlobalOptions){const w=s.visibleGlobalOptions(i).map($=>h(s.styleOptionTerm(s.optionTerm($)),s.styleOptionDescription(s.optionDescription($))));v=v.concat(this.formatItemList("Global Options:",w,s))}return this.groupItems(i.commands,s.visibleCommands(i),w=>w.helpGroup()||"Commands:").forEach((w,$)=>{const B=w.map(q=>h(s.styleSubcommandTerm(s.subcommandTerm(q)),s.styleSubcommandDescription(s.subcommandDescription(q))));v=v.concat(this.formatItemList($,B,s))}),v.join(`
2
- `)}displayWidth(i){return r(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,a,u){const v=" ".repeat(2);if(!a)return v+i;const _=i.padEnd(s+i.length-u.displayWidth(i)),P=2,w=(this.helpWidth??80)-s-P-2;let $;return w<this.minWidthToWrap||u.preformatted(a)?$=a:$=u.boxWrap(a,w).replace(/\n/g,`
3
- `+" ".repeat(s+P)),v+_+" ".repeat(P)+$.replace(/\n/g,`
4
- ${v}`)}boxWrap(i,s){if(s<this.minWidthToWrap)return i;const a=i.split(/\r\n|\n/),u=/[\s]*[^\s]+/g,h=[];return a.forEach(v=>{const _=v.match(u);if(_===null){h.push("");return}let P=[_.shift()],w=this.displayWidth(P[0]);_.forEach($=>{const B=this.displayWidth($);if(w+B<=s){P.push($),w+=B;return}h.push(P.join(""));const q=$.trimStart();P=[q],w=this.displayWidth(q)}),h.push(P.join(""))}),h.join(`
5
- `)}};function r(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}t.Help=n,t.stripColor=r})),Tt=X((t=>{var{InvalidArgumentError:e}=nt(),n=class{constructor(a,u){this.flags=a,this.description=u||"",this.required=a.includes("<"),this.optional=a.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(a),this.mandatory=!1;const h=s(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,u){return this.defaultValue=a,this.defaultValueDescription=u,this}preset(a){return this.presetArg=a,this}conflicts(a){return this.conflictsWith=this.conflictsWith.concat(a),this}implies(a){let u=a;return typeof a=="string"&&(u={[a]:!0}),this.implied=Object.assign(this.implied||{},u),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,u){return u===this.defaultValue||!Array.isArray(u)?[a]:(u.push(a),u)}choices(a){return this.argChoices=a.slice(),this.parseArg=(u,h)=>{if(!this.argChoices.includes(u))throw new e(`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(a){return this.helpGroupHeading=a,this}is(a){return this.short===a||this.long===a}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(a){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,a.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(a,u){const h=u.attributeName();if(!this.dualOptions.has(h))return!0;const v=this.negativeOptions.get(h).presetArg,_=v!==void 0?v:!1;return u.negate===(_===a)}};function i(a){return a.split("-").reduce((u,h)=>u+h[0].toUpperCase()+h.slice(1))}function s(a){let u,h;const v=/^-[^-]$/,_=/^--[^-]/,P=a.split(/[ |,]+/).concat("guard");if(v.test(P[0])&&(u=P.shift()),_.test(P[0])&&(h=P.shift()),!u&&v.test(P[0])&&(u=P.shift()),!u&&_.test(P[0])&&(u=h,h=P.shift()),P[0].startsWith("-")){const w=P[0],$=`option creation failed due to '${w}' in option flags '${a}'`;throw/^-[^-][^-]/.test(w)?new Error(`${$}
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')`):v.test(w)?new Error(`${$}
9
- - too many short flags`):_.test(w)?new Error(`${$}
10
- - too many long flags`):new Error(`${$}
11
- - unrecognised flag format`)}if(u===void 0&&h===void 0)throw new Error(`option creation failed due to no flags found in '${a}'.`);return{shortFlag:u,longFlag:h}}t.Option=n,t.DualOptions=r})),he=X((t=>{var e=3;function n(i,s){if(Math.abs(i.length-s.length)>e)return Math.max(i.length,s.length);const a=[];for(let u=0;u<=i.length;u++)a[u]=[u];for(let u=0;u<=s.length;u++)a[0][u]=u;for(let u=1;u<=s.length;u++)for(let h=1;h<=i.length;h++){let v=1;i[h-1]===s[u-1]?v=0:v=1,a[h][u]=Math.min(a[h-1][u]+1,a[h][u-1]+1,a[h-1][u-1]+v),h>1&&u>1&&i[h-1]===s[u-2]&&i[h-2]===s[u-1]&&(a[h][u]=Math.min(a[h][u],a[h-2][u-2]+1))}return a[i.length][s.length]}function r(i,s){if(!s||s.length===0)return"";s=Array.from(new Set(s));const a=i.startsWith("--");a&&(i=i.slice(2),s=s.map(_=>_.slice(2)));let u=[],h=e;const v=.4;return s.forEach(_=>{if(_.length<=1)return;const P=n(i,_),w=Math.max(i.length,_.length);(w-P)/w>v&&(P<h?(h=P,u=[_]):P===h&&u.push(_))}),u.sort((_,P)=>_.localeCompare(P)),a&&(u=u.map(_=>`--${_}`)),u.length>1?`
12
- (Did you mean one of ${u.join(", ")}?)`:u.length===1?`
13
- (Did you mean ${u[0]}?)`:""}t.suggestSimilar=r})),me=X((t=>{var e=require("node:events").EventEmitter,n=require("node:child_process"),r=require("node:path"),i=require("node:fs"),s=require("node:process"),{Argument:a,humanReadableArgName:u}=ht(),{CommanderError:h}=nt(),{Help:v,stripColor:_}=It(),{Option:P,DualOptions:w}=Tt(),{suggestSimilar:$}=he(),B=class xt extends e{constructor(o){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=o||"",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:l=>s.stdout.write(l),writeErr:l=>s.stderr.write(l),outputError:(l,d)=>d(l),getOutHelpWidth:()=>s.stdout.isTTY?s.stdout.columns:void 0,getErrHelpWidth:()=>s.stderr.isTTY?s.stderr.columns:void 0,getOutHasColors:()=>lt()??(s.stdout.isTTY&&s.stdout.hasColors?.()),getErrHasColors:()=>lt()??(s.stderr.isTTY&&s.stderr.hasColors?.()),stripColor:l=>_(l)},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(o){return this._outputConfiguration=o._outputConfiguration,this._helpOption=o._helpOption,this._helpCommand=o._helpCommand,this._helpConfiguration=o._helpConfiguration,this._exitCallback=o._exitCallback,this._storeOptionsAsProperties=o._storeOptionsAsProperties,this._combineFlagAndOptionalValue=o._combineFlagAndOptionalValue,this._allowExcessArguments=o._allowExcessArguments,this._enablePositionalOptions=o._enablePositionalOptions,this._showHelpAfterError=o._showHelpAfterError,this._showSuggestionAfterError=o._showSuggestionAfterError,this}_getCommandAndAncestors(){const o=[];for(let l=this;l;l=l.parent)o.push(l);return o}command(o,l,d){let c=l,p=d;typeof c=="object"&&c!==null&&(p=c,c=null),p=p||{};const[,g,b]=o.match(/([^ ]+) *(.*)/),E=this.createCommand(g);return c&&(E.description(c),E._executableHandler=!0),p.isDefault&&(this._defaultCommandName=E._name),E._hidden=!!(p.noHelp||p.hidden),E._executableFile=p.executableFile||null,b&&E.arguments(b),this._registerCommand(E),E.parent=this,E.copyInheritedSettings(this),c?this:E}createCommand(o){return new xt(o)}createHelp(){return Object.assign(new v,this.configureHelp())}configureHelp(o){return o===void 0?this._helpConfiguration:(this._helpConfiguration=o,this)}configureOutput(o){return o===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...o},this)}showHelpAfterError(o=!0){return typeof o!="string"&&(o=!!o),this._showHelpAfterError=o,this}showSuggestionAfterError(o=!0){return this._showSuggestionAfterError=!!o,this}addCommand(o,l){if(!o._name)throw new Error(`Command passed to .addCommand() must have a name
14
- - specify the name in Command constructor or using .name()`);return l=l||{},l.isDefault&&(this._defaultCommandName=o._name),(l.noHelp||l.hidden)&&(o._hidden=!0),this._registerCommand(o),o.parent=this,o._checkForBrokenPassThrough(),this}createArgument(o,l){return new a(o,l)}argument(o,l,d,c){const p=this.createArgument(o,l);return typeof d=="function"?p.default(c).argParser(d):p.default(d),this.addArgument(p),this}arguments(o){return o.trim().split(/ +/).forEach(l=>{this.argument(l)}),this}addArgument(o){const l=this.registeredArguments.slice(-1)[0];if(l?.variadic)throw new Error(`only the last argument can be variadic '${l.name()}'`);if(o.required&&o.defaultValue!==void 0&&o.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${o.name()}'`);return this.registeredArguments.push(o),this}helpCommand(o,l){if(typeof o=="boolean")return this._addImplicitHelpCommand=o,o&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,d,c]=(o??"help [command]").match(/([^ ]+) *(.*)/),p=l??"display help for command",g=this.createCommand(d);return g.helpOption(!1),c&&g.arguments(c),p&&g.description(p),this._addImplicitHelpCommand=!0,this._helpCommand=g,(o||l)&&this._initCommandGroup(g),this}addHelpCommand(o,l){return typeof o!="object"?(this.helpCommand(o,l),this):(this._addImplicitHelpCommand=!0,this._helpCommand=o,this._initCommandGroup(o),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(o,l){const d=["preSubcommand","preAction","postAction"];if(!d.includes(o))throw new Error(`Unexpected value for event passed to hook : '${o}'.
15
- Expecting one of '${d.join("', '")}'`);return this._lifeCycleHooks[o]?this._lifeCycleHooks[o].push(l):this._lifeCycleHooks[o]=[l],this}exitOverride(o){return o?this._exitCallback=o:this._exitCallback=l=>{if(l.code!=="commander.executeSubCommandAsync")throw l},this}_exit(o,l,d){this._exitCallback&&this._exitCallback(new h(o,l,d)),s.exit(o)}action(o){const l=d=>{const c=this.registeredArguments.length,p=d.slice(0,c);return this._storeOptionsAsProperties?p[c]=this:p[c]=this.opts(),p.push(this),o.apply(this,p)};return this._actionHandler=l,this}createOption(o,l){return new P(o,l)}_callParseArg(o,l,d,c){try{return o.parseArg(l,d)}catch(p){if(p.code==="commander.invalidArgument"){const g=`${c} ${p.message}`;this.error(g,{exitCode:p.exitCode,code:p.code})}throw p}}_registerOption(o){const l=o.short&&this._findOption(o.short)||o.long&&this._findOption(o.long);if(l){const d=o.long&&this._findOption(o.long)?o.long:o.short;throw new Error(`Cannot add option '${o.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${d}'
16
- - already used by option '${l.flags}'`)}this._initOptionGroup(o),this.options.push(o)}_registerCommand(o){const l=c=>[c.name()].concat(c.aliases()),d=l(o).find(c=>this._findCommand(c));if(d){const c=l(this._findCommand(d)).join("|"),p=l(o).join("|");throw new Error(`cannot add command '${p}' as already have command '${c}'`)}this._initCommandGroup(o),this.commands.push(o)}addOption(o){this._registerOption(o);const l=o.name(),d=o.attributeName();if(o.negate){const p=o.long.replace(/^--no-/,"--");this._findOption(p)||this.setOptionValueWithSource(d,o.defaultValue===void 0?!0:o.defaultValue,"default")}else o.defaultValue!==void 0&&this.setOptionValueWithSource(d,o.defaultValue,"default");const c=(p,g,b)=>{p==null&&o.presetArg!==void 0&&(p=o.presetArg);const E=this.getOptionValue(d);p!==null&&o.parseArg?p=this._callParseArg(o,p,E,g):p!==null&&o.variadic&&(p=o._collectValue(p,E)),p==null&&(o.negate?p=!1:o.isBoolean()||o.optional?p=!0:p=""),this.setOptionValueWithSource(d,p,b)};return this.on("option:"+l,p=>{c(p,`error: option '${o.flags}' argument '${p}' is invalid.`,"cli")}),o.envVar&&this.on("optionEnv:"+l,p=>{c(p,`error: option '${o.flags}' value '${p}' from env '${o.envVar}' is invalid.`,"env")}),this}_optionEx(o,l,d,c,p){if(typeof l=="object"&&l instanceof P)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const g=this.createOption(l,d);if(g.makeOptionMandatory(!!o.mandatory),typeof c=="function")g.default(p).argParser(c);else if(c instanceof RegExp){const b=c;c=(E,k)=>{const y=b.exec(E);return y?y[0]:k},g.default(p).argParser(c)}else g.default(c);return this.addOption(g)}option(o,l,d,c){return this._optionEx({},o,l,d,c)}requiredOption(o,l,d,c){return this._optionEx({mandatory:!0},o,l,d,c)}combineFlagAndOptionalValue(o=!0){return this._combineFlagAndOptionalValue=!!o,this}allowUnknownOption(o=!0){return this._allowUnknownOption=!!o,this}allowExcessArguments(o=!0){return this._allowExcessArguments=!!o,this}enablePositionalOptions(o=!0){return this._enablePositionalOptions=!!o,this}passThroughOptions(o=!0){return this._passThroughOptions=!!o,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(o=!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=!!o,this}getOptionValue(o){return this._storeOptionsAsProperties?this[o]:this._optionValues[o]}setOptionValue(o,l){return this.setOptionValueWithSource(o,l,void 0)}setOptionValueWithSource(o,l,d){return this._storeOptionsAsProperties?this[o]=l:this._optionValues[o]=l,this._optionValueSources[o]=d,this}getOptionValueSource(o){return this._optionValueSources[o]}getOptionValueSourceWithGlobals(o){let l;return this._getCommandAndAncestors().forEach(d=>{d.getOptionValueSource(o)!==void 0&&(l=d.getOptionValueSource(o))}),l}_prepareUserArgs(o,l){if(o!==void 0&&!Array.isArray(o))throw new Error("first parameter to parse must be array or undefined");if(l=l||{},o===void 0&&l.from===void 0){s.versions?.electron&&(l.from="electron");const c=s.execArgv??[];(c.includes("-e")||c.includes("--eval")||c.includes("-p")||c.includes("--print"))&&(l.from="eval")}o===void 0&&(o=s.argv),this.rawArgs=o.slice();let d;switch(l.from){case void 0:case"node":this._scriptPath=o[1],d=o.slice(2);break;case"electron":s.defaultApp?(this._scriptPath=o[1],d=o.slice(2)):d=o.slice(1);break;case"user":d=o.slice(0);break;case"eval":d=o.slice(1);break;default:throw new Error(`unexpected parse option { from: '${l.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",d}parse(o,l){this._prepareForParse();const d=this._prepareUserArgs(o,l);return this._parseCommand([],d),this}async parseAsync(o,l){this._prepareForParse();const d=this._prepareUserArgs(o,l);return await this._parseCommand([],d),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(o,l,d){if(i.existsSync(o))return;const c=`'${o}' does not exist
18
- - if '${d}' 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
- - ${l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;throw new Error(c)}_executeSubCommand(o,l){l=l.slice();let d=!1;const c=[".js",".ts",".tsx",".mjs",".cjs"];function p(y,I){const N=r.resolve(y,I);if(i.existsSync(N))return N;if(c.includes(r.extname(I)))return;const bt=c.find(ie=>i.existsSync(`${N}${ie}`));if(bt)return`${N}${bt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let g=o._executableFile||`${this._name}-${o._name}`,b=this._executableDir||"";if(this._scriptPath){let y;try{y=i.realpathSync(this._scriptPath)}catch{y=this._scriptPath}b=r.resolve(r.dirname(y),b)}if(b){let y=p(b,g);if(!y&&!o._executableFile&&this._scriptPath){const I=r.basename(this._scriptPath,r.extname(this._scriptPath));I!==this._name&&(y=p(b,`${I}-${o._name}`))}g=y||g}d=c.includes(r.extname(g));let E;s.platform!=="win32"?d?(l.unshift(g),l=q(s.execArgv).concat(l),E=n.spawn(s.argv[0],l,{stdio:"inherit"})):E=n.spawn(g,l,{stdio:"inherit"}):(this._checkForMissingExecutable(g,b,o._name),l.unshift(g),l=q(s.execArgv).concat(l),E=n.spawn(s.execPath,l,{stdio:"inherit"})),E.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(y=>{s.on(y,()=>{E.killed===!1&&E.exitCode===null&&E.kill(y)})});const k=this._exitCallback;E.on("close",y=>{y=y??1,k?k(new h(y,"commander.executeSubCommandAsync","(close)")):s.exit(y)}),E.on("error",y=>{if(y.code==="ENOENT")this._checkForMissingExecutable(g,b,o._name);else if(y.code==="EACCES")throw new Error(`'${g}' not executable`);if(!k)s.exit(1);else{const I=new h(1,"commander.executeSubCommandAsync","(error)");I.nestedError=y,k(I)}}),this.runningCommand=E}_dispatchSubcommand(o,l,d){const c=this._findCommand(o);c||this.help({error:!0}),c._prepareForParse();let p;return p=this._chainOrCallSubCommandHook(p,c,"preSubcommand"),p=this._chainOrCall(p,()=>{if(c._executableHandler)this._executeSubCommand(c,l.concat(d));else return c._parseCommand(l,d)}),p}_dispatchHelpCommand(o){o||this.help();const l=this._findCommand(o);return l&&!l._executableHandler&&l.help(),this._dispatchSubcommand(o,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((o,l)=>{o.required&&this.args[l]==null&&this.missingArgument(o.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const o=(d,c,p)=>{let g=c;if(c!==null&&d.parseArg){const b=`error: command-argument value '${c}' is invalid for argument '${d.name()}'.`;g=this._callParseArg(d,c,p,b)}return g};this._checkNumberOfArguments();const l=[];this.registeredArguments.forEach((d,c)=>{let p=d.defaultValue;d.variadic?c<this.args.length?(p=this.args.slice(c),d.parseArg&&(p=p.reduce((g,b)=>o(d,b,g),d.defaultValue))):p===void 0&&(p=[]):c<this.args.length&&(p=this.args[c],d.parseArg&&(p=o(d,p,d.defaultValue))),l[c]=p}),this.processedArgs=l}_chainOrCall(o,l){return o?.then&&typeof o.then=="function"?o.then(()=>l()):l()}_chainOrCallHooks(o,l){let d=o;const c=[];return this._getCommandAndAncestors().reverse().filter(p=>p._lifeCycleHooks[l]!==void 0).forEach(p=>{p._lifeCycleHooks[l].forEach(g=>{c.push({hookedCommand:p,callback:g})})}),l==="postAction"&&c.reverse(),c.forEach(p=>{d=this._chainOrCall(d,()=>p.callback(p.hookedCommand,this))}),d}_chainOrCallSubCommandHook(o,l,d){let c=o;return this._lifeCycleHooks[d]!==void 0&&this._lifeCycleHooks[d].forEach(p=>{c=this._chainOrCall(c,()=>p(this,l))}),c}_parseCommand(o,l){const d=this.parseOptions(l);if(this._parseOptionsEnv(),this._parseOptionsImplied(),o=o.concat(d.operands),l=d.unknown,this.args=o.concat(l),o&&this._findCommand(o[0]))return this._dispatchSubcommand(o[0],o.slice(1),l);if(this._getHelpCommand()&&o[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(o[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(l),this._dispatchSubcommand(this._defaultCommandName,o,l);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(d.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const c=()=>{d.unknown.length>0&&this.unknownOption(d.unknown[0])},p=`command:${this.name()}`;if(this._actionHandler){c(),this._processArguments();let g;return g=this._chainOrCallHooks(g,"preAction"),g=this._chainOrCall(g,()=>this._actionHandler(this.processedArgs)),this.parent&&(g=this._chainOrCall(g,()=>{this.parent.emit(p,o,l)})),g=this._chainOrCallHooks(g,"postAction"),g}if(this.parent?.listenerCount(p))c(),this._processArguments(),this.parent.emit(p,o,l);else if(o.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",o,l);this.listenerCount("command:*")?this.emit("command:*",o,l):this.commands.length?this.unknownCommand():(c(),this._processArguments())}else this.commands.length?(c(),this.help({error:!0})):(c(),this._processArguments())}_findCommand(o){if(o)return this.commands.find(l=>l._name===o||l._aliases.includes(o))}_findOption(o){return this.options.find(l=>l.is(o))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(o=>{o.options.forEach(l=>{l.mandatory&&o.getOptionValue(l.attributeName())===void 0&&o.missingMandatoryOptionValue(l)})})}_checkForConflictingLocalOptions(){const o=this.options.filter(l=>{const d=l.attributeName();return this.getOptionValue(d)===void 0?!1:this.getOptionValueSource(d)!=="default"});o.filter(l=>l.conflictsWith.length>0).forEach(l=>{const d=o.find(c=>l.conflictsWith.includes(c.attributeName()));d&&this._conflictingOption(l,d)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(o=>{o._checkForConflictingLocalOptions()})}parseOptions(o){const l=[],d=[];let c=l;function p(y){return y.length>1&&y[0]==="-"}const g=y=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(y)?!this._getCommandAndAncestors().some(I=>I.options.map(N=>N.short).some(N=>/^-\d$/.test(N))):!1;let b=null,E=null,k=0;for(;k<o.length||E;){const y=E??o[k++];if(E=null,y==="--"){c===d&&c.push(y),c.push(...o.slice(k));break}if(b&&(!p(y)||g(y))){this.emit(`option:${b.name()}`,y);continue}if(b=null,p(y)){const I=this._findOption(y);if(I){if(I.required){const N=o[k++];N===void 0&&this.optionMissingArgument(I),this.emit(`option:${I.name()}`,N)}else if(I.optional){let N=null;k<o.length&&(!p(o[k])||g(o[k]))&&(N=o[k++]),this.emit(`option:${I.name()}`,N)}else this.emit(`option:${I.name()}`);b=I.variadic?I:null;continue}}if(y.length>2&&y[0]==="-"&&y[1]!=="-"){const I=this._findOption(`-${y[1]}`);if(I){I.required||I.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${I.name()}`,y.slice(2)):(this.emit(`option:${I.name()}`),E=`-${y.slice(2)}`);continue}}if(/^--[^=]+=/.test(y)){const I=y.indexOf("="),N=this._findOption(y.slice(0,I));if(N&&(N.required||N.optional)){this.emit(`option:${N.name()}`,y.slice(I+1));continue}}if(c===l&&p(y)&&!(this.commands.length===0&&g(y))&&(c=d),(this._enablePositionalOptions||this._passThroughOptions)&&l.length===0&&d.length===0){if(this._findCommand(y)){l.push(y),d.push(...o.slice(k));break}else if(this._getHelpCommand()&&y===this._getHelpCommand().name()){l.push(y,...o.slice(k));break}else if(this._defaultCommandName){d.push(y,...o.slice(k));break}}if(this._passThroughOptions){c.push(y,...o.slice(k));break}c.push(y)}return{operands:l,unknown:d}}opts(){if(this._storeOptionsAsProperties){const o={},l=this.options.length;for(let d=0;d<l;d++){const c=this.options[d].attributeName();o[c]=c===this._versionOptionName?this._version:this[c]}return o}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((o,l)=>Object.assign(o,l.opts()),{})}error(o,l){this._outputConfiguration.outputError(`${o}
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 d=l||{},c=d.exitCode||1,p=d.code||"commander.error";this._exit(c,p,o)}_parseOptionsEnv(){this.options.forEach(o=>{if(o.envVar&&o.envVar in s.env){const l=o.attributeName();(this.getOptionValue(l)===void 0||["default","config","env"].includes(this.getOptionValueSource(l)))&&(o.required||o.optional?this.emit(`optionEnv:${o.name()}`,s.env[o.envVar]):this.emit(`optionEnv:${o.name()}`))}})}_parseOptionsImplied(){const o=new w(this.options),l=d=>this.getOptionValue(d)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(d));this.options.filter(d=>d.implied!==void 0&&l(d.attributeName())&&o.valueFromOption(this.getOptionValue(d.attributeName()),d)).forEach(d=>{Object.keys(d.implied).filter(c=>!l(c)).forEach(c=>{this.setOptionValueWithSource(c,d.implied[c],"implied")})})}missingArgument(o){const l=`error: missing required argument '${o}'`;this.error(l,{code:"commander.missingArgument"})}optionMissingArgument(o){const l=`error: option '${o.flags}' argument missing`;this.error(l,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(o){const l=`error: required option '${o.flags}' not specified`;this.error(l,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(o,l){const d=g=>{const b=g.attributeName(),E=this.getOptionValue(b),k=this.options.find(I=>I.negate&&b===I.attributeName()),y=this.options.find(I=>!I.negate&&b===I.attributeName());return k&&(k.presetArg===void 0&&E===!1||k.presetArg!==void 0&&E===k.presetArg)?k:y||g},c=g=>{const b=d(g),E=b.attributeName();return this.getOptionValueSource(E)==="env"?`environment variable '${b.envVar}'`:`option '${b.flags}'`},p=`error: ${c(o)} cannot be used with ${c(l)}`;this.error(p,{code:"commander.conflictingOption"})}unknownOption(o){if(this._allowUnknownOption)return;let l="";if(o.startsWith("--")&&this._showSuggestionAfterError){let c=[],p=this;do{const g=p.createHelp().visibleOptions(p).filter(b=>b.long).map(b=>b.long);c=c.concat(g),p=p.parent}while(p&&!p._enablePositionalOptions);l=$(o,c)}const d=`error: unknown option '${o}'${l}`;this.error(d,{code:"commander.unknownOption"})}_excessArguments(o){if(this._allowExcessArguments)return;const l=this.registeredArguments.length,d=l===1?"":"s",c=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${l} argument${d} but got ${o.length}.`;this.error(c,{code:"commander.excessArguments"})}unknownCommand(){const o=this.args[0];let l="";if(this._showSuggestionAfterError){const c=[];this.createHelp().visibleCommands(this).forEach(p=>{c.push(p.name()),p.alias()&&c.push(p.alias())}),l=$(o,c)}const d=`error: unknown command '${o}'${l}`;this.error(d,{code:"commander.unknownCommand"})}version(o,l,d){if(o===void 0)return this._version;this._version=o,l=l||"-V, --version",d=d||"output the version number";const c=this.createOption(l,d);return this._versionOptionName=c.attributeName(),this._registerOption(c),this.on("option:"+c.name(),()=>{this._outputConfiguration.writeOut(`${o}
24
- `),this._exit(0,"commander.version",o)}),this}description(o,l){return o===void 0&&l===void 0?this._description:(this._description=o,l&&(this._argsDescription=l),this)}summary(o){return o===void 0?this._summary:(this._summary=o,this)}alias(o){if(o===void 0)return this._aliases[0];let l=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(l=this.commands[this.commands.length-1]),o===l._name)throw new Error("Command alias can't be the same as its name");const d=this.parent?._findCommand(o);if(d){const c=[d.name()].concat(d.aliases()).join("|");throw new Error(`cannot add alias '${o}' to command '${this.name()}' as already have command '${c}'`)}return l._aliases.push(o),this}aliases(o){return o===void 0?this._aliases:(o.forEach(l=>this.alias(l)),this)}usage(o){if(o===void 0){if(this._usage)return this._usage;const l=this.registeredArguments.map(d=>u(d));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?l:[]).join(" ")}return this._usage=o,this}name(o){return o===void 0?this._name:(this._name=o,this)}helpGroup(o){return o===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=o,this)}commandsGroup(o){return o===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=o,this)}optionsGroup(o){return o===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=o,this)}_initOptionGroup(o){this._defaultOptionGroup&&!o.helpGroupHeading&&o.helpGroup(this._defaultOptionGroup)}_initCommandGroup(o){this._defaultCommandGroup&&!o.helpGroup()&&o.helpGroup(this._defaultCommandGroup)}nameFromFilename(o){return this._name=r.basename(o,r.extname(o)),this}executableDir(o){return o===void 0?this._executableDir:(this._executableDir=o,this)}helpInformation(o){const l=this.createHelp(),d=this._getOutputContext(o);l.prepareContext({error:d.error,helpWidth:d.helpWidth,outputHasColors:d.hasColors});const c=l.formatHelp(this,l);return d.hasColors?c:this._outputConfiguration.stripColor(c)}_getOutputContext(o){o=o||{};const l=!!o.error;let d,c,p;return l?(d=b=>this._outputConfiguration.writeErr(b),c=this._outputConfiguration.getErrHasColors(),p=this._outputConfiguration.getErrHelpWidth()):(d=b=>this._outputConfiguration.writeOut(b),c=this._outputConfiguration.getOutHasColors(),p=this._outputConfiguration.getOutHelpWidth()),{error:l,write:b=>(c||(b=this._outputConfiguration.stripColor(b)),d(b)),hasColors:c,helpWidth:p}}outputHelp(o){let l;typeof o=="function"&&(l=o,o=void 0);const d=this._getOutputContext(o),c={error:d.error,write:d.write,command:this};this._getCommandAndAncestors().reverse().forEach(g=>g.emit("beforeAllHelp",c)),this.emit("beforeHelp",c);let p=this.helpInformation({error:d.error});if(l&&(p=l(p),typeof p!="string"&&!Buffer.isBuffer(p)))throw new Error("outputHelp callback must return a string or a Buffer");d.write(p),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",c),this._getCommandAndAncestors().forEach(g=>g.emit("afterAllHelp",c))}helpOption(o,l){return typeof o=="boolean"?(o?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(o??"-h, --help",l??"display help for command"),(o||l)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(o){return this._helpOption=o,this._initOptionGroup(o),this}help(o){this.outputHelp(o);let l=Number(s.exitCode??0);l===0&&o&&typeof o!="function"&&o.error&&(l=1),this._exit(l,"commander.help","(outputHelp)")}addHelpText(o,l){const d=["beforeAll","before","after","afterAll"];if(!d.includes(o))throw new Error(`Unexpected value for position to addHelpText.
25
- Expecting one of '${d.join("', '")}'`);const c=`${o}Help`;return this.on(c,p=>{let g;typeof l=="function"?g=l({error:p.error,command:p.command}):g=l,g&&p.write(`${g}
26
- `)}),this}_outputHelpIfRequested(o){const l=this._getHelpOption();l&&o.find(d=>l.is(d))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function q(ee){return ee.map(o=>{if(!o.startsWith("--inspect"))return o;let l,d="127.0.0.1",c="9229",p;return(p=o.match(/^(--inspect(-brk)?)$/))!==null?l=p[1]:(p=o.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(l=p[1],/^\d+$/.test(p[3])?c=p[3]:d=p[3]):(p=o.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(l=p[1],d=p[3],c=p[4]),l&&c!=="0"?`${l}=${d}:${parseInt(c)+1}`:o})}function lt(){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}t.Command=B,t.useColor=lt})),fe=X((t=>{var{Argument:e}=ht(),{Command:n}=me(),{CommanderError:r,InvalidArgumentError:i}=nt(),{Help:s}=It(),{Option:a}=Tt();t.program=new n,t.createCommand=u=>new n(u),t.createOption=(u,h)=>new a(u,h),t.createArgument=(u,h)=>new e(u,h),t.Command=n,t.Option=a,t.Argument=e,t.Help=s,t.CommanderError=r,t.InvalidArgumentError=i,t.InvalidOptionArgumentError=i})),ge=ue(fe(),1),{program:Es,createCommand:Is,createArgument:Ts,createOption:xs,CommanderError:ve,InvalidArgumentError:ks,InvalidOptionArgumentError:js,Command:ye,Argument:$s,Option:M,Help:Ns}=ge.default;function A(t){return`${JSON.stringify(t,null,2)}
27
- `}var kt=(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 jt(t){return t.replace(/\s+/g," ").trim()}function U(t,e){const n=e.map(s=>t.map(a=>jt(a.value(s)))),r=t.map((s,a)=>{const u=n.map(h=>h[a].length);return Math.max(s.header.length,...u)}),i=s=>s.map((a,u)=>a.padEnd(r[u])).join(" ").trimEnd();return[i(t.map(s=>s.header)),i(r.map(s=>"-".repeat(s))),...n.map(i)].join(`
28
- `)}function H(t){const e=t.filter(([,r])=>r!==void 0&&r!==""),n=Math.max(...e.map(([r])=>r.length));return`${e.map(([r,i])=>`${r.padEnd(n)} ${jt(i??"")}`).join(`
29
- `)}
30
- `}function _t(t){return typeof t=="string"?t.trim():t?.value?.trim()??""}function W(t){return{sessionId:_t(t.sessionId),title:t.title,type:t.type,status:t.status,projectId:_t(t.projectId),proposalName:t.proposalName??void 0,archived:t.status===kt.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(W)}}function Nt(t,e){return e.length===0?`No ${t.toLowerCase()} found.
31
- `:`${t} (${e.length})
32
- ${U([{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"}],e)}
33
- `}function Q(t,e=[]){return H([["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 mt(t,e,n,r=[]){return`${t}
34
- ${H([["sessionId",e],["message",n.message],...r])}`}var m={BASE:"",VERSION:"1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0},ct=class extends Error{url;status;statusText;body;request;constructor(t,e,n){super(n),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,OPERATION_FAILED:30,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},j=class extends Error{constructor(t){super(t),this.name="CliUsageError"}},Dt=class extends Error{constructor(t){super(t),this.name="CliOperationFailedError"}},rt=class extends Error{status;details;constructor(t,e,n){super(e),this.name="CliHttpError",this.status=t,this.details=n}};function Vt(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Z(t,e){const n=Vt(t)?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function Ae(t){return t.includes("fetch failed")||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("Failed to parse URL")}function Pt(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 Oe(t,e={}){if(t instanceof j)return{exitCode:D.USAGE,message:t.message};if(t instanceof Dt)return{exitCode:D.OPERATION_FAILED,message:t.message};if(t instanceof rt)return{exitCode:Pt(t.status),status:t.status,message:t.message,details:t.details};if(t instanceof ct){const n=Z(t.body,"error")??Z(t.body,"message")??t.message;return{exitCode:Pt(t.status),status:t.status,message:n,errorCode:Z(t.body,"errorCode"),correlationId:Z(t.body,"correlationId"),details:t.body}}if(t instanceof Error){if(!Ae(t.message))return{exitCode:D.UNKNOWN,message:t.message};const n=e.baseUrl??"the configured backend";return{exitCode:D.TRANSPORT,message:t.message.includes("Failed to parse URL")?`Invalid HagiCode backend base URL: ${n}`:`Cannot reach HagiCode backend at ${n}. Check that the backend is running and the base URL is correct.`}}return{exitCode:D.UNKNOWN,message:String(t)}}function Se(t){const e=Vt(t)?.errors;return Array.isArray(e)?e.flatMap(n=>{const r=Z(n,"field"),i=Z(n,"message");return r&&i?[` - ${r}: ${i}`]:[]}):[]}function Ht(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 n=[t.status?`status=${t.status}`:void 0,t.errorCode?`errorCode=${t.errorCode}`:void 0,t.correlationId?`correlationId=${t.correlationId}`:void 0].filter(Boolean),r=n.length>0?` (${n.join(", ")})`:"";return[`${t.message}${r}`,...Se(t.details)].join(`
36
- `)+`
37
- `}function be(t){return`cli/${t??"unknown"}`}var Ce=be("0.1.0-dev.28.1.71f1989"),_e="--base-url",Pe="HAGI_API_BASE_URL";function G(t){const e=t?.trim();return e||void 0}function Rt(t=process.env){return(0,Ct.join)(G(t.XDG_CONFIG_HOME)??(0,Ct.join)((0,ce.homedir)(),".config"),"hagi","config.json")}function we(t=process.env){const e=Rt(t);let n;try{n=(0,de.readFileSync)(e,"utf8")}catch(s){if(s.code==="ENOENT")return;throw new j(`Cannot read CLI config file ${e}: ${s instanceof Error?s.message:String(s)}`)}let r;try{r=JSON.parse(n)}catch{throw new j(`CLI config file ${e} is not valid JSON.`)}const i=r&&typeof r=="object"&&!Array.isArray(r)?r.baseUrl:void 0;return typeof i=="string"?G(i):void 0}function Ee(t={},e=process.env){const n=G(t.baseUrl)??G(e.HAGI_API_BASE_URL)??we(e);if(!n)throw new j(`No backend base URL is configured. Set ${_e} <url>, the ${Pe} environment variable, or "baseUrl" in ${Rt(e)}.`);return{baseUrl:n,token:G(t.token)??G(e.HAGI_API_TOKEN),lang:G(t.lang)??G(e.HAGI_API_LANG)}}function Ie(t={},e=process.env){const n=Ee(t,e);return m.BASE=n.baseUrl,m.WITH_CREDENTIALS=!1,m.CREDENTIALS="omit",m.TOKEN=n.token,m.HEADERS={"X-Hagi-Client":Ce,...n.lang?{"Accept-Language":n.lang}:{}},n}function Te(){return G(m.BASE)}var xe=class extends Error{constructor(t){super(t),this.name="CancelError"}get isCancelled(){return!0}},ke=class{#e;#i;#t;#s;#n;#r;#o;constructor(t){this.#e=!1,this.#i=!1,this.#t=!1,this.#s=[],this.#n=new Promise((e,n)=>{this.#r=e,this.#o=n;const r=a=>{this.#e||this.#i||this.#t||(this.#e=!0,this.#r&&this.#r(a))},i=a=>{this.#e||this.#i||this.#t||(this.#i=!0,this.#o&&this.#o(a))},s=a=>{this.#e||this.#i||this.#t||this.#s.push(a)};return Object.defineProperty(s,"isResolved",{get:()=>this.#e}),Object.defineProperty(s,"isRejected",{get:()=>this.#i}),Object.defineProperty(s,"isCancelled",{get:()=>this.#t}),t(r,i,s)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(t,e){return this.#n.then(t,e)}catch(t){return this.#n.catch(t)}finally(t){return this.#n.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.#o&&this.#o(new xe("Request aborted"))}}get isCancelled(){return this.#t}},ft=t=>t!=null,tt=t=>typeof t=="string",ut=t=>tt(t)&&t!=="",gt=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]),qt=t=>t instanceof FormData,je=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},$e=t=>{const e=[],n=(i,s)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},r=(i,s)=>{ft(s)&&(Array.isArray(s)?s.forEach(a=>{r(i,a)}):typeof s=="object"?Object.entries(s).forEach(([a,u])=>{r(`${i}[${a}]`,u)}):n(i,s))};return Object.entries(t).forEach(([i,s])=>{r(i,s)}),e.length>0?`?${e.join("&")}`:""},Ne=(t,e)=>{const n=t.ENCODE_PATH||encodeURI,r=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(s,a)=>e.path?.hasOwnProperty(a)?n(String(e.path[a])):s),i=`${t.BASE}${r}`;return e.query?`${i}${$e(e.query)}`:i},De=t=>{if(t.formData){const e=new FormData,n=(r,i)=>{tt(i)||gt(i)?e.append(r,i):e.append(r,JSON.stringify(i))};return Object.entries(t.formData).filter(([r,i])=>ft(i)).forEach(([r,i])=>{Array.isArray(i)?i.forEach(s=>n(r,s)):n(r,i)}),e}},it=async(t,e)=>typeof e=="function"?e(t):e,Ve=async(t,e)=>{const[n,r,i,s]=await Promise.all([it(e,t.TOKEN),it(e,t.USERNAME),it(e,t.PASSWORD),it(e,t.HEADERS)]),a=Object.entries({Accept:"application/json",...s,...e.headers}).filter(([u,h])=>ft(h)).reduce((u,[h,v])=>({...u,[h]:String(v)}),{});return ut(n)&&(a.Authorization=`Bearer ${n}`),ut(r)&&ut(i)&&(a.Authorization=`Basic ${je(`${r}:${i}`)}`),e.body!==void 0&&(e.mediaType?a["Content-Type"]=e.mediaType:gt(e.body)?a["Content-Type"]=e.body.type||"application/octet-stream":tt(e.body)?a["Content-Type"]="text/plain":qt(e.body)||(a["Content-Type"]="application/json")),new Headers(a)},He=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):tt(t.body)||gt(t.body)||qt(t.body)?t.body:JSON.stringify(t.body)},Re=async(t,e,n,r,i,s,a)=>{const u=new AbortController,h={headers:s,body:r??i,method:e.method,signal:u.signal};return t.WITH_CREDENTIALS&&(h.credentials=t.CREDENTIALS),a(()=>u.abort()),await fetch(n,h)},qe=(t,e)=>{if(e){const n=t.headers.get(e);if(tt(n))return n}},Fe=async t=>{if(t.status!==204)try{const e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(n=>e.toLowerCase().startsWith(n))?await t.json():await t.text()}catch(e){console.error(e)}},Le=(t,e)=>{const n={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(n)throw new ct(t,e,n);if(!e.ok)throw new ct(t,e,`Generic Error: status: ${e.status??"unknown"}; status text: ${e.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})()}`)},f=(t,e)=>new ke(async(n,r,i)=>{try{const s=Ne(t,e),a=De(e),u=He(e),h=await Ve(t,e);if(!i.isCancelled){const v=await Re(t,e,s,u,a,h,i),_=await Fe(v),P=qe(v,e.responseHeader),w={url:s,ok:v.ok,status:v.status,statusText:v.statusText,body:P??_};Le(e,w),n(w.body)}}catch(s){r(s)}}),Ge=class{static getApiDataAggregation(){return f(m,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},dt=class{static postApiProject({requestBody:t}){return f(m,{method:"POST",url:"/api/Project",body:t,mediaType:"application/json"})}static postApiProjectDemo(){return f(m,{method:"POST",url:"/api/Project/demo"})}static putApiProject({id:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/Project/{id}",path:{id:t},body:e,mediaType:"application/json"})}static deleteApiProject({id:t}){return f(m,{method:"DELETE",url:"/api/Project/{id}",path:{id:t}})}static postApiProjectOpenInVscode({id:t,subPath:e}){return f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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:n="light"}){return f(m,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}/preview",path:{id:t,slug:e},query:{theme:n},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndex1({id:t,slug:e}){return f(m,{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:n}){return f(m,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:t},query:{branchName:e,repositoryPath:n},errors:{400:"Branch name is required",404:"Project not found"}})}static getApiProjectValidatePath({path:t}){return f(m,{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 f(m,{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 f(m,{method:"POST",url:"/api/Project/validate-monospecs",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error"}})}},J=class{static getApiScheduledPlans(){return f(m,{method:"GET",url:"/api/ScheduledPlans"})}static postApiScheduledPlans({requestBody:t}){return f(m,{method:"POST",url:"/api/ScheduledPlans",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiScheduledPlans1({id:t}){return f(m,{method:"GET",url:"/api/ScheduledPlans/{id}",path:{id:t},errors:{404:"Not Found"}})}static putApiScheduledPlans({id:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/ScheduledPlans/{id}",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found"}})}static deleteApiScheduledPlans({id:t}){return f(m,{method:"DELETE",url:"/api/ScheduledPlans/{id}",path:{id:t},errors:{404:"Not Found"}})}static postApiScheduledPlansRun({id:t}){return f(m,{method:"POST",url:"/api/ScheduledPlans/{id}/run",path:{id:t},errors:{400:"Bad Request",404:"Not Found"}})}static postApiScheduledPlansStart({id:t}){return f(m,{method:"POST",url:"/api/ScheduledPlans/{id}/start",path:{id:t},errors:{404:"Not Found",503:"Service Unavailable"}})}},V=class{static postApiSessionsAutoTask({requestBody:t}){return f(m,{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 f(m,{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 f(m,{method:"POST",url:"/api/Sessions/chat",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:t}){return f(m,{method:"POST",url:"/api/Sessions",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:t,activeOnly:e,includeArchived:n,projectId:r,projectIds:i}){return f(m,{method:"GET",url:"/api/Sessions",query:{type:t,activeOnly:e,includeArchived:n,projectId:r,projectIds:i}})}static getApiSessions1({sessionId:t}){return f(m,{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 f(m,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:t},body:e,mediaType:"application/json"})}static deleteApiSessions({sessionId:t,deleteFiles:e=!1}){return f(m,{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:n=50,historyScope:r,order:i="desc"}){return f(m,{method:"GET",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},query:{page:e,pageSize:n,historyScope:r,order:i},errors:{404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsMessages({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},body:e,mediaType:"application/json"})}static postApiSessionsCancel({sessionId:t}){return f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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"}})}},L=class{static getApiSkillsLocal(){return f(m,{method:"GET",url:"/api/skills/local"})}static postApiSkillsLocalUninstall({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/local/uninstall",body:t,mediaType:"application/json"})}static postApiSkillsLocalBuiltInAvailability({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/local/built-in/availability",body:t,mediaType:"application/json"})}static getApiSkillsGallery({query:t}){return f(m,{method:"GET",url:"/api/skills/gallery",query:{query:t}})}static getApiSkillsGalleryDetail({id:t,source:e}){return f(m,{method:"GET",url:"/api/skills/gallery/detail",query:{id:t,source:e}})}static getApiSkillsGalleryInstallContext({id:t,source:e}){return f(m,{method:"GET",url:"/api/skills/gallery/install-context",query:{id:t,source:e}})}static getApiSkillsProvidersTrusted(){return f(m,{method:"GET",url:"/api/skills/providers/trusted"})}static postApiSkillsProvidersTrusted({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/providers/trusted",body:t,mediaType:"application/json"})}static deleteApiSkillsProvidersTrusted({requestBody:t}){return f(m,{method:"DELETE",url:"/api/skills/providers/trusted",body:t,mediaType:"application/json"})}static postApiSkillsProvidersTrustedReset(){return f(m,{method:"POST",url:"/api/skills/providers/trusted/reset"})}static postApiSkillsGalleryInstall({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/gallery/install",body:t,mediaType:"application/json"})}static getApiSkillsGalleryInstallStream({id:t,source:e,skillSlug:n,version:r}){return f(m,{method:"GET",url:"/api/skills/gallery/install/stream",query:{id:t,source:e,skillSlug:n,version:r}})}},Y=class{static getApiVaults(){return f(m,{method:"GET",url:"/api/vaults"})}static postApiVaults({requestBody:t}){return f(m,{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 f(m,{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 f(m,{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 f(m,{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 f(m,{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 Ue(){return{listSessions:t=>V.getApiSessions(t),getSession:t=>V.getApiSessions1({sessionId:t}),createProposalSession:t=>V.postApiSessions({requestBody:t}),createChatSession:t=>V.postApiSessionsChat({requestBody:t}),createAutoTaskSession:t=>V.postApiSessionsAutoTask({requestBody:t}),updateSession:(t,e)=>V.putApiSessions({sessionId:t,requestBody:e}),deleteSession:(t,e)=>V.deleteApiSessions({sessionId:t,deleteFiles:e}),sendMessage:(t,e)=>V.postApiSessionsMessages({sessionId:t,requestBody:e}),optimizeProposal:(t,e)=>V.postApiSessionsOptimizeProposal({sessionId:t,requestBody:e}),generateProposal:(t,e)=>V.postApiSessionsGenerateProposal({sessionId:t,requestBody:e}),executeProposal:(t,e)=>V.postApiSessionsExecuteProposal({sessionId:t,requestBody:e}),archiveProposal:(t,e)=>V.postApiSessionsArchive({sessionId:t,requestBody:e}),completeProposal:t=>V.postApiSessionsComplete({sessionId:t}),submitAnnotations:(t,e)=>V.postApiSessionsAnnotations({sessionId:t,requestBody:e}),listProjects:()=>Ge.getApiDataAggregation(),createProject:t=>dt.postApiProject({requestBody:t}),updateProject:(t,e)=>dt.putApiProject({id:t,requestBody:e}),deleteProject:t=>dt.deleteApiProject({id:t}),listPlans:()=>J.getApiScheduledPlans(),getPlan:t=>J.getApiScheduledPlans1({id:t}),createPlan:t=>J.postApiScheduledPlans({requestBody:t}),updatePlan:(t,e)=>J.putApiScheduledPlans({id:t,requestBody:e}),deletePlan:t=>J.deleteApiScheduledPlans({id:t}),runPlan:t=>J.postApiScheduledPlansRun({id:t}),startPlan:t=>J.postApiScheduledPlansStart({id:t}),listVaults:()=>Y.getApiVaults(),createVault:t=>Y.postApiVaults({requestBody:t}),updateVault:(t,e)=>Y.putApiVaults({id:t,requestBody:e}),deleteVault:(t,e)=>Y.deleteApiVaults({id:t,deleteLocalFiles:e}),listVaultFiles:(t,e)=>Y.getApiVaultsFiles({id:t,path:e}),previewVaultFile:(t,e)=>Y.getApiVaultsFilesContent({id:t,path:e}),archiveChat:t=>V.postApiSessionsArchiveChat({sessionId:t}),listLocalSkills:()=>L.getApiSkillsLocal(),uninstallLocalSkill:t=>L.postApiSkillsLocalUninstall({requestBody:t}),setBuiltInSkillAvailability:t=>L.postApiSkillsLocalBuiltInAvailability({requestBody:t}),searchSkillGallery:t=>L.getApiSkillsGallery({query:t}),getSkillGalleryDetail:(t,e)=>L.getApiSkillsGalleryDetail({id:t,source:e}),installGallerySkill:t=>L.postApiSkillsGalleryInstall({requestBody:t}),listTrustedSkillProviders:()=>L.getApiSkillsProvidersTrusted(),upsertTrustedSkillProvider:t=>L.postApiSkillsProvidersTrusted({requestBody:t}),deleteTrustedSkillProvider:t=>L.deleteApiSkillsProvidersTrusted({requestBody:t}),resetTrustedSkillProviders:()=>L.postApiSkillsProvidersTrustedReset()}}function C(t){const e=t?.trim();return e||void 0}function x(t,e){const n=C(t);if(!n)throw new j(`${e} is required.`);return n}function Ft(t){const e=t?.map(n=>C(n)).filter(Boolean);return e&&e.length>0?e:void 0}function Lt(t=process.env,e={stdout:n=>{process.stdout.write(n)},stderr:n=>{process.stderr.write(n)}}){return{api:Ue(),env:t,io:e}}function Be(t){return t.option("--base-url <url>",'Backend API base URL. Overrides HAGI_API_BASE_URL and the "baseUrl" config file entry.').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 O(t){return t.option("--json","Emit deterministic JSON instead of human-readable text.")}function S(t,e){const n=t.optsWithGlobals();return{api:e.api,env:e.env,io:e.io,outputJson:n.json===!0,runtime:Ie({baseUrl:n.baseUrl,token:n.token,lang:n.lang},e.env)}}function Me(t,e){O(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 scenario script key.").option("--hero-id <id>","Optional preferred hero id.").option("--target-type <type>","Optional target type for the AutoTask session.").option("--vault-id <id>","Optional vault id for the AutoTask session.").action(async function(r){if(r.targetBranchName&&r.targetBranchMode!=="new-custom")throw new j("--target-branch-name requires --target-branch-mode new-custom.");if(r.targetBranchMode==="new-custom"&&!C(r.targetBranchName))throw new j("--target-branch-name is required when --target-branch-mode is new-custom.");const i=S(this,e),s={title:x(r.title,"--title"),projectId:x(r.projectId,"--project-id"),promptId:x(r.promptId,"--prompt-id"),message:C(r.message),presetId:C(r.presetId),repositoryPath:C(r.repositoryPath),projectIds:Ft(r.projectIds),needPush:r.needPush?!0:void 0,targetBranchMode:C(r.targetBranchMode),targetBranchName:C(r.targetBranchName),scriptKey:C(r.scriptKey),heroId:C(r.heroId),targetType:C(r.targetType),vaultId:C(r.vaultId)},a=W(await i.api.createAutoTaskSession(s));if(i.outputJson){i.io.stdout(A({session:a,promptId:s.promptId,requested:s}));return}i.io.stdout(`AutoTask session created
38
- ${Q(a,[["promptId",s.promptId],["repositoryPath",s.repositoryPath],["targetBranchMode",s.targetBranchMode],["targetBranchName",s.targetBranchName],["scriptKey",s.scriptKey],["heroId",s.heroId]])}`)})}var at=(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})({}),vt=(function(t){return t.READONLY="Readonly",t.EDIT="Edit",t})({});function We(t,e){O(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 M("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new M("--executor-type <type>","Executor override for this message.").choices(Object.values(at))).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:x(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(mt("AutoTask message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Je(t,e){const n=t.command("autotask").description("Manage AutoTask sessions.");Me(n,e),We(n,e)}function ze(t,e){O(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(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.archiveChat(s);if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message}));return}i.io.stdout(`Chat archived
39
- sessionId ${s}
40
- message ${a.message}
41
- `)})}function Ke(t,e){O(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 M("--executor-type <type>","Optional executor override.").choices(Object.values(at))).action(async function(r){const i=S(this,e),s=W(await i.api.createChatSession({title:x(r.title,"--title"),projectId:x(r.projectId,"--project-id"),heroId:C(r.heroId),executorType:r.executorType}));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Chat session created
42
- ${Q(s)}`)})}function Xe(t,e){O(t.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.deleteSession(s,!1);if(i.outputJson){i.io.stdout(A({sessionId:s,deleted:!0,message:a.message}));return}i.io.stdout(`Chat deleted
43
- sessionId ${s}
44
- message ${a.message}
45
- `)})}var yt=(function(t){return t.CHAT="Chat",t.PROPOSAL="Proposal",t})({});function Qe(t,e){O(t.command("list").description("List normal chat sessions.")).action(async function(r){if(r.projectId&&r.projectIds?.length)throw new j("Use either --project-id or --project-ids, not both.");const i=S(this,e),s=$t(await i.api.listSessions({type:yt.CHAT,projectId:C(r.projectId),projectIds:Ft(r.projectIds),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(Nt("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 Ye(t,e){O(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 M("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new M("--executor-type <type>","Executor override for this message.").choices(Object.values(at))).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:x(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(mt("Chat message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Ze(t,e){const n=t.command("chat").description("Manage normal chat sessions.");Qe(n,e),Ke(n,e),ze(n,e),Xe(n,e),Ye(n,e)}function F(t){const e=t?.trim();return e||void 0}function Gt(t){if(!t)return"";const e=F(t.mode);if(e==="once")return["once",F(t.runAt)].filter(Boolean).join(" ");const n=F(t.repeat?.rule)??e??"";return[n,n==="weekly"?(t.repeat?.weekdays??[]).map(r=>r.trim().slice(0,3).toLowerCase()).join(","):void 0,F(t.timeOfDay),F(t.timeZone)].filter(Boolean).join(" ")}function z(t){return{id:F(t.id)??"",type:F(t.type)??"",name:F(t.name)??"",enabled:t.enabled===!0,state:F(t.state)??"",nextRunAt:F(t.nextRunAt)??null,schedule:t.schedule,agentPool:t.agentPool,payload:t.payload}}function ti(t){return{plans:t.map(z)}}function ei(t){return t.length===0?`No scheduled plans found.
46
- `:`Plans (${t.length})
47
- ${U([{header:"ID",value:e=>e.id},{header:"Type",value:e=>e.type},{header:"Name",value:e=>e.name},{header:"Enabled",value:e=>e.enabled?"yes":"no"},{header:"State",value:e=>e.state},{header:"Next Run",value:e=>e.nextRunAt??"-"},{header:"Schedule",value:e=>Gt(e.schedule)}],t)}
48
- `}function et(t){return H([["id",t.id],["type",t.type],["name",t.name],["enabled",t.enabled?"yes":"no"],["state",t.state],["nextRun",t.nextRunAt??"-"],["schedule",Gt(t.schedule)]])}function ii(t){return{planId:t,deleted:!0}}function si(t){return`Plan deleted
49
- ${H([["planId",t.planId],["deleted",String(t.deleted)]])}`}function oi(t){return{planId:F(t.planId)??"",accepted:!0}}function ni(t){return`Plan run accepted
50
- ${H([["planId",t.planId],["accepted",String(t.accepted)]])}`}async function ri(){const t=[];for await(const e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}async function At(t){const e=t.trim();if(!e)throw new j("Provide --input <file> or --input - for stdin.");const n=e==="-"?await ri():await(0,pe.readFile)(e,"utf8");try{return JSON.parse(n)}catch(r){throw new j(`Invalid JSON input from ${e}: ${r instanceof Error?r.message:String(r)}`)}}var ai=["id","createdAt","updatedAt","state","nextRunAt"];async function Ut(t){let e;try{e=await At(t)}catch(n){throw n instanceof j?n:new j(`Cannot read plan input from ${t}: ${n instanceof Error?n.message:String(n)}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new j(`Plan input from ${t} must be a JSON object.`);return e}function ot(t){const e={...t};for(const n of ai)delete e[n];return e}function li(t){return{strategy:"random",agents:[{heroId:t}]}}function Bt(t){return{...t.name!==void 0?{name:t.name}:{},...t.heroId!==void 0?{agentPool:li(t.heroId)}:{},...t.enabled!==void 0?{enabled:t.enabled}:{}}}function Mt(t,e){return{...ot(t),...ot(e)}}function ui(t,e){O(t.command("create").description("Create a scheduled plan from a JSON document. Plans are enabled unless --disabled or the document says otherwise.")).requiredOption("--input <file|->","Plan JSON file path, or - to read from stdin.").option("--name <name>","Plan name. Overrides the document name.").option("--hero-id <id>","Hero for a single-agent pool. Replaces the document agent pool.").option("--disabled","Create the plan disabled. Overrides the document enabled value.").action(async function(r){const i=S(this,e),s=ot(await Ut(r.input)),a=z(await i.api.createPlan({enabled:!0,...s,...Bt({name:C(r.name),heroId:C(r.heroId),enabled:r.disabled?!1:void 0})}));if(i.outputJson){i.io.stdout(A({plan:a}));return}i.io.stdout(`Plan created
51
- ${et(a)}`)})}function di(t,e){O(t.command("delete").description("Delete a scheduled plan by id.")).requiredOption("--id <id>","Plan id to delete.").action(async function(r){const i=S(this,e),s=x(r.id,"--id");await i.api.deletePlan(s);const a=ii(s);if(i.outputJson){i.io.stdout(A(a));return}i.io.stdout(si(a))})}async function Wt(t,e,n){const r=await t.api.getPlan(e);return z(r).enabled===n?{view:z(r),changed:!1}:{view:z(await t.api.updatePlan(e,Mt(r,{enabled:n}))),changed:!0}}function ci(t,e){O(t.command("disable").description("Disable a scheduled plan. Nothing is sent when it is already disabled.")).requiredOption("--id <id>","Plan id to disable.").action(async function(r){const i=S(this,e),{view:s,changed:a}=await Wt(i,x(r.id,"--id"),!1);if(i.outputJson){i.io.stdout(A({plan:s,changed:a}));return}i.io.stdout(`${a?"Plan disabled":"Plan was already disabled"}
52
- ${et(s)}`)})}function pi(t,e){O(t.command("enable").description("Enable a scheduled plan. Nothing is sent when it is already enabled.")).requiredOption("--id <id>","Plan id to enable.").action(async function(r){const i=S(this,e),{view:s,changed:a}=await Wt(i,x(r.id,"--id"),!0);if(i.outputJson){i.io.stdout(A({plan:s,changed:a}));return}i.io.stdout(`${a?"Plan enabled":"Plan was already enabled"}
53
- ${et(s)}`)})}function hi(t,e){O(t.command("get").description("Show one scheduled plan, including its schedule, agent pool and payload in --json mode.")).requiredOption("--id <id>","Plan id to read.").action(async function(r){const i=S(this,e),s=z(await i.api.getPlan(x(r.id,"--id")));if(i.outputJson){i.io.stdout(A({plan:s}));return}i.io.stdout(et(s))})}function mi(t,e){O(t.command("list").description("List scheduled plans with their state, next run time and schedule.")).action(async function(){const r=S(this,e),i=ti(await r.api.listPlans());if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(ei(i.plans))})}function fi(t,e){O(t.command("run").description("Run a scheduled plan now from its stored inputs. The schedule is not changed.")).requiredOption("--id <id>","Plan id to run.").option("--background","Start the run and print the accepted plan id without waiting for the session.").action(async function(r){const i=S(this,e),s=x(r.id,"--id");if(r.background){const u=oi(await i.api.startPlan(s));if(i.outputJson){i.io.stdout(A(u));return}i.io.stdout(ni(u));return}const a=W(await i.api.runPlan(s));if(i.outputJson){i.io.stdout(A({session:a}));return}i.io.stdout(`Plan run created a session
54
- ${Q(a)}`)})}function gi(t,e){O(t.command("update").description("Update a scheduled plan. The current plan is read first and only the given fields change.")).requiredOption("--id <id>","Plan id to update.").option("--input <file|->","JSON document whose top-level fields replace the same fields of the plan.").option("--name <name>","Updated plan name.").option("--hero-id <id>","Hero for a single-agent pool. Replaces the agent pool.").option("--enabled","Enable the plan.").option("--disabled","Disable the plan.").action(async function(r){const i=x(r.id,"--id"),s=C(r.input),a=C(r.name),u=C(r.heroId);if(r.enabled&&r.disabled)throw new j("Pass either --enabled or --disabled, not both.");const h=r.enabled?!0:r.disabled?!1:void 0;if(!s&&!a&&!u&&h===void 0)throw new j("Provide at least one change: --input, --name, --enabled, --disabled, or --hero-id.");const v=s?ot(await Ut(s)):{},_=S(this,e),P=await _.api.getPlan(i),w=z(await _.api.updatePlan(i,Mt(P,{...v,...Bt({name:a,heroId:u,enabled:h})})));if(_.outputJson){_.io.stdout(A({plan:w}));return}_.io.stdout(`Plan updated
55
- ${et(w)}`)})}function vi(t,e){const n=t.command("plan").description("Manage scheduled plans: saved proposal or HagiTask inputs that run on a schedule.");mi(n,e),hi(n,e),ui(n,e),gi(n,e),pi(n,e),ci(n,e),di(n,e),fi(n,e)}function R(t){const e=t?.trim();return e||void 0}function Ot(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 Jt(t){return{projects:(t??[]).map(Ot)}}function yi(t){return t.length===0?`No projects found.
56
- `:`Projects (${t.length})
57
- ${U([{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)}
58
- `}function zt(t,e=[]){return H([["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 Ai(t){return{projectId:R(t.id)??"",name:R(t.name)??"",isMonoSpecs:t.isMonoSpecs===!0,hasError:t.hasError===!0,error:R(t.error),repositories:(t.repositories??[]).map(e=>({name:R(e.name),path:e.path??void 0,displayName:R(e.displayName),type:R(e.type),branch:R(e.branch),isValidGitRepo:typeof e.isValidGitRepo=="boolean"?e.isValidGitRepo:void 0}))}}function Oi(t){return`${H([["projectId",t.projectId],["name",t.name],["isMonoSpecs",String(t.isMonoSpecs)],["hasError",String(t.hasError)],["error",t.error??(t.hasError?"The project failed to load; its repository list may be incomplete.":void 0)]])}
59
- ${t.repositories.length===0?`This project lists no repositories.
60
- `:`${U([{header:"Name",value:e=>e.name??""},{header:"Path",value:e=>e.path??""},{header:"Display name",value:e=>e.displayName??""},{header:"Type",value:e=>e.type??""},{header:"Branch",value:e=>e.branch??""}],t.repositories)}
61
- `}`}function Si(t,e){O(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(r){const i=S(this,e),s=Ot(await i.api.createProject({name:x(r.name,"--name"),path:x(r.path,"--path"),description:C(r.description)}));if(i.outputJson){i.io.stdout(A({project:s}));return}i.io.stdout(`Project created
62
- ${zt(s)}`)})}function bi(t,e){O(t.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(r){const i=S(this,e),s=r.id.trim();if(await i.api.deleteProject(s),i.outputJson){i.io.stdout(A({projectId:s,deleted:!0}));return}i.io.stdout(`Project deleted
63
- projectId ${s}
64
- `)})}function Ci(t,e){O(t.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const r=S(this,e),i=Jt((await r.api.listProjects()).projects);if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(yi(i.projects))})}function _i(t,e){O(t.command("repositories").description("List the repositories of one project from the aggregation snapshot.")).requiredOption("--id <id>","Project id whose repositories to list.").action(async function(r){const i=S(this,e),s=r.id.trim(),a=((await i.api.listProjects()).projects??[]).find(h=>h.id===s);if(!a)throw new rt(404,`Project ${s} was not found in the aggregation snapshot.`);const u=Ai(a);if(i.outputJson){i.io.stdout(A(u));return}i.io.stdout(Oi(u))})}function Pi(t,e){O(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(r){if(!r.name&&!r.path&&!r.description&&!r.clearDescription)throw new j("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(r.description&&r.clearDescription)throw new j("Use either --description or --clear-description, not both.");const i=S(this,e),s=r.id.trim(),a=Jt((await i.api.listProjects()).projects).projects.find(h=>h.id===s);if(!a)throw new rt(404,`Project ${s} was not found in the aggregation snapshot.`);const u=Ot(await i.api.updateProject(s,{name:C(r.name)??a.name,path:C(r.path)??a.path,description:r.clearDescription?null:C(r.description)??a.description??null}));if(i.outputJson){i.io.stdout(A({project:u}));return}i.io.stdout(`Project updated
65
- ${zt(u)}`)})}function wi(t,e){const n=t.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");Ci(n,e),_i(n,e),Si(n,e),Pi(n,e),bi(n,e)}function Ei(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw new j("Annotation input must be a JSON object.");const n=e;if(!Array.isArray(n.files))throw new j("Annotation input must include a files array.");const r=typeof n.totalAnnotations=="number"?n.totalAnnotations:n.files.length,i=typeof n.submittedAt=="string"&&n.submittedAt.trim()?n.submittedAt:new Date().toISOString();return{...n,sessionId:t,totalAnnotations:r,submittedAt:i,files:n.files}}function Ii(t,e){O(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(r){const i=S(this,e),s=r.sessionId.trim(),a=Ei(s,await At(r.input)),u=await i.api.submitAnnotations(s,a);if(i.outputJson){i.io.stdout(A({sessionId:s,message:u.message,annotationCount:u.annotationCount??a.totalAnnotations,fileCount:u.fileCount??a.files.length}));return}i.io.stdout(`Proposal annotations submitted
66
- sessionId ${s}
67
- message ${u.message}
68
- annotationCount ${u.annotationCount??a.totalAnnotations}
69
- fileCount ${u.fileCount??a.files.length}
70
- `)})}function Ti(t,e){O(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(r){const i=S(this,e),s=W(await i.api.archiveProposal(r.sessionId.trim(),{heroId:C(r.heroId)}));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Proposal archive started
71
- ${Q(s)}`)})}function xi(t,e){O(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(r){const i=S(this,e),s=W(await i.api.completeProposal(r.sessionId.trim()));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Proposal completed
72
- ${Q(s)}`)})}function ki(t){return W(t)}function ji(t){return $t(t)}function $i(t){return Nt("Proposal sessions",t)}function Ni(t,e=[]){return Q(t,e)}var Kt="New Proposal";function Di(t){const e=C(t.title);if(e)return e;if(t.defaultTitle)return Kt;throw new j("Provide --title or pass --default-title to use the placeholder proposal title.")}function Vi(t,e){O(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 (${Kt}).`).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(r){const i=S(this,e),s=Di(r),a=ki(await i.api.createProposalSession({title:s,chiefComplaint:r.chiefComplaint.trim(),originalChiefComplaint:C(r.originalChiefComplaint),type:yt.PROPOSAL,projectId:r.projectId.trim(),enableIndependentWorkspace:r.enableIndependentWorkspace?!0:void 0,baseBranch:C(r.baseBranch),isDefaultTitle:!!r.defaultTitle})),u=`hagi proposal optimize-description --session-id ${a.sessionId} --description "<description>"`;if(i.outputJson){i.io.stdout(A({session:a,nextCommand:u}));return}i.io.stdout(`Proposal session created
73
- ${Ni(a,[["next",u]])}`)})}function Hi(t,e){O(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(r){const i=S(this,e),s=r.sessionId.trim(),a=C(r.heroId),u=await i.api.executeProposal(s,{heroId:a});if(i.outputJson){i.io.stdout(A({sessionId:s,message:u.message,requested:{heroId:a}}));return}i.io.stdout(`Proposal execution started
74
- sessionId ${s}
75
- message ${u.message}
76
- `)})}var pt=["zh-CN","zh-Hant","en-US","ja-JP","ko-KR","de-DE","fr-FR","es-ES","pt-BR","ru-RU"];function Ri(t){if(t.enableExploreMode&&t.disableExploreMode)throw new j("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(t.enableExploreMode)return!0;if(t.disableExploreMode)return!1}function qi(t){const e=t.trim();if(!pt.includes(e))throw new j(`--proposal-content-language must be one of: ${pt.join(", ")}.`);return e}function Fi(t,e){O(t.command("generate").description("Start proposal generation only. This command does not execute the proposal.")).requiredOption("--session-id <id>","Proposal session id to generate.").requiredOption("--proposal-content-language <language>",`Language of the generated proposal content (${pt.join(", ")}).`).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(r){const i=S(this,e),s=r.sessionId.trim(),a=Ri(r),u=qi(r.proposalContentLanguage),h=await i.api.generateProposal(s,{enableExploreMode:a,heroId:C(r.heroId),proposalContentLanguage:u}),v=`hagi proposal execute --session-id ${s}`;if(i.outputJson){i.io.stdout(A({sessionId:s,message:h.message,requested:{enableExploreMode:a,heroId:C(r.heroId),proposalContentLanguage:u},nextCommand:v}));return}i.io.stdout(`Proposal generation started
77
- sessionId ${s}
78
- message ${h.message}
79
- next Wait for the session to reach Reviewing, then run ${v}
80
- `)})}function Li(t,e){O(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(r){if(r.projectId&&r.projectIds?.length)throw new j("Use either --project-id or --project-ids, not both.");const i=S(this,e),s=ji(await i.api.listSessions({type:yt.PROPOSAL,projectId:C(r.projectId),projectIds:r.projectIds?.map(C).filter(Boolean),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout($i(s.sessions))})}function Gi(t,e){const n=e.summary,r=e.result,i=r?.validation?.isValid===!0,s=n?.appliedTitle||r?.optimizedTitle||"",a=n?.appliedProposalName||r?.optimizedProposalName||"",u=r?.validation?.diagnostics??[],h=[i?"Proposal optimized":"Proposal optimization returned diagnostics",`sessionId ${t}`,`title ${s}`,`proposalName ${a}`,`valid ${i?"yes":"no"}`];for(const v of u)h.push(`diagnostic ${v.code??"UNKNOWN"}: ${v.message??""}`.trimEnd());return i&&h.push(`next hagi proposal generate --session-id ${t}`),`${h.join(`
81
- `)}
82
- `}function Ui(t,e){O(t.command("optimize-description").description("Optimize the proposal description, title, and name in one backend step.")).requiredOption("--session-id <id>","Proposal session id to optimize.").requiredOption("--description <text>","Description text to optimize.").option("--title <title>","Current title snapshot. The session title is used when omitted.").option("--default-title","Treat the current title as the placeholder title.").option("--optimization-direction <text>","Optional optimization direction for AI guidance.").option("--original-chief-complaint <text>","Optional original chief complaint to keep as context.").action(async function(r){const i=S(this,e),s=x(r.sessionId,"--session-id"),a=await i.api.optimizeProposal(s,{description:x(r.description,"--description"),title:C(r.title),isDefaultTitle:r.defaultTitle?!0:void 0,optimizationDirection:C(r.optimizationDirection),originalChiefComplaint:C(r.originalChiefComplaint)});if(i.outputJson){i.io.stdout(A({sessionId:s,...a}));return}i.io.stdout(Gi(s,a))})}function Bi(t,e){O(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 M("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new M("--executor-type <type>","Executor override for this message.").choices(Object.values(at))).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:x(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(mt("Proposal message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Mi(t,e){O(t.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new M("--status <status>","Target session status.").choices(Object.values(kt)).makeOptionMandatory()).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.getSession(s);await i.api.updateSession(s,{title:a.title,description:a.description,status:r.status,metadata:a.metadata});const u=W({...a,status:r.status});if(i.outputJson){i.io.stdout(A({session:u}));return}i.io.stdout(`Proposal status updated
83
- ${Q(u)}`)})}function Wi(t,e){const n=t.command("proposal").description("Manage proposal sessions through backend session APIs.");Li(n,e),Vi(n,e),Ui(n,e),Fi(n,e),Ii(n,e),Hi(n,e),Ti(n,e),Mi(n,e),xi(n,e),Bi(n,e)}function K(t){return t?"yes":"no"}function Ji(t){return t&&t.length>0?t.join(", "):"-"}function Xt(t){return t.origin??"user"}function Qt(t){return Xt(t)==="built-in"}function zi(t){return Qt(t)?K(t.builtIn?.enabled):"-"}function Ki(t){return(Qt(t)?t.builtIn?.version:t.managedInstallMetadata?.version)??"-"}function Xi(t){const e=t.items??[];return e.length===0?`No local skills installed.
84
- `:`Local skills (${e.length})
85
- ${U([{header:"Name",value:n=>n.name??"-"},{header:"Origin",value:Xt},{header:"Enabled",value:zi},{header:"Version",value:Ki},{header:"Scope",value:n=>n.scope??"-"},{header:"Agents",value:n=>Ji(n.agents)},{header:"Path",value:n=>n.path??"-"}],e)}
86
- `}function Qi(t){return H([["skillName",t.skillName??void 0],["status",t.status??void 0],["message",t.userMessage??void 0],["diagnostic",t.diagnosticMessage??void 0]])}function Yi(t){return H([["skillName",t.slug??void 0],["enabled",K(t.enabled)],["message",t.userMessage??void 0],["diagnostic",t.diagnosticMessage??void 0]])}function Zi(t){const e=t.items??[];return e.length===0?`No gallery skills found.
87
- `:`Gallery skills (${e.length})
88
- ${U([{header:"ID",value:n=>n.id??"-"},{header:"Source",value:n=>n.source??"-"},{header:"Installs",value:n=>String(n.installs??0)},{header:"Trusted",value:n=>K(n.isTrustedSource)}],e)}
89
- `}function ts(t){const e=t.trustedProvider;return H([["id",t.id??void 0],["source",t.source??void 0],["skillSlug",t.skillSlug??void 0],["installable",K(t.isInstallable)],["description",t.description??void 0],["repository",t.repositoryFullName??t.repositoryName??void 0],["repositoryUrl",t.repositoryUrl??void 0],["defaultBranch",t.repositoryDefaultBranch??void 0],["trustedSource",K(t.isTrustedSource)],["trustedProvider",e?`${e.displayName??e.providerId??"-"}`:void 0],["installReference",t.installReference??void 0],["installCommand",t.installCommandPreview??void 0],["installVersion",t.installVersion??void 0],["installHint",t.installHint??void 0]])}function es(t){return H([["installReference",t.installReference??void 0],["normalizedSkillKey",t.normalizedSkillKey??void 0],["version",t.version??void 0],["status",t.status??void 0],["message",t.userMessage??void 0],["diagnostic",t.diagnosticMessage??void 0],["commandPreview",t.commandPreview??void 0]])}function st(t){const e=t.items??[];return e.length===0?`No trusted providers (directory version ${t.version??0}).
90
- `:`Trusted providers (${e.length}, directory version ${t.version??0})
91
- ${U([{header:"Provider ID",value:n=>n.providerId??"-"},{header:"Name",value:n=>n.displayName??"-"},{header:"Enabled",value:n=>K(n.isEnabled)},{header:"Preset",value:n=>K(n.isPreset)},{header:"Rules",value:n=>String(n.ruleCount??0)}],e)}
92
- `}function is(t,e){const n=t.command("gallery").description("Search the skill gallery, read skill details, and start managed installs.");O(n.command("search").description("Search the skill gallery by keyword.")).option("--query <query>","Keyword to search for. Omit to list the gallery.").action(async function(i){const s=S(this,e),a=await s.api.searchSkillGallery(C(i.query));if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Zi(a))}),O(n.command("detail").description("Show one gallery skill with installability, trust, and repository details.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").action(async function(i){const s=S(this,e),a=await s.api.getSkillGalleryDetail(x(i.id,"--id"),x(i.source,"--source"));if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(ts(a))}),O(n.command("install").description("Start a managed install of one gallery skill.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").requiredOption("--skill-slug <slug>","Skill slug inside the source repository.").option("--version <version>","Optional version token to install.").action(async function(i){const s=S(this,e),a=await s.api.installGallerySkill({id:x(i.id,"--id"),source:x(i.source,"--source"),skillSlug:x(i.skillSlug,"--skill-slug"),version:C(i.version)});if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(es(a))})}var ss="The change applies to agent runs that start afterwards; a run already in progress keeps its skills.";function wt(t,e,n){const r=n?"enable":"disable";O(t.command(r).description(`${n?"Turn on":"Turn off"} one built-in skill by name. ${ss}`)).requiredOption("--skill-name <name>",`Built-in skill name to ${r}.`).action(async function(s){const a=S(this,e),u=await a.api.setBuiltInSkillAvailability({slug:x(s.skillName,"--skill-name"),enabled:n});if(a.outputJson?a.io.stdout(A(u)):a.io.stdout(Yi(u)),!u.succeeded)throw new Dt(u.userMessage??`The built-in skill availability was not changed for ${u.slug??s.skillName}.`)})}function os(t,e){const n=t.command("local").description("List, enable or disable built-in skills, and uninstall user-installed local skills.");O(n.command("list").description("List installed local skills with their managed install metadata.")).action(async function(){const i=S(this,e),s=await i.api.listLocalSkills();if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(Xi(s))}),wt(n,e,!0),wt(n,e,!1),O(n.command("uninstall").description("Uninstall one user-installed local skill by name. Built-in skills cannot be uninstalled; use `skills local disable --skill-name <name>` to stop one from loading.")).requiredOption("--skill-name <name>","Local skill name to uninstall.").action(async function(i){const s=S(this,e),a=await s.api.uninstallLocalSkill({skillName:x(i.skillName,"--skill-name")});if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Qi(a))})}async function ns(t,e){const n=await At(t);if(!n||typeof n!="object"||Array.isArray(n))throw new j(`${e} must be a JSON object.`);return n}function rs(t,e){const n=t.command("trusted").description("Manage the trusted skill provider directory.");O(n.command("list").description("List trusted skill providers.")).action(async function(){const i=S(this,e),s=await i.api.listTrustedSkillProviders();if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(st(s))}),O(n.command("upsert").description("Create or update a trusted provider from a JSON document.")).requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(i){const s=S(this,e),a=await ns(x(i.input,"--input"),"Trusted provider input"),u=await s.api.upsertTrustedSkillProvider(a);if(s.outputJson){s.io.stdout(A(u));return}s.io.stdout(st(u))}),O(n.command("delete").description("Delete one trusted provider by id.")).requiredOption("--provider-id <id>","Trusted provider id to delete.").action(async function(i){const s=S(this,e),a={providerId:x(i.providerId,"--provider-id")},u=await s.api.deleteTrustedSkillProvider(a);if(s.outputJson){s.io.stdout(A(u));return}s.io.stdout(st(u))}),O(n.command("reset").description("Reset trusted providers to the backend defaults.")).action(async function(){const i=S(this,e),s=await i.api.resetTrustedSkillProviders();if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(st(s))})}function as(t,e){const n=t.command("skills").description("Manage local skills, the skill gallery, and trusted providers.");os(n,e),is(n,e),rs(n,e)}function T(t){const e=t?.trim();return e||void 0}function ls(t){return{severity:T(t.severity)??"",code:T(t.code)??"",message:T(t.message)??"",relativePath:T(t.relativePath)}}function St(t){return{id:T(t.id)??"",name:T(t.name)??"",type:T(t.type)??"",physicalPath:T(t.physicalPath)??"",gitUrl:T(t.gitUrl),createdAtUtc:T(t.createdAtUtc),updatedAtUtc:T(t.updatedAtUtc),bootstrapDiagnostics:(t.bootstrapDiagnostics??[]).map(ls)}}function Yt(t){return{generatedAtUtc:T(t.generatedAtUtc),vaults:(t.items??[]).map(St)}}function us(t){return t.length===0?`No vaults found.
93
- `:`Vaults (${t.length})
94
- ${U([{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)}
95
- `}function Zt(t,e=[]){return H([["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 ds(t){return{relativePath:T(t.relativePath)??"",fileName:T(t.fileName)??"",isDirectory:t.isDirectory===!0,extension:T(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:T(t.lastModifiedUtc),previewSupported:t.previewSupported===!0}}function cs(t){return{vaultId:T(t.id)??"",deleted:t.deleted===!0,deleteLocalFilesRequested:t.deleteLocalFilesRequested===!0,localFilesDeletionStatus:T(t.localFilesDeletionStatus),localFilesDeleted:t.localFilesDeleted===!0}}function ps(t){return`Vault deleted
96
- ${H([["vaultId",t.vaultId],["deleted",String(t.deleted)],["deleteLocalFilesRequested",String(t.deleteLocalFilesRequested)],["localFilesDeletionStatus",t.localFilesDeletionStatus],["localFilesDeleted",String(t.localFilesDeleted)]])}`}function hs(t){return{vaultId:T(t.vaultId)??"",vaultName:T(t.vaultName)??"",physicalPath:T(t.physicalPath)??"",status:T(t.status)??"",errorCode:T(t.errorCode),message:T(t.message),isTruncated:t.isTruncated===!0,totalFileCount:typeof t.totalFileCount=="number"?t.totalFileCount:0,items:(t.items??[]).map(ds)}}function ms(t){const e=H([["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
97
- ${e}No files found.
98
- `:`Vault files
99
- ${e}${U([{header:"Relative Path",value:n=>n.relativePath},{header:"Directory",value:n=>n.isDirectory?"yes":"no"},{header:"Extension",value:n=>n.extension},{header:"Size",value:n=>String(n.sizeBytes)},{header:"Preview",value:n=>n.previewSupported?"yes":"no"}],t.items)}
100
- `}function fs(t){return{vaultId:T(t.vaultId)??"",vaultName:T(t.vaultName)??"",physicalPath:T(t.physicalPath)??"",relativePath:T(t.relativePath)??"",fileName:T(t.fileName)??"",extension:T(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:T(t.lastModifiedUtc),status:T(t.status)??"",errorCode:T(t.errorCode),message:T(t.message),previewSupported:t.previewSupported===!0,contentTruncated:t.contentTruncated===!0,content:T(t.content)}}function gs(t){const e=H([["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
101
- ${e}`;const n=t.content.endsWith(`
102
- `)?"":`
103
- `;return`Vault file preview
104
- ${e}content
105
- -------
106
- ${t.content}${n}`}function vs(t,e){O(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(r){const i=S(this,e),s=St(await i.api.createVault({name:x(r.name,"--name"),type:x(r.type,"--type"),physicalPath:x(r.physicalPath,"--physical-path"),gitUrl:C(r.gitUrl)}));if(i.outputJson){i.io.stdout(A({vault:s}));return}i.io.stdout(`Vault created
107
- ${Zt(s)}`)})}function ys(t,e){O(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(r){const i=S(this,e),s=cs(await i.api.deleteVault(x(r.id,"--id"),r.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(ps(s))})}function As(t,e){O(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(r){const i=S(this,e),s=hs(await i.api.listVaultFiles(x(r.id,"--id"),C(r.path)));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(ms(s))})}function Os(t,e){O(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(r){const i=S(this,e),s=fs(await i.api.previewVaultFile(x(r.id,"--id"),x(r.path,"--path")));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(gs(s))})}function Ss(t,e){O(t.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const r=S(this,e),i=Yt(await r.api.listVaults());if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(us(i.vaults))})}function bs(t,e){O(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(r){const i=C(r.name),s=C(r.type),a=C(r.physicalPath),u=C(r.gitUrl);if(!i&&!s&&!a&&!u)throw new j("Provide at least one field to update: --name, --type, --physical-path, or --git-url.");const h=S(this,e),v=x(r.id,"--id"),_=Yt(await h.api.listVaults()).vaults.find(w=>w.id===v);if(!_)throw new rt(404,`Vault ${v} was not found in the latest vault snapshot.`);const P=St(await h.api.updateVault(v,{name:i??_.name,type:s??_.type,physicalPath:a??_.physicalPath,gitUrl:u??_.gitUrl??null}));if(h.outputJson){h.io.stdout(A({vault:P}));return}h.io.stdout(`Vault updated
108
- ${Zt(P)}`)})}function Cs(t,e){const n=t.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");Ss(n,e),vs(n,e),bs(n,e),ys(n,e);const r=n.command("files").description("Browse registered vault files and preview supported content.");As(r,e),Os(r,e)}function _s(t){return t.includes("--json")}function te(t=Lt(),e=!1){const n=new ye;return n.name("hagi").description("HagiCode CLI for project, proposal, vault, chat, AutoTask, and scheduled plan management.").showHelpAfterError().exitOverride(),n.configureOutput({writeOut:r=>{t.io.stdout(r)},writeErr:r=>{e||t.io.stderr(r)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),Be(n),wi(n,t),Wi(n,t),Cs(n,t),Ze(n,t),Je(n,t),vi(n,t),as(n,t),n}function Ps(t,e,n){return t.exitCode===0||t.code==="commander.helpDisplayed"||t.code==="commander.version"?0:(n&&e.io.stderr(Ht({exitCode:D.USAGE,message:t.message},{json:!0})),D.USAGE)}async function ws(t=process.argv,e=Lt()){const n=_s(t),r=te(e,n);try{return await r.parseAsync([...t]),0}catch(i){if(i instanceof ve)return Ps(i,e,n);const s=Oe(i,{baseUrl:Te()});return e.io.stderr(Ht(s,{json:n})),s.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return D}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return te}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return ws}});