@hagicode/cli 0.1.0-dev.16.1.e9c85cd → 0.1.0-dev.18.1.f7fa085

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
@@ -80,16 +80,63 @@ Example:
80
80
  hagi --base-url https://api.example.com --token "$HAGI_TOKEN" project list --json
81
81
  ```
82
82
 
83
+ ## Connection Setup
84
+
85
+ Every operation command resolves the backend base URL on each invocation, in this order:
86
+
87
+ 1. `--base-url <url>` flag
88
+ 2. `HAGI_API_BASE_URL` environment variable
89
+ 3. `baseUrl` in the local config file: `$XDG_CONFIG_HOME/hagi/config.json`, or `~/.config/hagi/config.json` when `XDG_CONFIG_HOME` is unset
90
+
91
+ ```json
92
+ {
93
+ "baseUrl": "https://hagicode.example.com"
94
+ }
95
+ ```
96
+
97
+ If none of the three is set, the command exits with code `2` and sends no backend request.
98
+
99
+ Operation commands send requests without a credential by default. Pass `--token` (or set `HAGI_API_TOKEN`) only when your backend requires one.
100
+
101
+ When the backend cannot be reached, the CLI names the base URL and exits with code `60`. A backend HTTP error is reported differently: it prints the HTTP status and the backend error message, and exits with a status-mapped code.
102
+
103
+ ```text
104
+ $ hagi --base-url http://127.0.0.1:1 project list
105
+ Cannot reach HagiCode backend at http://127.0.0.1:1. Check that the backend is running and the base URL is correct.
106
+
107
+ $ echo $?
108
+ 60
109
+ ```
110
+
83
111
  ## Command Overview
84
112
 
85
113
  ```text
86
114
  hagi
87
115
  |-- project list | create | update | delete
88
- |-- proposal list | create | generate-name | optimize-description | generate | annotate | execute | archive | status | complete | send
116
+ |-- proposal list | create | optimize-description | generate | annotate | execute | archive | status | complete | send
89
117
  |-- vault list | create | update | delete
90
118
  | `-- files list | preview
91
119
  |-- chat list | create | archive | delete | send
92
- `-- autotask create | send
120
+ |-- autotask create | send
121
+ `-- skills local list | uninstall
122
+ gallery search | detail | install
123
+ trusted list | upsert | delete | reset
124
+ ```
125
+
126
+ ## Example Setup
127
+
128
+ The examples in the family sections run in order against a local backend. They assume:
129
+
130
+ - the backend listens on `http://127.0.0.1:35167`
131
+ - `hagi` is on `PATH`
132
+ - `json_field` reads one field from `--json` output
133
+
134
+ ```bash
135
+ export HAGI_API_BASE_URL=http://127.0.0.1:35167
136
+ json_field() { node -pe "JSON.parse(require('node:fs').readFileSync(0, 'utf8'))$1"; }
137
+
138
+ mkdir -p /tmp/cli-examples/repos/cli
139
+ PROJECT_ID=$(hagi project create --name "CLI Examples" --path /tmp/cli-examples --json | json_field '.project.id')
93
140
  ```
94
141
 
95
142
  ## Project Commands
@@ -101,187 +148,223 @@ hagi project list
101
148
  hagi project list --json
102
149
  ```
103
150
 
104
- Create a project:
151
+ Create a project. The backend creates the directory if it does not exist. The new id is read from `project.id`:
105
152
 
106
153
  ```bash
107
- hagi project create \
154
+ DEMO_PROJECT_ID=$(hagi project create \
108
155
  --name "CLI Demo" \
109
- --path /workspace/cli-demo \
110
- --description "Automation sandbox"
156
+ --path /tmp/cli-demo \
157
+ --description "Automation sandbox" \
158
+ --json | json_field '.project.id')
111
159
  ```
112
160
 
113
161
  Update only part of a project record. The CLI resolves current project data first so omitted fields are preserved:
114
162
 
115
163
  ```bash
116
- hagi project update --id <project-id> --description "Updated description"
117
- hagi project update --id <project-id> --name "Renamed project" --path /workspace/new-path
164
+ hagi project update --id "$DEMO_PROJECT_ID" --description "Updated description"
165
+ hagi project update --id "$DEMO_PROJECT_ID" --name "CLI Demo renamed"
118
166
  ```
119
167
 
120
- Delete a project:
168
+ Delete the demo project:
121
169
 
122
170
  ```bash
123
- hagi project delete --id <project-id>
171
+ hagi project delete --id "$DEMO_PROJECT_ID"
124
172
  ```
125
173
 
126
174
  ## Proposal Commands
127
175
 
128
- List proposal sessions:
176
+ List proposal sessions for the example project:
129
177
 
130
178
  ```bash
131
- hagi proposal list --project-id <project-id>
179
+ hagi proposal list --project-id "$PROJECT_ID"
132
180
  hagi proposal list --include-archived --json
133
181
  ```
134
182
 
135
- Create a proposal session only:
183
+ Create a proposal session only. The new id is read from `session.sessionId`:
136
184
 
137
185
  ```bash
138
- hagi proposal create \
139
- --project-id <project-id> \
186
+ PROPOSAL_ID=$(hagi proposal create \
187
+ --project-id "$PROJECT_ID" \
140
188
  --chief-complaint "Add CLI completion for session workflows" \
141
- --default-title
142
- ```
143
-
144
- Generate a proposal name explicitly:
145
-
146
- ```bash
147
- hagi proposal generate-name --session-id <session-id>
148
- ```
149
-
150
- Optimize the description explicitly:
151
-
152
- ```bash
153
- hagi proposal optimize-description \
154
- --session-id <session-id> \
155
- --description "Improve the proposal framing" \
156
- --optimization-direction "Focus on implementation risk"
189
+ --default-title \
190
+ --json | json_field '.session.sessionId')
157
191
  ```
158
192
 
159
- Generate and execute the proposal as separate steps:
193
+ Update status and send a follow-up message:
160
194
 
161
195
  ```bash
162
- hagi proposal generate --session-id <session-id> --enable-explore-mode
163
- hagi proposal execute --session-id <session-id>
196
+ hagi proposal status --session-id "$PROPOSAL_ID" --status Reviewing
197
+ hagi proposal send --session-id "$PROPOSAL_ID" --content "Please continue"
164
198
  ```
165
199
 
166
- Submit structured annotation payloads from a file or stdin:
200
+ The next steps are AI lifecycle actions and need a backend with an AI executor. `optimize-description` writes the optimized title, description, and proposal name to the session in one backend step, and `generate` needs that name. Without the AI executor, or before the name exists, the backend answers with a 400 that names the missing state:
167
201
 
168
202
  ```bash
169
- hagi proposal annotate --session-id <session-id> --input annotations.json
170
- cat annotations.json | hagi proposal annotate --session-id <session-id> --input - --json
171
- ```
172
-
173
- Archive, update status, complete, or send a follow-up message:
174
-
175
- ```bash
176
- hagi proposal archive --session-id <session-id> --hero-id <hero-id>
177
- hagi proposal status --session-id <session-id> --status Reviewing
178
- hagi proposal complete --session-id <session-id>
179
- hagi proposal send --session-id <session-id> --content "Please continue"
203
+ hagi proposal optimize-description --session-id "$PROPOSAL_ID" --description "Add CLI completion for session workflows" --default-title
204
+ hagi proposal generate --session-id "$PROPOSAL_ID" --proposal-content-language en-US --enable-explore-mode
205
+
206
+ cat > annotations.json <<'EOF'
207
+ {"files":[{"fileName":"proposal.md","filePath":"proposal.md"}]}
208
+ EOF
209
+ hagi proposal annotate --session-id "$PROPOSAL_ID" --input annotations.json
210
+ cat annotations.json | hagi proposal annotate --session-id "$PROPOSAL_ID" --input - --json
211
+
212
+ hagi proposal execute --session-id "$PROPOSAL_ID"
213
+ hagi proposal complete --session-id "$PROPOSAL_ID"
214
+ hagi proposal archive --session-id "$PROPOSAL_ID"
180
215
  ```
181
216
 
182
217
  ### Explicit Lifecycle Sequence
183
218
 
184
- The CLI keeps proposal lifecycle actions explicit and non-interactive:
219
+ The CLI keeps proposal lifecycle actions explicit and non-interactive. Each command maps to one backend action:
185
220
 
186
221
  1. `hagi proposal list`
187
222
  2. `hagi proposal create`
188
- 3. `hagi proposal generate-name`
189
- 4. `hagi proposal optimize-description` (optional)
190
- 5. `hagi proposal generate`
191
- 6. `hagi proposal annotate` (optional review loop)
192
- 7. `hagi proposal execute`
193
- 8. `hagi proposal archive`
194
- 9. `hagi proposal complete`
223
+ 3. `hagi proposal optimize-description --session-id <session-id> --description <text>` (sets the title, description, and proposal name)
224
+ 4. `hagi proposal generate --session-id <session-id> --proposal-content-language <language>` (optionally `--enable-explore-mode`)
225
+ 5. `hagi proposal annotate --session-id <session-id> --input <file>` (optional review loop)
226
+ 6. `hagi proposal execute --session-id <session-id>`
227
+ 7. `hagi proposal complete --session-id <session-id>`
228
+ 8. `hagi proposal archive --session-id <session-id>`
229
+
230
+ The CLI may suggest a next command, but it never chains later lifecycle APIs automatically.
195
231
 
196
232
  Each command maps to one backend action. The CLI may suggest a next command, but it never chains later lifecycle APIs automatically.
197
233
 
198
234
  ## Vault Commands
199
235
 
200
- List registered vaults:
236
+ Create a vault with a local folder to browse. The new id is read from `vault.id`:
201
237
 
202
238
  ```bash
203
- hagi vault list
204
- hagi vault list --json
239
+ mkdir -p /tmp/cli-vault-notes/docs
240
+ printf '# Notes\n' > /tmp/cli-vault-notes/docs/readme.md
241
+
242
+ VAULT_ID=$(hagi vault create \
243
+ --name "Main Notes" \
244
+ --type folder \
245
+ --physical-path /tmp/cli-vault-notes \
246
+ --json | json_field '.vault.id')
205
247
  ```
206
248
 
207
- Create a vault with typed options:
249
+ List registered vaults:
208
250
 
209
251
  ```bash
210
- hagi vault create \
211
- --name "Main Notes" \
212
- --type obsidian \
213
- --physical-path /vaults/main \
214
- --git-url https://github.com/acme/notes.git
252
+ hagi vault list
253
+ hagi vault list --json
215
254
  ```
216
255
 
217
256
  Update only part of a vault record. The CLI resolves the current vault snapshot first so omitted fields are preserved:
218
257
 
219
258
  ```bash
220
- hagi vault update --id <vault-id> --name "Renamed Vault"
221
- hagi vault update --id <vault-id> --physical-path /vaults/new-home --git-url https://github.com/acme/notes.git
259
+ hagi vault update --id "$VAULT_ID" --name "Renamed Vault"
222
260
  ```
223
261
 
224
- Delete a vault and optionally request backend cleanup of local files:
262
+ Browse vault files and preview supported content:
225
263
 
226
264
  ```bash
227
- hagi vault delete --id <vault-id>
228
- hagi vault delete --id <vault-id> --delete-local-files --json
265
+ hagi vault files list --id "$VAULT_ID"
266
+ hagi vault files list --id "$VAULT_ID" --path docs --json
267
+ hagi vault files preview --id "$VAULT_ID" --path docs/readme.md
229
268
  ```
230
269
 
231
- Browse vault files and preview supported content:
270
+ Delete a vault and request backend cleanup of its local files:
232
271
 
233
272
  ```bash
234
- hagi vault files list --id <vault-id>
235
- hagi vault files list --id <vault-id> --path docs --json
236
- hagi vault files preview --id <vault-id> --path docs/readme.md
273
+ hagi vault delete --id "$VAULT_ID" --delete-local-files --json
237
274
  ```
238
275
 
239
276
  ## Chat Commands
240
277
 
241
- List chat sessions:
278
+ Create a chat session. The new id is read from `session.sessionId`:
242
279
 
243
280
  ```bash
244
- hagi chat list --active-only
245
- hagi chat list --include-archived --json
281
+ CHAT_ID=$(hagi chat create \
282
+ --title "Repository Q&A" \
283
+ --project-id "$PROJECT_ID" \
284
+ --json | json_field '.session.sessionId')
246
285
  ```
247
286
 
248
- Create a chat session:
287
+ List chat sessions:
249
288
 
250
289
  ```bash
251
- hagi chat create \
252
- --title "Repository Q&A" \
253
- --project-id <project-id> \
254
- --executor-type CodexCli
290
+ hagi chat list --active-only
291
+ hagi chat list --include-archived --json
255
292
  ```
256
293
 
257
- Archive, delete, or send a message:
294
+ Send a message, archive, and delete:
258
295
 
259
296
  ```bash
260
- hagi chat archive --session-id <session-id>
261
- hagi chat delete --session-id <session-id>
262
- hagi chat send --session-id <session-id> --content "Summarize the current diff"
297
+ hagi chat send --session-id "$CHAT_ID" --content "Summarize the current diff"
298
+ hagi chat archive --session-id "$CHAT_ID"
299
+ hagi chat delete --session-id "$CHAT_ID"
263
300
  ```
264
301
 
265
302
  ## AutoTask Commands
266
303
 
267
- Create an AutoTask session with package-first automation flags:
304
+ Create an AutoTask session with package-first automation flags. The new id is read from `session.sessionId`:
268
305
 
269
306
  ```bash
270
- hagi autotask create \
307
+ AUTOTASK_ID=$(hagi autotask create \
271
308
  --title "Auto compose commit" \
272
- --project-id <project-id> \
309
+ --project-id "$PROJECT_ID" \
273
310
  --prompt-id auto-compose-commit.en-US \
274
311
  --repository-path repos/cli \
275
312
  --need-push \
276
313
  --target-branch-mode new-custom \
277
314
  --target-branch-name feature/cli-completion \
278
- --script-key autotask.auto-compose-commit
315
+ --script-key autotask.auto-compose-commit \
316
+ --json | json_field '.session.sessionId')
317
+ ```
318
+
319
+ The backend must have a hero available for the prompt's script. Without one, `autotask create` fails with a 400 whose error is `no-executable-hero`.
320
+
321
+ Send a follow-up message to the AutoTask session:
322
+
323
+ ```bash
324
+ hagi autotask send --session-id "$AUTOTASK_ID" --content "Retry with a smaller diff"
325
+ ```
326
+
327
+ ## Skills Commands
328
+
329
+ List installed local skills and remove one by name:
330
+
331
+ ```bash
332
+ hagi skills local list
333
+ hagi skills local list --json
334
+ SKILL_NAME=demo-skill
335
+ hagi skills local uninstall --skill-name "$SKILL_NAME"
336
+ ```
337
+
338
+ The uninstall result reports a status such as `Succeeded` or `PrerequisiteMissing`, with the backend message.
339
+
340
+ Search the gallery and read one skill:
341
+
342
+ ```bash
343
+ hagi skills gallery search --query react
344
+ hagi skills gallery search --query react --json
345
+ hagi skills gallery detail --id vercel-react-best-practices --source vercel-labs/agent-skills
346
+ ```
347
+
348
+ Start a managed install of a gallery skill. This writes the skill into your local skill directories, so run it only when you intend to install it:
349
+
350
+ ```bash
351
+ hagi skills gallery install \
352
+ --id vercel-react-best-practices \
353
+ --source vercel-labs/agent-skills \
354
+ --skill-slug vercel-react-best-practices
279
355
  ```
280
356
 
281
- Send a follow-up message to an AutoTask session:
357
+ Manage the trusted provider directory. `upsert` reads a JSON document from `--input <file>` or `--input -`:
282
358
 
283
359
  ```bash
284
- hagi autotask send --session-id <session-id> --content "Retry with a smaller diff"
360
+ hagi skills trusted list
361
+ cat > provider.json <<'EOF'
362
+ {"providerId":"example-provider","displayName":"Example","isEnabled":true,"sortOrder":50,"matchRules":[{"matchType":"owner","value":"example"}]}
363
+ EOF
364
+ hagi skills trusted upsert --input provider.json
365
+ cat provider.json | hagi skills trusted upsert --input - --json
366
+ hagi skills trusted delete --provider-id example-provider
367
+ hagi skills trusted reset
285
368
  ```
286
369
 
287
370
  ## Maintainer Workflow (`repos/cli` only)
@@ -334,7 +417,7 @@ The CLI resolves runtime settings centrally before every command. Explicit flags
334
417
 
335
418
  | Variable | Purpose |
336
419
  | --- | --- |
337
- | `HAGI_API_BASE_URL` | Backend base URL. Defaults to `http://127.0.0.1:35168` when unset. |
420
+ | `HAGI_API_BASE_URL` | Backend base URL, used when `--base-url` is not given. Overrides the config file. Required when neither is set. |
338
421
  | `HAGI_API_TOKEN` | Bearer token attached as `Authorization: Bearer <token>`. |
339
422
  | `HAGI_API_LANG` | Shared `Accept-Language` header value. |
340
423
 
