@hagicode/cli 0.1.0-dev.27.1.26109f2 → 0.1.0-dev.28.1.71f1989

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 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, 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.
9
9
 
10
10
  ## Requirements
11
11
 
@@ -107,14 +107,14 @@ $ echo $?
107
107
 
108
108
  ```text
109
109
  hagi
110
- |-- project list | create | update | delete
110
+ |-- project list | repositories | create | update | delete
111
111
  |-- proposal list | create | optimize-description | generate | annotate | execute | archive | status | complete | send
112
112
  |-- vault list | create | update | delete
113
113
  | `-- files list | preview
114
114
  |-- chat list | create | archive | delete | send
115
115
  |-- autotask create | send
116
116
  |-- plan list | get | create | update | enable | disable | delete | run
117
- `-- skills local list | uninstall
117
+ `-- skills local list | enable | disable | uninstall
118
118
  gallery search | detail | install
119
119
  trusted list | upsert | delete | reset
120
120
  ```
@@ -144,6 +144,13 @@ hagi project list
144
144
  hagi project list --json
145
145
  ```
146
146
 
147
+ List the repositories of one project. The read-only command prints each repository's name, path relative to the project root, display name, type and branch. These paths are the values a proposal's repository scope names:
148
+
149
+ ```bash
150
+ hagi project repositories --id "$PROJECT_ID"
151
+ hagi project repositories --id "$PROJECT_ID" --json
152
+ ```
153
+
147
154
  Create a project. The backend creates the directory if it does not exist. The new id is read from `project.id`:
148
155
 
149
156
  ```bash
@@ -176,12 +183,20 @@ hagi proposal list --project-id "$PROJECT_ID"
176
183
  hagi proposal list --include-archived --json
177
184
  ```
178
185
 
186
+ Every proposal names its writable repositories and its read-only repositories. Take the paths from `hagi project repositories --id "$PROJECT_ID" --json`, and begin the chief complaint with a `Repository scope` section: a `Writable repositories:` list and a `Read-only repositories:` list, one `- <path>` entry per line, with `- none` for an empty list. The scope is a text convention in the chief complaint; `proposal create` has no scope flags. The format and a worked example are in [`skills/hagi/references/proposal-flow.md`](skills/hagi/references/proposal-flow.md#repository-scope).
187
+
179
188
  Create a proposal session only. The new id is read from `session.sessionId`:
180
189
 
181
190
  ```bash
182
191
  PROPOSAL_ID=$(hagi proposal create \
183
192
  --project-id "$PROJECT_ID" \
184
- --chief-complaint "Add CLI completion for session workflows" \
193
+ --chief-complaint "Repository scope
194
+ Writable repositories:
195
+ - repos/cli
196
+ Read-only repositories:
197
+ - none
198
+
199
+ Add CLI completion for session workflows" \
185
200
  --default-title \
186
201
  --json | json_field '.session.sessionId')
187
202
  ```
@@ -442,16 +457,30 @@ A manual run does not change the plan's state or next run time. It works for dis
442
457
 
443
458
  ## Skills Commands
444
459
 
445
- List installed local skills and remove one by name:
460
+ List installed local skills. The table shows each skill's origin (`user` or `built-in`), whether a built-in skill is enabled, its version, scope, agents and path. A user skill shows `-` in the Enabled column, because availability does not apply to it:
446
461
 
447
462
  ```bash
448
463
  hagi skills local list
449
464
  hagi skills local list --json
465
+ ```
466
+
467
+ Turn a built-in skill on or off by name. The change applies to agent runs that start afterwards; a run already in progress keeps its skills. A name that is not a built-in skill exits with code `30`, and the output carries the backend message:
468
+
469
+ ```bash
470
+ hagi skills local enable --skill-name hagi
471
+ hagi skills local disable --skill-name hagi --json
472
+ ```
473
+
474
+ Built-in skills cannot be uninstalled. Use `skills local disable` to stop one from loading. Remove a user skill by name:
475
+
476
+ ```bash
450
477
  SKILL_NAME=demo-skill
451
478
  hagi skills local uninstall --skill-name "$SKILL_NAME"
452
479
  ```
453
480
 
454
- The uninstall result reports a status such as `Succeeded` or `PrerequisiteMissing`, with the backend message.
481
+ The uninstall result reports a status such as `Succeeded` or `PrerequisiteMissing`, with the backend message. Passing a built-in skill's name returns the backend's refusal unchanged.
482
+
483
+ Skill recommendation and install progress streaming are not part of the CLI. `skills gallery search`, `detail` and `install` are the discovery and install path.
455
484
 
456
485
  Search the gallery and read one skill:
457
486
 
@@ -505,6 +534,7 @@ Stable non-zero exits used by the CLI:
505
534
  | `23` | HTTP 403 |
506
535
  | `24` | HTTP 404 |
507
536
  | `29` | HTTP 409 |
537
+ | `30` | Operation failed: the backend returned a refusal, for example `skills local enable` or `disable` on a name that is not a built-in skill |
508
538
  | `40` | Other HTTP 4xx |
509
539
  | `50` | HTTP 5xx |
510
540
  | `60` | Transport or connection failure |
@@ -1,105 +1,108 @@
1
- var Zt=Object.create,wt=Object.defineProperty,te=Object.getOwnPropertyDescriptor,ee=Object.getOwnPropertyNames,ie=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty,K=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),oe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(var i=ee(e),s=0,a=i.length,u;s<a;s++)u=i[s],!se.call(t,u)&&u!==n&&wt(t,u,{get:(h=>e[h]).bind(null,u),enumerable:!(r=te(e,u))||r.enumerable});return t},ne=(t,e,n)=>(n=t!=null?Zt(ie(t)):{},oe(e||!t||!t.__esModule?wt(n,"default",{value:t,enumerable:!0}):n,t));let bt=require("node:path"),re=require("node:fs"),ae=require("node:os"),le=require("node:fs/promises");var nt=K((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})),pt=K((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})),Et=K((t=>{var{humanReadableArgName:e}=pt(),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 G=w.map(R=>h(s.styleOptionTerm(s.optionTerm(R)),s.styleOptionDescription(s.optionDescription(R))));v=v.concat(this.formatItemList($,G,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 G=w.map(R=>h(s.styleSubcommandTerm(s.subcommandTerm(R)),s.styleSubcommandDescription(s.subcommandDescription(R))));v=v.concat(this.formatItemList($,G,s))}),v.join(`
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
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
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 G=this.displayWidth($);if(w+G<=s){P.push($),w+=G;return}h.push(P.join(""));const R=$.trimStart();P=[R],w=this.displayWidth(R)}),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=K((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(`${$}
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
6
  - a short flag is a single dash and a single character
7
7
  - either use a single dash and a single character (for a short flag)
8
8
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):v.test(w)?new Error(`${$}
9
9
  - too many short flags`):_.test(w)?new Error(`${$}
10
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})),ue=K((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?`
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
12
  (Did you mean one of ${u.join(", ")}?)`:u.length===1?`
13
- (Did you mean ${u[0]}?)`:""}t.suggestSimilar=r})),de=K((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}=pt(),{CommanderError:h}=nt(),{Help:v,stripColor:_}=Et(),{Option:P,DualOptions:w}=Tt(),{suggestSimilar:$}=ue(),G=class It 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:()=>at()??(s.stdout.isTTY&&s.stdout.hasColors?.()),getErrHasColors:()=>at()??(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,C]=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,C&&E.arguments(C),this._registerCommand(E),E.parent=this,E.copyInheritedSettings(this),c?this:E}createCommand(o){return new It(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
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
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
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,C)=>{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,C)};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 C=c;c=(E,k)=>{const y=C.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.
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
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
18
  - if '${d}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
19
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,T){const N=r.resolve(y,T);if(i.existsSync(N))return N;if(c.includes(r.extname(T)))return;const Ct=c.find(Yt=>i.existsSync(`${N}${Yt}`));if(Ct)return`${N}${Ct}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let g=o._executableFile||`${this._name}-${o._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,g);if(!y&&!o._executableFile&&this._scriptPath){const T=r.basename(this._scriptPath,r.extname(this._scriptPath));T!==this._name&&(y=p(C,`${T}-${o._name}`))}g=y||g}d=c.includes(r.extname(g));let E;s.platform!=="win32"?d?(l.unshift(g),l=R(s.execArgv).concat(l),E=n.spawn(s.argv[0],l,{stdio:"inherit"})):E=n.spawn(g,l,{stdio:"inherit"}):(this._checkForMissingExecutable(g,C,o._name),l.unshift(g),l=R(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,C,o._name);else if(y.code==="EACCES")throw new Error(`'${g}' not executable`);if(!k)s.exit(1);else{const T=new h(1,"commander.executeSubCommandAsync","(error)");T.nestedError=y,k(T)}}),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 C=`error: command-argument value '${c}' is invalid for argument '${d.name()}'.`;g=this._callParseArg(d,c,p,C)}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,C)=>o(d,C,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(T=>T.options.map(N=>N.short).some(N=>/^-\d$/.test(N))):!1;let C=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(C&&(!p(y)||g(y))){this.emit(`option:${C.name()}`,y);continue}if(C=null,p(y)){const T=this._findOption(y);if(T){if(T.required){const N=o[k++];N===void 0&&this.optionMissingArgument(T),this.emit(`option:${T.name()}`,N)}else if(T.optional){let N=null;k<o.length&&(!p(o[k])||g(o[k]))&&(N=o[k++]),this.emit(`option:${T.name()}`,N)}else this.emit(`option:${T.name()}`);C=T.variadic?T:null;continue}}if(y.length>2&&y[0]==="-"&&y[1]!=="-"){const T=this._findOption(`-${y[1]}`);if(T){T.required||T.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${T.name()}`,y.slice(2)):(this.emit(`option:${T.name()}`),E=`-${y.slice(2)}`);continue}}if(/^--[^=]+=/.test(y)){const T=y.indexOf("="),N=this._findOption(y.slice(0,T));if(N&&(N.required||N.optional)){this.emit(`option:${N.name()}`,y.slice(T+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}
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
21
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
22
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 C=g.attributeName(),E=this.getOptionValue(C),k=this.options.find(T=>T.negate&&C===T.attributeName()),y=this.options.find(T=>!T.negate&&C===T.attributeName());return k&&(k.presetArg===void 0&&E===!1||k.presetArg!==void 0&&E===k.presetArg)?k:y||g},c=g=>{const C=d(g),E=C.attributeName();return this.getOptionValueSource(E)==="env"?`environment variable '${C.envVar}'`:`option '${C.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(C=>C.long).map(C=>C.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=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(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.
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
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 R(Xt){return Xt.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 at(){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=G,t.useColor=at})),ce=K((t=>{var{Argument:e}=pt(),{Command:n}=de(),{CommanderError:r,InvalidArgumentError:i}=nt(),{Help:s}=Et(),{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})),pe=ne(ce(),1),{program:ms,createCommand:fs,createArgument:gs,createOption:vs,CommanderError:he,InvalidArgumentError:ys,InvalidOptionArgumentError:As,Command:me,Argument:Os,Option:U,Help:Ss}=pe.default;function A(t){return`${JSON.stringify(t,null,2)}
27
- `}var xt=(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 kt(t){return t.replace(/\s+/g," ").trim()}function B(t,e){const n=e.map(s=>t.map(a=>kt(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)} ${kt(i??"")}`).join(`
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
29
  `)}
30
- `}function _t(t){return typeof t=="string"?t.trim():t?.value?.trim()??""}function M(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===xt.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 jt(t){return{sessions:t.sessions.map(M)}}function $t(t,e){return e.length===0?`No ${t.toLowerCase()} found.
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
31
  `:`${t} (${e.length})
32
- ${B([{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 ht(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},dt=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}},V={USAGE:2,HTTP_BAD_REQUEST:20,HTTP_UNAUTHORIZED:21,HTTP_FORBIDDEN:23,HTTP_NOT_FOUND:24,HTTP_CONFLICT:29,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},j=class extends Error{constructor(t){super(t),this.name="CliUsageError"}},mt=class extends Error{status;details;constructor(t,e,n){super(e),this.name="CliHttpError",this.status=t,this.details=n}};function Nt(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Y(t,e){const n=Nt(t)?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function fe(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 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 t&&t>=400&&t<500?V.HTTP_CLIENT_ERROR:t&&t>=500?V.HTTP_SERVER_ERROR:V.UNKNOWN}}function ge(t,e={}){if(t instanceof j)return{exitCode:V.USAGE,message:t.message};if(t instanceof mt)return{exitCode:Pt(t.status),status:t.status,message:t.message,details:t.details};if(t instanceof dt){const n=Y(t.body,"error")??Y(t.body,"message")??t.message;return{exitCode:Pt(t.status),status:t.status,message:n,errorCode:Y(t.body,"errorCode"),correlationId:Y(t.body,"correlationId"),details:t.body}}if(t instanceof Error){if(!fe(t.message))return{exitCode:V.UNKNOWN,message:t.message};const n=e.baseUrl??"the configured backend";return{exitCode:V.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:V.UNKNOWN,message:String(t)}}function ve(t){const e=Nt(t)?.errors;return Array.isArray(e)?e.flatMap(n=>{const r=Y(n,"field"),i=Y(n,"message");return r&&i?[` - ${r}: ${i}`]:[]}):[]}function Dt(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}`,...ve(t.details)].join(`
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
36
  `)+`
37
- `}var ye="--base-url",Ae="HAGI_API_BASE_URL";function L(t){const e=t?.trim();return e||void 0}function Vt(t=process.env){return(0,bt.join)(L(t.XDG_CONFIG_HOME)??(0,bt.join)((0,ae.homedir)(),".config"),"hagi","config.json")}function Oe(t=process.env){const e=Vt(t);let n;try{n=(0,re.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"?L(i):void 0}function Se(t={},e=process.env){const n=L(t.baseUrl)??L(e.HAGI_API_BASE_URL)??Oe(e);if(!n)throw new j(`No backend base URL is configured. Set ${ye} <url>, the ${Ae} environment variable, or "baseUrl" in ${Vt(e)}.`);return{baseUrl:n,token:L(t.token)??L(e.HAGI_API_TOKEN),lang:L(t.lang)??L(e.HAGI_API_LANG)}}function Ce(t={},e=process.env){const n=Se(t,e);return m.BASE=n.baseUrl,m.WITH_CREDENTIALS=!1,m.CREDENTIALS="omit",m.TOKEN=n.token,m.HEADERS=n.lang?{"Accept-Language":n.lang}:void 0,n}function be(){return L(m.BASE)}var _e=class extends Error{constructor(t){super(t),this.name="CancelError"}get isCancelled(){return!0}},Pe=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 _e("Request aborted"))}}get isCancelled(){return this.#t}},ft=t=>t!=null,tt=t=>typeof t=="string",lt=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]),Ht=t=>t instanceof FormData,we=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ee=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("&")}`:""},Te=(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}${Ee(e.query)}`:i},Ie=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,xe=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 lt(n)&&(a.Authorization=`Bearer ${n}`),lt(r)&&lt(i)&&(a.Authorization=`Basic ${we(`${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":Ht(e.body)||(a["Content-Type"]="application/json")),new Headers(a)},ke=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):tt(t.body)||gt(t.body)||Ht(t.body)?t.body:JSON.stringify(t.body)},je=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)},$e=(t,e)=>{if(e){const n=t.headers.get(e);if(tt(n))return n}},Ne=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)}},De=(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 dt(t,e,n);if(!e.ok)throw new dt(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 Pe(async(n,r,i)=>{try{const s=Te(t,e),a=Ie(e),u=ke(e),h=await xe(t,e);if(!i.isCancelled){const v=await je(t,e,s,u,a,h,i),_=await Ne(v),P=$e(v,e.responseHeader),w={url:s,ok:v.ok,status:v.status,statusText:v.statusText,body:P??_};De(e,w),n(w.body)}}catch(s){r(s)}}),Ve=class{static getApiDataAggregation(){return f(m,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},ut=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"}})}},W=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"}})}},D=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"}})}},F=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 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 getApiSkillsRecommendationsConfig({locale:t}){return f(m,{method:"GET",url:"/api/skills/recommendations/config",query:{locale:t}})}static postApiSkillsRecommendationsGenerate({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/recommendations/generate",body:t,mediaType:"application/json"})}static postApiSkillsRecommendationsInstall({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/recommendations/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}})}},X=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 He(){return{listSessions:t=>D.getApiSessions(t),getSession:t=>D.getApiSessions1({sessionId:t}),createProposalSession:t=>D.postApiSessions({requestBody:t}),createChatSession:t=>D.postApiSessionsChat({requestBody:t}),createAutoTaskSession:t=>D.postApiSessionsAutoTask({requestBody:t}),updateSession:(t,e)=>D.putApiSessions({sessionId:t,requestBody:e}),deleteSession:(t,e)=>D.deleteApiSessions({sessionId:t,deleteFiles:e}),sendMessage:(t,e)=>D.postApiSessionsMessages({sessionId:t,requestBody:e}),optimizeProposal:(t,e)=>D.postApiSessionsOptimizeProposal({sessionId:t,requestBody:e}),generateProposal:(t,e)=>D.postApiSessionsGenerateProposal({sessionId:t,requestBody:e}),executeProposal:(t,e)=>D.postApiSessionsExecuteProposal({sessionId:t,requestBody:e}),archiveProposal:(t,e)=>D.postApiSessionsArchive({sessionId:t,requestBody:e}),completeProposal:t=>D.postApiSessionsComplete({sessionId:t}),submitAnnotations:(t,e)=>D.postApiSessionsAnnotations({sessionId:t,requestBody:e}),listProjects:()=>Ve.getApiDataAggregation(),createProject:t=>ut.postApiProject({requestBody:t}),updateProject:(t,e)=>ut.putApiProject({id:t,requestBody:e}),deleteProject:t=>ut.deleteApiProject({id:t}),listPlans:()=>W.getApiScheduledPlans(),getPlan:t=>W.getApiScheduledPlans1({id:t}),createPlan:t=>W.postApiScheduledPlans({requestBody:t}),updatePlan:(t,e)=>W.putApiScheduledPlans({id:t,requestBody:e}),deletePlan:t=>W.deleteApiScheduledPlans({id:t}),runPlan:t=>W.postApiScheduledPlansRun({id:t}),startPlan:t=>W.postApiScheduledPlansStart({id:t}),listVaults:()=>X.getApiVaults(),createVault:t=>X.postApiVaults({requestBody:t}),updateVault:(t,e)=>X.putApiVaults({id:t,requestBody:e}),deleteVault:(t,e)=>X.deleteApiVaults({id:t,deleteLocalFiles:e}),listVaultFiles:(t,e)=>X.getApiVaultsFiles({id:t,path:e}),previewVaultFile:(t,e)=>X.getApiVaultsFilesContent({id:t,path:e}),archiveChat:t=>D.postApiSessionsArchiveChat({sessionId:t}),listLocalSkills:()=>F.getApiSkillsLocal(),uninstallLocalSkill:t=>F.postApiSkillsLocalUninstall({requestBody:t}),searchSkillGallery:t=>F.getApiSkillsGallery({query:t}),getSkillGalleryDetail:(t,e)=>F.getApiSkillsGalleryDetail({id:t,source:e}),installGallerySkill:t=>F.postApiSkillsGalleryInstall({requestBody:t}),listTrustedSkillProviders:()=>F.getApiSkillsProvidersTrusted(),upsertTrustedSkillProvider:t=>F.postApiSkillsProvidersTrusted({requestBody:t}),deleteTrustedSkillProvider:t=>F.deleteApiSkillsProvidersTrusted({requestBody:t}),resetTrustedSkillProviders:()=>F.postApiSkillsProvidersTrustedReset()}}function b(t){const e=t?.trim();return e||void 0}function x(t,e){const n=b(t);if(!n)throw new j(`${e} is required.`);return n}function Rt(t){const e=t?.map(n=>b(n)).filter(Boolean);return e&&e.length>0?e:void 0}function qt(t=process.env,e={stdout:n=>{process.stdout.write(n)},stderr:n=>{process.stderr.write(n)}}){return{api:He(),env:t,io:e}}function Re(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:Ce({baseUrl:n.baseUrl,token:n.token,lang:n.lang},e.env)}}function qe(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"&&!b(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:b(r.message),presetId:b(r.presetId),repositoryPath:b(r.repositoryPath),projectIds:Rt(r.projectIds),needPush:r.needPush?!0:void 0,targetBranchMode:b(r.targetBranchMode),targetBranchName:b(r.targetBranchName),scriptKey:b(r.scriptKey),heroId:b(r.heroId),targetType:b(r.targetType),vaultId:b(r.vaultId)},a=M(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 rt=(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 Fe(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 U("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new U("--executor-type <type>","Executor override for this message.").choices(Object.values(rt))).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(ht("AutoTask message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Le(t,e){const n=t.command("autotask").description("Manage AutoTask sessions.");qe(n,e),Fe(n,e)}function Ge(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
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
39
  sessionId ${s}
40
40
  message ${a.message}
41
- `)})}function Ue(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 U("--executor-type <type>","Optional executor override.").choices(Object.values(rt))).action(async function(r){const i=S(this,e),s=M(await i.api.createChatSession({title:x(r.title,"--title"),projectId:x(r.projectId,"--project-id"),heroId:b(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 Be(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
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
43
  sessionId ${s}
44
44
  message ${a.message}
45
- `)})}var yt=(function(t){return t.CHAT="Chat",t.PROPOSAL="Proposal",t})({});function Me(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=jt(await i.api.listSessions({type:yt.CHAT,projectId:b(r.projectId),projectIds:Rt(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($t("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 We(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 U("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new U("--executor-type <type>","Executor override for this message.").choices(Object.values(rt))).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(ht("Chat message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Je(t,e){const n=t.command("chat").description("Manage normal chat sessions.");Me(n,e),Ue(n,e),Ge(n,e),Be(n,e),We(n,e)}function q(t){const e=t?.trim();return e||void 0}function Ft(t){if(!t)return"";const e=q(t.mode);if(e==="once")return["once",q(t.runAt)].filter(Boolean).join(" ");const n=q(t.repeat?.rule)??e??"";return[n,n==="weekly"?(t.repeat?.weekdays??[]).map(r=>r.trim().slice(0,3).toLowerCase()).join(","):void 0,q(t.timeOfDay),q(t.timeZone)].filter(Boolean).join(" ")}function z(t){return{id:q(t.id)??"",type:q(t.type)??"",name:q(t.name)??"",enabled:t.enabled===!0,state:q(t.state)??"",nextRunAt:q(t.nextRunAt)??null,schedule:t.schedule,agentPool:t.agentPool,payload:t.payload}}function ze(t){return{plans:t.map(z)}}function Ke(t){return t.length===0?`No scheduled plans found.
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
46
  `:`Plans (${t.length})
47
- ${B([{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=>Ft(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",Ft(t.schedule)]])}function Qe(t){return{planId:t,deleted:!0}}function Xe(t){return`Plan deleted
49
- ${H([["planId",t.planId],["deleted",String(t.deleted)]])}`}function Ye(t){return{planId:q(t.planId)??"",accepted:!0}}function Ze(t){return`Plan run accepted
50
- ${H([["planId",t.planId],["accepted",String(t.accepted)]])}`}async function ti(){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 ti():await(0,le.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 ei=["id","createdAt","updatedAt","state","nextRunAt"];async function Lt(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 ei)delete e[n];return e}function ii(t){return{strategy:"random",agents:[{heroId:t}]}}function Gt(t){return{...t.name!==void 0?{name:t.name}:{},...t.heroId!==void 0?{agentPool:ii(t.heroId)}:{},...t.enabled!==void 0?{enabled:t.enabled}:{}}}function Ut(t,e){return{...ot(t),...ot(e)}}function si(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 Lt(r.input)),a=z(await i.api.createPlan({enabled:!0,...s,...Gt({name:b(r.name),heroId:b(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 oi(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=Qe(s);if(i.outputJson){i.io.stdout(A(a));return}i.io.stdout(Xe(a))})}async function Bt(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,Ut(r,{enabled:n}))),changed:!0}}function ni(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 Bt(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 ri(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 Bt(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 ai(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 li(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=ze(await r.api.listPlans());if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(Ke(i.plans))})}function ui(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=Ye(await i.api.startPlan(s));if(i.outputJson){i.io.stdout(A(u));return}i.io.stdout(Ze(u));return}const a=M(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 di(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=b(r.input),a=b(r.name),u=b(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 Lt(s)):{},_=S(this,e),P=await _.api.getPlan(i),w=z(await _.api.updatePlan(i,Ut(P,{...v,...Gt({name:a,heroId:u,enabled:h})})));if(_.outputJson){_.io.stdout(A({plan:w}));return}_.io.stdout(`Plan updated
55
- ${et(w)}`)})}function ci(t,e){const n=t.command("plan").description("Manage scheduled plans: saved proposal or HagiTask inputs that run on a schedule.");li(n,e),ai(n,e),si(n,e),di(n,e),ri(n,e),ni(n,e),oi(n,e),ui(n,e)}function J(t){const e=t?.trim();return e||void 0}function Ot(t){return{id:J(t.id)??"",name:J(t.name)??"",path:J(t.path)??"",description:J(t.description),isMonoSpecs:t.isMonoSpecs===!0,monoSpecsVersion:J(t.monoSpecsVersion),monoSpecsRepoDirectory:J(t.monoSpecsRepoDirectory),monoSpecsCommitWhenArchive:typeof t.monoSpecsCommitWhenArchive=="boolean"?t.monoSpecsCommitWhenArchive:void 0,hasError:"hasError"in t?t.hasError===!0:!1,error:"error"in t?J(t.error):void 0}}function Mt(t){return{projects:(t??[]).map(Ot)}}function pi(t){return t.length===0?`No projects found.
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
56
  `:`Projects (${t.length})
57
- ${B([{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 Wt(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 hi(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:b(r.description)}));if(i.outputJson){i.io.stdout(A({project:s}));return}i.io.stdout(`Project created
59
- ${Wt(s)}`)})}function mi(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
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
60
63
  projectId ${s}
61
- `)})}function fi(t,e){O(t.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const r=S(this,e),i=Mt((await r.api.listProjects()).projects);if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(pi(i.projects))})}function gi(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=Mt((await i.api.listProjects()).projects).projects.find(h=>h.id===s);if(!a)throw new mt(404,`Project ${s} was not found in the aggregation snapshot.`);const u=Ot(await i.api.updateProject(s,{name:b(r.name)??a.name,path:b(r.path)??a.path,description:r.clearDescription?null:b(r.description)??a.description??null}));if(i.outputJson){i.io.stdout(A({project:u}));return}i.io.stdout(`Project updated
62
- ${Wt(u)}`)})}function vi(t,e){const n=t.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");fi(n,e),hi(n,e),gi(n,e),mi(n,e)}function yi(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 Ai(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=yi(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
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
63
66
  sessionId ${s}
64
67
  message ${u.message}
65
68
  annotationCount ${u.annotationCount??a.totalAnnotations}
66
69
  fileCount ${u.fileCount??a.files.length}
67
- `)})}function Oi(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=M(await i.api.archiveProposal(r.sessionId.trim(),{heroId:b(r.heroId)}));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Proposal archive started
68
- ${Q(s)}`)})}function Si(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=M(await i.api.completeProposal(r.sessionId.trim()));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Proposal completed
69
- ${Q(s)}`)})}function Ci(t){return M(t)}function bi(t){return jt(t)}function _i(t){return $t("Proposal sessions",t)}function Pi(t,e=[]){return Q(t,e)}var Jt="New Proposal";function wi(t){const e=b(t.title);if(e)return e;if(t.defaultTitle)return Jt;throw new j("Provide --title or pass --default-title to use the placeholder proposal title.")}function Ei(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 (${Jt}).`).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=wi(r),a=Ci(await i.api.createProposalSession({title:s,chiefComplaint:r.chiefComplaint.trim(),originalChiefComplaint:b(r.originalChiefComplaint),type:yt.PROPOSAL,projectId:r.projectId.trim(),enableIndependentWorkspace:r.enableIndependentWorkspace?!0:void 0,baseBranch:b(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
70
- ${Pi(a,[["next",u]])}`)})}function Ti(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=b(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
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
71
74
  sessionId ${s}
72
75
  message ${u.message}
73
- `)})}var ct=["zh-CN","zh-Hant","en-US","ja-JP","ko-KR","de-DE","fr-FR","es-ES","pt-BR","ru-RU"];function Ii(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 xi(t){const e=t.trim();if(!ct.includes(e))throw new j(`--proposal-content-language must be one of: ${ct.join(", ")}.`);return e}function ki(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 (${ct.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=Ii(r),u=xi(r.proposalContentLanguage),h=await i.api.generateProposal(s,{enableExploreMode:a,heroId:b(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:b(r.heroId),proposalContentLanguage:u},nextCommand:v}));return}i.io.stdout(`Proposal generation started
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
74
77
  sessionId ${s}
75
78
  message ${h.message}
76
79
  next Wait for the session to reach Reviewing, then run ${v}
77
- `)})}function ji(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=bi(await i.api.listSessions({type:yt.PROPOSAL,projectId:b(r.projectId),projectIds:r.projectIds?.map(b).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 $i(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(`
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(`
78
81
  `)}
79
- `}function Ni(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:b(r.title),isDefaultTitle:r.defaultTitle?!0:void 0,optimizationDirection:b(r.optimizationDirection),originalChiefComplaint:b(r.originalChiefComplaint)});if(i.outputJson){i.io.stdout(A({sessionId:s,...a}));return}i.io.stdout($i(s,a))})}function Di(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 U("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new U("--executor-type <type>","Executor override for this message.").choices(Object.values(rt))).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(ht("Proposal message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Vi(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 U("--status <status>","Target session status.").choices(Object.values(xt)).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=M({...a,status:r.status});if(i.outputJson){i.io.stdout(A({session:u}));return}i.io.stdout(`Proposal status updated
80
- ${Q(u)}`)})}function Hi(t,e){const n=t.command("proposal").description("Manage proposal sessions through backend session APIs.");ji(n,e),Ei(n,e),Ni(n,e),ki(n,e),Ai(n,e),Ti(n,e),Oi(n,e),Vi(n,e),Si(n,e),Di(n,e)}function Z(t){return t?"yes":"no"}function Ri(t){return t&&t.length>0?t.join(", "):"-"}function qi(t){const e=t.items??[];return e.length===0?`No local skills installed.
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.
81
84
  `:`Local skills (${e.length})
82
- ${B([{header:"Name",value:n=>n.name??"-"},{header:"Scope",value:n=>n.scope??"-"},{header:"Agents",value:n=>Ri(n.agents)},{header:"Path",value:n=>n.path??"-"}],e)}
83
- `}function Fi(t){return H([["skillName",t.skillName??void 0],["status",t.status??void 0],["message",t.userMessage??void 0],["diagnostic",t.diagnosticMessage??void 0]])}function Li(t){const e=t.items??[];return e.length===0?`No gallery skills found.
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.
84
87
  `:`Gallery skills (${e.length})
85
- ${B([{header:"ID",value:n=>n.id??"-"},{header:"Source",value:n=>n.source??"-"},{header:"Installs",value:n=>String(n.installs??0)},{header:"Trusted",value:n=>Z(n.isTrustedSource)}],e)}
86
- `}function Gi(t){const e=t.trustedProvider;return H([["id",t.id??void 0],["source",t.source??void 0],["skillSlug",t.skillSlug??void 0],["installable",Z(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",Z(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 Ui(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}).
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}).
87
90
  `:`Trusted providers (${e.length}, directory version ${t.version??0})
88
- ${B([{header:"Provider ID",value:n=>n.providerId??"-"},{header:"Name",value:n=>n.displayName??"-"},{header:"Enabled",value:n=>Z(n.isEnabled)},{header:"Preset",value:n=>Z(n.isPreset)},{header:"Rules",value:n=>String(n.ruleCount??0)}],e)}
89
- `}function Bi(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(b(i.query));if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Li(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(Gi(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:b(i.version)});if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Ui(a))})}function Mi(t,e){const n=t.command("local").description("List and uninstall globally 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(qi(s))}),O(n.command("uninstall").description("Uninstall one managed local skill by name.")).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(Fi(a))})}async function Wi(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 Ji(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 Wi(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 zi(t,e){const n=t.command("skills").description("Manage local skills, the skill gallery, and trusted providers.");Mi(n,e),Bi(n,e),Ji(n,e)}function I(t){const e=t?.trim();return e||void 0}function Ki(t){return{severity:I(t.severity)??"",code:I(t.code)??"",message:I(t.message)??"",relativePath:I(t.relativePath)}}function St(t){return{id:I(t.id)??"",name:I(t.name)??"",type:I(t.type)??"",physicalPath:I(t.physicalPath)??"",gitUrl:I(t.gitUrl),createdAtUtc:I(t.createdAtUtc),updatedAtUtc:I(t.updatedAtUtc),bootstrapDiagnostics:(t.bootstrapDiagnostics??[]).map(Ki)}}function zt(t){return{generatedAtUtc:I(t.generatedAtUtc),vaults:(t.items??[]).map(St)}}function Qi(t){return t.length===0?`No vaults found.
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.
90
93
  `:`Vaults (${t.length})
91
- ${B([{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)}
92
- `}function Kt(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 Xi(t){return{relativePath:I(t.relativePath)??"",fileName:I(t.fileName)??"",isDirectory:t.isDirectory===!0,extension:I(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:I(t.lastModifiedUtc),previewSupported:t.previewSupported===!0}}function Yi(t){return{vaultId:I(t.id)??"",deleted:t.deleted===!0,deleteLocalFilesRequested:t.deleteLocalFilesRequested===!0,localFilesDeletionStatus:I(t.localFilesDeletionStatus),localFilesDeleted:t.localFilesDeleted===!0}}function Zi(t){return`Vault deleted
93
- ${H([["vaultId",t.vaultId],["deleted",String(t.deleted)],["deleteLocalFilesRequested",String(t.deleteLocalFilesRequested)],["localFilesDeletionStatus",t.localFilesDeletionStatus],["localFilesDeleted",String(t.localFilesDeleted)]])}`}function ts(t){return{vaultId:I(t.vaultId)??"",vaultName:I(t.vaultName)??"",physicalPath:I(t.physicalPath)??"",status:I(t.status)??"",errorCode:I(t.errorCode),message:I(t.message),isTruncated:t.isTruncated===!0,totalFileCount:typeof t.totalFileCount=="number"?t.totalFileCount:0,items:(t.items??[]).map(Xi)}}function es(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
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
94
97
  ${e}No files found.
95
98
  `:`Vault files
96
- ${e}${B([{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)}
97
- `}function is(t){return{vaultId:I(t.vaultId)??"",vaultName:I(t.vaultName)??"",physicalPath:I(t.physicalPath)??"",relativePath:I(t.relativePath)??"",fileName:I(t.fileName)??"",extension:I(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:I(t.lastModifiedUtc),status:I(t.status)??"",errorCode:I(t.errorCode),message:I(t.message),previewSupported:t.previewSupported===!0,contentTruncated:t.contentTruncated===!0,content:I(t.content)}}function ss(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
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
98
101
  ${e}`;const n=t.content.endsWith(`
99
102
  `)?"":`
100
103
  `;return`Vault file preview
101
104
  ${e}content
102
105
  -------
103
- ${t.content}${n}`}function os(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:b(r.gitUrl)}));if(i.outputJson){i.io.stdout(A({vault:s}));return}i.io.stdout(`Vault created
104
- ${Kt(s)}`)})}function ns(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=Yi(await i.api.deleteVault(x(r.id,"--id"),r.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(Zi(s))})}function rs(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=ts(await i.api.listVaultFiles(x(r.id,"--id"),b(r.path)));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(es(s))})}function as(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=is(await i.api.previewVaultFile(x(r.id,"--id"),x(r.path,"--path")));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(ss(s))})}function ls(t,e){O(t.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const r=S(this,e),i=zt(await r.api.listVaults());if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(Qi(i.vaults))})}function us(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=b(r.name),s=b(r.type),a=b(r.physicalPath),u=b(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"),_=zt(await h.api.listVaults()).vaults.find(w=>w.id===v);if(!_)throw new mt(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
105
- ${Kt(P)}`)})}function ds(t,e){const n=t.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");ls(n,e),os(n,e),us(n,e),ns(n,e);const r=n.command("files").description("Browse registered vault files and preview supported content.");rs(r,e),as(r,e)}function cs(t){return t.includes("--json")}function Qt(t=qt(),e=!1){const n=new me;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}),Re(n),vi(n,t),Hi(n,t),ds(n,t),Je(n,t),Le(n,t),ci(n,t),zi(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(Dt({exitCode:V.USAGE,message:t.message},{json:!0})),V.USAGE)}async function hs(t=process.argv,e=qt()){const n=cs(t),r=Qt(e,n);try{return await r.parseAsync([...t]),0}catch(i){if(i instanceof he)return ps(i,e,n);const s=ge(i,{baseUrl:be()});return e.io.stderr(Dt(s,{json:n})),s.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return V}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return Qt}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return hs}});
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}});
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-OnauE7J3.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-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}
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-OnauE7J3.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/main-KH2FkAFy.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.27.1.26109f2",
3
+ "version": "0.1.0-dev.28.1.71f1989",
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": {