@@ -0,0 +1,94 @@
1
+ var Lt=Object.create,At=Object.defineProperty,Ut=Object.getOwnPropertyDescriptor,Bt=Object.getOwnPropertyNames,Mt=Object.getPrototypeOf,Wt=Object.prototype.hasOwnProperty,B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Jt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(var i=Bt(e),s=0,l=i.length,u;s<l;s++)u=i[s],!Wt.call(t,u)&&u!==o&&At(t,u,{get:(h=>e[h]).bind(null,u),enumerable:!(n=Ut(e,u))||n.enumerable});return t},zt=(t,e,o)=>(o=t!=null?Lt(Mt(t)):{},Jt(e||!t||!t.__esModule?At(o,"default",{value:t,enumerable:!0}):o,t));let vt=require("node:path"),Kt=require("node:fs"),Qt=require("node:os"),Xt=require("node:fs/promises");var tt=B((t=>{var e=class extends Error{constructor(n,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=n,this.nestedError=void 0}},o=class extends e{constructor(n){super(1,"commander.invalidArgument",n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};t.CommanderError=e,t.InvalidArgumentError=o})),at=B((t=>{var{InvalidArgumentError:e}=tt(),o=class{constructor(i,s){switch(this.description=s||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(i,s){return s===this.defaultValue||!Array.isArray(s)?[i]:(s.push(i),s)}default(i,s){return this.defaultValue=i,this.defaultValueDescription=s,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(s,l)=>{if(!this.argChoices.includes(s))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(s,l):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function n(i){const s=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+s+">":"["+s+"]"}t.Argument=o,t.humanReadableArgName=n})),St=B((t=>{var{humanReadableArgName:e}=at(),o=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(i){this.helpWidth=this.helpWidth??i.helpWidth??80}visibleCommands(i){const s=i.commands.filter(u=>!u._hidden),l=i._getHelpCommand();return l&&!l._hidden&&s.push(l),this.sortSubcommands&&s.sort((u,h)=>u.name().localeCompare(h.name())),s}compareOptions(i,s){const l=u=>u.short?u.short.replace(/^-/,""):u.long.replace(/^--/,"");return l(i).localeCompare(l(s))}visibleOptions(i){const s=i.options.filter(u=>!u.hidden),l=i._getHelpOption();if(l&&!l.hidden){const u=l.short&&i._findOption(l.short),h=l.long&&i._findOption(l.long);!u&&!h?s.push(l):l.long&&!h?s.push(i.createOption(l.long,l.description)):l.short&&!u&&s.push(i.createOption(l.short,l.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const s=[];for(let l=i.parent;l;l=l.parent){const u=l.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(l=>e(l)).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((l,u)=>Math.max(l,this.displayWidth(s.styleSubcommandTerm(s.subcommandTerm(u)))),0)}longestOptionTermLength(i,s){return s.visibleOptions(i).reduce((l,u)=>Math.max(l,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestGlobalOptionTermLength(i,s){return s.visibleGlobalOptions(i).reduce((l,u)=>Math.max(l,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestArgumentTermLength(i,s){return s.visibleArguments(i).reduce((l,u)=>Math.max(l,this.displayWidth(s.styleArgumentTerm(s.argumentTerm(u)))),0)}commandUsage(i){let s=i._name;i._aliases[0]&&(s=s+"|"+i._aliases[0]);let l="";for(let u=i.parent;u;u=u.parent)l=u.name()+" "+l;return l+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(l=>JSON.stringify(l)).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 l=`(${s.join(", ")})`;return i.description?`${i.description} ${l}`:l}return i.description}argumentDescription(i){const s=[];if(i.argChoices&&s.push(`choices: ${i.argChoices.map(l=>JSON.stringify(l)).join(", ")}`),i.defaultValue!==void 0&&s.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),s.length>0){const l=`(${s.join(", ")})`;return i.description?`${i.description} ${l}`:l}return i.description}formatItemList(i,s,l){return s.length===0?[]:[l.styleTitle(i),...s,""]}groupItems(i,s,l){const u=new Map;return i.forEach(h=>{const y=l(h);u.has(y)||u.set(y,[])}),s.forEach(h=>{const y=l(h);u.has(y)||u.set(y,[]),u.get(y).push(h)}),u}formatHelp(i,s){const l=s.padWidth(i,s),u=s.helpWidth??80;function h(_,j){return s.formatItem(_,l,j,s)}let y=[`${s.styleTitle("Usage:")} ${s.styleUsage(s.commandUsage(i))}`,""];const C=s.commandDescription(i);C.length>0&&(y=y.concat([s.boxWrap(s.styleCommandDescription(C),u),""]));const S=s.visibleArguments(i).map(_=>h(s.styleArgumentTerm(s.argumentTerm(_)),s.styleArgumentDescription(s.argumentDescription(_))));if(y=y.concat(this.formatItemList("Arguments:",S,s)),this.groupItems(i.options,s.visibleOptions(i),_=>_.helpGroupHeading??"Options:").forEach((_,j)=>{const G=_.map(H=>h(s.styleOptionTerm(s.optionTerm(H)),s.styleOptionDescription(s.optionDescription(H))));y=y.concat(this.formatItemList(j,G,s))}),s.showGlobalOptions){const _=s.visibleGlobalOptions(i).map(j=>h(s.styleOptionTerm(s.optionTerm(j)),s.styleOptionDescription(s.optionDescription(j))));y=y.concat(this.formatItemList("Global Options:",_,s))}return this.groupItems(i.commands,s.visibleCommands(i),_=>_.helpGroup()||"Commands:").forEach((_,j)=>{const G=_.map(H=>h(s.styleSubcommandTerm(s.subcommandTerm(H)),s.styleSubcommandDescription(s.subcommandDescription(H))));y=y.concat(this.formatItemList(j,G,s))}),y.join(`
2
+ `)}displayWidth(i){return n(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,l,u){const y=" ".repeat(2);if(!l)return y+i;const C=i.padEnd(s+i.length-u.displayWidth(i)),S=2,_=(this.helpWidth??80)-s-S-2;let j;return _<this.minWidthToWrap||u.preformatted(l)?j=l:j=u.boxWrap(l,_).replace(/\n/g,`
3
+ `+" ".repeat(s+S)),y+C+" ".repeat(S)+j.replace(/\n/g,`
4
+ ${y}`)}boxWrap(i,s){if(s<this.minWidthToWrap)return i;const l=i.split(/\r\n|\n/),u=/[\s]*[^\s]+/g,h=[];return l.forEach(y=>{const C=y.match(u);if(C===null){h.push("");return}let S=[C.shift()],_=this.displayWidth(S[0]);C.forEach(j=>{const G=this.displayWidth(j);if(_+G<=s){S.push(j),_+=G;return}h.push(S.join(""));const H=j.trimStart();S=[H],_=this.displayWidth(H)}),h.push(S.join(""))}),h.join(`
5
+ `)}};function n(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}t.Help=o,t.stripColor=n})),Ct=B((t=>{var{InvalidArgumentError:e}=tt(),o=class{constructor(l,u){this.flags=l,this.description=u||"",this.required=l.includes("<"),this.optional=l.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(l),this.mandatory=!1;const h=s(l);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(l,u){return this.defaultValue=l,this.defaultValueDescription=u,this}preset(l){return this.presetArg=l,this}conflicts(l){return this.conflictsWith=this.conflictsWith.concat(l),this}implies(l){let u=l;return typeof l=="string"&&(u={[l]:!0}),this.implied=Object.assign(this.implied||{},u),this}env(l){return this.envVar=l,this}argParser(l){return this.parseArg=l,this}makeOptionMandatory(l=!0){return this.mandatory=!!l,this}hideHelp(l=!0){return this.hidden=!!l,this}_collectValue(l,u){return u===this.defaultValue||!Array.isArray(u)?[l]:(u.push(l),u)}choices(l){return this.argChoices=l.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(l){return this.helpGroupHeading=l,this}is(l){return this.short===l||this.long===l}isBoolean(){return!this.required&&!this.optional&&!this.negate}},n=class{constructor(l){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,l.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(l,u){const h=u.attributeName();if(!this.dualOptions.has(h))return!0;const y=this.negativeOptions.get(h).presetArg,C=y!==void 0?y:!1;return u.negate===(C===l)}};function i(l){return l.split("-").reduce((u,h)=>u+h[0].toUpperCase()+h.slice(1))}function s(l){let u,h;const y=/^-[^-]$/,C=/^--[^-]/,S=l.split(/[ |,]+/).concat("guard");if(y.test(S[0])&&(u=S.shift()),C.test(S[0])&&(h=S.shift()),!u&&y.test(S[0])&&(u=S.shift()),!u&&C.test(S[0])&&(u=h,h=S.shift()),S[0].startsWith("-")){const _=S[0],j=`option creation failed due to '${_}' in option flags '${l}'`;throw/^-[^-][^-]/.test(_)?new Error(`${j}
6
+ - a short flag is a single dash and a single character
7
+ - either use a single dash and a single character (for a short flag)
8
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):y.test(_)?new Error(`${j}
9
+ - too many short flags`):C.test(_)?new Error(`${j}
10
+ - too many long flags`):new Error(`${j}
11
+ - unrecognised flag format`)}if(u===void 0&&h===void 0)throw new Error(`option creation failed due to no flags found in '${l}'.`);return{shortFlag:u,longFlag:h}}t.Option=o,t.DualOptions=n})),Yt=B((t=>{var e=3;function o(i,s){if(Math.abs(i.length-s.length)>e)return Math.max(i.length,s.length);const l=[];for(let u=0;u<=i.length;u++)l[u]=[u];for(let u=0;u<=s.length;u++)l[0][u]=u;for(let u=1;u<=s.length;u++)for(let h=1;h<=i.length;h++){let y=1;i[h-1]===s[u-1]?y=0:y=1,l[h][u]=Math.min(l[h-1][u]+1,l[h][u-1]+1,l[h-1][u-1]+y),h>1&&u>1&&i[h-1]===s[u-2]&&i[h-2]===s[u-1]&&(l[h][u]=Math.min(l[h][u],l[h-2][u-2]+1))}return l[i.length][s.length]}function n(i,s){if(!s||s.length===0)return"";s=Array.from(new Set(s));const l=i.startsWith("--");l&&(i=i.slice(2),s=s.map(C=>C.slice(2)));let u=[],h=e;const y=.4;return s.forEach(C=>{if(C.length<=1)return;const S=o(i,C),_=Math.max(i.length,C.length);(_-S)/_>y&&(S<h?(h=S,u=[C]):S===h&&u.push(C))}),u.sort((C,S)=>C.localeCompare(S)),l&&(u=u.map(C=>`--${C}`)),u.length>1?`
12
+ (Did you mean one of ${u.join(", ")}?)`:u.length===1?`
13
+ (Did you mean ${u[0]}?)`:""}t.suggestSimilar=n})),Zt=B((t=>{var e=require("node:events").EventEmitter,o=require("node:child_process"),n=require("node:path"),i=require("node:fs"),s=require("node:process"),{Argument:l,humanReadableArgName:u}=at(),{CommanderError:h}=tt(),{Help:y,stripColor:C}=St(),{Option:S,DualOptions:_}=Ct(),{suggestSimilar:j}=Yt(),G=class _t extends e{constructor(r){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=r||"",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:a=>s.stdout.write(a),writeErr:a=>s.stderr.write(a),outputError:(a,c)=>c(a),getOutHelpWidth:()=>s.stdout.isTTY?s.stdout.columns:void 0,getErrHelpWidth:()=>s.stderr.isTTY?s.stderr.columns:void 0,getOutHasColors:()=>it()??(s.stdout.isTTY&&s.stdout.hasColors?.()),getErrHasColors:()=>it()??(s.stderr.isTTY&&s.stderr.hasColors?.()),stripColor:a=>C(a)},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(r){return this._outputConfiguration=r._outputConfiguration,this._helpOption=r._helpOption,this._helpCommand=r._helpCommand,this._helpConfiguration=r._helpConfiguration,this._exitCallback=r._exitCallback,this._storeOptionsAsProperties=r._storeOptionsAsProperties,this._combineFlagAndOptionalValue=r._combineFlagAndOptionalValue,this._allowExcessArguments=r._allowExcessArguments,this._enablePositionalOptions=r._enablePositionalOptions,this._showHelpAfterError=r._showHelpAfterError,this._showSuggestionAfterError=r._showSuggestionAfterError,this}_getCommandAndAncestors(){const r=[];for(let a=this;a;a=a.parent)r.push(a);return r}command(r,a,c){let d=a,p=c;typeof d=="object"&&d!==null&&(p=d,d=null),p=p||{};const[,f,O]=r.match(/([^ ]+) *(.*)/),b=this.createCommand(f);return d&&(b.description(d),b._executableHandler=!0),p.isDefault&&(this._defaultCommandName=b._name),b._hidden=!!(p.noHelp||p.hidden),b._executableFile=p.executableFile||null,O&&b.arguments(O),this._registerCommand(b),b.parent=this,b.copyInheritedSettings(this),d?this:b}createCommand(r){return new _t(r)}createHelp(){return Object.assign(new y,this.configureHelp())}configureHelp(r){return r===void 0?this._helpConfiguration:(this._helpConfiguration=r,this)}configureOutput(r){return r===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...r},this)}showHelpAfterError(r=!0){return typeof r!="string"&&(r=!!r),this._showHelpAfterError=r,this}showSuggestionAfterError(r=!0){return this._showSuggestionAfterError=!!r,this}addCommand(r,a){if(!r._name)throw new Error(`Command passed to .addCommand() must have a name
14
+ - specify the name in Command constructor or using .name()`);return a=a||{},a.isDefault&&(this._defaultCommandName=r._name),(a.noHelp||a.hidden)&&(r._hidden=!0),this._registerCommand(r),r.parent=this,r._checkForBrokenPassThrough(),this}createArgument(r,a){return new l(r,a)}argument(r,a,c,d){const p=this.createArgument(r,a);return typeof c=="function"?p.default(d).argParser(c):p.default(c),this.addArgument(p),this}arguments(r){return r.trim().split(/ +/).forEach(a=>{this.argument(a)}),this}addArgument(r){const a=this.registeredArguments.slice(-1)[0];if(a?.variadic)throw new Error(`only the last argument can be variadic '${a.name()}'`);if(r.required&&r.defaultValue!==void 0&&r.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${r.name()}'`);return this.registeredArguments.push(r),this}helpCommand(r,a){if(typeof r=="boolean")return this._addImplicitHelpCommand=r,r&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,c,d]=(r??"help [command]").match(/([^ ]+) *(.*)/),p=a??"display help for command",f=this.createCommand(c);return f.helpOption(!1),d&&f.arguments(d),p&&f.description(p),this._addImplicitHelpCommand=!0,this._helpCommand=f,(r||a)&&this._initCommandGroup(f),this}addHelpCommand(r,a){return typeof r!="object"?(this.helpCommand(r,a),this):(this._addImplicitHelpCommand=!0,this._helpCommand=r,this._initCommandGroup(r),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(r,a){const c=["preSubcommand","preAction","postAction"];if(!c.includes(r))throw new Error(`Unexpected value for event passed to hook : '${r}'.
15
+ Expecting one of '${c.join("', '")}'`);return this._lifeCycleHooks[r]?this._lifeCycleHooks[r].push(a):this._lifeCycleHooks[r]=[a],this}exitOverride(r){return r?this._exitCallback=r:this._exitCallback=a=>{if(a.code!=="commander.executeSubCommandAsync")throw a},this}_exit(r,a,c){this._exitCallback&&this._exitCallback(new h(r,a,c)),s.exit(r)}action(r){const a=c=>{const d=this.registeredArguments.length,p=c.slice(0,d);return this._storeOptionsAsProperties?p[d]=this:p[d]=this.opts(),p.push(this),r.apply(this,p)};return this._actionHandler=a,this}createOption(r,a){return new S(r,a)}_callParseArg(r,a,c,d){try{return r.parseArg(a,c)}catch(p){if(p.code==="commander.invalidArgument"){const f=`${d} ${p.message}`;this.error(f,{exitCode:p.exitCode,code:p.code})}throw p}}_registerOption(r){const a=r.short&&this._findOption(r.short)||r.long&&this._findOption(r.long);if(a){const c=r.long&&this._findOption(r.long)?r.long:r.short;throw new Error(`Cannot add option '${r.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${c}'
16
+ - already used by option '${a.flags}'`)}this._initOptionGroup(r),this.options.push(r)}_registerCommand(r){const a=d=>[d.name()].concat(d.aliases()),c=a(r).find(d=>this._findCommand(d));if(c){const d=a(this._findCommand(c)).join("|"),p=a(r).join("|");throw new Error(`cannot add command '${p}' as already have command '${d}'`)}this._initCommandGroup(r),this.commands.push(r)}addOption(r){this._registerOption(r);const a=r.name(),c=r.attributeName();if(r.negate){const p=r.long.replace(/^--no-/,"--");this._findOption(p)||this.setOptionValueWithSource(c,r.defaultValue===void 0?!0:r.defaultValue,"default")}else r.defaultValue!==void 0&&this.setOptionValueWithSource(c,r.defaultValue,"default");const d=(p,f,O)=>{p==null&&r.presetArg!==void 0&&(p=r.presetArg);const b=this.getOptionValue(c);p!==null&&r.parseArg?p=this._callParseArg(r,p,b,f):p!==null&&r.variadic&&(p=r._collectValue(p,b)),p==null&&(r.negate?p=!1:r.isBoolean()||r.optional?p=!0:p=""),this.setOptionValueWithSource(c,p,O)};return this.on("option:"+a,p=>{d(p,`error: option '${r.flags}' argument '${p}' is invalid.`,"cli")}),r.envVar&&this.on("optionEnv:"+a,p=>{d(p,`error: option '${r.flags}' value '${p}' from env '${r.envVar}' is invalid.`,"env")}),this}_optionEx(r,a,c,d,p){if(typeof a=="object"&&a instanceof S)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const f=this.createOption(a,c);if(f.makeOptionMandatory(!!r.mandatory),typeof d=="function")f.default(p).argParser(d);else if(d instanceof RegExp){const O=d;d=(b,k)=>{const v=O.exec(b);return v?v[0]:k},f.default(p).argParser(d)}else f.default(d);return this.addOption(f)}option(r,a,c,d){return this._optionEx({},r,a,c,d)}requiredOption(r,a,c,d){return this._optionEx({mandatory:!0},r,a,c,d)}combineFlagAndOptionalValue(r=!0){return this._combineFlagAndOptionalValue=!!r,this}allowUnknownOption(r=!0){return this._allowUnknownOption=!!r,this}allowExcessArguments(r=!0){return this._allowExcessArguments=!!r,this}enablePositionalOptions(r=!0){return this._enablePositionalOptions=!!r,this}passThroughOptions(r=!0){return this._passThroughOptions=!!r,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(r=!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=!!r,this}getOptionValue(r){return this._storeOptionsAsProperties?this[r]:this._optionValues[r]}setOptionValue(r,a){return this.setOptionValueWithSource(r,a,void 0)}setOptionValueWithSource(r,a,c){return this._storeOptionsAsProperties?this[r]=a:this._optionValues[r]=a,this._optionValueSources[r]=c,this}getOptionValueSource(r){return this._optionValueSources[r]}getOptionValueSourceWithGlobals(r){let a;return this._getCommandAndAncestors().forEach(c=>{c.getOptionValueSource(r)!==void 0&&(a=c.getOptionValueSource(r))}),a}_prepareUserArgs(r,a){if(r!==void 0&&!Array.isArray(r))throw new Error("first parameter to parse must be array or undefined");if(a=a||{},r===void 0&&a.from===void 0){s.versions?.electron&&(a.from="electron");const d=s.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(a.from="eval")}r===void 0&&(r=s.argv),this.rawArgs=r.slice();let c;switch(a.from){case void 0:case"node":this._scriptPath=r[1],c=r.slice(2);break;case"electron":s.defaultApp?(this._scriptPath=r[1],c=r.slice(2)):c=r.slice(1);break;case"user":c=r.slice(0);break;case"eval":c=r.slice(1);break;default:throw new Error(`unexpected parse option { from: '${a.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",c}parse(r,a){this._prepareForParse();const c=this._prepareUserArgs(r,a);return this._parseCommand([],c),this}async parseAsync(r,a){this._prepareForParse();const c=this._prepareUserArgs(r,a);return await this._parseCommand([],c),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(r,a,c){if(i.existsSync(r))return;const d=`'${r}' does not exist
18
+ - if '${c}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
19
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
20
+ - ${a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;throw new Error(d)}_executeSubCommand(r,a){a=a.slice();let c=!1;const d=[".js",".ts",".tsx",".mjs",".cjs"];function p(v,w){const N=n.resolve(v,w);if(i.existsSync(N))return N;if(d.includes(n.extname(w)))return;const gt=d.find(Gt=>i.existsSync(`${N}${Gt}`));if(gt)return`${N}${gt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let f=r._executableFile||`${this._name}-${r._name}`,O=this._executableDir||"";if(this._scriptPath){let v;try{v=i.realpathSync(this._scriptPath)}catch{v=this._scriptPath}O=n.resolve(n.dirname(v),O)}if(O){let v=p(O,f);if(!v&&!r._executableFile&&this._scriptPath){const w=n.basename(this._scriptPath,n.extname(this._scriptPath));w!==this._name&&(v=p(O,`${w}-${r._name}`))}f=v||f}c=d.includes(n.extname(f));let b;s.platform!=="win32"?c?(a.unshift(f),a=H(s.execArgv).concat(a),b=o.spawn(s.argv[0],a,{stdio:"inherit"})):b=o.spawn(f,a,{stdio:"inherit"}):(this._checkForMissingExecutable(f,O,r._name),a.unshift(f),a=H(s.execArgv).concat(a),b=o.spawn(s.execPath,a,{stdio:"inherit"})),b.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(v=>{s.on(v,()=>{b.killed===!1&&b.exitCode===null&&b.kill(v)})});const k=this._exitCallback;b.on("close",v=>{v=v??1,k?k(new h(v,"commander.executeSubCommandAsync","(close)")):s.exit(v)}),b.on("error",v=>{if(v.code==="ENOENT")this._checkForMissingExecutable(f,O,r._name);else if(v.code==="EACCES")throw new Error(`'${f}' not executable`);if(!k)s.exit(1);else{const w=new h(1,"commander.executeSubCommandAsync","(error)");w.nestedError=v,k(w)}}),this.runningCommand=b}_dispatchSubcommand(r,a,c){const d=this._findCommand(r);d||this.help({error:!0}),d._prepareForParse();let p;return p=this._chainOrCallSubCommandHook(p,d,"preSubcommand"),p=this._chainOrCall(p,()=>{if(d._executableHandler)this._executeSubCommand(d,a.concat(c));else return d._parseCommand(a,c)}),p}_dispatchHelpCommand(r){r||this.help();const a=this._findCommand(r);return a&&!a._executableHandler&&a.help(),this._dispatchSubcommand(r,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((r,a)=>{r.required&&this.args[a]==null&&this.missingArgument(r.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const r=(c,d,p)=>{let f=d;if(d!==null&&c.parseArg){const O=`error: command-argument value '${d}' is invalid for argument '${c.name()}'.`;f=this._callParseArg(c,d,p,O)}return f};this._checkNumberOfArguments();const a=[];this.registeredArguments.forEach((c,d)=>{let p=c.defaultValue;c.variadic?d<this.args.length?(p=this.args.slice(d),c.parseArg&&(p=p.reduce((f,O)=>r(c,O,f),c.defaultValue))):p===void 0&&(p=[]):d<this.args.length&&(p=this.args[d],c.parseArg&&(p=r(c,p,c.defaultValue))),a[d]=p}),this.processedArgs=a}_chainOrCall(r,a){return r?.then&&typeof r.then=="function"?r.then(()=>a()):a()}_chainOrCallHooks(r,a){let c=r;const d=[];return this._getCommandAndAncestors().reverse().filter(p=>p._lifeCycleHooks[a]!==void 0).forEach(p=>{p._lifeCycleHooks[a].forEach(f=>{d.push({hookedCommand:p,callback:f})})}),a==="postAction"&&d.reverse(),d.forEach(p=>{c=this._chainOrCall(c,()=>p.callback(p.hookedCommand,this))}),c}_chainOrCallSubCommandHook(r,a,c){let d=r;return this._lifeCycleHooks[c]!==void 0&&this._lifeCycleHooks[c].forEach(p=>{d=this._chainOrCall(d,()=>p(this,a))}),d}_parseCommand(r,a){const c=this.parseOptions(a);if(this._parseOptionsEnv(),this._parseOptionsImplied(),r=r.concat(c.operands),a=c.unknown,this.args=r.concat(a),r&&this._findCommand(r[0]))return this._dispatchSubcommand(r[0],r.slice(1),a);if(this._getHelpCommand()&&r[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(r[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(a),this._dispatchSubcommand(this._defaultCommandName,r,a);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(c.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const d=()=>{c.unknown.length>0&&this.unknownOption(c.unknown[0])},p=`command:${this.name()}`;if(this._actionHandler){d(),this._processArguments();let f;return f=this._chainOrCallHooks(f,"preAction"),f=this._chainOrCall(f,()=>this._actionHandler(this.processedArgs)),this.parent&&(f=this._chainOrCall(f,()=>{this.parent.emit(p,r,a)})),f=this._chainOrCallHooks(f,"postAction"),f}if(this.parent?.listenerCount(p))d(),this._processArguments(),this.parent.emit(p,r,a);else if(r.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",r,a);this.listenerCount("command:*")?this.emit("command:*",r,a):this.commands.length?this.unknownCommand():(d(),this._processArguments())}else this.commands.length?(d(),this.help({error:!0})):(d(),this._processArguments())}_findCommand(r){if(r)return this.commands.find(a=>a._name===r||a._aliases.includes(r))}_findOption(r){return this.options.find(a=>a.is(r))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(r=>{r.options.forEach(a=>{a.mandatory&&r.getOptionValue(a.attributeName())===void 0&&r.missingMandatoryOptionValue(a)})})}_checkForConflictingLocalOptions(){const r=this.options.filter(a=>{const c=a.attributeName();return this.getOptionValue(c)===void 0?!1:this.getOptionValueSource(c)!=="default"});r.filter(a=>a.conflictsWith.length>0).forEach(a=>{const c=r.find(d=>a.conflictsWith.includes(d.attributeName()));c&&this._conflictingOption(a,c)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(r=>{r._checkForConflictingLocalOptions()})}parseOptions(r){const a=[],c=[];let d=a;function p(v){return v.length>1&&v[0]==="-"}const f=v=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(v)?!this._getCommandAndAncestors().some(w=>w.options.map(N=>N.short).some(N=>/^-\d$/.test(N))):!1;let O=null,b=null,k=0;for(;k<r.length||b;){const v=b??r[k++];if(b=null,v==="--"){d===c&&d.push(v),d.push(...r.slice(k));break}if(O&&(!p(v)||f(v))){this.emit(`option:${O.name()}`,v);continue}if(O=null,p(v)){const w=this._findOption(v);if(w){if(w.required){const N=r[k++];N===void 0&&this.optionMissingArgument(w),this.emit(`option:${w.name()}`,N)}else if(w.optional){let N=null;k<r.length&&(!p(r[k])||f(r[k]))&&(N=r[k++]),this.emit(`option:${w.name()}`,N)}else this.emit(`option:${w.name()}`);O=w.variadic?w:null;continue}}if(v.length>2&&v[0]==="-"&&v[1]!=="-"){const w=this._findOption(`-${v[1]}`);if(w){w.required||w.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${w.name()}`,v.slice(2)):(this.emit(`option:${w.name()}`),b=`-${v.slice(2)}`);continue}}if(/^--[^=]+=/.test(v)){const w=v.indexOf("="),N=this._findOption(v.slice(0,w));if(N&&(N.required||N.optional)){this.emit(`option:${N.name()}`,v.slice(w+1));continue}}if(d===a&&p(v)&&!(this.commands.length===0&&f(v))&&(d=c),(this._enablePositionalOptions||this._passThroughOptions)&&a.length===0&&c.length===0){if(this._findCommand(v)){a.push(v),c.push(...r.slice(k));break}else if(this._getHelpCommand()&&v===this._getHelpCommand().name()){a.push(v,...r.slice(k));break}else if(this._defaultCommandName){c.push(v,...r.slice(k));break}}if(this._passThroughOptions){d.push(v,...r.slice(k));break}d.push(v)}return{operands:a,unknown:c}}opts(){if(this._storeOptionsAsProperties){const r={},a=this.options.length;for(let c=0;c<a;c++){const d=this.options[c].attributeName();r[d]=d===this._versionOptionName?this._version:this[d]}return r}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((r,a)=>Object.assign(r,a.opts()),{})}error(r,a){this._outputConfiguration.outputError(`${r}
21
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
22
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
23
+ `),this.outputHelp({error:!0}));const c=a||{},d=c.exitCode||1,p=c.code||"commander.error";this._exit(d,p,r)}_parseOptionsEnv(){this.options.forEach(r=>{if(r.envVar&&r.envVar in s.env){const a=r.attributeName();(this.getOptionValue(a)===void 0||["default","config","env"].includes(this.getOptionValueSource(a)))&&(r.required||r.optional?this.emit(`optionEnv:${r.name()}`,s.env[r.envVar]):this.emit(`optionEnv:${r.name()}`))}})}_parseOptionsImplied(){const r=new _(this.options),a=c=>this.getOptionValue(c)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(c));this.options.filter(c=>c.implied!==void 0&&a(c.attributeName())&&r.valueFromOption(this.getOptionValue(c.attributeName()),c)).forEach(c=>{Object.keys(c.implied).filter(d=>!a(d)).forEach(d=>{this.setOptionValueWithSource(d,c.implied[d],"implied")})})}missingArgument(r){const a=`error: missing required argument '${r}'`;this.error(a,{code:"commander.missingArgument"})}optionMissingArgument(r){const a=`error: option '${r.flags}' argument missing`;this.error(a,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(r){const a=`error: required option '${r.flags}' not specified`;this.error(a,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(r,a){const c=f=>{const O=f.attributeName(),b=this.getOptionValue(O),k=this.options.find(w=>w.negate&&O===w.attributeName()),v=this.options.find(w=>!w.negate&&O===w.attributeName());return k&&(k.presetArg===void 0&&b===!1||k.presetArg!==void 0&&b===k.presetArg)?k:v||f},d=f=>{const O=c(f),b=O.attributeName();return this.getOptionValueSource(b)==="env"?`environment variable '${O.envVar}'`:`option '${O.flags}'`},p=`error: ${d(r)} cannot be used with ${d(a)}`;this.error(p,{code:"commander.conflictingOption"})}unknownOption(r){if(this._allowUnknownOption)return;let a="";if(r.startsWith("--")&&this._showSuggestionAfterError){let d=[],p=this;do{const f=p.createHelp().visibleOptions(p).filter(O=>O.long).map(O=>O.long);d=d.concat(f),p=p.parent}while(p&&!p._enablePositionalOptions);a=j(r,d)}const c=`error: unknown option '${r}'${a}`;this.error(c,{code:"commander.unknownOption"})}_excessArguments(r){if(this._allowExcessArguments)return;const a=this.registeredArguments.length,c=a===1?"":"s",d=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${a} argument${c} but got ${r.length}.`;this.error(d,{code:"commander.excessArguments"})}unknownCommand(){const r=this.args[0];let a="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(p=>{d.push(p.name()),p.alias()&&d.push(p.alias())}),a=j(r,d)}const c=`error: unknown command '${r}'${a}`;this.error(c,{code:"commander.unknownCommand"})}version(r,a,c){if(r===void 0)return this._version;this._version=r,a=a||"-V, --version",c=c||"output the version number";const d=this.createOption(a,c);return this._versionOptionName=d.attributeName(),this._registerOption(d),this.on("option:"+d.name(),()=>{this._outputConfiguration.writeOut(`${r}
24
+ `),this._exit(0,"commander.version",r)}),this}description(r,a){return r===void 0&&a===void 0?this._description:(this._description=r,a&&(this._argsDescription=a),this)}summary(r){return r===void 0?this._summary:(this._summary=r,this)}alias(r){if(r===void 0)return this._aliases[0];let a=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(a=this.commands[this.commands.length-1]),r===a._name)throw new Error("Command alias can't be the same as its name");const c=this.parent?._findCommand(r);if(c){const d=[c.name()].concat(c.aliases()).join("|");throw new Error(`cannot add alias '${r}' to command '${this.name()}' as already have command '${d}'`)}return a._aliases.push(r),this}aliases(r){return r===void 0?this._aliases:(r.forEach(a=>this.alias(a)),this)}usage(r){if(r===void 0){if(this._usage)return this._usage;const a=this.registeredArguments.map(c=>u(c));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?a:[]).join(" ")}return this._usage=r,this}name(r){return r===void 0?this._name:(this._name=r,this)}helpGroup(r){return r===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=r,this)}commandsGroup(r){return r===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=r,this)}optionsGroup(r){return r===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=r,this)}_initOptionGroup(r){this._defaultOptionGroup&&!r.helpGroupHeading&&r.helpGroup(this._defaultOptionGroup)}_initCommandGroup(r){this._defaultCommandGroup&&!r.helpGroup()&&r.helpGroup(this._defaultCommandGroup)}nameFromFilename(r){return this._name=n.basename(r,n.extname(r)),this}executableDir(r){return r===void 0?this._executableDir:(this._executableDir=r,this)}helpInformation(r){const a=this.createHelp(),c=this._getOutputContext(r);a.prepareContext({error:c.error,helpWidth:c.helpWidth,outputHasColors:c.hasColors});const d=a.formatHelp(this,a);return c.hasColors?d:this._outputConfiguration.stripColor(d)}_getOutputContext(r){r=r||{};const a=!!r.error;let c,d,p;return a?(c=O=>this._outputConfiguration.writeErr(O),d=this._outputConfiguration.getErrHasColors(),p=this._outputConfiguration.getErrHelpWidth()):(c=O=>this._outputConfiguration.writeOut(O),d=this._outputConfiguration.getOutHasColors(),p=this._outputConfiguration.getOutHelpWidth()),{error:a,write:O=>(d||(O=this._outputConfiguration.stripColor(O)),c(O)),hasColors:d,helpWidth:p}}outputHelp(r){let a;typeof r=="function"&&(a=r,r=void 0);const c=this._getOutputContext(r),d={error:c.error,write:c.write,command:this};this._getCommandAndAncestors().reverse().forEach(f=>f.emit("beforeAllHelp",d)),this.emit("beforeHelp",d);let p=this.helpInformation({error:c.error});if(a&&(p=a(p),typeof p!="string"&&!Buffer.isBuffer(p)))throw new Error("outputHelp callback must return a string or a Buffer");c.write(p),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",d),this._getCommandAndAncestors().forEach(f=>f.emit("afterAllHelp",d))}helpOption(r,a){return typeof r=="boolean"?(r?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(r??"-h, --help",a??"display help for command"),(r||a)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(r){return this._helpOption=r,this._initOptionGroup(r),this}help(r){this.outputHelp(r);let a=Number(s.exitCode??0);a===0&&r&&typeof r!="function"&&r.error&&(a=1),this._exit(a,"commander.help","(outputHelp)")}addHelpText(r,a){const c=["beforeAll","before","after","afterAll"];if(!c.includes(r))throw new Error(`Unexpected value for position to addHelpText.
25
+ Expecting one of '${c.join("', '")}'`);const d=`${r}Help`;return this.on(d,p=>{let f;typeof a=="function"?f=a({error:p.error,command:p.command}):f=a,f&&p.write(`${f}
26
+ `)}),this}_outputHelpIfRequested(r){const a=this._getHelpOption();a&&r.find(c=>a.is(c))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function H(Rt){return Rt.map(r=>{if(!r.startsWith("--inspect"))return r;let a,c="127.0.0.1",d="9229",p;return(p=r.match(/^(--inspect(-brk)?)$/))!==null?a=p[1]:(p=r.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(a=p[1],/^\d+$/.test(p[3])?d=p[3]:c=p[3]):(p=r.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(a=p[1],c=p[3],d=p[4]),a&&d!=="0"?`${a}=${c}:${parseInt(d)+1}`:r})}function it(){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=it})),te=B((t=>{var{Argument:e}=at(),{Command:o}=Zt(),{CommanderError:n,InvalidArgumentError:i}=tt(),{Help:s}=St(),{Option:l}=Ct();t.program=new o,t.createCommand=u=>new o(u),t.createOption=(u,h)=>new l(u,h),t.createArgument=(u,h)=>new e(u,h),t.Command=o,t.Option=l,t.Argument=e,t.Help=s,t.CommanderError=n,t.InvalidArgumentError=i,t.InvalidOptionArgumentError=i})),ee=zt(te(),1),{program:Ri,createCommand:Gi,createArgument:Li,createOption:Ui,CommanderError:ie,InvalidArgumentError:Bi,InvalidOptionArgumentError:Mi,Command:se,Argument:Wi,Option:L,Help:Ji}=ee.default;function E(t){return`${JSON.stringify(t,null,2)}
27
+ `}var bt=(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 Et(t){return t.replace(/\s+/g," ").trim()}function M(t,e){const o=e.map(s=>t.map(l=>Et(l.value(s)))),n=t.map((s,l)=>{const u=o.map(h=>h[l].length);return Math.max(s.header.length,...u)}),i=s=>s.map((l,u)=>l.padEnd(n[u])).join(" ").trimEnd();return[i(t.map(s=>s.header)),i(n.map(s=>"-".repeat(s))),...o.map(i)].join(`
28
+ `)}function q(t){const e=t.filter(([,n])=>n!==void 0&&n!==""),o=Math.max(...e.map(([n])=>n.length));return`${e.map(([n,i])=>`${n.padEnd(o)} ${Et(i??"")}`).join(`
29
+ `)}
30
+ `}function yt(t){return typeof t=="string"?t.trim():t?.value?.trim()??""}function W(t){return{sessionId:yt(t.sessionId),title:t.title,type:t.type,status:t.status,projectId:yt(t.projectId),proposalName:t.proposalName??void 0,archived:t.status===bt.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 Pt(t){return{sessions:t.sessions.map(W)}}function Tt(t,e){return e.length===0?`No ${t.toLowerCase()} found.
31
+ `:`${t} (${e.length})
32
+ ${M([{header:"Session ID",value:o=>o.sessionId},{header:"Title",value:o=>o.title},{header:"Status",value:o=>o.status},{header:"Project ID",value:o=>o.projectId},{header:"Archived",value:o=>o.archived?"yes":"no"}],e)}
33
+ `}function z(t,e=[]){return q([["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 lt(t,e,o,n=[]){return`${t}
34
+ ${q([["sessionId",e],["message",o.message],...n])}`}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},ot=class extends Error{url;status;statusText;body;request;constructor(t,e,o){super(o),this.name="ApiError",this.url=e.url,this.status=e.status,this.statusText=e.statusText,this.body=e.body,this.request=t}},D={USAGE:2,HTTP_BAD_REQUEST:20,HTTP_UNAUTHORIZED:21,HTTP_FORBIDDEN:23,HTTP_NOT_FOUND:24,HTTP_CONFLICT:29,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},$=class extends Error{constructor(t){super(t),this.name="CliUsageError"}},ut=class extends Error{status;details;constructor(t,e,o){super(e),this.name="CliHttpError",this.status=t,this.details=o}};function re(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function X(t,e){const o=re(t)?.[e];return typeof o=="string"&&o.trim()?o.trim():void 0}function oe(t){return t.includes("fetch failed")||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("Failed to parse URL")}function Ot(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 ne(t,e={}){if(t instanceof $)return{exitCode:D.USAGE,message:t.message};if(t instanceof ut)return{exitCode:Ot(t.status),status:t.status,message:t.message,details:t.details};if(t instanceof ot){const o=X(t.body,"error")??X(t.body,"message")??t.message;return{exitCode:Ot(t.status),status:t.status,message:o,errorCode:X(t.body,"errorCode"),correlationId:X(t.body,"correlationId"),details:t.body}}if(t instanceof Error){if(!oe(t.message))return{exitCode:D.UNKNOWN,message:t.message};const o=e.baseUrl??"the configured backend";return{exitCode:D.TRANSPORT,message:t.message.includes("Failed to parse URL")?`Invalid HagiCode backend base URL: ${o}`:`Cannot reach HagiCode backend at ${o}. Check that the backend is running and the base URL is correct.`}}return{exitCode:D.UNKNOWN,message:String(t)}}function wt(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 o=[t.status?`status=${t.status}`:void 0,t.errorCode?`errorCode=${t.errorCode}`:void 0,t.correlationId?`correlationId=${t.correlationId}`:void 0].filter(Boolean),n=o.length>0?` (${o.join(", ")})`:"";return`${t.message}${n}
36
+ `}var ae="--base-url",le="HAGI_API_BASE_URL";function R(t){const e=t?.trim();return e||void 0}function It(t=process.env){return(0,vt.join)(R(t.XDG_CONFIG_HOME)??(0,vt.join)((0,Qt.homedir)(),".config"),"hagi","config.json")}function ue(t=process.env){const e=It(t);let o;try{o=(0,Kt.readFileSync)(e,"utf8")}catch(s){if(s.code==="ENOENT")return;throw new $(`Cannot read CLI config file ${e}: ${s instanceof Error?s.message:String(s)}`)}let n;try{n=JSON.parse(o)}catch{throw new $(`CLI config file ${e} is not valid JSON.`)}const i=n&&typeof n=="object"&&!Array.isArray(n)?n.baseUrl:void 0;return typeof i=="string"?R(i):void 0}function ce(t={},e=process.env){const o=R(t.baseUrl)??R(e.HAGI_API_BASE_URL)??ue(e);if(!o)throw new $(`No backend base URL is configured. Set ${ae} <url>, the ${le} environment variable, or "baseUrl" in ${It(e)}.`);return{baseUrl:o,token:R(t.token)??R(e.HAGI_API_TOKEN),lang:R(t.lang)??R(e.HAGI_API_LANG)}}function de(t={},e=process.env){const o=ce(t,e);return m.BASE=o.baseUrl,m.WITH_CREDENTIALS=!1,m.CREDENTIALS="omit",m.TOKEN=o.token,m.HEADERS=o.lang?{"Accept-Language":o.lang}:void 0,o}function pe(){return R(m.BASE)}var he=class extends Error{constructor(t){super(t),this.name="CancelError"}get isCancelled(){return!0}},me=class{#e;#i;#t;#s;#o;#n;#r;constructor(t){this.#e=!1,this.#i=!1,this.#t=!1,this.#s=[],this.#o=new Promise((e,o)=>{this.#n=e,this.#r=o;const n=l=>{this.#e||this.#i||this.#t||(this.#e=!0,this.#n&&this.#n(l))},i=l=>{this.#e||this.#i||this.#t||(this.#i=!0,this.#r&&this.#r(l))},s=l=>{this.#e||this.#i||this.#t||this.#s.push(l)};return Object.defineProperty(s,"isResolved",{get:()=>this.#e}),Object.defineProperty(s,"isRejected",{get:()=>this.#i}),Object.defineProperty(s,"isCancelled",{get:()=>this.#t}),t(n,i,s)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(t,e){return this.#o.then(t,e)}catch(t){return this.#o.catch(t)}finally(t){return this.#o.finally(t)}cancel(){if(!(this.#e||this.#i||this.#t)){if(this.#t=!0,this.#s.length)try{for(const t of this.#s)t()}catch(t){console.warn("Cancellation threw an error",t);return}this.#s.length=0,this.#r&&this.#r(new he("Request aborted"))}}get isCancelled(){return this.#t}},ct=t=>t!=null,Q=t=>typeof t=="string",st=t=>Q(t)&&t!=="",dt=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]),xt=t=>t instanceof FormData,fe=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},ge=t=>{const e=[],o=(i,s)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},n=(i,s)=>{ct(s)&&(Array.isArray(s)?s.forEach(l=>{n(i,l)}):typeof s=="object"?Object.entries(s).forEach(([l,u])=>{n(`${i}[${l}]`,u)}):o(i,s))};return Object.entries(t).forEach(([i,s])=>{n(i,s)}),e.length>0?`?${e.join("&")}`:""},ve=(t,e)=>{const o=t.ENCODE_PATH||encodeURI,n=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(s,l)=>e.path?.hasOwnProperty(l)?o(String(e.path[l])):s),i=`${t.BASE}${n}`;return e.query?`${i}${ge(e.query)}`:i},ye=t=>{if(t.formData){const e=new FormData,o=(n,i)=>{Q(i)||dt(i)?e.append(n,i):e.append(n,JSON.stringify(i))};return Object.entries(t.formData).filter(([n,i])=>ct(i)).forEach(([n,i])=>{Array.isArray(i)?i.forEach(s=>o(n,s)):o(n,i)}),e}},Y=async(t,e)=>typeof e=="function"?e(t):e,Oe=async(t,e)=>{const[o,n,i,s]=await Promise.all([Y(e,t.TOKEN),Y(e,t.USERNAME),Y(e,t.PASSWORD),Y(e,t.HEADERS)]),l=Object.entries({Accept:"application/json",...s,...e.headers}).filter(([u,h])=>ct(h)).reduce((u,[h,y])=>({...u,[h]:String(y)}),{});return st(o)&&(l.Authorization=`Bearer ${o}`),st(n)&&st(i)&&(l.Authorization=`Basic ${fe(`${n}:${i}`)}`),e.body!==void 0&&(e.mediaType?l["Content-Type"]=e.mediaType:dt(e.body)?l["Content-Type"]=e.body.type||"application/octet-stream":Q(e.body)?l["Content-Type"]="text/plain":xt(e.body)||(l["Content-Type"]="application/json")),new Headers(l)},Ae=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):Q(t.body)||dt(t.body)||xt(t.body)?t.body:JSON.stringify(t.body)},Se=async(t,e,o,n,i,s,l)=>{const u=new AbortController,h={headers:s,body:n??i,method:e.method,signal:u.signal};return t.WITH_CREDENTIALS&&(h.credentials=t.CREDENTIALS),l(()=>u.abort()),await fetch(o,h)},Ce=(t,e)=>{if(e){const o=t.headers.get(e);if(Q(o))return o}},_e=async t=>{if(t.status!==204)try{const e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(o=>e.toLowerCase().startsWith(o))?await t.json():await t.text()}catch(e){console.error(e)}},be=(t,e)=>{const o={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(o)throw new ot(t,e,o);if(!e.ok)throw new ot(t,e,`Generic Error: status: ${e.status??"unknown"}; status text: ${e.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})()}`)},g=(t,e)=>new me(async(o,n,i)=>{try{const s=ve(t,e),l=ye(e),u=Ae(e),h=await Oe(t,e);if(!i.isCancelled){const y=await Se(t,e,s,u,l,h,i),C=await _e(y),S=Ce(y,e.responseHeader),_={url:s,ok:y.ok,status:y.status,statusText:y.statusText,body:S??C};be(e,_),o(_.body)}}catch(s){n(s)}}),Ee=class{static getApiDataAggregation(){return g(m,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},rt=class{static postApiProject({requestBody:t}){return g(m,{method:"POST",url:"/api/Project",body:t,mediaType:"application/json"})}static postApiProjectDemo(){return g(m,{method:"POST",url:"/api/Project/demo"})}static putApiProject({id:t,requestBody:e}){return g(m,{method:"PUT",url:"/api/Project/{id}",path:{id:t},body:e,mediaType:"application/json"})}static deleteApiProject({id:t}){return g(m,{method:"DELETE",url:"/api/Project/{id}",path:{id:t}})}static postApiProjectOpenInVscode({id:t,subPath:e}){return g(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 g(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 g(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 g(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 g(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 g(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 g(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:o="light"}){return g(m,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}/preview",path:{id:t,slug:e},query:{theme:o},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndex1({id:t,slug:e}){return g(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:o}){return g(m,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:t},query:{branchName:e,repositoryPath:o},errors:{400:"Branch name is required",404:"Project not found"}})}static getApiProjectValidatePath({path:t}){return g(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 g(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 g(m,{method:"POST",url:"/api/Project/validate-monospecs",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error"}})}},V=class{static postApiSessionsAutoTask({requestBody:t}){return g(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 g(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 g(m,{method:"POST",url:"/api/Sessions/chat",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:t}){return g(m,{method:"POST",url:"/api/Sessions",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:t,activeOnly:e,includeArchived:o,projectId:n,projectIds:i}){return g(m,{method:"GET",url:"/api/Sessions",query:{type:t,activeOnly:e,includeArchived:o,projectId:n,projectIds:i}})}static getApiSessions1({sessionId:t}){return g(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 g(m,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:t},body:e,mediaType:"application/json"})}static deleteApiSessions({sessionId:t,deleteFiles:e=!1}){return g(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:o=50,historyScope:n,order:i="desc"}){return g(m,{method:"GET",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},query:{page:e,pageSize:o,historyScope:n,order:i},errors:{404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsMessages({sessionId:t,requestBody:e}){return g(m,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},body:e,mediaType:"application/json"})}static postApiSessionsCancel({sessionId:t}){return g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(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 g(m,{method:"GET",url:"/api/skills/local"})}static postApiSkillsLocalUninstall({requestBody:t}){return g(m,{method:"POST",url:"/api/skills/local/uninstall",body:t,mediaType:"application/json"})}static getApiSkillsGallery({query:t}){return g(m,{method:"GET",url:"/api/skills/gallery",query:{query:t}})}static getApiSkillsGalleryDetail({id:t,source:e}){return g(m,{method:"GET",url:"/api/skills/gallery/detail",query:{id:t,source:e}})}static getApiSkillsGalleryInstallContext({id:t,source:e}){return g(m,{method:"GET",url:"/api/skills/gallery/install-context",query:{id:t,source:e}})}static getApiSkillsProvidersTrusted(){return g(m,{method:"GET",url:"/api/skills/providers/trusted"})}static postApiSkillsProvidersTrusted({requestBody:t}){return g(m,{method:"POST",url:"/api/skills/providers/trusted",body:t,mediaType:"application/json"})}static deleteApiSkillsProvidersTrusted({requestBody:t}){return g(m,{method:"DELETE",url:"/api/skills/providers/trusted",body:t,mediaType:"application/json"})}static postApiSkillsProvidersTrustedReset(){return g(m,{method:"POST",url:"/api/skills/providers/trusted/reset"})}static postApiSkillsGalleryInstall({requestBody:t}){return g(m,{method:"POST",url:"/api/skills/gallery/install",body:t,mediaType:"application/json"})}static getApiSkillsRecommendationsConfig({locale:t}){return g(m,{method:"GET",url:"/api/skills/recommendations/config",query:{locale:t}})}static postApiSkillsRecommendationsGenerate({requestBody:t}){return g(m,{method:"POST",url:"/api/skills/recommendations/generate",body:t,mediaType:"application/json"})}static postApiSkillsRecommendationsInstall({requestBody:t}){return g(m,{method:"POST",url:"/api/skills/recommendations/install",body:t,mediaType:"application/json"})}static getApiSkillsGalleryInstallStream({id:t,source:e,skillSlug:o,version:n}){return g(m,{method:"GET",url:"/api/skills/gallery/install/stream",query:{id:t,source:e,skillSlug:o,version:n}})}},J=class{static getApiVaults(){return g(m,{method:"GET",url:"/api/vaults"})}static postApiVaults({requestBody:t}){return g(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 g(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 g(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 g(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 g(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 Pe(){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:()=>Ee.getApiDataAggregation(),createProject:t=>rt.postApiProject({requestBody:t}),updateProject:(t,e)=>rt.putApiProject({id:t,requestBody:e}),deleteProject:t=>rt.deleteApiProject({id:t}),listVaults:()=>J.getApiVaults(),createVault:t=>J.postApiVaults({requestBody:t}),updateVault:(t,e)=>J.putApiVaults({id:t,requestBody:e}),deleteVault:(t,e)=>J.deleteApiVaults({id:t,deleteLocalFiles:e}),listVaultFiles:(t,e)=>J.getApiVaultsFiles({id:t,path:e}),previewVaultFile:(t,e)=>J.getApiVaultsFilesContent({id:t,path:e}),archiveChat:t=>V.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 A(t){const e=t?.trim();return e||void 0}function x(t,e){const o=A(t);if(!o)throw new $(`${e} is required.`);return o}function kt(t){const e=t?.map(o=>A(o)).filter(Boolean);return e&&e.length>0?e:void 0}function jt(t=process.env,e={stdout:o=>{process.stdout.write(o)},stderr:o=>{process.stderr.write(o)}}){return{api:Pe(),env:t,io:e}}function Te(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 P(t){return t.option("--json","Emit deterministic JSON instead of human-readable text.")}function T(t,e){const o=t.optsWithGlobals();return{api:e.api,env:e.env,io:e.io,outputJson:o.json===!0,runtime:de({baseUrl:o.baseUrl,token:o.token,lang:o.lang},e.env)}}function we(t,e){P(t.command("create").description("Create an AutoTask session through the dedicated generated endpoint.")).requiredOption("--title <title>","AutoTask session title.").requiredOption("--project-id <id>","Owning project id.").requiredOption("--prompt-id <id>","Prompt template id.").option("--message <text>","Optional custom message override.").option("--preset-id <id>","Optional preset id.").option("--repository-path <path>","Optional MonoSpecs repository path.").option("--project-ids <ids...>","Optional extra project ids for multi-project flows.").option("--need-push","Request push after commit creation when supported.").option("--target-branch-mode <mode>","Optional target branch mode.").option("--target-branch-name <name>","Optional custom target branch name.").option("--script-key <key>","Optional stable dungeon script key.").option("--hero-id <id>","Optional preferred hero id.").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(n){if(n.targetBranchName&&n.targetBranchMode!=="new-custom")throw new $("--target-branch-name requires --target-branch-mode new-custom.");if(n.targetBranchMode==="new-custom"&&!A(n.targetBranchName))throw new $("--target-branch-name is required when --target-branch-mode is new-custom.");const i=T(this,e),s={title:x(n.title,"--title"),projectId:x(n.projectId,"--project-id"),promptId:x(n.promptId,"--prompt-id"),message:A(n.message),presetId:A(n.presetId),repositoryPath:A(n.repositoryPath),projectIds:kt(n.projectIds),needPush:n.needPush?!0:void 0,targetBranchMode:A(n.targetBranchMode),targetBranchName:A(n.targetBranchName),scriptKey:A(n.scriptKey),heroId:A(n.heroId),targetType:A(n.targetType),vaultId:A(n.vaultId)},l=W(await i.api.createAutoTaskSession(s));if(i.outputJson){i.io.stdout(E({session:l,promptId:s.promptId,requested:s}));return}i.io.stdout(`AutoTask session created
37
+ ${z(l,[["promptId",s.promptId],["repositoryPath",s.repositoryPath],["targetBranchMode",s.targetBranchMode],["targetBranchName",s.targetBranchName],["scriptKey",s.scriptKey],["heroId",s.heroId]])}`)})}var et=(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})({}),pt=(function(t){return t.READONLY="Readonly",t.EDIT="Edit",t})({});function Ie(t,e){P(t.command("send").description("Send a follow-up message to an AutoTask session.")).requiredOption("--session-id <id>","AutoTask session id.").requiredOption("--content <text>","Message content.").addOption(new L("--mode <mode>","Message mode override.").choices(Object.values(pt))).addOption(new L("--executor-type <type>","Executor override for this message.").choices(Object.values(et))).action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=await i.api.sendMessage(s,{content:x(n.content,"--content"),mode:n.mode,executorType:n.executorType});if(i.outputJson){i.io.stdout(E({sessionId:s,message:l.message,requested:{mode:n.mode,executorType:n.executorType}}));return}i.io.stdout(lt("AutoTask message sent",s,l,[["mode",n.mode],["executorType",n.executorType]]))})}function xe(t,e){const o=t.command("autotask").description("Manage AutoTask sessions.");we(o,e),Ie(o,e)}function ke(t,e){P(t.command("archive").description("Archive a chat session through the dedicated chat archive endpoint.")).requiredOption("--session-id <id>","Chat session id to archive.").action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=await i.api.archiveChat(s);if(i.outputJson){i.io.stdout(E({sessionId:s,message:l.message}));return}i.io.stdout(`Chat archived
38
+ sessionId ${s}
39
+ message ${l.message}
40
+ `)})}function je(t,e){P(t.command("create").description("Create a normal chat session.")).requiredOption("--title <title>","Chat session title.").requiredOption("--project-id <id>","Owning project id.").option("--hero-id <id>","Optional bound hero id.").addOption(new L("--executor-type <type>","Optional executor override.").choices(Object.values(et))).action(async function(n){const i=T(this,e),s=W(await i.api.createChatSession({title:x(n.title,"--title"),projectId:x(n.projectId,"--project-id"),heroId:A(n.heroId),executorType:n.executorType}));if(i.outputJson){i.io.stdout(E({session:s}));return}i.io.stdout(`Chat session created
41
+ ${z(s)}`)})}function $e(t,e){P(t.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=await i.api.deleteSession(s,!1);if(i.outputJson){i.io.stdout(E({sessionId:s,deleted:!0,message:l.message}));return}i.io.stdout(`Chat deleted
42
+ sessionId ${s}
43
+ message ${l.message}
44
+ `)})}var ht=(function(t){return t.CHAT="Chat",t.PROPOSAL="Proposal",t})({});function Ne(t,e){P(t.command("list").description("List normal chat sessions.")).action(async function(n){if(n.projectId&&n.projectIds?.length)throw new $("Use either --project-id or --project-ids, not both.");const i=T(this,e),s=Pt(await i.api.listSessions({type:ht.CHAT,projectId:A(n.projectId),projectIds:kt(n.projectIds),activeOnly:n.activeOnly?!0:void 0,includeArchived:n.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(Tt("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 Ve(t,e){P(t.command("send").description("Send a follow-up message to a chat session.")).requiredOption("--session-id <id>","Chat session id.").requiredOption("--content <text>","Message content.").addOption(new L("--mode <mode>","Message mode override.").choices(Object.values(pt))).addOption(new L("--executor-type <type>","Executor override for this message.").choices(Object.values(et))).action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=await i.api.sendMessage(s,{content:x(n.content,"--content"),mode:n.mode,executorType:n.executorType});if(i.outputJson){i.io.stdout(E({sessionId:s,message:l.message,requested:{mode:n.mode,executorType:n.executorType}}));return}i.io.stdout(lt("Chat message sent",s,l,[["mode",n.mode],["executorType",n.executorType]]))})}function De(t,e){const o=t.command("chat").description("Manage normal chat sessions.");Ne(o,e),je(o,e),ke(o,e),$e(o,e),Ve(o,e)}function U(t){const e=t?.trim();return e||void 0}function mt(t){return{id:U(t.id)??"",name:U(t.name)??"",path:U(t.path)??"",description:U(t.description),isMonoSpecs:t.isMonoSpecs===!0,monoSpecsVersion:U(t.monoSpecsVersion),monoSpecsRepoDirectory:U(t.monoSpecsRepoDirectory),monoSpecsCommitWhenArchive:typeof t.monoSpecsCommitWhenArchive=="boolean"?t.monoSpecsCommitWhenArchive:void 0,hasError:"hasError"in t?t.hasError===!0:!1,error:"error"in t?U(t.error):void 0}}function $t(t){return{projects:(t??[]).map(mt)}}function He(t){return t.length===0?`No projects found.
45
+ `:`Projects (${t.length})
46
+ ${M([{header:"Project ID",value:e=>e.id},{header:"Name",value:e=>e.name},{header:"Path",value:e=>e.path},{header:"MonoSpecs",value:e=>e.isMonoSpecs?"yes":"no"},{header:"Error",value:e=>e.hasError?"yes":"no"}],t)}
47
+ `}function Nt(t,e=[]){return q([["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 qe(t,e){P(t.command("create").description("Create a project through the generated project client.")).requiredOption("--name <name>","Project display name.").requiredOption("--path <path>","Project root path.").option("--description <text>","Optional project description.").action(async function(n){const i=T(this,e),s=mt(await i.api.createProject({name:x(n.name,"--name"),path:x(n.path,"--path"),description:A(n.description)}));if(i.outputJson){i.io.stdout(E({project:s}));return}i.io.stdout(`Project created
48
+ ${Nt(s)}`)})}function Fe(t,e){P(t.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(n){const i=T(this,e),s=n.id.trim();if(await i.api.deleteProject(s),i.outputJson){i.io.stdout(E({projectId:s,deleted:!0}));return}i.io.stdout(`Project deleted
49
+ projectId ${s}
50
+ `)})}function Re(t,e){P(t.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const n=T(this,e),i=$t((await n.api.listProjects()).projects);if(n.outputJson){n.io.stdout(E(i));return}n.io.stdout(He(i.projects))})}function Ge(t,e){P(t.command("update").description("Update a project by merging provided fields into the aggregation snapshot.")).requiredOption("--id <id>","Project id to update.").option("--name <name>","Updated project name.").option("--path <path>","Updated project path.").option("--description <text>","Updated project description.").option("--clear-description","Clear the stored description.").action(async function(n){if(!n.name&&!n.path&&!n.description&&!n.clearDescription)throw new $("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(n.description&&n.clearDescription)throw new $("Use either --description or --clear-description, not both.");const i=T(this,e),s=n.id.trim(),l=$t((await i.api.listProjects()).projects).projects.find(h=>h.id===s);if(!l)throw new ut(404,`Project ${s} was not found in the aggregation snapshot.`);const u=mt(await i.api.updateProject(s,{name:A(n.name)??l.name,path:A(n.path)??l.path,description:n.clearDescription?null:A(n.description)??l.description??null}));if(i.outputJson){i.io.stdout(E({project:u}));return}i.io.stdout(`Project updated
51
+ ${Nt(u)}`)})}function Le(t,e){const o=t.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");Re(o,e),qe(o,e),Ge(o,e),Fe(o,e)}async function Ue(){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 Vt(t){const e=t.trim();if(!e)throw new $("Provide --input <file> or --input - for stdin.");const o=e==="-"?await Ue():await(0,Xt.readFile)(e,"utf8");try{return JSON.parse(o)}catch(n){throw new $(`Invalid JSON input from ${e}: ${n instanceof Error?n.message:String(n)}`)}}function Be(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw new $("Annotation input must be a JSON object.");const o=e;if(!Array.isArray(o.files))throw new $("Annotation input must include a files array.");const n=typeof o.totalAnnotations=="number"?o.totalAnnotations:o.files.length,i=typeof o.submittedAt=="string"&&o.submittedAt.trim()?o.submittedAt:new Date().toISOString();return{...o,sessionId:t,totalAnnotations:n,submittedAt:i,files:o.files}}function Me(t,e){P(t.command("annotate").description("Submit proposal annotations from structured JSON input.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=Be(s,await Vt(n.input)),u=await i.api.submitAnnotations(s,l);if(i.outputJson){i.io.stdout(E({sessionId:s,message:u.message,annotationCount:u.annotationCount??l.totalAnnotations,fileCount:u.fileCount??l.files.length}));return}i.io.stdout(`Proposal annotations submitted
52
+ sessionId ${s}
53
+ message ${u.message}
54
+ annotationCount ${u.annotationCount??l.totalAnnotations}
55
+ fileCount ${u.fileCount??l.files.length}
56
+ `)})}function We(t,e){P(t.command("archive").description("Archive a proposal session through the explicit archive endpoint.")).requiredOption("--session-id <id>","Proposal session id to archive.").option("--hero-id <id>","Optional hero override for archiving.").action(async function(n){const i=T(this,e),s=W(await i.api.archiveProposal(n.sessionId.trim(),{heroId:A(n.heroId)}));if(i.outputJson){i.io.stdout(E({session:s}));return}i.io.stdout(`Proposal archive started
57
+ ${z(s)}`)})}function Je(t,e){P(t.command("complete").description("Mark a proposal session as completed through the dedicated completion endpoint.")).requiredOption("--session-id <id>","Proposal session id to complete.").action(async function(n){const i=T(this,e),s=W(await i.api.completeProposal(n.sessionId.trim()));if(i.outputJson){i.io.stdout(E({session:s}));return}i.io.stdout(`Proposal completed
58
+ ${z(s)}`)})}function ze(t){return W(t)}function Ke(t){return Pt(t)}function Qe(t){return Tt("Proposal sessions",t)}function Xe(t,e=[]){return z(t,e)}var Dt="New Proposal";function Ye(t){const e=A(t.title);if(e)return e;if(t.defaultTitle)return Dt;throw new $("Provide --title or pass --default-title to use the placeholder proposal title.")}function Ze(t,e){P(t.command("create").description("Create a proposal session only. This command does not trigger later lifecycle APIs.")).requiredOption("--project-id <id>","Project id that owns the new proposal session.").requiredOption("--chief-complaint <text>","Proposal chief complaint to store on the new session.").option("--original-chief-complaint <text>","Optional raw chief complaint text to keep alongside the stitched content.").option("--title <title>","Explicit proposal session title.").option("--default-title",`Mark the title as the placeholder title (${Dt}).`).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(n){const i=T(this,e),s=Ye(n),l=ze(await i.api.createProposalSession({title:s,chiefComplaint:n.chiefComplaint.trim(),originalChiefComplaint:A(n.originalChiefComplaint),type:ht.PROPOSAL,projectId:n.projectId.trim(),enableIndependentWorkspace:n.enableIndependentWorkspace?!0:void 0,baseBranch:A(n.baseBranch),isDefaultTitle:!!n.defaultTitle})),u=`hagi proposal optimize-description --session-id ${l.sessionId} --description "<description>"`;if(i.outputJson){i.io.stdout(E({session:l,nextCommand:u}));return}i.io.stdout(`Proposal session created
59
+ ${Xe(l,[["next",u]])}`)})}function ti(t,e){P(t.command("execute").description("Start proposal execution only. This command maps to the execute-proposal backend action.")).requiredOption("--session-id <id>","Proposal session id to execute.").option("--hero-id <id>","Optional hero override for the execute stage.").action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=A(n.heroId),u=await i.api.executeProposal(s,{heroId:l});if(i.outputJson){i.io.stdout(E({sessionId:s,message:u.message,requested:{heroId:l}}));return}i.io.stdout(`Proposal execution started
60
+ sessionId ${s}
61
+ message ${u.message}
62
+ `)})}var nt=["zh-CN","zh-Hant","en-US","ja-JP","ko-KR","de-DE","fr-FR","es-ES","pt-BR","ru-RU"];function ei(t){if(t.enableExploreMode&&t.disableExploreMode)throw new $("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(t.enableExploreMode)return!0;if(t.disableExploreMode)return!1}function ii(t){const e=t.trim();if(!nt.includes(e))throw new $(`--proposal-content-language must be one of: ${nt.join(", ")}.`);return e}function si(t,e){P(t.command("generate").description("Start proposal generation only. This command does not execute the proposal.")).requiredOption("--session-id <id>","Proposal session id to generate.").requiredOption("--proposal-content-language <language>",`Language of the generated proposal content (${nt.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(n){const i=T(this,e),s=n.sessionId.trim(),l=ei(n),u=ii(n.proposalContentLanguage),h=await i.api.generateProposal(s,{enableExploreMode:l,heroId:A(n.heroId),proposalContentLanguage:u}),y=`hagi proposal execute --session-id ${s}`;if(i.outputJson){i.io.stdout(E({sessionId:s,message:h.message,requested:{enableExploreMode:l,heroId:A(n.heroId),proposalContentLanguage:u},nextCommand:y}));return}i.io.stdout(`Proposal generation started
63
+ sessionId ${s}
64
+ message ${h.message}
65
+ next Wait for the session to reach Reviewing, then run ${y}
66
+ `)})}function ri(t,e){P(t.command("list").description("List proposal sessions from the backend Sessions API.")).option("--project-id <id>","Filter proposal sessions by a single project id.").option("--project-ids <ids...>","Filter proposal sessions by multiple project ids.").option("--active-only","Only return non-archived proposal sessions.").option("--include-archived","Include archived proposal sessions in the result set.").action(async function(n){if(n.projectId&&n.projectIds?.length)throw new $("Use either --project-id or --project-ids, not both.");const i=T(this,e),s=Ke(await i.api.listSessions({type:ht.PROPOSAL,projectId:A(n.projectId),projectIds:n.projectIds?.map(A).filter(Boolean),activeOnly:n.activeOnly?!0:void 0,includeArchived:n.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(Qe(s.sessions))})}function oi(t,e){const o=e.summary,n=e.result,i=n?.validation?.isValid===!0,s=o?.appliedTitle||n?.optimizedTitle||"",l=o?.appliedProposalName||n?.optimizedProposalName||"",u=n?.validation?.diagnostics??[],h=[i?"Proposal optimized":"Proposal optimization returned diagnostics",`sessionId ${t}`,`title ${s}`,`proposalName ${l}`,`valid ${i?"yes":"no"}`];for(const y of u)h.push(`diagnostic ${y.code??"UNKNOWN"}: ${y.message??""}`.trimEnd());return i&&h.push(`next hagi proposal generate --session-id ${t}`),`${h.join(`
67
+ `)}
68
+ `}function ni(t,e){P(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(n){const i=T(this,e),s=x(n.sessionId,"--session-id"),l=await i.api.optimizeProposal(s,{description:x(n.description,"--description"),title:A(n.title),isDefaultTitle:n.defaultTitle?!0:void 0,optimizationDirection:A(n.optimizationDirection),originalChiefComplaint:A(n.originalChiefComplaint)});if(i.outputJson){i.io.stdout(E({sessionId:s,...l}));return}i.io.stdout(oi(s,l))})}function ai(t,e){P(t.command("send").description("Send a follow-up message to a proposal session.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--content <text>","Message content.").addOption(new L("--mode <mode>","Message mode override.").choices(Object.values(pt))).addOption(new L("--executor-type <type>","Executor override for this message.").choices(Object.values(et))).action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=await i.api.sendMessage(s,{content:x(n.content,"--content"),mode:n.mode,executorType:n.executorType});if(i.outputJson){i.io.stdout(E({sessionId:s,message:l.message,requested:{mode:n.mode,executorType:n.executorType}}));return}i.io.stdout(lt("Proposal message sent",s,l,[["mode",n.mode],["executorType",n.executorType]]))})}function li(t,e){P(t.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new L("--status <status>","Target session status.").choices(Object.values(bt)).makeOptionMandatory()).action(async function(n){const i=T(this,e),s=n.sessionId.trim(),l=await i.api.getSession(s);await i.api.updateSession(s,{title:l.title,description:l.description,status:n.status,metadata:l.metadata});const u=W({...l,status:n.status});if(i.outputJson){i.io.stdout(E({session:u}));return}i.io.stdout(`Proposal status updated
69
+ ${z(u)}`)})}function ui(t,e){const o=t.command("proposal").description("Manage proposal sessions through backend session APIs.");ri(o,e),Ze(o,e),ni(o,e),si(o,e),Me(o,e),ti(o,e),We(o,e),li(o,e),Je(o,e),ai(o,e)}function K(t){return t?"yes":"no"}function ci(t){return t&&t.length>0?t.join(", "):"-"}function di(t){const e=t.items??[];return e.length===0?`No local skills installed.
70
+ `:`Local skills (${e.length})
71
+ ${M([{header:"Name",value:o=>o.name??"-"},{header:"Scope",value:o=>o.scope??"-"},{header:"Agents",value:o=>ci(o.agents)},{header:"Path",value:o=>o.path??"-"}],e)}
72
+ `}function pi(t){return q([["skillName",t.skillName??void 0],["status",t.status??void 0],["message",t.userMessage??void 0],["diagnostic",t.diagnosticMessage??void 0]])}function hi(t){const e=t.items??[];return e.length===0?`No gallery skills found.
73
+ `:`Gallery skills (${e.length})
74
+ ${M([{header:"ID",value:o=>o.id??"-"},{header:"Source",value:o=>o.source??"-"},{header:"Installs",value:o=>String(o.installs??0)},{header:"Trusted",value:o=>K(o.isTrustedSource)}],e)}
75
+ `}function mi(t){const e=t.trustedProvider;return q([["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 fi(t){return q([["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 Z(t){const e=t.items??[];return e.length===0?`No trusted providers (directory version ${t.version??0}).
76
+ `:`Trusted providers (${e.length}, directory version ${t.version??0})
77
+ ${M([{header:"Provider ID",value:o=>o.providerId??"-"},{header:"Name",value:o=>o.displayName??"-"},{header:"Enabled",value:o=>K(o.isEnabled)},{header:"Preset",value:o=>K(o.isPreset)},{header:"Rules",value:o=>String(o.ruleCount??0)}],e)}
78
+ `}function gi(t,e){const o=t.command("gallery").description("Search the skill gallery, read skill details, and start managed installs.");P(o.command("search").description("Search the skill gallery by keyword.")).option("--query <query>","Keyword to search for. Omit to list the gallery.").action(async function(i){const s=T(this,e),l=await s.api.searchSkillGallery(A(i.query));if(s.outputJson){s.io.stdout(E(l));return}s.io.stdout(hi(l))}),P(o.command("detail").description("Show one gallery skill with installability, trust, and repository details.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").action(async function(i){const s=T(this,e),l=await s.api.getSkillGalleryDetail(x(i.id,"--id"),x(i.source,"--source"));if(s.outputJson){s.io.stdout(E(l));return}s.io.stdout(mi(l))}),P(o.command("install").description("Start a managed install of one gallery skill.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").requiredOption("--skill-slug <slug>","Skill slug inside the source repository.").option("--version <version>","Optional version token to install.").action(async function(i){const s=T(this,e),l=await s.api.installGallerySkill({id:x(i.id,"--id"),source:x(i.source,"--source"),skillSlug:x(i.skillSlug,"--skill-slug"),version:A(i.version)});if(s.outputJson){s.io.stdout(E(l));return}s.io.stdout(fi(l))})}function vi(t,e){const o=t.command("local").description("List and uninstall globally installed local skills.");P(o.command("list").description("List installed local skills with their managed install metadata.")).action(async function(){const i=T(this,e),s=await i.api.listLocalSkills();if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(di(s))}),P(o.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=T(this,e),l=await s.api.uninstallLocalSkill({skillName:x(i.skillName,"--skill-name")});if(s.outputJson){s.io.stdout(E(l));return}s.io.stdout(pi(l))})}async function yi(t,e){const o=await Vt(t);if(!o||typeof o!="object"||Array.isArray(o))throw new $(`${e} must be a JSON object.`);return o}function Oi(t,e){const o=t.command("trusted").description("Manage the trusted skill provider directory.");P(o.command("list").description("List trusted skill providers.")).action(async function(){const i=T(this,e),s=await i.api.listTrustedSkillProviders();if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(Z(s))}),P(o.command("upsert").description("Create or update a trusted provider from a JSON document.")).requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(i){const s=T(this,e),l=await yi(x(i.input,"--input"),"Trusted provider input"),u=await s.api.upsertTrustedSkillProvider(l);if(s.outputJson){s.io.stdout(E(u));return}s.io.stdout(Z(u))}),P(o.command("delete").description("Delete one trusted provider by id.")).requiredOption("--provider-id <id>","Trusted provider id to delete.").action(async function(i){const s=T(this,e),l={providerId:x(i.providerId,"--provider-id")},u=await s.api.deleteTrustedSkillProvider(l);if(s.outputJson){s.io.stdout(E(u));return}s.io.stdout(Z(u))}),P(o.command("reset").description("Reset trusted providers to the backend defaults.")).action(async function(){const i=T(this,e),s=await i.api.resetTrustedSkillProviders();if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(Z(s))})}function Ai(t,e){const o=t.command("skills").description("Manage local skills, the skill gallery, and trusted providers.");vi(o,e),gi(o,e),Oi(o,e)}function I(t){const e=t?.trim();return e||void 0}function Si(t){return{severity:I(t.severity)??"",code:I(t.code)??"",message:I(t.message)??"",relativePath:I(t.relativePath)}}function ft(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(Si)}}function Ht(t){return{generatedAtUtc:I(t.generatedAtUtc),vaults:(t.items??[]).map(ft)}}function Ci(t){return t.length===0?`No vaults found.
79
+ `:`Vaults (${t.length})
80
+ ${M([{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)}
81
+ `}function qt(t,e=[]){return q([["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 _i(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 bi(t){return{vaultId:I(t.id)??"",deleted:t.deleted===!0,deleteLocalFilesRequested:t.deleteLocalFilesRequested===!0,localFilesDeletionStatus:I(t.localFilesDeletionStatus),localFilesDeleted:t.localFilesDeleted===!0}}function Ei(t){return`Vault deleted
82
+ ${q([["vaultId",t.vaultId],["deleted",String(t.deleted)],["deleteLocalFilesRequested",String(t.deleteLocalFilesRequested)],["localFilesDeletionStatus",t.localFilesDeletionStatus],["localFilesDeleted",String(t.localFilesDeleted)]])}`}function Pi(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(_i)}}function Ti(t){const e=q([["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
83
+ ${e}No files found.
84
+ `:`Vault files
85
+ ${e}${M([{header:"Relative Path",value:o=>o.relativePath},{header:"Directory",value:o=>o.isDirectory?"yes":"no"},{header:"Extension",value:o=>o.extension},{header:"Size",value:o=>String(o.sizeBytes)},{header:"Preview",value:o=>o.previewSupported?"yes":"no"}],t.items)}
86
+ `}function wi(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 Ii(t){const e=q([["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
87
+ ${e}`;const o=t.content.endsWith(`
88
+ `)?"":`
89
+ `;return`Vault file preview
90
+ ${e}content
91
+ -------
92
+ ${t.content}${o}`}function xi(t,e){P(t.command("create").description("Create a vault through the generated vault client.")).requiredOption("--name <name>","Vault display name.").requiredOption("--type <type>","Vault type, such as folder, obsidian, or coderef.").requiredOption("--physical-path <path>","Vault physical path.").option("--git-url <url>","Optional git remote URL for git-backed vaults.").action(async function(n){const i=T(this,e),s=ft(await i.api.createVault({name:x(n.name,"--name"),type:x(n.type,"--type"),physicalPath:x(n.physicalPath,"--physical-path"),gitUrl:A(n.gitUrl)}));if(i.outputJson){i.io.stdout(E({vault:s}));return}i.io.stdout(`Vault created
93
+ ${qt(s)}`)})}function ki(t,e){P(t.command("delete").description("Delete a vault by id and optionally request local file cleanup.")).requiredOption("--id <id>","Vault id to delete.").option("--delete-local-files","Request backend deletion of local vault files.").action(async function(n){const i=T(this,e),s=bi(await i.api.deleteVault(x(n.id,"--id"),n.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(Ei(s))})}function ji(t,e){P(t.command("list").description("List files under a registered vault path.")).requiredOption("--id <id>","Vault id to browse.").option("--path <path>","Optional relative path under the vault root.").action(async function(n){const i=T(this,e),s=Pi(await i.api.listVaultFiles(x(n.id,"--id"),A(n.path)));if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(Ti(s))})}function $i(t,e){P(t.command("preview").description("Preview supported file content from a registered vault.")).requiredOption("--id <id>","Vault id to browse.").requiredOption("--path <path>","Relative file path to preview.").action(async function(n){const i=T(this,e),s=wi(await i.api.previewVaultFile(x(n.id,"--id"),x(n.path,"--path")));if(i.outputJson){i.io.stdout(E(s));return}i.io.stdout(Ii(s))})}function Ni(t,e){P(t.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const n=T(this,e),i=Ht(await n.api.listVaults());if(n.outputJson){n.io.stdout(E(i));return}n.io.stdout(Ci(i.vaults))})}function Vi(t,e){P(t.command("update").description("Update a vault by merging provided fields into the current vault snapshot.")).requiredOption("--id <id>","Vault id to update.").option("--name <name>","Updated vault display name.").option("--type <type>","Updated vault type.").option("--physical-path <path>","Updated vault physical path.").option("--git-url <url>","Updated git remote URL.").action(async function(n){const i=A(n.name),s=A(n.type),l=A(n.physicalPath),u=A(n.gitUrl);if(!i&&!s&&!l&&!u)throw new $("Provide at least one field to update: --name, --type, --physical-path, or --git-url.");const h=T(this,e),y=x(n.id,"--id"),C=Ht(await h.api.listVaults()).vaults.find(_=>_.id===y);if(!C)throw new ut(404,`Vault ${y} was not found in the latest vault snapshot.`);const S=ft(await h.api.updateVault(y,{name:i??C.name,type:s??C.type,physicalPath:l??C.physicalPath,gitUrl:u??C.gitUrl??null}));if(h.outputJson){h.io.stdout(E({vault:S}));return}h.io.stdout(`Vault updated
94
+ ${qt(S)}`)})}function Di(t,e){const o=t.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");Ni(o,e),xi(o,e),Vi(o,e),ki(o,e);const n=o.command("files").description("Browse registered vault files and preview supported content.");ji(n,e),$i(n,e)}function Hi(t){return t.includes("--json")}function Ft(t=jt(),e=!1){const o=new se;return o.name("hagi").description("HagiCode CLI for project, proposal, vault, chat, and AutoTask management.").showHelpAfterError().exitOverride(),o.configureOutput({writeOut:n=>{t.io.stdout(n)},writeErr:n=>{e||t.io.stderr(n)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),Te(o),Le(o,t),ui(o,t),Di(o,t),De(o,t),xe(o,t),Ai(o,t),o}function qi(t,e,o){return t.exitCode===0||t.code==="commander.helpDisplayed"||t.code==="commander.version"?0:(o&&e.io.stderr(wt({exitCode:D.USAGE,message:t.message},{json:!0})),D.USAGE)}async function Fi(t=process.argv,e=jt()){const o=Hi(t),n=Ft(e,o);try{return await n.parseAsync([...t]),0}catch(i){if(i instanceof ie)return qi(i,e,o);const s=ne(i,{baseUrl:pe()});return e.io.stderr(wt(s,{json:o})),s.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return D}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return Ft}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return Fi}});
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-CILDKeJ3.js");s.runCli().then(e=>{e!==0&&(process.exitCode=e)}).catch(e=>{const n=e instanceof Error?e.stack??e.message:String(e);process.stderr.write(`${n}
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./chunks/main-CL02Q4Mn.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-CILDKeJ3.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/main-CL02Q4Mn.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.16.1.e9c85cd",
3
+ "version": "0.1.0-dev.18.1.f7fa085",
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": {
@@ -61,7 +61,7 @@
61
61
  "openapi-typescript-codegen": "^0.29.0",
62
62
  "rimraf": "^6.1.2",
63
63
  "tsx": "^4.20.6",
64
- "typescript": "^5.9.3",
64
+ "typescript": "^6.0.3",
65
65
  "vite": "^8.0.3",
66
66
  "vitest": "^4.1.1"
67
67
  }
@@ -1,91 +0,0 @@
1
- var Ht=Object.create,gt=Object.defineProperty,Ft=Object.getOwnPropertyDescriptor,qt=Object.getOwnPropertyNames,kt=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty,U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ut=(t,e,u,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(var i=qt(e),r=0,a=i.length,c;r<a;r++)c=i[r],!Rt.call(t,c)&&c!==u&&gt(t,c,{get:(h=>e[h]).bind(null,c),enumerable:!(o=Ft(e,c))||o.enumerable});return t},Lt=(t,e,u)=>(u=t!=null?Ht(kt(t)):{},Ut(e||!t||!t.__esModule?gt(u,"default",{value:t,enumerable:!0}):u,t));let Gt=require("node:process"),Bt=require("node:fs/promises");var Q=U((t=>{var e=class extends Error{constructor(o,i,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=o,this.nestedError=void 0}},u=class extends e{constructor(o){super(1,"commander.invalidArgument",o),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};t.CommanderError=e,t.InvalidArgumentError=u})),st=U((t=>{var{InvalidArgumentError:e}=Q(),u=class{constructor(i,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(i,r){return r===this.defaultValue||!Array.isArray(r)?[i]:(r.push(i),r)}default(i,r){return this.defaultValue=i,this.defaultValueDescription=r,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(r,a)=>{if(!this.argChoices.includes(r))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(r,a):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function o(i){const r=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+r+">":"["+r+"]"}t.Argument=u,t.humanReadableArgName=o})),vt=U((t=>{var{humanReadableArgName:e}=st(),u=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(i){this.helpWidth=this.helpWidth??i.helpWidth??80}visibleCommands(i){const r=i.commands.filter(c=>!c._hidden),a=i._getHelpCommand();return a&&!a._hidden&&r.push(a),this.sortSubcommands&&r.sort((c,h)=>c.name().localeCompare(h.name())),r}compareOptions(i,r){const a=c=>c.short?c.short.replace(/^-/,""):c.long.replace(/^--/,"");return a(i).localeCompare(a(r))}visibleOptions(i){const r=i.options.filter(c=>!c.hidden),a=i._getHelpOption();if(a&&!a.hidden){const c=a.short&&i._findOption(a.short),h=a.long&&i._findOption(a.long);!c&&!h?r.push(a):a.long&&!h?r.push(i.createOption(a.long,a.description)):a.short&&!c&&r.push(i.createOption(a.short,a.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const r=[];for(let a=i.parent;a;a=a.parent){const c=a.options.filter(h=>!h.hidden);r.push(...c)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(i){return i._argsDescription&&i.registeredArguments.forEach(r=>{r.description=r.description||i._argsDescription[r.name()]||""}),i.registeredArguments.find(r=>r.description)?i.registeredArguments:[]}subcommandTerm(i){const r=i.registeredArguments.map(a=>e(a)).join(" ");return i._name+(i._aliases[0]?"|"+i._aliases[0]:"")+(i.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(i){return i.flags}argumentTerm(i){return i.name()}longestSubcommandTermLength(i,r){return r.visibleCommands(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleSubcommandTerm(r.subcommandTerm(c)))),0)}longestOptionTermLength(i,r){return r.visibleOptions(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleOptionTerm(r.optionTerm(c)))),0)}longestGlobalOptionTermLength(i,r){return r.visibleGlobalOptions(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleOptionTerm(r.optionTerm(c)))),0)}longestArgumentTermLength(i,r){return r.visibleArguments(i).reduce((a,c)=>Math.max(a,this.displayWidth(r.styleArgumentTerm(r.argumentTerm(c)))),0)}commandUsage(i){let r=i._name;i._aliases[0]&&(r=r+"|"+i._aliases[0]);let a="";for(let c=i.parent;c;c=c.parent)a=c.name()+" "+a;return a+r+" "+i.usage()}commandDescription(i){return i.description()}subcommandDescription(i){return i.summary()||i.description()}optionDescription(i){const r=[];if(i.argChoices&&r.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&(i.required||i.optional||i.isBoolean()&&typeof i.defaultValue=="boolean")&&r.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),i.presetArg!==void 0&&i.optional&&r.push(`preset: ${JSON.stringify(i.presetArg)}`),i.envVar!==void 0&&r.push(`env: ${i.envVar}`),r.length>0){const a=`(${r.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}argumentDescription(i){const r=[];if(i.argChoices&&r.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&r.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),r.length>0){const a=`(${r.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}formatItemList(i,r,a){return r.length===0?[]:[a.styleTitle(i),...r,""]}groupItems(i,r,a){const c=new Map;return i.forEach(h=>{const O=a(h);c.has(O)||c.set(O,[])}),r.forEach(h=>{const O=a(h);c.has(O)||c.set(O,[]),c.get(O).push(h)}),c}formatHelp(i,r){const a=r.padWidth(i,r),c=r.helpWidth??80;function h(_,j){return r.formatItem(_,a,j,r)}let O=[`${r.styleTitle("Usage:")} ${r.styleUsage(r.commandUsage(i))}`,""];const A=r.commandDescription(i);A.length>0&&(O=O.concat([r.boxWrap(r.styleCommandDescription(A),c),""]));const C=r.visibleArguments(i).map(_=>h(r.styleArgumentTerm(r.argumentTerm(_)),r.styleArgumentDescription(r.argumentDescription(_))));if(O=O.concat(this.formatItemList("Arguments:",C,r)),this.groupItems(i.options,r.visibleOptions(i),_=>_.helpGroupHeading??"Options:").forEach((_,j)=>{const q=_.map(F=>h(r.styleOptionTerm(r.optionTerm(F)),r.styleOptionDescription(r.optionDescription(F))));O=O.concat(this.formatItemList(j,q,r))}),r.showGlobalOptions){const _=r.visibleGlobalOptions(i).map(j=>h(r.styleOptionTerm(r.optionTerm(j)),r.styleOptionDescription(r.optionDescription(j))));O=O.concat(this.formatItemList("Global Options:",_,r))}return this.groupItems(i.commands,r.visibleCommands(i),_=>_.helpGroup()||"Commands:").forEach((_,j)=>{const q=_.map(F=>h(r.styleSubcommandTerm(r.subcommandTerm(F)),r.styleSubcommandDescription(r.subcommandDescription(F))));O=O.concat(this.formatItemList(j,q,r))}),O.join(`
2
- `)}displayWidth(i){return o(i).length}styleTitle(i){return i}styleUsage(i){return i.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r==="[command]"?this.styleSubcommandText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleCommandText(r)).join(" ")}styleCommandDescription(i){return this.styleDescriptionText(i)}styleOptionDescription(i){return this.styleDescriptionText(i)}styleSubcommandDescription(i){return this.styleDescriptionText(i)}styleArgumentDescription(i){return this.styleDescriptionText(i)}styleDescriptionText(i){return i}styleOptionTerm(i){return this.styleOptionText(i)}styleSubcommandTerm(i){return i.split(" ").map(r=>r==="[options]"?this.styleOptionText(r):r[0]==="["||r[0]==="<"?this.styleArgumentText(r):this.styleSubcommandText(r)).join(" ")}styleArgumentTerm(i){return this.styleArgumentText(i)}styleOptionText(i){return i}styleArgumentText(i){return i}styleSubcommandText(i){return i}styleCommandText(i){return i}padWidth(i,r){return Math.max(r.longestOptionTermLength(i,r),r.longestGlobalOptionTermLength(i,r),r.longestSubcommandTermLength(i,r),r.longestArgumentTermLength(i,r))}preformatted(i){return/\n[^\S\r\n]/.test(i)}formatItem(i,r,a,c){const O=" ".repeat(2);if(!a)return O+i;const A=i.padEnd(r+i.length-c.displayWidth(i)),C=2,_=(this.helpWidth??80)-r-C-2;let j;return _<this.minWidthToWrap||c.preformatted(a)?j=a:j=c.boxWrap(a,_).replace(/\n/g,`
3
- `+" ".repeat(r+C)),O+A+" ".repeat(C)+j.replace(/\n/g,`
4
- ${O}`)}boxWrap(i,r){if(r<this.minWidthToWrap)return i;const a=i.split(/\r\n|\n/),c=/[\s]*[^\s]+/g,h=[];return a.forEach(O=>{const A=O.match(c);if(A===null){h.push("");return}let C=[A.shift()],_=this.displayWidth(C[0]);A.forEach(j=>{const q=this.displayWidth(j);if(_+q<=r){C.push(j),_+=q;return}h.push(C.join(""));const F=j.trimStart();C=[F],_=this.displayWidth(F)}),h.push(C.join(""))}),h.join(`
5
- `)}};function o(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}t.Help=u,t.stripColor=o})),Ot=U((t=>{var{InvalidArgumentError:e}=Q(),u=class{constructor(a,c){this.flags=a,this.description=c||"",this.required=a.includes("<"),this.optional=a.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(a),this.mandatory=!1;const h=r(a);this.short=h.shortFlag,this.long=h.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(a,c){return this.defaultValue=a,this.defaultValueDescription=c,this}preset(a){return this.presetArg=a,this}conflicts(a){return this.conflictsWith=this.conflictsWith.concat(a),this}implies(a){let c=a;return typeof a=="string"&&(c={[a]:!0}),this.implied=Object.assign(this.implied||{},c),this}env(a){return this.envVar=a,this}argParser(a){return this.parseArg=a,this}makeOptionMandatory(a=!0){return this.mandatory=!!a,this}hideHelp(a=!0){return this.hidden=!!a,this}_collectValue(a,c){return c===this.defaultValue||!Array.isArray(c)?[a]:(c.push(a),c)}choices(a){return this.argChoices=a.slice(),this.parseArg=(c,h)=>{if(!this.argChoices.includes(c))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(c,h):c},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?i(this.name().replace(/^no-/,"")):i(this.name())}helpGroup(a){return this.helpGroupHeading=a,this}is(a){return this.short===a||this.long===a}isBoolean(){return!this.required&&!this.optional&&!this.negate}},o=class{constructor(a){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,a.forEach(c=>{c.negate?this.negativeOptions.set(c.attributeName(),c):this.positiveOptions.set(c.attributeName(),c)}),this.negativeOptions.forEach((c,h)=>{this.positiveOptions.has(h)&&this.dualOptions.add(h)})}valueFromOption(a,c){const h=c.attributeName();if(!this.dualOptions.has(h))return!0;const O=this.negativeOptions.get(h).presetArg,A=O!==void 0?O:!1;return c.negate===(A===a)}};function i(a){return a.split("-").reduce((c,h)=>c+h[0].toUpperCase()+h.slice(1))}function r(a){let c,h;const O=/^-[^-]$/,A=/^--[^-]/,C=a.split(/[ |,]+/).concat("guard");if(O.test(C[0])&&(c=C.shift()),A.test(C[0])&&(h=C.shift()),!c&&O.test(C[0])&&(c=C.shift()),!c&&A.test(C[0])&&(c=h,h=C.shift()),C[0].startsWith("-")){const _=C[0],j=`option creation failed due to '${_}' in option flags '${a}'`;throw/^-[^-][^-]/.test(_)?new Error(`${j}
6
- - a short flag is a single dash and a single character
7
- - either use a single dash and a single character (for a short flag)
8
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):O.test(_)?new Error(`${j}
9
- - too many short flags`):A.test(_)?new Error(`${j}
10
- - too many long flags`):new Error(`${j}
11
- - unrecognised flag format`)}if(c===void 0&&h===void 0)throw new Error(`option creation failed due to no flags found in '${a}'.`);return{shortFlag:c,longFlag:h}}t.Option=u,t.DualOptions=o})),Wt=U((t=>{var e=3;function u(i,r){if(Math.abs(i.length-r.length)>e)return Math.max(i.length,r.length);const a=[];for(let c=0;c<=i.length;c++)a[c]=[c];for(let c=0;c<=r.length;c++)a[0][c]=c;for(let c=1;c<=r.length;c++)for(let h=1;h<=i.length;h++){let O=1;i[h-1]===r[c-1]?O=0:O=1,a[h][c]=Math.min(a[h-1][c]+1,a[h][c-1]+1,a[h-1][c-1]+O),h>1&&c>1&&i[h-1]===r[c-2]&&i[h-2]===r[c-1]&&(a[h][c]=Math.min(a[h][c],a[h-2][c-2]+1))}return a[i.length][r.length]}function o(i,r){if(!r||r.length===0)return"";r=Array.from(new Set(r));const a=i.startsWith("--");a&&(i=i.slice(2),r=r.map(A=>A.slice(2)));let c=[],h=e;const O=.4;return r.forEach(A=>{if(A.length<=1)return;const C=u(i,A),_=Math.max(i.length,A.length);(_-C)/_>O&&(C<h?(h=C,c=[A]):C===h&&c.push(A))}),c.sort((A,C)=>A.localeCompare(C)),a&&(c=c.map(A=>`--${A}`)),c.length>1?`
12
- (Did you mean one of ${c.join(", ")}?)`:c.length===1?`
13
- (Did you mean ${c[0]}?)`:""}t.suggestSimilar=o})),Mt=U((t=>{var e=require("node:events").EventEmitter,u=require("node:child_process"),o=require("node:path"),i=require("node:fs"),r=require("node:process"),{Argument:a,humanReadableArgName:c}=st(),{CommanderError:h}=Q(),{Help:O,stripColor:A}=vt(),{Option:C,DualOptions:_}=Ot(),{suggestSimilar:j}=Wt(),q=class yt extends e{constructor(s){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=s||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:n=>r.stdout.write(n),writeErr:n=>r.stderr.write(n),outputError:(n,l)=>l(n),getOutHelpWidth:()=>r.stdout.isTTY?r.stdout.columns:void 0,getErrHelpWidth:()=>r.stderr.isTTY?r.stderr.columns:void 0,getOutHasColors:()=>Z()??(r.stdout.isTTY&&r.stdout.hasColors?.()),getErrHasColors:()=>Z()??(r.stderr.isTTY&&r.stderr.hasColors?.()),stripColor:n=>A(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(s){return this._outputConfiguration=s._outputConfiguration,this._helpOption=s._helpOption,this._helpCommand=s._helpCommand,this._helpConfiguration=s._helpConfiguration,this._exitCallback=s._exitCallback,this._storeOptionsAsProperties=s._storeOptionsAsProperties,this._combineFlagAndOptionalValue=s._combineFlagAndOptionalValue,this._allowExcessArguments=s._allowExcessArguments,this._enablePositionalOptions=s._enablePositionalOptions,this._showHelpAfterError=s._showHelpAfterError,this._showSuggestionAfterError=s._showSuggestionAfterError,this}_getCommandAndAncestors(){const s=[];for(let n=this;n;n=n.parent)s.push(n);return s}command(s,n,l){let d=n,p=l;typeof d=="object"&&d!==null&&(p=d,d=null),p=p||{};const[,m,y]=s.match(/([^ ]+) *(.*)/),S=this.createCommand(m);return d&&(S.description(d),S._executableHandler=!0),p.isDefault&&(this._defaultCommandName=S._name),S._hidden=!!(p.noHelp||p.hidden),S._executableFile=p.executableFile||null,y&&S.arguments(y),this._registerCommand(S),S.parent=this,S.copyInheritedSettings(this),d?this:S}createCommand(s){return new yt(s)}createHelp(){return Object.assign(new O,this.configureHelp())}configureHelp(s){return s===void 0?this._helpConfiguration:(this._helpConfiguration=s,this)}configureOutput(s){return s===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...s},this)}showHelpAfterError(s=!0){return typeof s!="string"&&(s=!!s),this._showHelpAfterError=s,this}showSuggestionAfterError(s=!0){return this._showSuggestionAfterError=!!s,this}addCommand(s,n){if(!s._name)throw new Error(`Command passed to .addCommand() must have a name
14
- - specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=s._name),(n.noHelp||n.hidden)&&(s._hidden=!0),this._registerCommand(s),s.parent=this,s._checkForBrokenPassThrough(),this}createArgument(s,n){return new a(s,n)}argument(s,n,l,d){const p=this.createArgument(s,n);return typeof l=="function"?p.default(d).argParser(l):p.default(l),this.addArgument(p),this}arguments(s){return s.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(s){const n=this.registeredArguments.slice(-1)[0];if(n?.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(s.required&&s.defaultValue!==void 0&&s.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${s.name()}'`);return this.registeredArguments.push(s),this}helpCommand(s,n){if(typeof s=="boolean")return this._addImplicitHelpCommand=s,s&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,l,d]=(s??"help [command]").match(/([^ ]+) *(.*)/),p=n??"display help for command",m=this.createCommand(l);return m.helpOption(!1),d&&m.arguments(d),p&&m.description(p),this._addImplicitHelpCommand=!0,this._helpCommand=m,(s||n)&&this._initCommandGroup(m),this}addHelpCommand(s,n){return typeof s!="object"?(this.helpCommand(s,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=s,this._initCommandGroup(s),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(s,n){const l=["preSubcommand","preAction","postAction"];if(!l.includes(s))throw new Error(`Unexpected value for event passed to hook : '${s}'.
15
- Expecting one of '${l.join("', '")}'`);return this._lifeCycleHooks[s]?this._lifeCycleHooks[s].push(n):this._lifeCycleHooks[s]=[n],this}exitOverride(s){return s?this._exitCallback=s:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(s,n,l){this._exitCallback&&this._exitCallback(new h(s,n,l)),r.exit(s)}action(s){const n=l=>{const d=this.registeredArguments.length,p=l.slice(0,d);return this._storeOptionsAsProperties?p[d]=this:p[d]=this.opts(),p.push(this),s.apply(this,p)};return this._actionHandler=n,this}createOption(s,n){return new C(s,n)}_callParseArg(s,n,l,d){try{return s.parseArg(n,l)}catch(p){if(p.code==="commander.invalidArgument"){const m=`${d} ${p.message}`;this.error(m,{exitCode:p.exitCode,code:p.code})}throw p}}_registerOption(s){const n=s.short&&this._findOption(s.short)||s.long&&this._findOption(s.long);if(n){const l=s.long&&this._findOption(s.long)?s.long:s.short;throw new Error(`Cannot add option '${s.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${l}'
16
- - already used by option '${n.flags}'`)}this._initOptionGroup(s),this.options.push(s)}_registerCommand(s){const n=d=>[d.name()].concat(d.aliases()),l=n(s).find(d=>this._findCommand(d));if(l){const d=n(this._findCommand(l)).join("|"),p=n(s).join("|");throw new Error(`cannot add command '${p}' as already have command '${d}'`)}this._initCommandGroup(s),this.commands.push(s)}addOption(s){this._registerOption(s);const n=s.name(),l=s.attributeName();if(s.negate){const p=s.long.replace(/^--no-/,"--");this._findOption(p)||this.setOptionValueWithSource(l,s.defaultValue===void 0?!0:s.defaultValue,"default")}else s.defaultValue!==void 0&&this.setOptionValueWithSource(l,s.defaultValue,"default");const d=(p,m,y)=>{p==null&&s.presetArg!==void 0&&(p=s.presetArg);const S=this.getOptionValue(l);p!==null&&s.parseArg?p=this._callParseArg(s,p,S,m):p!==null&&s.variadic&&(p=s._collectValue(p,S)),p==null&&(s.negate?p=!1:s.isBoolean()||s.optional?p=!0:p=""),this.setOptionValueWithSource(l,p,y)};return this.on("option:"+n,p=>{d(p,`error: option '${s.flags}' argument '${p}' is invalid.`,"cli")}),s.envVar&&this.on("optionEnv:"+n,p=>{d(p,`error: option '${s.flags}' value '${p}' from env '${s.envVar}' is invalid.`,"env")}),this}_optionEx(s,n,l,d,p){if(typeof n=="object"&&n instanceof C)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const m=this.createOption(n,l);if(m.makeOptionMandatory(!!s.mandatory),typeof d=="function")m.default(p).argParser(d);else if(d instanceof RegExp){const y=d;d=(S,x)=>{const f=y.exec(S);return f?f[0]:x},m.default(p).argParser(d)}else m.default(d);return this.addOption(m)}option(s,n,l,d){return this._optionEx({},s,n,l,d)}requiredOption(s,n,l,d){return this._optionEx({mandatory:!0},s,n,l,d)}combineFlagAndOptionalValue(s=!0){return this._combineFlagAndOptionalValue=!!s,this}allowUnknownOption(s=!0){return this._allowUnknownOption=!!s,this}allowExcessArguments(s=!0){return this._allowExcessArguments=!!s,this}enablePositionalOptions(s=!0){return this._enablePositionalOptions=!!s,this}passThroughOptions(s=!0){return this._passThroughOptions=!!s,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(s=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!s,this}getOptionValue(s){return this._storeOptionsAsProperties?this[s]:this._optionValues[s]}setOptionValue(s,n){return this.setOptionValueWithSource(s,n,void 0)}setOptionValueWithSource(s,n,l){return this._storeOptionsAsProperties?this[s]=n:this._optionValues[s]=n,this._optionValueSources[s]=l,this}getOptionValueSource(s){return this._optionValueSources[s]}getOptionValueSourceWithGlobals(s){let n;return this._getCommandAndAncestors().forEach(l=>{l.getOptionValueSource(s)!==void 0&&(n=l.getOptionValueSource(s))}),n}_prepareUserArgs(s,n){if(s!==void 0&&!Array.isArray(s))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},s===void 0&&n.from===void 0){r.versions?.electron&&(n.from="electron");const d=r.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(n.from="eval")}s===void 0&&(s=r.argv),this.rawArgs=s.slice();let l;switch(n.from){case void 0:case"node":this._scriptPath=s[1],l=s.slice(2);break;case"electron":r.defaultApp?(this._scriptPath=s[1],l=s.slice(2)):l=s.slice(1);break;case"user":l=s.slice(0);break;case"eval":l=s.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",l}parse(s,n){this._prepareForParse();const l=this._prepareUserArgs(s,n);return this._parseCommand([],l),this}async parseAsync(s,n){this._prepareForParse();const l=this._prepareUserArgs(s,n);return await this._parseCommand([],l),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17
- - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(s,n,l){if(i.existsSync(s))return;const d=`'${s}' does not exist
18
- - if '${l}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
19
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
20
- - ${n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;throw new Error(d)}_executeSubCommand(s,n){n=n.slice();let l=!1;const d=[".js",".ts",".tsx",".mjs",".cjs"];function p(f,b){const $=o.resolve(f,b);if(i.existsSync($))return $;if(d.includes(o.extname(b)))return;const pt=d.find(Nt=>i.existsSync(`${$}${Nt}`));if(pt)return`${$}${pt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let m=s._executableFile||`${this._name}-${s._name}`,y=this._executableDir||"";if(this._scriptPath){let f;try{f=i.realpathSync(this._scriptPath)}catch{f=this._scriptPath}y=o.resolve(o.dirname(f),y)}if(y){let f=p(y,m);if(!f&&!s._executableFile&&this._scriptPath){const b=o.basename(this._scriptPath,o.extname(this._scriptPath));b!==this._name&&(f=p(y,`${b}-${s._name}`))}m=f||m}l=d.includes(o.extname(m));let S;r.platform!=="win32"?l?(n.unshift(m),n=F(r.execArgv).concat(n),S=u.spawn(r.argv[0],n,{stdio:"inherit"})):S=u.spawn(m,n,{stdio:"inherit"}):(this._checkForMissingExecutable(m,y,s._name),n.unshift(m),n=F(r.execArgv).concat(n),S=u.spawn(r.execPath,n,{stdio:"inherit"})),S.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{r.on(f,()=>{S.killed===!1&&S.exitCode===null&&S.kill(f)})});const x=this._exitCallback;S.on("close",f=>{f=f??1,x?x(new h(f,"commander.executeSubCommandAsync","(close)")):r.exit(f)}),S.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(m,y,s._name);else if(f.code==="EACCES")throw new Error(`'${m}' not executable`);if(!x)r.exit(1);else{const b=new h(1,"commander.executeSubCommandAsync","(error)");b.nestedError=f,x(b)}}),this.runningCommand=S}_dispatchSubcommand(s,n,l){const d=this._findCommand(s);d||this.help({error:!0}),d._prepareForParse();let p;return p=this._chainOrCallSubCommandHook(p,d,"preSubcommand"),p=this._chainOrCall(p,()=>{if(d._executableHandler)this._executeSubCommand(d,n.concat(l));else return d._parseCommand(n,l)}),p}_dispatchHelpCommand(s){s||this.help();const n=this._findCommand(s);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(s,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((s,n)=>{s.required&&this.args[n]==null&&this.missingArgument(s.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const s=(l,d,p)=>{let m=d;if(d!==null&&l.parseArg){const y=`error: command-argument value '${d}' is invalid for argument '${l.name()}'.`;m=this._callParseArg(l,d,p,y)}return m};this._checkNumberOfArguments();const n=[];this.registeredArguments.forEach((l,d)=>{let p=l.defaultValue;l.variadic?d<this.args.length?(p=this.args.slice(d),l.parseArg&&(p=p.reduce((m,y)=>s(l,y,m),l.defaultValue))):p===void 0&&(p=[]):d<this.args.length&&(p=this.args[d],l.parseArg&&(p=s(l,p,l.defaultValue))),n[d]=p}),this.processedArgs=n}_chainOrCall(s,n){return s?.then&&typeof s.then=="function"?s.then(()=>n()):n()}_chainOrCallHooks(s,n){let l=s;const d=[];return this._getCommandAndAncestors().reverse().filter(p=>p._lifeCycleHooks[n]!==void 0).forEach(p=>{p._lifeCycleHooks[n].forEach(m=>{d.push({hookedCommand:p,callback:m})})}),n==="postAction"&&d.reverse(),d.forEach(p=>{l=this._chainOrCall(l,()=>p.callback(p.hookedCommand,this))}),l}_chainOrCallSubCommandHook(s,n,l){let d=s;return this._lifeCycleHooks[l]!==void 0&&this._lifeCycleHooks[l].forEach(p=>{d=this._chainOrCall(d,()=>p(this,n))}),d}_parseCommand(s,n){const l=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),s=s.concat(l.operands),n=l.unknown,this.args=s.concat(n),s&&this._findCommand(s[0]))return this._dispatchSubcommand(s[0],s.slice(1),n);if(this._getHelpCommand()&&s[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(s[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,s,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(l.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const d=()=>{l.unknown.length>0&&this.unknownOption(l.unknown[0])},p=`command:${this.name()}`;if(this._actionHandler){d(),this._processArguments();let m;return m=this._chainOrCallHooks(m,"preAction"),m=this._chainOrCall(m,()=>this._actionHandler(this.processedArgs)),this.parent&&(m=this._chainOrCall(m,()=>{this.parent.emit(p,s,n)})),m=this._chainOrCallHooks(m,"postAction"),m}if(this.parent?.listenerCount(p))d(),this._processArguments(),this.parent.emit(p,s,n);else if(s.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",s,n);this.listenerCount("command:*")?this.emit("command:*",s,n):this.commands.length?this.unknownCommand():(d(),this._processArguments())}else this.commands.length?(d(),this.help({error:!0})):(d(),this._processArguments())}_findCommand(s){if(s)return this.commands.find(n=>n._name===s||n._aliases.includes(s))}_findOption(s){return this.options.find(n=>n.is(s))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(s=>{s.options.forEach(n=>{n.mandatory&&s.getOptionValue(n.attributeName())===void 0&&s.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){const s=this.options.filter(n=>{const l=n.attributeName();return this.getOptionValue(l)===void 0?!1:this.getOptionValueSource(l)!=="default"});s.filter(n=>n.conflictsWith.length>0).forEach(n=>{const l=s.find(d=>n.conflictsWith.includes(d.attributeName()));l&&this._conflictingOption(n,l)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(s=>{s._checkForConflictingLocalOptions()})}parseOptions(s){const n=[],l=[];let d=n;function p(f){return f.length>1&&f[0]==="-"}const m=f=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(f)?!this._getCommandAndAncestors().some(b=>b.options.map($=>$.short).some($=>/^-\d$/.test($))):!1;let y=null,S=null,x=0;for(;x<s.length||S;){const f=S??s[x++];if(S=null,f==="--"){d===l&&d.push(f),d.push(...s.slice(x));break}if(y&&(!p(f)||m(f))){this.emit(`option:${y.name()}`,f);continue}if(y=null,p(f)){const b=this._findOption(f);if(b){if(b.required){const $=s[x++];$===void 0&&this.optionMissingArgument(b),this.emit(`option:${b.name()}`,$)}else if(b.optional){let $=null;x<s.length&&(!p(s[x])||m(s[x]))&&($=s[x++]),this.emit(`option:${b.name()}`,$)}else this.emit(`option:${b.name()}`);y=b.variadic?b:null;continue}}if(f.length>2&&f[0]==="-"&&f[1]!=="-"){const b=this._findOption(`-${f[1]}`);if(b){b.required||b.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${b.name()}`,f.slice(2)):(this.emit(`option:${b.name()}`),S=`-${f.slice(2)}`);continue}}if(/^--[^=]+=/.test(f)){const b=f.indexOf("="),$=this._findOption(f.slice(0,b));if($&&($.required||$.optional)){this.emit(`option:${$.name()}`,f.slice(b+1));continue}}if(d===n&&p(f)&&!(this.commands.length===0&&m(f))&&(d=l),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&l.length===0){if(this._findCommand(f)){n.push(f),l.push(...s.slice(x));break}else if(this._getHelpCommand()&&f===this._getHelpCommand().name()){n.push(f,...s.slice(x));break}else if(this._defaultCommandName){l.push(f,...s.slice(x));break}}if(this._passThroughOptions){d.push(f,...s.slice(x));break}d.push(f)}return{operands:n,unknown:l}}opts(){if(this._storeOptionsAsProperties){const s={},n=this.options.length;for(let l=0;l<n;l++){const d=this.options[l].attributeName();s[d]=d===this._versionOptionName?this._version:this[d]}return s}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((s,n)=>Object.assign(s,n.opts()),{})}error(s,n){this._outputConfiguration.outputError(`${s}
21
- `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
22
- `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
23
- `),this.outputHelp({error:!0}));const l=n||{},d=l.exitCode||1,p=l.code||"commander.error";this._exit(d,p,s)}_parseOptionsEnv(){this.options.forEach(s=>{if(s.envVar&&s.envVar in r.env){const n=s.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(s.required||s.optional?this.emit(`optionEnv:${s.name()}`,r.env[s.envVar]):this.emit(`optionEnv:${s.name()}`))}})}_parseOptionsImplied(){const s=new _(this.options),n=l=>this.getOptionValue(l)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(l));this.options.filter(l=>l.implied!==void 0&&n(l.attributeName())&&s.valueFromOption(this.getOptionValue(l.attributeName()),l)).forEach(l=>{Object.keys(l.implied).filter(d=>!n(d)).forEach(d=>{this.setOptionValueWithSource(d,l.implied[d],"implied")})})}missingArgument(s){const n=`error: missing required argument '${s}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(s){const n=`error: option '${s.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(s){const n=`error: required option '${s.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(s,n){const l=m=>{const y=m.attributeName(),S=this.getOptionValue(y),x=this.options.find(b=>b.negate&&y===b.attributeName()),f=this.options.find(b=>!b.negate&&y===b.attributeName());return x&&(x.presetArg===void 0&&S===!1||x.presetArg!==void 0&&S===x.presetArg)?x:f||m},d=m=>{const y=l(m),S=y.attributeName();return this.getOptionValueSource(S)==="env"?`environment variable '${y.envVar}'`:`option '${y.flags}'`},p=`error: ${d(s)} cannot be used with ${d(n)}`;this.error(p,{code:"commander.conflictingOption"})}unknownOption(s){if(this._allowUnknownOption)return;let n="";if(s.startsWith("--")&&this._showSuggestionAfterError){let d=[],p=this;do{const m=p.createHelp().visibleOptions(p).filter(y=>y.long).map(y=>y.long);d=d.concat(m),p=p.parent}while(p&&!p._enablePositionalOptions);n=j(s,d)}const l=`error: unknown option '${s}'${n}`;this.error(l,{code:"commander.unknownOption"})}_excessArguments(s){if(this._allowExcessArguments)return;const n=this.registeredArguments.length,l=n===1?"":"s",d=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${l} but got ${s.length}.`;this.error(d,{code:"commander.excessArguments"})}unknownCommand(){const s=this.args[0];let n="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(p=>{d.push(p.name()),p.alias()&&d.push(p.alias())}),n=j(s,d)}const l=`error: unknown command '${s}'${n}`;this.error(l,{code:"commander.unknownCommand"})}version(s,n,l){if(s===void 0)return this._version;this._version=s,n=n||"-V, --version",l=l||"output the version number";const d=this.createOption(n,l);return this._versionOptionName=d.attributeName(),this._registerOption(d),this.on("option:"+d.name(),()=>{this._outputConfiguration.writeOut(`${s}
24
- `),this._exit(0,"commander.version",s)}),this}description(s,n){return s===void 0&&n===void 0?this._description:(this._description=s,n&&(this._argsDescription=n),this)}summary(s){return s===void 0?this._summary:(this._summary=s,this)}alias(s){if(s===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),s===n._name)throw new Error("Command alias can't be the same as its name");const l=this.parent?._findCommand(s);if(l){const d=[l.name()].concat(l.aliases()).join("|");throw new Error(`cannot add alias '${s}' to command '${this.name()}' as already have command '${d}'`)}return n._aliases.push(s),this}aliases(s){return s===void 0?this._aliases:(s.forEach(n=>this.alias(n)),this)}usage(s){if(s===void 0){if(this._usage)return this._usage;const n=this.registeredArguments.map(l=>c(l));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=s,this}name(s){return s===void 0?this._name:(this._name=s,this)}helpGroup(s){return s===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=s,this)}commandsGroup(s){return s===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=s,this)}optionsGroup(s){return s===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=s,this)}_initOptionGroup(s){this._defaultOptionGroup&&!s.helpGroupHeading&&s.helpGroup(this._defaultOptionGroup)}_initCommandGroup(s){this._defaultCommandGroup&&!s.helpGroup()&&s.helpGroup(this._defaultCommandGroup)}nameFromFilename(s){return this._name=o.basename(s,o.extname(s)),this}executableDir(s){return s===void 0?this._executableDir:(this._executableDir=s,this)}helpInformation(s){const n=this.createHelp(),l=this._getOutputContext(s);n.prepareContext({error:l.error,helpWidth:l.helpWidth,outputHasColors:l.hasColors});const d=n.formatHelp(this,n);return l.hasColors?d:this._outputConfiguration.stripColor(d)}_getOutputContext(s){s=s||{};const n=!!s.error;let l,d,p;return n?(l=y=>this._outputConfiguration.writeErr(y),d=this._outputConfiguration.getErrHasColors(),p=this._outputConfiguration.getErrHelpWidth()):(l=y=>this._outputConfiguration.writeOut(y),d=this._outputConfiguration.getOutHasColors(),p=this._outputConfiguration.getOutHelpWidth()),{error:n,write:y=>(d||(y=this._outputConfiguration.stripColor(y)),l(y)),hasColors:d,helpWidth:p}}outputHelp(s){let n;typeof s=="function"&&(n=s,s=void 0);const l=this._getOutputContext(s),d={error:l.error,write:l.write,command:this};this._getCommandAndAncestors().reverse().forEach(m=>m.emit("beforeAllHelp",d)),this.emit("beforeHelp",d);let p=this.helpInformation({error:l.error});if(n&&(p=n(p),typeof p!="string"&&!Buffer.isBuffer(p)))throw new Error("outputHelp callback must return a string or a Buffer");l.write(p),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",d),this._getCommandAndAncestors().forEach(m=>m.emit("afterAllHelp",d))}helpOption(s,n){return typeof s=="boolean"?(s?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(s??"-h, --help",n??"display help for command"),(s||n)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(s){return this._helpOption=s,this._initOptionGroup(s),this}help(s){this.outputHelp(s);let n=Number(r.exitCode??0);n===0&&s&&typeof s!="function"&&s.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(s,n){const l=["beforeAll","before","after","afterAll"];if(!l.includes(s))throw new Error(`Unexpected value for position to addHelpText.
25
- Expecting one of '${l.join("', '")}'`);const d=`${s}Help`;return this.on(d,p=>{let m;typeof n=="function"?m=n({error:p.error,command:p.command}):m=n,m&&p.write(`${m}
26
- `)}),this}_outputHelpIfRequested(s){const n=this._getHelpOption();n&&s.find(l=>n.is(l))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function F(Dt){return Dt.map(s=>{if(!s.startsWith("--inspect"))return s;let n,l="127.0.0.1",d="9229",p;return(p=s.match(/^(--inspect(-brk)?)$/))!==null?n=p[1]:(p=s.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=p[1],/^\d+$/.test(p[3])?d=p[3]:l=p[3]):(p=s.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=p[1],l=p[3],d=p[4]),n&&d!=="0"?`${n}=${l}:${parseInt(d)+1}`:s})}function Z(){if(r.env.NO_COLOR||r.env.FORCE_COLOR==="0"||r.env.FORCE_COLOR==="false")return!1;if(r.env.FORCE_COLOR||r.env.CLICOLOR_FORCE!==void 0)return!0}t.Command=q,t.useColor=Z})),Jt=U((t=>{var{Argument:e}=st(),{Command:u}=Mt(),{CommanderError:o,InvalidArgumentError:i}=Q(),{Help:r}=vt(),{Option:a}=Ot();t.program=new u,t.createCommand=c=>new u(c),t.createOption=(c,h)=>new a(c,h),t.createArgument=(c,h)=>new e(c,h),t.Command=u,t.Option=a,t.Argument=e,t.Help=r,t.CommanderError=o,t.InvalidArgumentError=i,t.InvalidOptionArgumentError=i})),zt=Lt(Jt(),1),{program:Oi,createCommand:yi,createArgument:Ci,createOption:Ai,CommanderError:Kt,InvalidArgumentError:_i,InvalidOptionArgumentError:Si,Command:Qt,Argument:bi,Option:k,Help:Ei}=zt.default;function w(t){return`${JSON.stringify(t,null,2)}
27
- `}var Ct=(function(t){return t.INIT="Init",t.COMPLETED="Completed",t.ARCHIVED="Archived",t.DRAFTING="Drafting",t.EXECUTION_COMPLETED="ExecutionCompleted",t.OPTIMIZING="Optimizing",t.OPENSPECING="Openspecing",t.REVIEWING="Reviewing",t.EXECUTING="Executing",t.ARCHIVING="Archiving",t})({});function At(t){return t.replace(/\s+/g," ").trim()}function Y(t,e){const u=e.map(r=>t.map(a=>At(a.value(r)))),o=t.map((r,a)=>{const c=u.map(h=>h[a].length);return Math.max(r.header.length,...c)}),i=r=>r.map((a,c)=>a.padEnd(o[c])).join(" ").trimEnd();return[i(t.map(r=>r.header)),i(o.map(r=>"-".repeat(r))),...u.map(i)].join(`
28
- `)}function L(t){const e=t.filter(([,o])=>o!==void 0&&o!==""),u=Math.max(...e.map(([o])=>o.length));return`${e.map(([o,i])=>`${o.padEnd(u)} ${At(i??"")}`).join(`
29
- `)}
30
- `}function ht(t){return typeof t=="string"?t.trim():t?.value?.trim()??""}function G(t){return{sessionId:ht(t.sessionId),title:t.title,type:t.type,status:t.status,projectId:ht(t.projectId),proposalName:t.proposalName??void 0,archived:t.status===Ct.ARCHIVED,lastActiveAt:t.lastActiveAt??void 0,enableIndependentWorkspace:t.enableIndependentWorkspace,baseBranch:t.baseBranch??void 0,metadata:t.metadata??void 0,chatExecutorType:t.chatExecutorType??void 0}}function _t(t){return{sessions:t.sessions.map(G)}}function St(t,e){return e.length===0?`No ${t.toLowerCase()} found.
31
- `:`${t} (${e.length})
32
- ${Y([{header:"Session ID",value:u=>u.sessionId},{header:"Title",value:u=>u.title},{header:"Status",value:u=>u.status},{header:"Project ID",value:u=>u.projectId},{header:"Archived",value:u=>u.archived?"yes":"no"}],e)}
33
- `}function M(t,e=[]){return L([["sessionId",t.sessionId],["type",t.type],["title",t.title],["status",t.status],["projectId",t.projectId],["proposalName",t.proposalName],["independentWorkspace",String(t.enableIndependentWorkspace)],["baseBranch",t.baseBranch],["chatExecutorType",t.chatExecutorType],["metadata",t.metadata],...e])}function rt(t,e,u,o=[]){return`${t}
34
- ${L([["sessionId",e],["message",u.message],...o])}`}var g={BASE:"",VERSION:"1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};function B(t){const e=t?.trim();return e||void 0}function Yt(t={},e=process.env){return{baseUrl:B(t.baseUrl)??B(e.HAGI_API_BASE_URL)??"http://127.0.0.1:35168",token:B(t.token)??B(e.HAGI_API_TOKEN),lang:B(t.lang)??B(e.HAGI_API_LANG)}}function Xt(t={},e=process.env){const u=Yt(t,e);return g.BASE=u.baseUrl,g.WITH_CREDENTIALS=!1,g.CREDENTIALS="omit",g.TOKEN=u.token,g.HEADERS=u.lang?{"Accept-Language":u.lang}:void 0,u}var it=class extends Error{url;status;statusText;body;request;constructor(t,e,u){super(u),this.name="ApiError",this.url=e.url,this.status=e.status,this.statusText=e.statusText,this.body=e.body,this.request=t}},D={USAGE:2,HTTP_BAD_REQUEST:20,HTTP_UNAUTHORIZED:21,HTTP_FORBIDDEN:23,HTTP_NOT_FOUND:24,HTTP_CONFLICT:29,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},N=class extends Error{constructor(t){super(t),this.name="CliUsageError"}},ot=class extends Error{status;details;constructor(t,e,u){super(e),this.name="CliHttpError",this.status=t,this.details=u}};function Zt(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function z(t,e){const u=Zt(t)?.[e];return typeof u=="string"&&u.trim()?u.trim():void 0}function te(t){return t.includes("fetch failed")||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("Failed to parse URL")}function mt(t){switch(t){case 400:return D.HTTP_BAD_REQUEST;case 401:return D.HTTP_UNAUTHORIZED;case 403:return D.HTTP_FORBIDDEN;case 404:return D.HTTP_NOT_FOUND;case 409:return D.HTTP_CONFLICT;default:return t&&t>=400&&t<500?D.HTTP_CLIENT_ERROR:t&&t>=500?D.HTTP_SERVER_ERROR:D.UNKNOWN}}function ee(t){if(t instanceof N)return{exitCode:D.USAGE,message:t.message};if(t instanceof ot)return{exitCode:mt(t.status),status:t.status,message:t.message,details:t.details};if(t instanceof it){const e=z(t.body,"error")??z(t.body,"message")??t.message;return{exitCode:mt(t.status),status:t.status,message:e,errorCode:z(t.body,"errorCode"),correlationId:z(t.body,"correlationId"),details:t.body}}return t instanceof Error?{exitCode:te(t.message)?D.TRANSPORT:D.UNKNOWN,message:t.message}:{exitCode:D.UNKNOWN,message:String(t)}}function bt(t,e={}){if(e.json)return`${JSON.stringify({error:{message:t.message,status:t.status,exitCode:t.exitCode,errorCode:t.errorCode,correlationId:t.correlationId,details:t.details}},null,2)}
35
- `;const u=[t.status?`status=${t.status}`:void 0,t.errorCode?`errorCode=${t.errorCode}`:void 0,t.correlationId?`correlationId=${t.correlationId}`:void 0].filter(Boolean),o=u.length>0?` (${u.join(", ")})`:"";return`${t.message}${o}
36
- `}var ie=class extends Error{constructor(t){super(t),this.name="CancelError"}get isCancelled(){return!0}},se=class{#e;#i;#t;#s;#o;#n;#r;constructor(t){this.#e=!1,this.#i=!1,this.#t=!1,this.#s=[],this.#o=new Promise((e,u)=>{this.#n=e,this.#r=u;const o=a=>{this.#e||this.#i||this.#t||(this.#e=!0,this.#n&&this.#n(a))},i=a=>{this.#e||this.#i||this.#t||(this.#i=!0,this.#r&&this.#r(a))},r=a=>{this.#e||this.#i||this.#t||this.#s.push(a)};return Object.defineProperty(r,"isResolved",{get:()=>this.#e}),Object.defineProperty(r,"isRejected",{get:()=>this.#i}),Object.defineProperty(r,"isCancelled",{get:()=>this.#t}),t(o,i,r)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(t,e){return this.#o.then(t,e)}catch(t){return this.#o.catch(t)}finally(t){return this.#o.finally(t)}cancel(){if(!(this.#e||this.#i||this.#t)){if(this.#t=!0,this.#s.length)try{for(const t of this.#s)t()}catch(t){console.warn("Cancellation threw an error",t);return}this.#s.length=0,this.#r&&this.#r(new ie("Request aborted"))}}get isCancelled(){return this.#t}},nt=t=>t!=null,J=t=>typeof t=="string",tt=t=>J(t)&&t!=="",at=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),Et=t=>t instanceof FormData,re=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},oe=t=>{const e=[],u=(i,r)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(r))}`)},o=(i,r)=>{nt(r)&&(Array.isArray(r)?r.forEach(a=>{o(i,a)}):typeof r=="object"?Object.entries(r).forEach(([a,c])=>{o(`${i}[${a}]`,c)}):u(i,r))};return Object.entries(t).forEach(([i,r])=>{o(i,r)}),e.length>0?`?${e.join("&")}`:""},ne=(t,e)=>{const u=t.ENCODE_PATH||encodeURI,o=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(r,a)=>e.path?.hasOwnProperty(a)?u(String(e.path[a])):r),i=`${t.BASE}${o}`;return e.query?`${i}${oe(e.query)}`:i},ae=t=>{if(t.formData){const e=new FormData,u=(o,i)=>{J(i)||at(i)?e.append(o,i):e.append(o,JSON.stringify(i))};return Object.entries(t.formData).filter(([o,i])=>nt(i)).forEach(([o,i])=>{Array.isArray(i)?i.forEach(r=>u(o,r)):u(o,i)}),e}},K=async(t,e)=>typeof e=="function"?e(t):e,ue=async(t,e)=>{const[u,o,i,r]=await Promise.all([K(e,t.TOKEN),K(e,t.USERNAME),K(e,t.PASSWORD),K(e,t.HEADERS)]),a=Object.entries({Accept:"application/json",...r,...e.headers}).filter(([c,h])=>nt(h)).reduce((c,[h,O])=>({...c,[h]:String(O)}),{});return tt(u)&&(a.Authorization=`Bearer ${u}`),tt(o)&&tt(i)&&(a.Authorization=`Basic ${re(`${o}:${i}`)}`),e.body!==void 0&&(e.mediaType?a["Content-Type"]=e.mediaType:at(e.body)?a["Content-Type"]=e.body.type||"application/octet-stream":J(e.body)?a["Content-Type"]="text/plain":Et(e.body)||(a["Content-Type"]="application/json")),new Headers(a)},ce=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):J(t.body)||at(t.body)||Et(t.body)?t.body:JSON.stringify(t.body)},le=async(t,e,u,o,i,r,a)=>{const c=new AbortController,h={headers:r,body:o??i,method:e.method,signal:c.signal};return t.WITH_CREDENTIALS&&(h.credentials=t.CREDENTIALS),a(()=>c.abort()),await fetch(u,h)},de=(t,e)=>{if(e){const u=t.headers.get(e);if(J(u))return u}},pe=async t=>{if(t.status!==204)try{const e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(u=>e.toLowerCase().startsWith(u))?await t.json():await t.text()}catch(e){console.error(e)}},he=(t,e)=>{const u={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(u)throw new it(t,e,u);if(!e.ok)throw new it(t,e,`Generic Error: status: ${e.status??"unknown"}; status text: ${e.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})()}`)},v=(t,e)=>new se(async(u,o,i)=>{try{const r=ne(t,e),a=ae(e),c=ce(e),h=await ue(t,e);if(!i.isCancelled){const O=await le(t,e,r,c,a,h,i),A=await pe(O),C=de(O,e.responseHeader),_={url:r,ok:O.ok,status:O.status,statusText:O.statusText,body:C??A};he(e,_),u(_.body)}}catch(r){o(r)}}),me=class{static getApiDataAggregation(){return v(g,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},et=class{static postApiProject({requestBody:t}){return v(g,{method:"POST",url:"/api/Project",body:t,mediaType:"application/json"})}static postApiProjectDemo(){return v(g,{method:"POST",url:"/api/Project/demo"})}static putApiProject({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Project/{id}",path:{id:t},body:e,mediaType:"application/json"})}static deleteApiProject({id:t}){return v(g,{method:"DELETE",url:"/api/Project/{id}",path:{id:t}})}static postApiProjectOpenInVscode({id:t,subPath:e}){return v(g,{method:"POST",url:"/api/Project/{id}/open-in-vscode",path:{id:t},query:{subPath:e},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Project not found",500:"Failed to launch VS Code"}})}static getApiProjectMonospecsManagement({id:t}){return v(g,{method:"GET",url:"/api/Project/{id}/monospecs/management",path:{id:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectMonospecsManagement({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Project/{id}/monospecs/management",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiProjectMonospecsInitialize({id:t}){return v(g,{method:"POST",url:"/api/Project/{id}/monospecs/initialize",path:{id:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiProjectDesignMd({id:t,repositoryPath:e}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md",path:{id:t},query:{repositoryPath:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectDesignMd({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Project/{id}/design-md",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static getApiProjectDesignMdSiteIndex({id:t}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md/site-index",path:{id:t},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndexPreview({id:t,slug:e,theme:u="light"}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}/preview",path:{id:t,slug:e},query:{theme:u},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndex1({id:t,slug:e}){return v(g,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}",path:{id:t,slug:e},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectBranchesValidate({id:t,branchName:e,repositoryPath:u}){return v(g,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:t},query:{branchName:e,repositoryPath:u},errors:{400:"Branch name is required",404:"Project not found"}})}static getApiProjectValidatePath({path:t}){return v(g,{method:"GET",url:"/api/Project/validate-path",query:{path:t},errors:{400:"Path parameter is missing or invalid",500:"Internal server error during validation"}})}static postApiProjectScanGitRepos({requestBody:t}){return v(g,{method:"POST",url:"/api/Project/scan-git-repos",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error during scan"}})}static postApiProjectValidateMonospecs({requestBody:t}){return v(g,{method:"POST",url:"/api/Project/validate-monospecs",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error"}})}},H=class{static postApiSessionsAutoTask({requestBody:t}){return v(g,{method:"POST",url:"/api/Sessions/auto-task",body:t,mediaType:"application/json",errors:{400:"Missing required fields or invalid prompt ID",404:"Project not found",500:"Internal server error"}})}static postApiSessionsArchiveChat({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/archive-chat",path:{sessionId:t},errors:{400:"Session is not a chat session",404:"Session not found",500:"Failed to archive chat session"}})}static postApiSessionsChat({requestBody:t}){return v(g,{method:"POST",url:"/api/Sessions/chat",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:t}){return v(g,{method:"POST",url:"/api/Sessions",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:t,activeOnly:e,includeArchived:u,projectId:o,projectIds:i}){return v(g,{method:"GET",url:"/api/Sessions",query:{type:t,activeOnly:e,includeArchived:u,projectId:o,projectIds:i}})}static getApiSessions1({sessionId:t}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}",path:{sessionId:t},errors:{400:"Invalid session ID format",404:"Session not found",500:"Internal server error occurred"}})}static putApiSessions({sessionId:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:t},body:e,mediaType:"application/json"})}static deleteApiSessions({sessionId:t,deleteFiles:e=!1}){return v(g,{method:"DELETE",url:"/api/Sessions/{sessionId}",path:{sessionId:t},query:{deleteFiles:e},errors:{404:"Session not found",500:"Failed to delete session"}})}static getApiSessionsMessages({sessionId:t,page:e=1,pageSize:u=50,historyScope:o,order:i="desc"}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},query:{page:e,pageSize:u,historyScope:o,order:i},errors:{404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsMessages({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},body:e,mediaType:"application/json"})}static postApiSessionsCancel({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/cancel",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to cancel session"}})}static getApiSessionsProcessingStatus({sessionId:t}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}/processing-status",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to get processing status"}})}static deleteApiSessionsQueue({sessionId:t,queueIndex:e}){return v(g,{method:"DELETE",url:"/api/Sessions/{sessionId}/queue/{queueIndex}",path:{sessionId:t,queueIndex:e},errors:{400:"Invalid queue index",404:"Session not found",500:"Failed to cancel message"}})}static postApiSessionsAnnotations({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/annotations",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Invalid request or session is not a proposal session",404:"Session not found",500:"Failed to process annotations"}})}static postApiSessionsOptimizeProposal({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsGenerateProposal({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name not generated",404:"Session not found",500:"Failed to generate proposal"}})}static postApiSessionsArchive({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/archive",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name missing",404:"Session not found",500:"Failed to archive session"}})}static postApiSessionsExecuteProposal({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/execute-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session, not in valid status, or proposal name missing",404:"Session not found",500:"Failed to execute proposal"}})}static postApiSessionsComplete({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/complete",path:{sessionId:t},errors:{400:"Session is not in ExecutionCompleted status",404:"Session not found",500:"Failed to complete session"}})}static postApiSessionsValidateExecute({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-execute",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateStart({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-start",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateArchive({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/validate-archive",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static getApiSessionsOpenspecFile({sessionId:t,relativePath:e}){return v(g,{method:"GET",url:"/api/Sessions/{sessionId}/openspec-file",path:{sessionId:t},query:{relativePath:e},errors:{404:"Session not found or file not found",500:"Failed to read file"}})}static postApiSessionsUpdateCessionId({sessionId:t}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/update-cession-id",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to update CessionId"}})}static postApiSessionsOpenInVscode({sessionId:t,subPath:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/open-in-vscode",path:{sessionId:t},query:{subPath:e},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Session not found",500:"Failed to launch VS Code"}})}static postApiSessionsCorrectProposalName({sessionId:t,requestBody:e}){return v(g,{method:"POST",url:"/api/Sessions/{sessionId}/correct-proposal-name",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Invalid name format or validation failed",404:"Session not found",409:"Name already in use by another session",500:"Internal server error"}})}static deleteApiSessionsWorkspace({sessionId:t}){return v(g,{method:"DELETE",url:"/api/Sessions/{sessionId}/workspace",path:{sessionId:t},errors:{400:"Session does not have an independent workspace",404:"Session not found",500:"Failed to delete workspace"}})}},W=class{static getApiVaults(){return v(g,{method:"GET",url:"/api/vaults"})}static postApiVaults({requestBody:t}){return v(g,{method:"POST",url:"/api/vaults",body:t,mediaType:"application/json",errors:{400:"Bad Request",500:"Internal Server Error"}})}static putApiVaults({id:t,requestBody:e}){return v(g,{method:"PUT",url:"/api/vaults/{id}",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static deleteApiVaults({id:t,deleteLocalFiles:e=!1}){return v(g,{method:"DELETE",url:"/api/vaults/{id}",path:{id:t},query:{deleteLocalFiles:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFiles({id:t,path:e}){return v(g,{method:"GET",url:"/api/vaults/{id}/files",path:{id:t},query:{path:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFilesContent({id:t,path:e}){return v(g,{method:"GET",url:"/api/vaults/{id}/files/content",path:{id:t},query:{path:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}};function ft(t,e,u){return v(g,{method:"POST",url:`/api/Sessions/{sessionId}/${e}`,path:{sessionId:t},body:u,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}function fe(){return{listSessions:t=>H.getApiSessions(t),getSession:t=>H.getApiSessions1({sessionId:t}),createProposalSession:t=>H.postApiSessions({requestBody:t}),createChatSession:t=>H.postApiSessionsChat({requestBody:t}),createAutoTaskSession:t=>H.postApiSessionsAutoTask({requestBody:t}),updateSession:(t,e)=>H.putApiSessions({sessionId:t,requestBody:e}),deleteSession:(t,e)=>H.deleteApiSessions({sessionId:t,deleteFiles:e}),sendMessage:(t,e)=>H.postApiSessionsMessages({sessionId:t,requestBody:e}),generateProposalName:t=>ft(t,"generate-proposal-name"),optimizeDescription:(t,e)=>ft(t,"optimize-description",e),generateProposal:(t,e)=>H.postApiSessionsGenerateProposal({sessionId:t,requestBody:e}),executeProposal:(t,e)=>H.postApiSessionsExecuteProposal({sessionId:t,requestBody:e}),archiveProposal:(t,e)=>H.postApiSessionsArchive({sessionId:t,requestBody:e}),completeProposal:t=>H.postApiSessionsComplete({sessionId:t}),submitAnnotations:(t,e)=>H.postApiSessionsAnnotations({sessionId:t,requestBody:e}),listProjects:()=>me.getApiDataAggregation(),createProject:t=>et.postApiProject({requestBody:t}),updateProject:(t,e)=>et.putApiProject({id:t,requestBody:e}),deleteProject:t=>et.deleteApiProject({id:t}),listVaults:()=>W.getApiVaults(),createVault:t=>W.postApiVaults({requestBody:t}),updateVault:(t,e)=>W.putApiVaults({id:t,requestBody:e}),deleteVault:(t,e)=>W.deleteApiVaults({id:t,deleteLocalFiles:e}),listVaultFiles:(t,e)=>W.getApiVaultsFiles({id:t,path:e}),previewVaultFile:(t,e)=>W.getApiVaultsFilesContent({id:t,path:e}),archiveChat:t=>H.postApiSessionsArchiveChat({sessionId:t})}}function I(t){const e=t?.trim();return e||void 0}function V(t,e){const u=I(t);if(!u)throw new N(`${e} is required.`);return u}function It(t){const e=t?.map(u=>I(u)).filter(Boolean);return e&&e.length>0?e:void 0}function wt(t=process.env,e={stdout:u=>{process.stdout.write(u)},stderr:u=>{process.stderr.write(u)}}){return{api:fe(),env:t,io:e}}function ge(t){return t.option("--base-url <url>","Backend API base URL. Defaults to HAGI_API_BASE_URL or the local dev URL.").option("--token <token>","Bearer token for backend API calls. Overrides HAGI_API_TOKEN.").option("--lang <lang>","Accept-Language value for backend API calls. Overrides HAGI_API_LANG.")}function P(t){return t.option("--json","Emit deterministic JSON instead of human-readable text.")}function T(t,e){const u=t.optsWithGlobals();return{api:e.api,env:e.env,io:e.io,outputJson:u.json===!0,runtime:Xt({baseUrl:u.baseUrl,token:u.token,lang:u.lang},e.env)}}function ve(t,e){P(t.command("create").description("Create an AutoTask session through the dedicated generated endpoint.")).requiredOption("--title <title>","AutoTask session title.").requiredOption("--project-id <id>","Owning project id.").requiredOption("--prompt-id <id>","Prompt template id.").option("--message <text>","Optional custom message override.").option("--preset-id <id>","Optional preset id.").option("--repository-path <path>","Optional MonoSpecs repository path.").option("--project-ids <ids...>","Optional extra project ids for multi-project flows.").option("--need-push","Request push after commit creation when supported.").option("--target-branch-mode <mode>","Optional target branch mode.").option("--target-branch-name <name>","Optional custom target branch name.").option("--script-key <key>","Optional stable dungeon script key.").option("--hero-id <id>","Optional preferred hero id.").action(async function(o){if(o.targetBranchName&&o.targetBranchMode!=="new-custom")throw new N("--target-branch-name requires --target-branch-mode new-custom.");if(o.targetBranchMode==="new-custom"&&!I(o.targetBranchName))throw new N("--target-branch-name is required when --target-branch-mode is new-custom.");const i=T(this,e),r={title:V(o.title,"--title"),projectId:V(o.projectId,"--project-id"),promptId:V(o.promptId,"--prompt-id"),message:I(o.message),presetId:I(o.presetId),repositoryPath:I(o.repositoryPath),projectIds:It(o.projectIds),needPush:o.needPush?!0:void 0,targetBranchMode:I(o.targetBranchMode),targetBranchName:I(o.targetBranchName),scriptKey:I(o.scriptKey),heroId:I(o.heroId)},a=G(await i.api.createAutoTaskSession(r));if(i.outputJson){i.io.stdout(w({session:a,promptId:r.promptId,requested:r}));return}i.io.stdout(`AutoTask session created
37
- ${M(a,[["promptId",r.promptId],["repositoryPath",r.repositoryPath],["targetBranchMode",r.targetBranchMode],["targetBranchName",r.targetBranchName],["scriptKey",r.scriptKey],["heroId",r.heroId]])}`)})}var X=(function(t){return t.CLAUDE_CODE_CLI="ClaudeCodeCli",t.CODEX_CLI="CodexCli",t.GIT_HUB_COPILOT="GitHubCopilot",t.CODEBUDDY_CLI="CodebuddyCli",t.OPEN_CODE_CLI="OpenCodeCli",t.IFLOW_CLI="IFlowCli",t.HERMES_CLI="HermesCli",t.QODER_CLI="QoderCli",t.KIRO_CLI="KiroCli",t.KIMI_CLI="KimiCli",t.GEMINI_CLI="GeminiCli",t.DEEP_AGENTS_CLI="DeepAgentsCli",t})({}),ut=(function(t){return t.READONLY="Readonly",t.EDIT="Edit",t})({});function Oe(t,e){P(t.command("send").description("Send a follow-up message to an AutoTask session.")).requiredOption("--session-id <id>","AutoTask session id.").requiredOption("--content <text>","Message content.").addOption(new k("--mode <mode>","Message mode override.").choices(Object.values(ut))).addOption(new k("--executor-type <type>","Executor override for this message.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.sendMessage(r,{content:V(o.content,"--content"),mode:o.mode,executorType:o.executorType});if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message,requested:{mode:o.mode,executorType:o.executorType}}));return}i.io.stdout(rt("AutoTask message sent",r,a,[["mode",o.mode],["executorType",o.executorType]]))})}function ye(t,e){const u=t.command("autotask").description("Manage AutoTask sessions.");ve(u,e),Oe(u,e)}function Ce(t,e){P(t.command("archive").description("Archive a chat session through the dedicated chat archive endpoint.")).requiredOption("--session-id <id>","Chat session id to archive.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.archiveChat(r);if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message}));return}i.io.stdout(`Chat archived
38
- sessionId ${r}
39
- message ${a.message}
40
- `)})}function Ae(t,e){P(t.command("create").description("Create a normal chat session.")).requiredOption("--title <title>","Chat session title.").requiredOption("--project-id <id>","Owning project id.").option("--hero-id <id>","Optional bound hero id.").addOption(new k("--executor-type <type>","Optional executor override.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=G(await i.api.createChatSession({title:V(o.title,"--title"),projectId:V(o.projectId,"--project-id"),heroId:I(o.heroId),executorType:o.executorType}));if(i.outputJson){i.io.stdout(w({session:r}));return}i.io.stdout(`Chat session created
41
- ${M(r)}`)})}function _e(t,e){P(t.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.deleteSession(r,!1);if(i.outputJson){i.io.stdout(w({sessionId:r,deleted:!0,message:a.message}));return}i.io.stdout(`Chat deleted
42
- sessionId ${r}
43
- message ${a.message}
44
- `)})}var ct=(function(t){return t.CHAT="Chat",t.PROPOSAL="Proposal",t})({});function Se(t,e){P(t.command("list").description("List normal chat sessions.")).action(async function(o){if(o.projectId&&o.projectIds?.length)throw new N("Use either --project-id or --project-ids, not both.");const i=T(this,e),r=_t(await i.api.listSessions({type:ct.CHAT,projectId:I(o.projectId),projectIds:It(o.projectIds),activeOnly:o.activeOnly?!0:void 0,includeArchived:o.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(St("Chat sessions",r.sessions))}).option("--project-id <id>","Filter chat sessions by a single project id.").option("--project-ids <ids...>","Filter chat sessions by multiple project ids.").option("--active-only","Only return non-archived chat sessions.").option("--include-archived","Include archived chat sessions.")}function be(t,e){P(t.command("send").description("Send a follow-up message to a chat session.")).requiredOption("--session-id <id>","Chat session id.").requiredOption("--content <text>","Message content.").addOption(new k("--mode <mode>","Message mode override.").choices(Object.values(ut))).addOption(new k("--executor-type <type>","Executor override for this message.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.sendMessage(r,{content:V(o.content,"--content"),mode:o.mode,executorType:o.executorType});if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message,requested:{mode:o.mode,executorType:o.executorType}}));return}i.io.stdout(rt("Chat message sent",r,a,[["mode",o.mode],["executorType",o.executorType]]))})}function Ee(t,e){const u=t.command("chat").description("Manage normal chat sessions.");Se(u,e),Ae(u,e),Ce(u,e),_e(u,e),be(u,e)}function R(t){const e=t?.trim();return e||void 0}function lt(t){return{id:R(t.id)??"",name:R(t.name)??"",path:R(t.path)??"",description:R(t.description),isMonoSpecs:t.isMonoSpecs===!0,monoSpecsVersion:R(t.monoSpecsVersion),monoSpecsRepoDirectory:R(t.monoSpecsRepoDirectory),monoSpecsCommitWhenArchive:typeof t.monoSpecsCommitWhenArchive=="boolean"?t.monoSpecsCommitWhenArchive:void 0,hasError:"hasError"in t?t.hasError===!0:!1,error:"error"in t?R(t.error):void 0}}function Pt(t){return{projects:(t??[]).map(lt)}}function Ie(t){return t.length===0?`No projects found.
45
- `:`Projects (${t.length})
46
- ${Y([{header:"Project ID",value:e=>e.id},{header:"Name",value:e=>e.name},{header:"Path",value:e=>e.path},{header:"MonoSpecs",value:e=>e.isMonoSpecs?"yes":"no"},{header:"Error",value:e=>e.hasError?"yes":"no"}],t)}
47
- `}function Tt(t,e=[]){return L([["id",t.id],["name",t.name],["path",t.path],["description",t.description],["isMonoSpecs",String(t.isMonoSpecs)],["monoSpecsVersion",t.monoSpecsVersion],["monoSpecsRepoDirectory",t.monoSpecsRepoDirectory],["monoSpecsCommitWhenArchive",typeof t.monoSpecsCommitWhenArchive=="boolean"?String(t.monoSpecsCommitWhenArchive):void 0],["hasError",String(t.hasError)],["error",t.error],...e])}function we(t,e){P(t.command("create").description("Create a project through the generated project client.")).requiredOption("--name <name>","Project display name.").requiredOption("--path <path>","Project root path.").option("--description <text>","Optional project description.").action(async function(o){const i=T(this,e),r=lt(await i.api.createProject({name:V(o.name,"--name"),path:V(o.path,"--path"),description:I(o.description)}));if(i.outputJson){i.io.stdout(w({project:r}));return}i.io.stdout(`Project created
48
- ${Tt(r)}`)})}function Pe(t,e){P(t.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(o){const i=T(this,e),r=o.id.trim();if(await i.api.deleteProject(r),i.outputJson){i.io.stdout(w({projectId:r,deleted:!0}));return}i.io.stdout(`Project deleted
49
- projectId ${r}
50
- `)})}function Te(t,e){P(t.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const o=T(this,e),i=Pt((await o.api.listProjects()).projects);if(o.outputJson){o.io.stdout(w(i));return}o.io.stdout(Ie(i.projects))})}function xe(t,e){P(t.command("update").description("Update a project by merging provided fields into the aggregation snapshot.")).requiredOption("--id <id>","Project id to update.").option("--name <name>","Updated project name.").option("--path <path>","Updated project path.").option("--description <text>","Updated project description.").option("--clear-description","Clear the stored description.").action(async function(o){if(!o.name&&!o.path&&!o.description&&!o.clearDescription)throw new N("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(o.description&&o.clearDescription)throw new N("Use either --description or --clear-description, not both.");const i=T(this,e),r=o.id.trim(),a=Pt((await i.api.listProjects()).projects).projects.find(h=>h.id===r);if(!a)throw new ot(404,`Project ${r} was not found in the aggregation snapshot.`);const c=lt(await i.api.updateProject(r,{name:I(o.name)??a.name,path:I(o.path)??a.path,description:o.clearDescription?null:I(o.description)??a.description??null}));if(i.outputJson){i.io.stdout(w({project:c}));return}i.io.stdout(`Project updated
51
- ${Tt(c)}`)})}function je(t,e){const u=t.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");Te(u,e),we(u,e),xe(u,e),Pe(u,e)}async function $e(){const t=[];for await(const e of Gt.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}async function Ve(t){const e=t.trim();if(!e)throw new N("Provide --input <file> or --input - for stdin.");const u=e==="-"?await $e():await(0,Bt.readFile)(e,"utf8");try{return JSON.parse(u)}catch(o){throw new N(`Invalid JSON input from ${e}: ${o instanceof Error?o.message:String(o)}`)}}function De(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw new N("Annotation input must be a JSON object.");const u=e;if(!Array.isArray(u.files))throw new N("Annotation input must include a files array.");const o=typeof u.totalAnnotations=="number"?u.totalAnnotations:u.files.length,i=typeof u.submittedAt=="string"&&u.submittedAt.trim()?u.submittedAt:new Date().toISOString();return{...u,sessionId:t,totalAnnotations:o,submittedAt:i,files:u.files}}function Ne(t,e){P(t.command("annotate").description("Submit proposal annotations from structured JSON input.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=De(r,await Ve(o.input)),c=await i.api.submitAnnotations(r,a);if(i.outputJson){i.io.stdout(w({sessionId:r,message:c.message,annotationCount:c.annotationCount??a.totalAnnotations,fileCount:c.fileCount??a.files.length}));return}i.io.stdout(`Proposal annotations submitted
52
- sessionId ${r}
53
- message ${c.message}
54
- annotationCount ${c.annotationCount??a.totalAnnotations}
55
- fileCount ${c.fileCount??a.files.length}
56
- `)})}function He(t,e){P(t.command("archive").description("Archive a proposal session through the explicit archive endpoint.")).requiredOption("--session-id <id>","Proposal session id to archive.").option("--hero-id <id>","Optional hero override for archiving.").action(async function(o){const i=T(this,e),r=G(await i.api.archiveProposal(o.sessionId.trim(),{heroId:I(o.heroId)}));if(i.outputJson){i.io.stdout(w({session:r}));return}i.io.stdout(`Proposal archive started
57
- ${M(r)}`)})}function Fe(t,e){P(t.command("complete").description("Mark a proposal session as completed through the dedicated completion endpoint.")).requiredOption("--session-id <id>","Proposal session id to complete.").action(async function(o){const i=T(this,e),r=G(await i.api.completeProposal(o.sessionId.trim()));if(i.outputJson){i.io.stdout(w({session:r}));return}i.io.stdout(`Proposal completed
58
- ${M(r)}`)})}function qe(t){return G(t)}function ke(t){return _t(t)}function Re(t){return St("Proposal sessions",t)}function Ue(t,e=[]){return M(t,e)}var xt="New Proposal";function Le(t){const e=I(t.title);if(e)return e;if(t.defaultTitle)return xt;throw new N("Provide --title or pass --default-title to use the placeholder proposal title.")}function Ge(t,e){P(t.command("create").description("Create a proposal session only. This command does not trigger later lifecycle APIs.")).requiredOption("--project-id <id>","Project id that owns the new proposal session.").requiredOption("--chief-complaint <text>","Proposal chief complaint to store on the new session.").option("--original-chief-complaint <text>","Optional raw chief complaint text to keep alongside the stitched content.").option("--title <title>","Explicit proposal session title.").option("--default-title",`Mark the title as the placeholder title (${xt}).`).option("--enable-independent-workspace","Request an independent workspace for the proposal session.").option("--base-branch <branch>","Optional base branch for the independent workspace.").action(async function(o){const i=T(this,e),r=Le(o),a=qe(await i.api.createProposalSession({title:r,chiefComplaint:o.chiefComplaint.trim(),originalChiefComplaint:I(o.originalChiefComplaint),type:ct.PROPOSAL,projectId:o.projectId.trim(),enableIndependentWorkspace:o.enableIndependentWorkspace?!0:void 0,baseBranch:I(o.baseBranch),isDefaultTitle:!!o.defaultTitle})),c=`hagi proposal generate-name --session-id ${a.sessionId}`;if(i.outputJson){i.io.stdout(w({session:a,nextCommand:c}));return}i.io.stdout(`Proposal session created
59
- ${Ue(a,[["next",c]])}`)})}function Be(t,e){P(t.command("execute").description("Start proposal execution only. This command maps to the execute-proposal backend action.")).requiredOption("--session-id <id>","Proposal session id to execute.").option("--hero-id <id>","Optional hero override for the execute stage.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=I(o.heroId),c=await i.api.executeProposal(r,{heroId:a});if(i.outputJson){i.io.stdout(w({sessionId:r,message:c.message,requested:{heroId:a}}));return}i.io.stdout(`Proposal execution started
60
- sessionId ${r}
61
- message ${c.message}
62
- `)})}function We(t){if(t.enableExploreMode&&t.disableExploreMode)throw new N("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(t.enableExploreMode)return!0;if(t.disableExploreMode)return!1}function Me(t,e){P(t.command("generate").description("Start proposal generation only. This command does not execute the proposal.")).requiredOption("--session-id <id>","Proposal session id to generate.").option("--enable-explore-mode","Explicitly enable explore mode for proposal generation.").option("--disable-explore-mode","Explicitly disable explore mode for proposal generation.").option("--hero-id <id>","Optional hero override for the generate stage.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=We(o),c=await i.api.generateProposal(r,{enableExploreMode:a,heroId:I(o.heroId)}),h=`hagi proposal execute --session-id ${r}`;if(i.outputJson){i.io.stdout(w({sessionId:r,message:c.message,requested:{enableExploreMode:a,heroId:I(o.heroId)},nextCommand:h}));return}i.io.stdout(`Proposal generation started
63
- sessionId ${r}
64
- message ${c.message}
65
- next Wait for the session to reach Reviewing, then run ${h}
66
- `)})}function Je(t,e){P(t.command("generate-name").description("Generate a proposal name only. This command maps to the generate-proposal-name backend action.")).requiredOption("--session-id <id>","Proposal session id to update.").action(async function(o){const i=T(this,e),r=await i.api.generateProposalName(o.sessionId.trim()),a=`hagi proposal generate --session-id ${o.sessionId.trim()}`;if(i.outputJson){i.io.stdout(w({sessionId:o.sessionId.trim(),proposalName:r.proposalName,nextCommand:a}));return}i.io.stdout(`Proposal name generated
67
- sessionId ${o.sessionId.trim()}
68
- proposalName ${r.proposalName}
69
- next ${a}
70
- `)})}function ze(t,e){P(t.command("list").description("List proposal sessions from the backend Sessions API.")).option("--project-id <id>","Filter proposal sessions by a single project id.").option("--project-ids <ids...>","Filter proposal sessions by multiple project ids.").option("--active-only","Only return non-archived proposal sessions.").option("--include-archived","Include archived proposal sessions in the result set.").action(async function(o){if(o.projectId&&o.projectIds?.length)throw new N("Use either --project-id or --project-ids, not both.");const i=T(this,e),r=ke(await i.api.listSessions({type:ct.PROPOSAL,projectId:I(o.projectId),projectIds:o.projectIds?.map(I).filter(Boolean),activeOnly:o.activeOnly?!0:void 0,includeArchived:o.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(Re(r.sessions))})}function Ke(t,e){P(t.command("optimize-description").description("Start asynchronous proposal description optimization only.")).requiredOption("--session-id <id>","Proposal session id to optimize.").requiredOption("--description <text>","Description text to optimize.").option("--optimization-direction <text>","Optional optimization direction for AI guidance.").option("--disable-memory-optimization","Disable long-term memory during optimization.").option("--default-title","Treat the current title as a placeholder title.").action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.optimizeDescription(r,{description:V(o.description,"--description"),optimizationDirection:I(o.optimizationDirection),enableMemoryOptimization:o.disableMemoryOptimization?!1:void 0,isDefaultTitle:o.defaultTitle?!0:void 0});if(i.outputJson){i.io.stdout(w({sessionId:r,taskId:a.taskId,status:a.status}));return}i.io.stdout(`Proposal description optimization started
71
- sessionId ${r}
72
- taskId ${a.taskId??""}
73
- status ${a.status??""}
74
- `)})}function Qe(t,e){P(t.command("send").description("Send a follow-up message to a proposal session.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--content <text>","Message content.").addOption(new k("--mode <mode>","Message mode override.").choices(Object.values(ut))).addOption(new k("--executor-type <type>","Executor override for this message.").choices(Object.values(X))).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.sendMessage(r,{content:V(o.content,"--content"),mode:o.mode,executorType:o.executorType});if(i.outputJson){i.io.stdout(w({sessionId:r,message:a.message,requested:{mode:o.mode,executorType:o.executorType}}));return}i.io.stdout(rt("Proposal message sent",r,a,[["mode",o.mode],["executorType",o.executorType]]))})}function Ye(t,e){P(t.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new k("--status <status>","Target session status.").choices(Object.values(Ct)).makeOptionMandatory()).action(async function(o){const i=T(this,e),r=o.sessionId.trim(),a=await i.api.getSession(r);await i.api.updateSession(r,{title:a.title,description:a.description,status:o.status,metadata:a.metadata});const c=G({...a,status:o.status});if(i.outputJson){i.io.stdout(w({session:c}));return}i.io.stdout(`Proposal status updated
75
- ${M(c)}`)})}function Xe(t,e){const u=t.command("proposal").description("Manage proposal sessions through backend session APIs.");ze(u,e),Ge(u,e),Je(u,e),Ke(u,e),Me(u,e),Ne(u,e),Be(u,e),He(u,e),Ye(u,e),Fe(u,e),Qe(u,e)}function E(t){const e=t?.trim();return e||void 0}function Ze(t){return{severity:E(t.severity)??"",code:E(t.code)??"",message:E(t.message)??"",relativePath:E(t.relativePath)}}function dt(t){return{id:E(t.id)??"",name:E(t.name)??"",type:E(t.type)??"",physicalPath:E(t.physicalPath)??"",gitUrl:E(t.gitUrl),createdAtUtc:E(t.createdAtUtc),updatedAtUtc:E(t.updatedAtUtc),bootstrapDiagnostics:(t.bootstrapDiagnostics??[]).map(Ze)}}function jt(t){return{generatedAtUtc:E(t.generatedAtUtc),vaults:(t.items??[]).map(dt)}}function ti(t){return t.length===0?`No vaults found.
76
- `:`Vaults (${t.length})
77
- ${Y([{header:"Vault ID",value:e=>e.id},{header:"Type",value:e=>e.type},{header:"Name",value:e=>e.name},{header:"Path",value:e=>e.physicalPath}],t)}
78
- `}function $t(t,e=[]){return L([["id",t.id],["name",t.name],["type",t.type],["physicalPath",t.physicalPath],["gitUrl",t.gitUrl],["createdAtUtc",t.createdAtUtc],["updatedAtUtc",t.updatedAtUtc],["bootstrapDiagnostics",String(t.bootstrapDiagnostics.length)],...e])}function ei(t){return{relativePath:E(t.relativePath)??"",fileName:E(t.fileName)??"",isDirectory:t.isDirectory===!0,extension:E(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:E(t.lastModifiedUtc),previewSupported:t.previewSupported===!0}}function ii(t){return{vaultId:E(t.id)??"",deleted:t.deleted===!0,deleteLocalFilesRequested:t.deleteLocalFilesRequested===!0,localFilesDeletionStatus:E(t.localFilesDeletionStatus),localFilesDeleted:t.localFilesDeleted===!0}}function si(t){return`Vault deleted
79
- ${L([["vaultId",t.vaultId],["deleted",String(t.deleted)],["deleteLocalFilesRequested",String(t.deleteLocalFilesRequested)],["localFilesDeletionStatus",t.localFilesDeletionStatus],["localFilesDeleted",String(t.localFilesDeleted)]])}`}function ri(t){return{vaultId:E(t.vaultId)??"",vaultName:E(t.vaultName)??"",physicalPath:E(t.physicalPath)??"",status:E(t.status)??"",errorCode:E(t.errorCode),message:E(t.message),isTruncated:t.isTruncated===!0,totalFileCount:typeof t.totalFileCount=="number"?t.totalFileCount:0,items:(t.items??[]).map(ei)}}function oi(t){const e=L([["vaultId",t.vaultId],["vaultName",t.vaultName],["physicalPath",t.physicalPath],["status",t.status],["errorCode",t.errorCode],["message",t.message],["isTruncated",String(t.isTruncated)],["totalFileCount",String(t.totalFileCount)]]);return t.items.length===0?`Vault files
80
- ${e}No files found.
81
- `:`Vault files
82
- ${e}${Y([{header:"Relative Path",value:u=>u.relativePath},{header:"Directory",value:u=>u.isDirectory?"yes":"no"},{header:"Extension",value:u=>u.extension},{header:"Size",value:u=>String(u.sizeBytes)},{header:"Preview",value:u=>u.previewSupported?"yes":"no"}],t.items)}
83
- `}function ni(t){return{vaultId:E(t.vaultId)??"",vaultName:E(t.vaultName)??"",physicalPath:E(t.physicalPath)??"",relativePath:E(t.relativePath)??"",fileName:E(t.fileName)??"",extension:E(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:E(t.lastModifiedUtc),status:E(t.status)??"",errorCode:E(t.errorCode),message:E(t.message),previewSupported:t.previewSupported===!0,contentTruncated:t.contentTruncated===!0,content:E(t.content)}}function ai(t){const e=L([["vaultId",t.vaultId],["vaultName",t.vaultName],["physicalPath",t.physicalPath],["relativePath",t.relativePath],["fileName",t.fileName],["extension",t.extension],["sizeBytes",String(t.sizeBytes)],["lastModifiedUtc",t.lastModifiedUtc],["status",t.status],["errorCode",t.errorCode],["message",t.message],["previewSupported",String(t.previewSupported)],["contentTruncated",String(t.contentTruncated)]]);if(!t.content)return`Vault file preview
84
- ${e}`;const u=t.content.endsWith(`
85
- `)?"":`
86
- `;return`Vault file preview
87
- ${e}content
88
- -------
89
- ${t.content}${u}`}function ui(t,e){P(t.command("create").description("Create a vault through the generated vault client.")).requiredOption("--name <name>","Vault display name.").requiredOption("--type <type>","Vault type, such as folder, obsidian, or coderef.").requiredOption("--physical-path <path>","Vault physical path.").option("--git-url <url>","Optional git remote URL for git-backed vaults.").action(async function(o){const i=T(this,e),r=dt(await i.api.createVault({name:V(o.name,"--name"),type:V(o.type,"--type"),physicalPath:V(o.physicalPath,"--physical-path"),gitUrl:I(o.gitUrl)}));if(i.outputJson){i.io.stdout(w({vault:r}));return}i.io.stdout(`Vault created
90
- ${$t(r)}`)})}function ci(t,e){P(t.command("delete").description("Delete a vault by id and optionally request local file cleanup.")).requiredOption("--id <id>","Vault id to delete.").option("--delete-local-files","Request backend deletion of local vault files.").action(async function(o){const i=T(this,e),r=ii(await i.api.deleteVault(V(o.id,"--id"),o.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(si(r))})}function li(t,e){P(t.command("list").description("List files under a registered vault path.")).requiredOption("--id <id>","Vault id to browse.").option("--path <path>","Optional relative path under the vault root.").action(async function(o){const i=T(this,e),r=ri(await i.api.listVaultFiles(V(o.id,"--id"),I(o.path)));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(oi(r))})}function di(t,e){P(t.command("preview").description("Preview supported file content from a registered vault.")).requiredOption("--id <id>","Vault id to browse.").requiredOption("--path <path>","Relative file path to preview.").action(async function(o){const i=T(this,e),r=ni(await i.api.previewVaultFile(V(o.id,"--id"),V(o.path,"--path")));if(i.outputJson){i.io.stdout(w(r));return}i.io.stdout(ai(r))})}function pi(t,e){P(t.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const o=T(this,e),i=jt(await o.api.listVaults());if(o.outputJson){o.io.stdout(w(i));return}o.io.stdout(ti(i.vaults))})}function hi(t,e){P(t.command("update").description("Update a vault by merging provided fields into the current vault snapshot.")).requiredOption("--id <id>","Vault id to update.").option("--name <name>","Updated vault display name.").option("--type <type>","Updated vault type.").option("--physical-path <path>","Updated vault physical path.").option("--git-url <url>","Updated git remote URL.").action(async function(o){const i=I(o.name),r=I(o.type),a=I(o.physicalPath),c=I(o.gitUrl);if(!i&&!r&&!a&&!c)throw new N("Provide at least one field to update: --name, --type, --physical-path, or --git-url.");const h=T(this,e),O=V(o.id,"--id"),A=jt(await h.api.listVaults()).vaults.find(_=>_.id===O);if(!A)throw new ot(404,`Vault ${O} was not found in the latest vault snapshot.`);const C=dt(await h.api.updateVault(O,{name:i??A.name,type:r??A.type,physicalPath:a??A.physicalPath,gitUrl:c??A.gitUrl??null}));if(h.outputJson){h.io.stdout(w({vault:C}));return}h.io.stdout(`Vault updated
91
- ${$t(C)}`)})}function mi(t,e){const u=t.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");pi(u,e),ui(u,e),hi(u,e),ci(u,e);const o=u.command("files").description("Browse registered vault files and preview supported content.");li(o,e),di(o,e)}function fi(t){return t.includes("--json")}function Vt(t=wt(),e=!1){const u=new Qt;return u.name("hagi").description("HagiCode CLI for project, proposal, vault, chat, and AutoTask management.").showHelpAfterError().exitOverride(),u.configureOutput({writeOut:o=>{t.io.stdout(o)},writeErr:o=>{e||t.io.stderr(o)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),ge(u),je(u,t),Xe(u,t),mi(u,t),Ee(u,t),ye(u,t),u}function gi(t,e,u){return t.exitCode===0||t.code==="commander.helpDisplayed"||t.code==="commander.version"?0:(u&&e.io.stderr(bt({exitCode:D.USAGE,message:t.message},{json:!0})),D.USAGE)}async function vi(t=process.argv,e=wt()){const u=fi(t),o=Vt(e,u);try{return await o.parseAsync([...t]),0}catch(i){if(i instanceof Kt)return gi(i,e,u);const r=ee(i);return e.io.stderr(bt(r,{json:u})),r.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return D}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return Vt}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return vi}});