@hagicode/cli 0.1.0-dev.18.1.f7fa085 → 0.1.0-dev.20.1.7843819

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![license](https://img.shields.io/npm/l/%40hagicode%2Fcli?color=ffd43b)](https://www.npmjs.com/package/@hagicode/cli)
6
6
  [![Node.js](https://img.shields.io/badge/node-%3E%3D24.0.0-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
7
7
 
8
- `@hagicode/cli` provides the published `hagi` command for project, proposal, vault, chat, and AutoTask management against a HagiCode backend API.
8
+ `@hagicode/cli` provides the published `hagi` command for project, proposal, vault, chat, AutoTask, and scheduled plan management against a HagiCode backend API.
9
9
  The same repository also carries the canonical embedded Hagi skill under [`skills/`](skills/), so package usage and AI-oriented guidance live in one writable source.
10
10
 
11
11
  ## Requirements
@@ -118,6 +118,7 @@ hagi
118
118
  | `-- files list | preview
119
119
  |-- chat list | create | archive | delete | send
120
120
  |-- autotask create | send
121
+ |-- plan list | get | create | update | enable | disable | delete | run
121
122
  `-- skills local list | uninstall
122
123
  gallery search | detail | install
123
124
  trusted list | upsert | delete | reset
@@ -324,6 +325,126 @@ Send a follow-up message to the AutoTask session:
324
325
  hagi autotask send --session-id "$AUTOTASK_ID" --content "Retry with a smaller diff"
325
326
  ```
326
327
 
328
+ ## Plan Commands
329
+
330
+ A scheduled plan saves a proposal or HagiTask input with a schedule and an agent pool. The backend runs it on that schedule. `plan list` and `plan get` show the plans that exist:
331
+
332
+ ```bash
333
+ hagi plan list
334
+ hagi plan list --json
335
+ hagi plan get --id "$PLAN_ID"
336
+ hagi plan get --id "$PLAN_ID" --json | jq .plan
337
+ ```
338
+
339
+ `plan list` prints one row per plan with its schedule summary, and an explicit message when there are none. `--json` prints `{ "plans": [...] }`, where each entry carries `id`, `type`, `name`, `enabled`, `state`, `nextRunAt`, `schedule`, `agentPool` and `payload` exactly as the backend returns them. `plan get --json` prints `{ "plan": {...} }` with the same fields.
340
+
341
+ ### Create a plan
342
+
343
+ `plan create` reads a plan document with `--input <file>` or `--input -` for stdin. A recurring HagiTask plan:
344
+
345
+ ```json
346
+ {
347
+ "type": "hagitask",
348
+ "name": "Nightly review",
349
+ "enabled": true,
350
+ "schedule": {
351
+ "mode": "recurring",
352
+ "timeZone": "Asia/Shanghai",
353
+ "startDate": "2026-05-01",
354
+ "endDate": "2026-05-31",
355
+ "timeOfDay": "02:00",
356
+ "repeat": { "rule": "daily", "weekdays": [] }
357
+ },
358
+ "agentPool": { "strategy": "random", "agents": [ { "heroId": "5de02573-0000-4000-8000-000000000001" } ] },
359
+ "payload": {
360
+ "projectId": "11111111-2222-3333-4444-555555555555",
361
+ "presetTaskId": "nightly-review"
362
+ }
363
+ }
364
+ ```
365
+
366
+ A one-time proposal plan runs once at `runAt` and has no time zone or repeat fields:
367
+
368
+ ```json
369
+ {
370
+ "type": "proposal",
371
+ "name": "Weekly triage",
372
+ "schedule": { "mode": "once", "runAt": "2026-06-12T10:30:00Z" },
373
+ "payload": {
374
+ "title": "Weekly triage",
375
+ "chiefComplaint": "Triage the open issues and propose the next sprint",
376
+ "projectId": "11111111-2222-3333-4444-555555555555"
377
+ }
378
+ }
379
+ ```
380
+
381
+ ```bash
382
+ hagi plan create --input nightly-review.json
383
+ hagi plan create --input weekly-triage.json --disabled
384
+ PLAN_ID=$(hagi plan create --input nightly-review.json --json | json_field '.plan.id')
385
+ ```
386
+
387
+ A plan is **enabled by default**. `create` sends `enabled: true` unless the document sets `enabled` or you pass `--disabled`. `--name` and `--hero-id` replace the document's `name` and agent pool, and `--hero-id` builds the single-agent `random` pool. Server-owned fields (`id`, `createdAt`, `updatedAt`, `state`, `nextRunAt`) in the document are ignored.
388
+
389
+ ### Update, enable, disable and delete
390
+
391
+ `plan update` reads the current plan, applies your changes and sends the full plan back, so fields you do not mention keep their values:
392
+
393
+ ```bash
394
+ hagi plan update --id "$PLAN_ID" --name "Nightly review (EU)"
395
+ hagi plan update --id "$PLAN_ID" --input changes.json
396
+ hagi plan update --id "$PLAN_ID" --hero-id 5de02573-0000-4000-8000-000000000002 --enabled
397
+ ```
398
+
399
+ `--input` on update is a **shallow merge** over the top-level keys of the plan (`type`, `name`, `enabled`, `schedule`, `agentPool`, `payload`). Each key in the file replaces the current value as a whole, and keys missing from the file are kept. A `schedule` in the file replaces the whole current schedule, so write the complete object, without the fields you want removed (for example `endDate`). Passing `--enabled` and `--disabled` together is a usage error, and so is an update with no change.
400
+
401
+ `enable` and `disable` change only the enabled flag. When the plan already has that flag, nothing is sent and the output says so:
402
+
403
+ ```bash
404
+ hagi plan disable --id "$PLAN_ID"
405
+ hagi plan enable --id "$PLAN_ID" --json
406
+ ```
407
+
408
+ Delete a plan. It never runs again:
409
+
410
+ ```bash
411
+ hagi plan delete --id "$PLAN_ID"
412
+ hagi plan delete --id "$PLAN_ID" --json
413
+ ```
414
+
415
+ To change a plan with a text editor, take the current document, edit it and feed it back. Server-owned fields are dropped automatically:
416
+
417
+ ```bash
418
+ hagi plan get --id "$PLAN_ID" --json | jq .plan > plan.json
419
+ # edit plan.json, then:
420
+ hagi plan update --id "$PLAN_ID" --input plan.json
421
+ ```
422
+
423
+ When the backend rejects a plan with 400 (exit code `20`), the CLI prints the summary and then one line per problem, naming its field:
424
+
425
+ ```text
426
+ Scheduled plan is invalid. (status=400)
427
+ - agentPool: A HagiTask plan needs an agent pool with one agent.
428
+ ```
429
+
430
+ Use `--json` to get the full backend body under `error.details`.
431
+
432
+ ### Run a plan now
433
+
434
+ `plan run` creates a session from the plan's stored inputs immediately, without waiting for the schedule. It waits for the session and prints its summary, or `{ "session": {...} }` with `--json`:
435
+
436
+ ```bash
437
+ hagi plan run --id "$PLAN_ID"
438
+ ```
439
+
440
+ `plan run --background` starts the same run and returns as soon as the backend accepts it, before the session exists. It prints the plan id and `accepted: true`. The session shows up in the normal session list:
441
+
442
+ ```bash
443
+ hagi plan run --id "$PLAN_ID" --background --json
444
+ ```
445
+
446
+ A manual run does not change the plan's state or next run time. It works for disabled and completed plans, and the next automatic run still happens on the original schedule.
447
+
327
448
  ## Skills Commands
328
449
 
329
450
  List installed local skills and remove one by name:
@@ -0,0 +1,105 @@
1
+ var Zt=Object.create,wt=Object.defineProperty,te=Object.getOwnPropertyDescriptor,ee=Object.getOwnPropertyNames,ie=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty,K=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),oe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(var i=ee(e),s=0,a=i.length,u;s<a;s++)u=i[s],!se.call(t,u)&&u!==n&&wt(t,u,{get:(h=>e[h]).bind(null,u),enumerable:!(r=te(e,u))||r.enumerable});return t},ne=(t,e,n)=>(n=t!=null?Zt(ie(t)):{},oe(e||!t||!t.__esModule?wt(n,"default",{value:t,enumerable:!0}):n,t));let bt=require("node:path"),re=require("node:fs"),ae=require("node:os"),le=require("node:fs/promises");var nt=K((t=>{var e=class extends Error{constructor(r,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=r,this.nestedError=void 0}},n=class extends e{constructor(r){super(1,"commander.invalidArgument",r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};t.CommanderError=e,t.InvalidArgumentError=n})),pt=K((t=>{var{InvalidArgumentError:e}=nt(),n=class{constructor(i,s){switch(this.description=s||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(i,s){return s===this.defaultValue||!Array.isArray(s)?[i]:(s.push(i),s)}default(i,s){return this.defaultValue=i,this.defaultValueDescription=s,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(s,a)=>{if(!this.argChoices.includes(s))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(s,a):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(i){const s=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+s+">":"["+s+"]"}t.Argument=n,t.humanReadableArgName=r})),Et=K((t=>{var{humanReadableArgName:e}=pt(),n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(i){this.helpWidth=this.helpWidth??i.helpWidth??80}visibleCommands(i){const s=i.commands.filter(u=>!u._hidden),a=i._getHelpCommand();return a&&!a._hidden&&s.push(a),this.sortSubcommands&&s.sort((u,h)=>u.name().localeCompare(h.name())),s}compareOptions(i,s){const a=u=>u.short?u.short.replace(/^-/,""):u.long.replace(/^--/,"");return a(i).localeCompare(a(s))}visibleOptions(i){const s=i.options.filter(u=>!u.hidden),a=i._getHelpOption();if(a&&!a.hidden){const u=a.short&&i._findOption(a.short),h=a.long&&i._findOption(a.long);!u&&!h?s.push(a):a.long&&!h?s.push(i.createOption(a.long,a.description)):a.short&&!u&&s.push(i.createOption(a.short,a.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const s=[];for(let a=i.parent;a;a=a.parent){const u=a.options.filter(h=>!h.hidden);s.push(...u)}return this.sortOptions&&s.sort(this.compareOptions),s}visibleArguments(i){return i._argsDescription&&i.registeredArguments.forEach(s=>{s.description=s.description||i._argsDescription[s.name()]||""}),i.registeredArguments.find(s=>s.description)?i.registeredArguments:[]}subcommandTerm(i){const s=i.registeredArguments.map(a=>e(a)).join(" ");return i._name+(i._aliases[0]?"|"+i._aliases[0]:"")+(i.options.length?" [options]":"")+(s?" "+s:"")}optionTerm(i){return i.flags}argumentTerm(i){return i.name()}longestSubcommandTermLength(i,s){return s.visibleCommands(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleSubcommandTerm(s.subcommandTerm(u)))),0)}longestOptionTermLength(i,s){return s.visibleOptions(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestGlobalOptionTermLength(i,s){return s.visibleGlobalOptions(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleOptionTerm(s.optionTerm(u)))),0)}longestArgumentTermLength(i,s){return s.visibleArguments(i).reduce((a,u)=>Math.max(a,this.displayWidth(s.styleArgumentTerm(s.argumentTerm(u)))),0)}commandUsage(i){let s=i._name;i._aliases[0]&&(s=s+"|"+i._aliases[0]);let a="";for(let u=i.parent;u;u=u.parent)a=u.name()+" "+a;return a+s+" "+i.usage()}commandDescription(i){return i.description()}subcommandDescription(i){return i.summary()||i.description()}optionDescription(i){const s=[];if(i.argChoices&&s.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&(i.required||i.optional||i.isBoolean()&&typeof i.defaultValue=="boolean")&&s.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),i.presetArg!==void 0&&i.optional&&s.push(`preset: ${JSON.stringify(i.presetArg)}`),i.envVar!==void 0&&s.push(`env: ${i.envVar}`),s.length>0){const a=`(${s.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}argumentDescription(i){const s=[];if(i.argChoices&&s.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&s.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),s.length>0){const a=`(${s.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}formatItemList(i,s,a){return s.length===0?[]:[a.styleTitle(i),...s,""]}groupItems(i,s,a){const u=new Map;return i.forEach(h=>{const v=a(h);u.has(v)||u.set(v,[])}),s.forEach(h=>{const v=a(h);u.has(v)||u.set(v,[]),u.get(v).push(h)}),u}formatHelp(i,s){const a=s.padWidth(i,s),u=s.helpWidth??80;function h(w,$){return s.formatItem(w,a,$,s)}let v=[`${s.styleTitle("Usage:")} ${s.styleUsage(s.commandUsage(i))}`,""];const _=s.commandDescription(i);_.length>0&&(v=v.concat([s.boxWrap(s.styleCommandDescription(_),u),""]));const P=s.visibleArguments(i).map(w=>h(s.styleArgumentTerm(s.argumentTerm(w)),s.styleArgumentDescription(s.argumentDescription(w))));if(v=v.concat(this.formatItemList("Arguments:",P,s)),this.groupItems(i.options,s.visibleOptions(i),w=>w.helpGroupHeading??"Options:").forEach((w,$)=>{const G=w.map(R=>h(s.styleOptionTerm(s.optionTerm(R)),s.styleOptionDescription(s.optionDescription(R))));v=v.concat(this.formatItemList($,G,s))}),s.showGlobalOptions){const w=s.visibleGlobalOptions(i).map($=>h(s.styleOptionTerm(s.optionTerm($)),s.styleOptionDescription(s.optionDescription($))));v=v.concat(this.formatItemList("Global Options:",w,s))}return this.groupItems(i.commands,s.visibleCommands(i),w=>w.helpGroup()||"Commands:").forEach((w,$)=>{const G=w.map(R=>h(s.styleSubcommandTerm(s.subcommandTerm(R)),s.styleSubcommandDescription(s.subcommandDescription(R))));v=v.concat(this.formatItemList($,G,s))}),v.join(`
2
+ `)}displayWidth(i){return r(i).length}styleTitle(i){return i}styleUsage(i){return i.split(" ").map(s=>s==="[options]"?this.styleOptionText(s):s==="[command]"?this.styleSubcommandText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleCommandText(s)).join(" ")}styleCommandDescription(i){return this.styleDescriptionText(i)}styleOptionDescription(i){return this.styleDescriptionText(i)}styleSubcommandDescription(i){return this.styleDescriptionText(i)}styleArgumentDescription(i){return this.styleDescriptionText(i)}styleDescriptionText(i){return i}styleOptionTerm(i){return this.styleOptionText(i)}styleSubcommandTerm(i){return i.split(" ").map(s=>s==="[options]"?this.styleOptionText(s):s[0]==="["||s[0]==="<"?this.styleArgumentText(s):this.styleSubcommandText(s)).join(" ")}styleArgumentTerm(i){return this.styleArgumentText(i)}styleOptionText(i){return i}styleArgumentText(i){return i}styleSubcommandText(i){return i}styleCommandText(i){return i}padWidth(i,s){return Math.max(s.longestOptionTermLength(i,s),s.longestGlobalOptionTermLength(i,s),s.longestSubcommandTermLength(i,s),s.longestArgumentTermLength(i,s))}preformatted(i){return/\n[^\S\r\n]/.test(i)}formatItem(i,s,a,u){const v=" ".repeat(2);if(!a)return v+i;const _=i.padEnd(s+i.length-u.displayWidth(i)),P=2,w=(this.helpWidth??80)-s-P-2;let $;return w<this.minWidthToWrap||u.preformatted(a)?$=a:$=u.boxWrap(a,w).replace(/\n/g,`
3
+ `+" ".repeat(s+P)),v+_+" ".repeat(P)+$.replace(/\n/g,`
4
+ ${v}`)}boxWrap(i,s){if(s<this.minWidthToWrap)return i;const a=i.split(/\r\n|\n/),u=/[\s]*[^\s]+/g,h=[];return a.forEach(v=>{const _=v.match(u);if(_===null){h.push("");return}let P=[_.shift()],w=this.displayWidth(P[0]);_.forEach($=>{const G=this.displayWidth($);if(w+G<=s){P.push($),w+=G;return}h.push(P.join(""));const R=$.trimStart();P=[R],w=this.displayWidth(R)}),h.push(P.join(""))}),h.join(`
5
+ `)}};function r(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}t.Help=n,t.stripColor=r})),Tt=K((t=>{var{InvalidArgumentError:e}=nt(),n=class{constructor(a,u){this.flags=a,this.description=u||"",this.required=a.includes("<"),this.optional=a.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(a),this.mandatory=!1;const h=s(a);this.short=h.shortFlag,this.long=h.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(a,u){return this.defaultValue=a,this.defaultValueDescription=u,this}preset(a){return this.presetArg=a,this}conflicts(a){return this.conflictsWith=this.conflictsWith.concat(a),this}implies(a){let u=a;return typeof a=="string"&&(u={[a]:!0}),this.implied=Object.assign(this.implied||{},u),this}env(a){return this.envVar=a,this}argParser(a){return this.parseArg=a,this}makeOptionMandatory(a=!0){return this.mandatory=!!a,this}hideHelp(a=!0){return this.hidden=!!a,this}_collectValue(a,u){return u===this.defaultValue||!Array.isArray(u)?[a]:(u.push(a),u)}choices(a){return this.argChoices=a.slice(),this.parseArg=(u,h)=>{if(!this.argChoices.includes(u))throw new e(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(u,h):u},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?i(this.name().replace(/^no-/,"")):i(this.name())}helpGroup(a){return this.helpGroupHeading=a,this}is(a){return this.short===a||this.long===a}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(a){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,a.forEach(u=>{u.negate?this.negativeOptions.set(u.attributeName(),u):this.positiveOptions.set(u.attributeName(),u)}),this.negativeOptions.forEach((u,h)=>{this.positiveOptions.has(h)&&this.dualOptions.add(h)})}valueFromOption(a,u){const h=u.attributeName();if(!this.dualOptions.has(h))return!0;const v=this.negativeOptions.get(h).presetArg,_=v!==void 0?v:!1;return u.negate===(_===a)}};function i(a){return a.split("-").reduce((u,h)=>u+h[0].toUpperCase()+h.slice(1))}function s(a){let u,h;const v=/^-[^-]$/,_=/^--[^-]/,P=a.split(/[ |,]+/).concat("guard");if(v.test(P[0])&&(u=P.shift()),_.test(P[0])&&(h=P.shift()),!u&&v.test(P[0])&&(u=P.shift()),!u&&_.test(P[0])&&(u=h,h=P.shift()),P[0].startsWith("-")){const w=P[0],$=`option creation failed due to '${w}' in option flags '${a}'`;throw/^-[^-][^-]/.test(w)?new Error(`${$}
6
+ - a short flag is a single dash and a single character
7
+ - either use a single dash and a single character (for a short flag)
8
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):v.test(w)?new Error(`${$}
9
+ - too many short flags`):_.test(w)?new Error(`${$}
10
+ - too many long flags`):new Error(`${$}
11
+ - unrecognised flag format`)}if(u===void 0&&h===void 0)throw new Error(`option creation failed due to no flags found in '${a}'.`);return{shortFlag:u,longFlag:h}}t.Option=n,t.DualOptions=r})),ue=K((t=>{var e=3;function n(i,s){if(Math.abs(i.length-s.length)>e)return Math.max(i.length,s.length);const a=[];for(let u=0;u<=i.length;u++)a[u]=[u];for(let u=0;u<=s.length;u++)a[0][u]=u;for(let u=1;u<=s.length;u++)for(let h=1;h<=i.length;h++){let v=1;i[h-1]===s[u-1]?v=0:v=1,a[h][u]=Math.min(a[h-1][u]+1,a[h][u-1]+1,a[h-1][u-1]+v),h>1&&u>1&&i[h-1]===s[u-2]&&i[h-2]===s[u-1]&&(a[h][u]=Math.min(a[h][u],a[h-2][u-2]+1))}return a[i.length][s.length]}function r(i,s){if(!s||s.length===0)return"";s=Array.from(new Set(s));const a=i.startsWith("--");a&&(i=i.slice(2),s=s.map(_=>_.slice(2)));let u=[],h=e;const v=.4;return s.forEach(_=>{if(_.length<=1)return;const P=n(i,_),w=Math.max(i.length,_.length);(w-P)/w>v&&(P<h?(h=P,u=[_]):P===h&&u.push(_))}),u.sort((_,P)=>_.localeCompare(P)),a&&(u=u.map(_=>`--${_}`)),u.length>1?`
12
+ (Did you mean one of ${u.join(", ")}?)`:u.length===1?`
13
+ (Did you mean ${u[0]}?)`:""}t.suggestSimilar=r})),de=K((t=>{var e=require("node:events").EventEmitter,n=require("node:child_process"),r=require("node:path"),i=require("node:fs"),s=require("node:process"),{Argument:a,humanReadableArgName:u}=pt(),{CommanderError:h}=nt(),{Help:v,stripColor:_}=Et(),{Option:P,DualOptions:w}=Tt(),{suggestSimilar:$}=ue(),G=class It extends e{constructor(o){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=o||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:l=>s.stdout.write(l),writeErr:l=>s.stderr.write(l),outputError:(l,d)=>d(l),getOutHelpWidth:()=>s.stdout.isTTY?s.stdout.columns:void 0,getErrHelpWidth:()=>s.stderr.isTTY?s.stderr.columns:void 0,getOutHasColors:()=>at()??(s.stdout.isTTY&&s.stdout.hasColors?.()),getErrHasColors:()=>at()??(s.stderr.isTTY&&s.stderr.hasColors?.()),stripColor:l=>_(l)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(o){return this._outputConfiguration=o._outputConfiguration,this._helpOption=o._helpOption,this._helpCommand=o._helpCommand,this._helpConfiguration=o._helpConfiguration,this._exitCallback=o._exitCallback,this._storeOptionsAsProperties=o._storeOptionsAsProperties,this._combineFlagAndOptionalValue=o._combineFlagAndOptionalValue,this._allowExcessArguments=o._allowExcessArguments,this._enablePositionalOptions=o._enablePositionalOptions,this._showHelpAfterError=o._showHelpAfterError,this._showSuggestionAfterError=o._showSuggestionAfterError,this}_getCommandAndAncestors(){const o=[];for(let l=this;l;l=l.parent)o.push(l);return o}command(o,l,d){let c=l,p=d;typeof c=="object"&&c!==null&&(p=c,c=null),p=p||{};const[,g,C]=o.match(/([^ ]+) *(.*)/),E=this.createCommand(g);return c&&(E.description(c),E._executableHandler=!0),p.isDefault&&(this._defaultCommandName=E._name),E._hidden=!!(p.noHelp||p.hidden),E._executableFile=p.executableFile||null,C&&E.arguments(C),this._registerCommand(E),E.parent=this,E.copyInheritedSettings(this),c?this:E}createCommand(o){return new It(o)}createHelp(){return Object.assign(new v,this.configureHelp())}configureHelp(o){return o===void 0?this._helpConfiguration:(this._helpConfiguration=o,this)}configureOutput(o){return o===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...o},this)}showHelpAfterError(o=!0){return typeof o!="string"&&(o=!!o),this._showHelpAfterError=o,this}showSuggestionAfterError(o=!0){return this._showSuggestionAfterError=!!o,this}addCommand(o,l){if(!o._name)throw new Error(`Command passed to .addCommand() must have a name
14
+ - specify the name in Command constructor or using .name()`);return l=l||{},l.isDefault&&(this._defaultCommandName=o._name),(l.noHelp||l.hidden)&&(o._hidden=!0),this._registerCommand(o),o.parent=this,o._checkForBrokenPassThrough(),this}createArgument(o,l){return new a(o,l)}argument(o,l,d,c){const p=this.createArgument(o,l);return typeof d=="function"?p.default(c).argParser(d):p.default(d),this.addArgument(p),this}arguments(o){return o.trim().split(/ +/).forEach(l=>{this.argument(l)}),this}addArgument(o){const l=this.registeredArguments.slice(-1)[0];if(l?.variadic)throw new Error(`only the last argument can be variadic '${l.name()}'`);if(o.required&&o.defaultValue!==void 0&&o.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${o.name()}'`);return this.registeredArguments.push(o),this}helpCommand(o,l){if(typeof o=="boolean")return this._addImplicitHelpCommand=o,o&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,d,c]=(o??"help [command]").match(/([^ ]+) *(.*)/),p=l??"display help for command",g=this.createCommand(d);return g.helpOption(!1),c&&g.arguments(c),p&&g.description(p),this._addImplicitHelpCommand=!0,this._helpCommand=g,(o||l)&&this._initCommandGroup(g),this}addHelpCommand(o,l){return typeof o!="object"?(this.helpCommand(o,l),this):(this._addImplicitHelpCommand=!0,this._helpCommand=o,this._initCommandGroup(o),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(o,l){const d=["preSubcommand","preAction","postAction"];if(!d.includes(o))throw new Error(`Unexpected value for event passed to hook : '${o}'.
15
+ Expecting one of '${d.join("', '")}'`);return this._lifeCycleHooks[o]?this._lifeCycleHooks[o].push(l):this._lifeCycleHooks[o]=[l],this}exitOverride(o){return o?this._exitCallback=o:this._exitCallback=l=>{if(l.code!=="commander.executeSubCommandAsync")throw l},this}_exit(o,l,d){this._exitCallback&&this._exitCallback(new h(o,l,d)),s.exit(o)}action(o){const l=d=>{const c=this.registeredArguments.length,p=d.slice(0,c);return this._storeOptionsAsProperties?p[c]=this:p[c]=this.opts(),p.push(this),o.apply(this,p)};return this._actionHandler=l,this}createOption(o,l){return new P(o,l)}_callParseArg(o,l,d,c){try{return o.parseArg(l,d)}catch(p){if(p.code==="commander.invalidArgument"){const g=`${c} ${p.message}`;this.error(g,{exitCode:p.exitCode,code:p.code})}throw p}}_registerOption(o){const l=o.short&&this._findOption(o.short)||o.long&&this._findOption(o.long);if(l){const d=o.long&&this._findOption(o.long)?o.long:o.short;throw new Error(`Cannot add option '${o.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${d}'
16
+ - already used by option '${l.flags}'`)}this._initOptionGroup(o),this.options.push(o)}_registerCommand(o){const l=c=>[c.name()].concat(c.aliases()),d=l(o).find(c=>this._findCommand(c));if(d){const c=l(this._findCommand(d)).join("|"),p=l(o).join("|");throw new Error(`cannot add command '${p}' as already have command '${c}'`)}this._initCommandGroup(o),this.commands.push(o)}addOption(o){this._registerOption(o);const l=o.name(),d=o.attributeName();if(o.negate){const p=o.long.replace(/^--no-/,"--");this._findOption(p)||this.setOptionValueWithSource(d,o.defaultValue===void 0?!0:o.defaultValue,"default")}else o.defaultValue!==void 0&&this.setOptionValueWithSource(d,o.defaultValue,"default");const c=(p,g,C)=>{p==null&&o.presetArg!==void 0&&(p=o.presetArg);const E=this.getOptionValue(d);p!==null&&o.parseArg?p=this._callParseArg(o,p,E,g):p!==null&&o.variadic&&(p=o._collectValue(p,E)),p==null&&(o.negate?p=!1:o.isBoolean()||o.optional?p=!0:p=""),this.setOptionValueWithSource(d,p,C)};return this.on("option:"+l,p=>{c(p,`error: option '${o.flags}' argument '${p}' is invalid.`,"cli")}),o.envVar&&this.on("optionEnv:"+l,p=>{c(p,`error: option '${o.flags}' value '${p}' from env '${o.envVar}' is invalid.`,"env")}),this}_optionEx(o,l,d,c,p){if(typeof l=="object"&&l instanceof P)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const g=this.createOption(l,d);if(g.makeOptionMandatory(!!o.mandatory),typeof c=="function")g.default(p).argParser(c);else if(c instanceof RegExp){const C=c;c=(E,k)=>{const y=C.exec(E);return y?y[0]:k},g.default(p).argParser(c)}else g.default(c);return this.addOption(g)}option(o,l,d,c){return this._optionEx({},o,l,d,c)}requiredOption(o,l,d,c){return this._optionEx({mandatory:!0},o,l,d,c)}combineFlagAndOptionalValue(o=!0){return this._combineFlagAndOptionalValue=!!o,this}allowUnknownOption(o=!0){return this._allowUnknownOption=!!o,this}allowExcessArguments(o=!0){return this._allowExcessArguments=!!o,this}enablePositionalOptions(o=!0){return this._enablePositionalOptions=!!o,this}passThroughOptions(o=!0){return this._passThroughOptions=!!o,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(o=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!o,this}getOptionValue(o){return this._storeOptionsAsProperties?this[o]:this._optionValues[o]}setOptionValue(o,l){return this.setOptionValueWithSource(o,l,void 0)}setOptionValueWithSource(o,l,d){return this._storeOptionsAsProperties?this[o]=l:this._optionValues[o]=l,this._optionValueSources[o]=d,this}getOptionValueSource(o){return this._optionValueSources[o]}getOptionValueSourceWithGlobals(o){let l;return this._getCommandAndAncestors().forEach(d=>{d.getOptionValueSource(o)!==void 0&&(l=d.getOptionValueSource(o))}),l}_prepareUserArgs(o,l){if(o!==void 0&&!Array.isArray(o))throw new Error("first parameter to parse must be array or undefined");if(l=l||{},o===void 0&&l.from===void 0){s.versions?.electron&&(l.from="electron");const c=s.execArgv??[];(c.includes("-e")||c.includes("--eval")||c.includes("-p")||c.includes("--print"))&&(l.from="eval")}o===void 0&&(o=s.argv),this.rawArgs=o.slice();let d;switch(l.from){case void 0:case"node":this._scriptPath=o[1],d=o.slice(2);break;case"electron":s.defaultApp?(this._scriptPath=o[1],d=o.slice(2)):d=o.slice(1);break;case"user":d=o.slice(0);break;case"eval":d=o.slice(1);break;default:throw new Error(`unexpected parse option { from: '${l.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",d}parse(o,l){this._prepareForParse();const d=this._prepareUserArgs(o,l);return this._parseCommand([],d),this}async parseAsync(o,l){this._prepareForParse();const d=this._prepareUserArgs(o,l);return await this._parseCommand([],d),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
17
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(o,l,d){if(i.existsSync(o))return;const c=`'${o}' does not exist
18
+ - if '${d}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
19
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
20
+ - ${l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;throw new Error(c)}_executeSubCommand(o,l){l=l.slice();let d=!1;const c=[".js",".ts",".tsx",".mjs",".cjs"];function p(y,T){const N=r.resolve(y,T);if(i.existsSync(N))return N;if(c.includes(r.extname(T)))return;const Ct=c.find(Yt=>i.existsSync(`${N}${Yt}`));if(Ct)return`${N}${Ct}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let g=o._executableFile||`${this._name}-${o._name}`,C=this._executableDir||"";if(this._scriptPath){let y;try{y=i.realpathSync(this._scriptPath)}catch{y=this._scriptPath}C=r.resolve(r.dirname(y),C)}if(C){let y=p(C,g);if(!y&&!o._executableFile&&this._scriptPath){const T=r.basename(this._scriptPath,r.extname(this._scriptPath));T!==this._name&&(y=p(C,`${T}-${o._name}`))}g=y||g}d=c.includes(r.extname(g));let E;s.platform!=="win32"?d?(l.unshift(g),l=R(s.execArgv).concat(l),E=n.spawn(s.argv[0],l,{stdio:"inherit"})):E=n.spawn(g,l,{stdio:"inherit"}):(this._checkForMissingExecutable(g,C,o._name),l.unshift(g),l=R(s.execArgv).concat(l),E=n.spawn(s.execPath,l,{stdio:"inherit"})),E.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(y=>{s.on(y,()=>{E.killed===!1&&E.exitCode===null&&E.kill(y)})});const k=this._exitCallback;E.on("close",y=>{y=y??1,k?k(new h(y,"commander.executeSubCommandAsync","(close)")):s.exit(y)}),E.on("error",y=>{if(y.code==="ENOENT")this._checkForMissingExecutable(g,C,o._name);else if(y.code==="EACCES")throw new Error(`'${g}' not executable`);if(!k)s.exit(1);else{const T=new h(1,"commander.executeSubCommandAsync","(error)");T.nestedError=y,k(T)}}),this.runningCommand=E}_dispatchSubcommand(o,l,d){const c=this._findCommand(o);c||this.help({error:!0}),c._prepareForParse();let p;return p=this._chainOrCallSubCommandHook(p,c,"preSubcommand"),p=this._chainOrCall(p,()=>{if(c._executableHandler)this._executeSubCommand(c,l.concat(d));else return c._parseCommand(l,d)}),p}_dispatchHelpCommand(o){o||this.help();const l=this._findCommand(o);return l&&!l._executableHandler&&l.help(),this._dispatchSubcommand(o,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((o,l)=>{o.required&&this.args[l]==null&&this.missingArgument(o.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const o=(d,c,p)=>{let g=c;if(c!==null&&d.parseArg){const C=`error: command-argument value '${c}' is invalid for argument '${d.name()}'.`;g=this._callParseArg(d,c,p,C)}return g};this._checkNumberOfArguments();const l=[];this.registeredArguments.forEach((d,c)=>{let p=d.defaultValue;d.variadic?c<this.args.length?(p=this.args.slice(c),d.parseArg&&(p=p.reduce((g,C)=>o(d,C,g),d.defaultValue))):p===void 0&&(p=[]):c<this.args.length&&(p=this.args[c],d.parseArg&&(p=o(d,p,d.defaultValue))),l[c]=p}),this.processedArgs=l}_chainOrCall(o,l){return o?.then&&typeof o.then=="function"?o.then(()=>l()):l()}_chainOrCallHooks(o,l){let d=o;const c=[];return this._getCommandAndAncestors().reverse().filter(p=>p._lifeCycleHooks[l]!==void 0).forEach(p=>{p._lifeCycleHooks[l].forEach(g=>{c.push({hookedCommand:p,callback:g})})}),l==="postAction"&&c.reverse(),c.forEach(p=>{d=this._chainOrCall(d,()=>p.callback(p.hookedCommand,this))}),d}_chainOrCallSubCommandHook(o,l,d){let c=o;return this._lifeCycleHooks[d]!==void 0&&this._lifeCycleHooks[d].forEach(p=>{c=this._chainOrCall(c,()=>p(this,l))}),c}_parseCommand(o,l){const d=this.parseOptions(l);if(this._parseOptionsEnv(),this._parseOptionsImplied(),o=o.concat(d.operands),l=d.unknown,this.args=o.concat(l),o&&this._findCommand(o[0]))return this._dispatchSubcommand(o[0],o.slice(1),l);if(this._getHelpCommand()&&o[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(o[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(l),this._dispatchSubcommand(this._defaultCommandName,o,l);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(d.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const c=()=>{d.unknown.length>0&&this.unknownOption(d.unknown[0])},p=`command:${this.name()}`;if(this._actionHandler){c(),this._processArguments();let g;return g=this._chainOrCallHooks(g,"preAction"),g=this._chainOrCall(g,()=>this._actionHandler(this.processedArgs)),this.parent&&(g=this._chainOrCall(g,()=>{this.parent.emit(p,o,l)})),g=this._chainOrCallHooks(g,"postAction"),g}if(this.parent?.listenerCount(p))c(),this._processArguments(),this.parent.emit(p,o,l);else if(o.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",o,l);this.listenerCount("command:*")?this.emit("command:*",o,l):this.commands.length?this.unknownCommand():(c(),this._processArguments())}else this.commands.length?(c(),this.help({error:!0})):(c(),this._processArguments())}_findCommand(o){if(o)return this.commands.find(l=>l._name===o||l._aliases.includes(o))}_findOption(o){return this.options.find(l=>l.is(o))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(o=>{o.options.forEach(l=>{l.mandatory&&o.getOptionValue(l.attributeName())===void 0&&o.missingMandatoryOptionValue(l)})})}_checkForConflictingLocalOptions(){const o=this.options.filter(l=>{const d=l.attributeName();return this.getOptionValue(d)===void 0?!1:this.getOptionValueSource(d)!=="default"});o.filter(l=>l.conflictsWith.length>0).forEach(l=>{const d=o.find(c=>l.conflictsWith.includes(c.attributeName()));d&&this._conflictingOption(l,d)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(o=>{o._checkForConflictingLocalOptions()})}parseOptions(o){const l=[],d=[];let c=l;function p(y){return y.length>1&&y[0]==="-"}const g=y=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(y)?!this._getCommandAndAncestors().some(T=>T.options.map(N=>N.short).some(N=>/^-\d$/.test(N))):!1;let C=null,E=null,k=0;for(;k<o.length||E;){const y=E??o[k++];if(E=null,y==="--"){c===d&&c.push(y),c.push(...o.slice(k));break}if(C&&(!p(y)||g(y))){this.emit(`option:${C.name()}`,y);continue}if(C=null,p(y)){const T=this._findOption(y);if(T){if(T.required){const N=o[k++];N===void 0&&this.optionMissingArgument(T),this.emit(`option:${T.name()}`,N)}else if(T.optional){let N=null;k<o.length&&(!p(o[k])||g(o[k]))&&(N=o[k++]),this.emit(`option:${T.name()}`,N)}else this.emit(`option:${T.name()}`);C=T.variadic?T:null;continue}}if(y.length>2&&y[0]==="-"&&y[1]!=="-"){const T=this._findOption(`-${y[1]}`);if(T){T.required||T.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${T.name()}`,y.slice(2)):(this.emit(`option:${T.name()}`),E=`-${y.slice(2)}`);continue}}if(/^--[^=]+=/.test(y)){const T=y.indexOf("="),N=this._findOption(y.slice(0,T));if(N&&(N.required||N.optional)){this.emit(`option:${N.name()}`,y.slice(T+1));continue}}if(c===l&&p(y)&&!(this.commands.length===0&&g(y))&&(c=d),(this._enablePositionalOptions||this._passThroughOptions)&&l.length===0&&d.length===0){if(this._findCommand(y)){l.push(y),d.push(...o.slice(k));break}else if(this._getHelpCommand()&&y===this._getHelpCommand().name()){l.push(y,...o.slice(k));break}else if(this._defaultCommandName){d.push(y,...o.slice(k));break}}if(this._passThroughOptions){c.push(y,...o.slice(k));break}c.push(y)}return{operands:l,unknown:d}}opts(){if(this._storeOptionsAsProperties){const o={},l=this.options.length;for(let d=0;d<l;d++){const c=this.options[d].attributeName();o[c]=c===this._versionOptionName?this._version:this[c]}return o}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((o,l)=>Object.assign(o,l.opts()),{})}error(o,l){this._outputConfiguration.outputError(`${o}
21
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
22
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
23
+ `),this.outputHelp({error:!0}));const d=l||{},c=d.exitCode||1,p=d.code||"commander.error";this._exit(c,p,o)}_parseOptionsEnv(){this.options.forEach(o=>{if(o.envVar&&o.envVar in s.env){const l=o.attributeName();(this.getOptionValue(l)===void 0||["default","config","env"].includes(this.getOptionValueSource(l)))&&(o.required||o.optional?this.emit(`optionEnv:${o.name()}`,s.env[o.envVar]):this.emit(`optionEnv:${o.name()}`))}})}_parseOptionsImplied(){const o=new w(this.options),l=d=>this.getOptionValue(d)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(d));this.options.filter(d=>d.implied!==void 0&&l(d.attributeName())&&o.valueFromOption(this.getOptionValue(d.attributeName()),d)).forEach(d=>{Object.keys(d.implied).filter(c=>!l(c)).forEach(c=>{this.setOptionValueWithSource(c,d.implied[c],"implied")})})}missingArgument(o){const l=`error: missing required argument '${o}'`;this.error(l,{code:"commander.missingArgument"})}optionMissingArgument(o){const l=`error: option '${o.flags}' argument missing`;this.error(l,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(o){const l=`error: required option '${o.flags}' not specified`;this.error(l,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(o,l){const d=g=>{const C=g.attributeName(),E=this.getOptionValue(C),k=this.options.find(T=>T.negate&&C===T.attributeName()),y=this.options.find(T=>!T.negate&&C===T.attributeName());return k&&(k.presetArg===void 0&&E===!1||k.presetArg!==void 0&&E===k.presetArg)?k:y||g},c=g=>{const C=d(g),E=C.attributeName();return this.getOptionValueSource(E)==="env"?`environment variable '${C.envVar}'`:`option '${C.flags}'`},p=`error: ${c(o)} cannot be used with ${c(l)}`;this.error(p,{code:"commander.conflictingOption"})}unknownOption(o){if(this._allowUnknownOption)return;let l="";if(o.startsWith("--")&&this._showSuggestionAfterError){let c=[],p=this;do{const g=p.createHelp().visibleOptions(p).filter(C=>C.long).map(C=>C.long);c=c.concat(g),p=p.parent}while(p&&!p._enablePositionalOptions);l=$(o,c)}const d=`error: unknown option '${o}'${l}`;this.error(d,{code:"commander.unknownOption"})}_excessArguments(o){if(this._allowExcessArguments)return;const l=this.registeredArguments.length,d=l===1?"":"s",c=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${l} argument${d} but got ${o.length}.`;this.error(c,{code:"commander.excessArguments"})}unknownCommand(){const o=this.args[0];let l="";if(this._showSuggestionAfterError){const c=[];this.createHelp().visibleCommands(this).forEach(p=>{c.push(p.name()),p.alias()&&c.push(p.alias())}),l=$(o,c)}const d=`error: unknown command '${o}'${l}`;this.error(d,{code:"commander.unknownCommand"})}version(o,l,d){if(o===void 0)return this._version;this._version=o,l=l||"-V, --version",d=d||"output the version number";const c=this.createOption(l,d);return this._versionOptionName=c.attributeName(),this._registerOption(c),this.on("option:"+c.name(),()=>{this._outputConfiguration.writeOut(`${o}
24
+ `),this._exit(0,"commander.version",o)}),this}description(o,l){return o===void 0&&l===void 0?this._description:(this._description=o,l&&(this._argsDescription=l),this)}summary(o){return o===void 0?this._summary:(this._summary=o,this)}alias(o){if(o===void 0)return this._aliases[0];let l=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(l=this.commands[this.commands.length-1]),o===l._name)throw new Error("Command alias can't be the same as its name");const d=this.parent?._findCommand(o);if(d){const c=[d.name()].concat(d.aliases()).join("|");throw new Error(`cannot add alias '${o}' to command '${this.name()}' as already have command '${c}'`)}return l._aliases.push(o),this}aliases(o){return o===void 0?this._aliases:(o.forEach(l=>this.alias(l)),this)}usage(o){if(o===void 0){if(this._usage)return this._usage;const l=this.registeredArguments.map(d=>u(d));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?l:[]).join(" ")}return this._usage=o,this}name(o){return o===void 0?this._name:(this._name=o,this)}helpGroup(o){return o===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=o,this)}commandsGroup(o){return o===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=o,this)}optionsGroup(o){return o===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=o,this)}_initOptionGroup(o){this._defaultOptionGroup&&!o.helpGroupHeading&&o.helpGroup(this._defaultOptionGroup)}_initCommandGroup(o){this._defaultCommandGroup&&!o.helpGroup()&&o.helpGroup(this._defaultCommandGroup)}nameFromFilename(o){return this._name=r.basename(o,r.extname(o)),this}executableDir(o){return o===void 0?this._executableDir:(this._executableDir=o,this)}helpInformation(o){const l=this.createHelp(),d=this._getOutputContext(o);l.prepareContext({error:d.error,helpWidth:d.helpWidth,outputHasColors:d.hasColors});const c=l.formatHelp(this,l);return d.hasColors?c:this._outputConfiguration.stripColor(c)}_getOutputContext(o){o=o||{};const l=!!o.error;let d,c,p;return l?(d=C=>this._outputConfiguration.writeErr(C),c=this._outputConfiguration.getErrHasColors(),p=this._outputConfiguration.getErrHelpWidth()):(d=C=>this._outputConfiguration.writeOut(C),c=this._outputConfiguration.getOutHasColors(),p=this._outputConfiguration.getOutHelpWidth()),{error:l,write:C=>(c||(C=this._outputConfiguration.stripColor(C)),d(C)),hasColors:c,helpWidth:p}}outputHelp(o){let l;typeof o=="function"&&(l=o,o=void 0);const d=this._getOutputContext(o),c={error:d.error,write:d.write,command:this};this._getCommandAndAncestors().reverse().forEach(g=>g.emit("beforeAllHelp",c)),this.emit("beforeHelp",c);let p=this.helpInformation({error:d.error});if(l&&(p=l(p),typeof p!="string"&&!Buffer.isBuffer(p)))throw new Error("outputHelp callback must return a string or a Buffer");d.write(p),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",c),this._getCommandAndAncestors().forEach(g=>g.emit("afterAllHelp",c))}helpOption(o,l){return typeof o=="boolean"?(o?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(o??"-h, --help",l??"display help for command"),(o||l)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(o){return this._helpOption=o,this._initOptionGroup(o),this}help(o){this.outputHelp(o);let l=Number(s.exitCode??0);l===0&&o&&typeof o!="function"&&o.error&&(l=1),this._exit(l,"commander.help","(outputHelp)")}addHelpText(o,l){const d=["beforeAll","before","after","afterAll"];if(!d.includes(o))throw new Error(`Unexpected value for position to addHelpText.
25
+ Expecting one of '${d.join("', '")}'`);const c=`${o}Help`;return this.on(c,p=>{let g;typeof l=="function"?g=l({error:p.error,command:p.command}):g=l,g&&p.write(`${g}
26
+ `)}),this}_outputHelpIfRequested(o){const l=this._getHelpOption();l&&o.find(d=>l.is(d))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function R(Xt){return Xt.map(o=>{if(!o.startsWith("--inspect"))return o;let l,d="127.0.0.1",c="9229",p;return(p=o.match(/^(--inspect(-brk)?)$/))!==null?l=p[1]:(p=o.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(l=p[1],/^\d+$/.test(p[3])?c=p[3]:d=p[3]):(p=o.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(l=p[1],d=p[3],c=p[4]),l&&c!=="0"?`${l}=${d}:${parseInt(c)+1}`:o})}function at(){if(s.env.NO_COLOR||s.env.FORCE_COLOR==="0"||s.env.FORCE_COLOR==="false")return!1;if(s.env.FORCE_COLOR||s.env.CLICOLOR_FORCE!==void 0)return!0}t.Command=G,t.useColor=at})),ce=K((t=>{var{Argument:e}=pt(),{Command:n}=de(),{CommanderError:r,InvalidArgumentError:i}=nt(),{Help:s}=Et(),{Option:a}=Tt();t.program=new n,t.createCommand=u=>new n(u),t.createOption=(u,h)=>new a(u,h),t.createArgument=(u,h)=>new e(u,h),t.Command=n,t.Option=a,t.Argument=e,t.Help=s,t.CommanderError=r,t.InvalidArgumentError=i,t.InvalidOptionArgumentError=i})),pe=ne(ce(),1),{program:ms,createCommand:fs,createArgument:gs,createOption:vs,CommanderError:he,InvalidArgumentError:ys,InvalidOptionArgumentError:As,Command:me,Argument:Os,Option:U,Help:Ss}=pe.default;function A(t){return`${JSON.stringify(t,null,2)}
27
+ `}var xt=(function(t){return t.INIT="Init",t.COMPLETED="Completed",t.ARCHIVED="Archived",t.DRAFTING="Drafting",t.EXECUTION_COMPLETED="ExecutionCompleted",t.OPTIMIZING="Optimizing",t.OPENSPECING="Openspecing",t.REVIEWING="Reviewing",t.EXECUTING="Executing",t.ARCHIVING="Archiving",t})({});function kt(t){return t.replace(/\s+/g," ").trim()}function B(t,e){const n=e.map(s=>t.map(a=>kt(a.value(s)))),r=t.map((s,a)=>{const u=n.map(h=>h[a].length);return Math.max(s.header.length,...u)}),i=s=>s.map((a,u)=>a.padEnd(r[u])).join(" ").trimEnd();return[i(t.map(s=>s.header)),i(r.map(s=>"-".repeat(s))),...n.map(i)].join(`
28
+ `)}function H(t){const e=t.filter(([,r])=>r!==void 0&&r!==""),n=Math.max(...e.map(([r])=>r.length));return`${e.map(([r,i])=>`${r.padEnd(n)} ${kt(i??"")}`).join(`
29
+ `)}
30
+ `}function _t(t){return typeof t=="string"?t.trim():t?.value?.trim()??""}function M(t){return{sessionId:_t(t.sessionId),title:t.title,type:t.type,status:t.status,projectId:_t(t.projectId),proposalName:t.proposalName??void 0,archived:t.status===xt.ARCHIVED,lastActiveAt:t.lastActiveAt??void 0,enableIndependentWorkspace:t.enableIndependentWorkspace,baseBranch:t.baseBranch??void 0,metadata:t.metadata??void 0,chatExecutorType:t.chatExecutorType??void 0}}function jt(t){return{sessions:t.sessions.map(M)}}function $t(t,e){return e.length===0?`No ${t.toLowerCase()} found.
31
+ `:`${t} (${e.length})
32
+ ${B([{header:"Session ID",value:n=>n.sessionId},{header:"Title",value:n=>n.title},{header:"Status",value:n=>n.status},{header:"Project ID",value:n=>n.projectId},{header:"Archived",value:n=>n.archived?"yes":"no"}],e)}
33
+ `}function Q(t,e=[]){return H([["sessionId",t.sessionId],["type",t.type],["title",t.title],["status",t.status],["projectId",t.projectId],["proposalName",t.proposalName],["independentWorkspace",String(t.enableIndependentWorkspace)],["baseBranch",t.baseBranch],["chatExecutorType",t.chatExecutorType],["metadata",t.metadata],...e])}function ht(t,e,n,r=[]){return`${t}
34
+ ${H([["sessionId",e],["message",n.message],...r])}`}var m={BASE:"",VERSION:"1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0},dt=class extends Error{url;status;statusText;body;request;constructor(t,e,n){super(n),this.name="ApiError",this.url=e.url,this.status=e.status,this.statusText=e.statusText,this.body=e.body,this.request=t}},V={USAGE:2,HTTP_BAD_REQUEST:20,HTTP_UNAUTHORIZED:21,HTTP_FORBIDDEN:23,HTTP_NOT_FOUND:24,HTTP_CONFLICT:29,HTTP_CLIENT_ERROR:40,HTTP_SERVER_ERROR:50,TRANSPORT:60,UNKNOWN:70},j=class extends Error{constructor(t){super(t),this.name="CliUsageError"}},mt=class extends Error{status;details;constructor(t,e,n){super(e),this.name="CliHttpError",this.status=t,this.details=n}};function Nt(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Y(t,e){const n=Nt(t)?.[e];return typeof n=="string"&&n.trim()?n.trim():void 0}function fe(t){return t.includes("fetch failed")||t.includes("ECONNREFUSED")||t.includes("ENOTFOUND")||t.includes("Failed to parse URL")}function Pt(t){switch(t){case 400:return V.HTTP_BAD_REQUEST;case 401:return V.HTTP_UNAUTHORIZED;case 403:return V.HTTP_FORBIDDEN;case 404:return V.HTTP_NOT_FOUND;case 409:return V.HTTP_CONFLICT;default:return t&&t>=400&&t<500?V.HTTP_CLIENT_ERROR:t&&t>=500?V.HTTP_SERVER_ERROR:V.UNKNOWN}}function ge(t,e={}){if(t instanceof j)return{exitCode:V.USAGE,message:t.message};if(t instanceof mt)return{exitCode:Pt(t.status),status:t.status,message:t.message,details:t.details};if(t instanceof dt){const n=Y(t.body,"error")??Y(t.body,"message")??t.message;return{exitCode:Pt(t.status),status:t.status,message:n,errorCode:Y(t.body,"errorCode"),correlationId:Y(t.body,"correlationId"),details:t.body}}if(t instanceof Error){if(!fe(t.message))return{exitCode:V.UNKNOWN,message:t.message};const n=e.baseUrl??"the configured backend";return{exitCode:V.TRANSPORT,message:t.message.includes("Failed to parse URL")?`Invalid HagiCode backend base URL: ${n}`:`Cannot reach HagiCode backend at ${n}. Check that the backend is running and the base URL is correct.`}}return{exitCode:V.UNKNOWN,message:String(t)}}function ve(t){const e=Nt(t)?.errors;return Array.isArray(e)?e.flatMap(n=>{const r=Y(n,"field"),i=Y(n,"message");return r&&i?[` - ${r}: ${i}`]:[]}):[]}function Dt(t,e={}){if(e.json)return`${JSON.stringify({error:{message:t.message,status:t.status,exitCode:t.exitCode,errorCode:t.errorCode,correlationId:t.correlationId,details:t.details}},null,2)}
35
+ `;const n=[t.status?`status=${t.status}`:void 0,t.errorCode?`errorCode=${t.errorCode}`:void 0,t.correlationId?`correlationId=${t.correlationId}`:void 0].filter(Boolean),r=n.length>0?` (${n.join(", ")})`:"";return[`${t.message}${r}`,...ve(t.details)].join(`
36
+ `)+`
37
+ `}var ye="--base-url",Ae="HAGI_API_BASE_URL";function L(t){const e=t?.trim();return e||void 0}function Vt(t=process.env){return(0,bt.join)(L(t.XDG_CONFIG_HOME)??(0,bt.join)((0,ae.homedir)(),".config"),"hagi","config.json")}function Oe(t=process.env){const e=Vt(t);let n;try{n=(0,re.readFileSync)(e,"utf8")}catch(s){if(s.code==="ENOENT")return;throw new j(`Cannot read CLI config file ${e}: ${s instanceof Error?s.message:String(s)}`)}let r;try{r=JSON.parse(n)}catch{throw new j(`CLI config file ${e} is not valid JSON.`)}const i=r&&typeof r=="object"&&!Array.isArray(r)?r.baseUrl:void 0;return typeof i=="string"?L(i):void 0}function Se(t={},e=process.env){const n=L(t.baseUrl)??L(e.HAGI_API_BASE_URL)??Oe(e);if(!n)throw new j(`No backend base URL is configured. Set ${ye} <url>, the ${Ae} environment variable, or "baseUrl" in ${Vt(e)}.`);return{baseUrl:n,token:L(t.token)??L(e.HAGI_API_TOKEN),lang:L(t.lang)??L(e.HAGI_API_LANG)}}function Ce(t={},e=process.env){const n=Se(t,e);return m.BASE=n.baseUrl,m.WITH_CREDENTIALS=!1,m.CREDENTIALS="omit",m.TOKEN=n.token,m.HEADERS=n.lang?{"Accept-Language":n.lang}:void 0,n}function be(){return L(m.BASE)}var _e=class extends Error{constructor(t){super(t),this.name="CancelError"}get isCancelled(){return!0}},Pe=class{#e;#i;#t;#s;#n;#r;#o;constructor(t){this.#e=!1,this.#i=!1,this.#t=!1,this.#s=[],this.#n=new Promise((e,n)=>{this.#r=e,this.#o=n;const r=a=>{this.#e||this.#i||this.#t||(this.#e=!0,this.#r&&this.#r(a))},i=a=>{this.#e||this.#i||this.#t||(this.#i=!0,this.#o&&this.#o(a))},s=a=>{this.#e||this.#i||this.#t||this.#s.push(a)};return Object.defineProperty(s,"isResolved",{get:()=>this.#e}),Object.defineProperty(s,"isRejected",{get:()=>this.#i}),Object.defineProperty(s,"isCancelled",{get:()=>this.#t}),t(r,i,s)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(t,e){return this.#n.then(t,e)}catch(t){return this.#n.catch(t)}finally(t){return this.#n.finally(t)}cancel(){if(!(this.#e||this.#i||this.#t)){if(this.#t=!0,this.#s.length)try{for(const t of this.#s)t()}catch(t){console.warn("Cancellation threw an error",t);return}this.#s.length=0,this.#o&&this.#o(new _e("Request aborted"))}}get isCancelled(){return this.#t}},ft=t=>t!=null,tt=t=>typeof t=="string",lt=t=>tt(t)&&t!=="",gt=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),Ht=t=>t instanceof FormData,we=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ee=t=>{const e=[],n=(i,s)=>{e.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(s))}`)},r=(i,s)=>{ft(s)&&(Array.isArray(s)?s.forEach(a=>{r(i,a)}):typeof s=="object"?Object.entries(s).forEach(([a,u])=>{r(`${i}[${a}]`,u)}):n(i,s))};return Object.entries(t).forEach(([i,s])=>{r(i,s)}),e.length>0?`?${e.join("&")}`:""},Te=(t,e)=>{const n=t.ENCODE_PATH||encodeURI,r=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(s,a)=>e.path?.hasOwnProperty(a)?n(String(e.path[a])):s),i=`${t.BASE}${r}`;return e.query?`${i}${Ee(e.query)}`:i},Ie=t=>{if(t.formData){const e=new FormData,n=(r,i)=>{tt(i)||gt(i)?e.append(r,i):e.append(r,JSON.stringify(i))};return Object.entries(t.formData).filter(([r,i])=>ft(i)).forEach(([r,i])=>{Array.isArray(i)?i.forEach(s=>n(r,s)):n(r,i)}),e}},it=async(t,e)=>typeof e=="function"?e(t):e,xe=async(t,e)=>{const[n,r,i,s]=await Promise.all([it(e,t.TOKEN),it(e,t.USERNAME),it(e,t.PASSWORD),it(e,t.HEADERS)]),a=Object.entries({Accept:"application/json",...s,...e.headers}).filter(([u,h])=>ft(h)).reduce((u,[h,v])=>({...u,[h]:String(v)}),{});return lt(n)&&(a.Authorization=`Bearer ${n}`),lt(r)&&lt(i)&&(a.Authorization=`Basic ${we(`${r}:${i}`)}`),e.body!==void 0&&(e.mediaType?a["Content-Type"]=e.mediaType:gt(e.body)?a["Content-Type"]=e.body.type||"application/octet-stream":tt(e.body)?a["Content-Type"]="text/plain":Ht(e.body)||(a["Content-Type"]="application/json")),new Headers(a)},ke=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):tt(t.body)||gt(t.body)||Ht(t.body)?t.body:JSON.stringify(t.body)},je=async(t,e,n,r,i,s,a)=>{const u=new AbortController,h={headers:s,body:r??i,method:e.method,signal:u.signal};return t.WITH_CREDENTIALS&&(h.credentials=t.CREDENTIALS),a(()=>u.abort()),await fetch(n,h)},$e=(t,e)=>{if(e){const n=t.headers.get(e);if(tt(n))return n}},Ne=async t=>{if(t.status!==204)try{const e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(n=>e.toLowerCase().startsWith(n))?await t.json():await t.text()}catch(e){console.error(e)}},De=(t,e)=>{const n={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(n)throw new dt(t,e,n);if(!e.ok)throw new dt(t,e,`Generic Error: status: ${e.status??"unknown"}; status text: ${e.statusText??"unknown"}; body: ${(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})()}`)},f=(t,e)=>new Pe(async(n,r,i)=>{try{const s=Te(t,e),a=Ie(e),u=ke(e),h=await xe(t,e);if(!i.isCancelled){const v=await je(t,e,s,u,a,h,i),_=await Ne(v),P=$e(v,e.responseHeader),w={url:s,ok:v.ok,status:v.status,statusText:v.statusText,body:P??_};De(e,w),n(w.body)}}catch(s){r(s)}}),Ve=class{static getApiDataAggregation(){return f(m,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},ut=class{static postApiProject({requestBody:t}){return f(m,{method:"POST",url:"/api/Project",body:t,mediaType:"application/json"})}static postApiProjectDemo(){return f(m,{method:"POST",url:"/api/Project/demo"})}static putApiProject({id:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/Project/{id}",path:{id:t},body:e,mediaType:"application/json"})}static deleteApiProject({id:t}){return f(m,{method:"DELETE",url:"/api/Project/{id}",path:{id:t}})}static postApiProjectOpenInVscode({id:t,subPath:e}){return f(m,{method:"POST",url:"/api/Project/{id}/open-in-vscode",path:{id:t},query:{subPath:e},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Project not found",500:"Failed to launch VS Code"}})}static getApiProjectMonospecsManagement({id:t}){return f(m,{method:"GET",url:"/api/Project/{id}/monospecs/management",path:{id:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectMonospecsManagement({id:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/Project/{id}/monospecs/management",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiProjectMonospecsInitialize({id:t}){return f(m,{method:"POST",url:"/api/Project/{id}/monospecs/initialize",path:{id:t},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiProjectDesignMd({id:t,repositoryPath:e}){return f(m,{method:"GET",url:"/api/Project/{id}/design-md",path:{id:t},query:{repositoryPath:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static putApiProjectDesignMd({id:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/Project/{id}/design-md",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static getApiProjectDesignMdSiteIndex({id:t}){return f(m,{method:"GET",url:"/api/Project/{id}/design-md/site-index",path:{id:t},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndexPreview({id:t,slug:e,theme:n="light"}){return f(m,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}/preview",path:{id:t,slug:e},query:{theme:n},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectDesignMdSiteIndex1({id:t,slug:e}){return f(m,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}",path:{id:t,slug:e},errors:{400:"Bad Request",404:"Not Found",502:"Bad Gateway",504:"Gateway Timeout"}})}static getApiProjectBranchesValidate({id:t,branchName:e,repositoryPath:n}){return f(m,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:t},query:{branchName:e,repositoryPath:n},errors:{400:"Branch name is required",404:"Project not found"}})}static getApiProjectValidatePath({path:t}){return f(m,{method:"GET",url:"/api/Project/validate-path",query:{path:t},errors:{400:"Path parameter is missing or invalid",500:"Internal server error during validation"}})}static postApiProjectScanGitRepos({requestBody:t}){return f(m,{method:"POST",url:"/api/Project/scan-git-repos",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error during scan"}})}static postApiProjectValidateMonospecs({requestBody:t}){return f(m,{method:"POST",url:"/api/Project/validate-monospecs",body:t,mediaType:"application/json",errors:{400:"Invalid request parameters",500:"Internal server error"}})}},W=class{static getApiScheduledPlans(){return f(m,{method:"GET",url:"/api/ScheduledPlans"})}static postApiScheduledPlans({requestBody:t}){return f(m,{method:"POST",url:"/api/ScheduledPlans",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiScheduledPlans1({id:t}){return f(m,{method:"GET",url:"/api/ScheduledPlans/{id}",path:{id:t},errors:{404:"Not Found"}})}static putApiScheduledPlans({id:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/ScheduledPlans/{id}",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found"}})}static deleteApiScheduledPlans({id:t}){return f(m,{method:"DELETE",url:"/api/ScheduledPlans/{id}",path:{id:t},errors:{404:"Not Found"}})}static postApiScheduledPlansRun({id:t}){return f(m,{method:"POST",url:"/api/ScheduledPlans/{id}/run",path:{id:t},errors:{400:"Bad Request",404:"Not Found"}})}static postApiScheduledPlansStart({id:t}){return f(m,{method:"POST",url:"/api/ScheduledPlans/{id}/start",path:{id:t},errors:{404:"Not Found",503:"Service Unavailable"}})}},D=class{static postApiSessionsAutoTask({requestBody:t}){return f(m,{method:"POST",url:"/api/Sessions/auto-task",body:t,mediaType:"application/json",errors:{400:"Missing required fields or invalid prompt ID",404:"Project not found",500:"Internal server error"}})}static postApiSessionsArchiveChat({sessionId:t}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/archive-chat",path:{sessionId:t},errors:{400:"Session is not a chat session",404:"Session not found",500:"Failed to archive chat session"}})}static postApiSessionsChat({requestBody:t}){return f(m,{method:"POST",url:"/api/Sessions/chat",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static postApiSessions({requestBody:t}){return f(m,{method:"POST",url:"/api/Sessions",body:t,mediaType:"application/json",errors:{400:"Bad Request"}})}static getApiSessions({type:t,activeOnly:e,includeArchived:n,projectId:r,projectIds:i}){return f(m,{method:"GET",url:"/api/Sessions",query:{type:t,activeOnly:e,includeArchived:n,projectId:r,projectIds:i}})}static getApiSessions1({sessionId:t}){return f(m,{method:"GET",url:"/api/Sessions/{sessionId}",path:{sessionId:t},errors:{400:"Invalid session ID format",404:"Session not found",500:"Internal server error occurred"}})}static putApiSessions({sessionId:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/Sessions/{sessionId}",path:{sessionId:t},body:e,mediaType:"application/json"})}static deleteApiSessions({sessionId:t,deleteFiles:e=!1}){return f(m,{method:"DELETE",url:"/api/Sessions/{sessionId}",path:{sessionId:t},query:{deleteFiles:e},errors:{404:"Session not found",500:"Failed to delete session"}})}static getApiSessionsMessages({sessionId:t,page:e=1,pageSize:n=50,historyScope:r,order:i="desc"}){return f(m,{method:"GET",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},query:{page:e,pageSize:n,historyScope:r,order:i},errors:{404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsMessages({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:t},body:e,mediaType:"application/json"})}static postApiSessionsCancel({sessionId:t}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/cancel",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to cancel session"}})}static getApiSessionsProcessingStatus({sessionId:t}){return f(m,{method:"GET",url:"/api/Sessions/{sessionId}/processing-status",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to get processing status"}})}static deleteApiSessionsQueue({sessionId:t,queueIndex:e}){return f(m,{method:"DELETE",url:"/api/Sessions/{sessionId}/queue/{queueIndex}",path:{sessionId:t,queueIndex:e},errors:{400:"Invalid queue index",404:"Session not found",500:"Failed to cancel message"}})}static postApiSessionsAnnotations({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/annotations",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Invalid request or session is not a proposal session",404:"Session not found",500:"Failed to process annotations"}})}static postApiSessionsOptimizeProposal({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/optimize-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiSessionsGenerateProposal({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/generate-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name not generated",404:"Session not found",500:"Failed to generate proposal"}})}static postApiSessionsArchive({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/archive",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session or proposal name missing",404:"Session not found",500:"Failed to archive session"}})}static postApiSessionsExecuteProposal({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/execute-proposal",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Session is not a proposal session, not in valid status, or proposal name missing",404:"Session not found",500:"Failed to execute proposal"}})}static postApiSessionsComplete({sessionId:t}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/complete",path:{sessionId:t},errors:{400:"Session is not in ExecutionCompleted status",404:"Session not found",500:"Failed to complete session"}})}static postApiSessionsValidateExecute({sessionId:t}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/validate-execute",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateStart({sessionId:t}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/validate-start",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static postApiSessionsValidateArchive({sessionId:t}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/validate-archive",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to validate session"}})}static getApiSessionsOpenspecFile({sessionId:t,relativePath:e}){return f(m,{method:"GET",url:"/api/Sessions/{sessionId}/openspec-file",path:{sessionId:t},query:{relativePath:e},errors:{404:"Session not found or file not found",500:"Failed to read file"}})}static postApiSessionsUpdateCessionId({sessionId:t}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/update-cession-id",path:{sessionId:t},errors:{404:"Session not found",500:"Failed to update CessionId"}})}static postApiSessionsOpenInVscode({sessionId:t,subPath:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/open-in-vscode",path:{sessionId:t},query:{subPath:e},errors:{400:"Invalid project path or sub-path",403:"Sub-path is outside project directory",404:"Session not found",500:"Failed to launch VS Code"}})}static postApiSessionsCorrectProposalName({sessionId:t,requestBody:e}){return f(m,{method:"POST",url:"/api/Sessions/{sessionId}/correct-proposal-name",path:{sessionId:t},body:e,mediaType:"application/json",errors:{400:"Invalid name format or validation failed",404:"Session not found",409:"Name already in use by another session",500:"Internal server error"}})}static deleteApiSessionsWorkspace({sessionId:t}){return f(m,{method:"DELETE",url:"/api/Sessions/{sessionId}/workspace",path:{sessionId:t},errors:{400:"Session does not have an independent workspace",404:"Session not found",500:"Failed to delete workspace"}})}},F=class{static getApiSkillsLocal(){return f(m,{method:"GET",url:"/api/skills/local"})}static postApiSkillsLocalUninstall({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/local/uninstall",body:t,mediaType:"application/json"})}static getApiSkillsGallery({query:t}){return f(m,{method:"GET",url:"/api/skills/gallery",query:{query:t}})}static getApiSkillsGalleryDetail({id:t,source:e}){return f(m,{method:"GET",url:"/api/skills/gallery/detail",query:{id:t,source:e}})}static getApiSkillsGalleryInstallContext({id:t,source:e}){return f(m,{method:"GET",url:"/api/skills/gallery/install-context",query:{id:t,source:e}})}static getApiSkillsProvidersTrusted(){return f(m,{method:"GET",url:"/api/skills/providers/trusted"})}static postApiSkillsProvidersTrusted({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/providers/trusted",body:t,mediaType:"application/json"})}static deleteApiSkillsProvidersTrusted({requestBody:t}){return f(m,{method:"DELETE",url:"/api/skills/providers/trusted",body:t,mediaType:"application/json"})}static postApiSkillsProvidersTrustedReset(){return f(m,{method:"POST",url:"/api/skills/providers/trusted/reset"})}static postApiSkillsGalleryInstall({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/gallery/install",body:t,mediaType:"application/json"})}static getApiSkillsRecommendationsConfig({locale:t}){return f(m,{method:"GET",url:"/api/skills/recommendations/config",query:{locale:t}})}static postApiSkillsRecommendationsGenerate({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/recommendations/generate",body:t,mediaType:"application/json"})}static postApiSkillsRecommendationsInstall({requestBody:t}){return f(m,{method:"POST",url:"/api/skills/recommendations/install",body:t,mediaType:"application/json"})}static getApiSkillsGalleryInstallStream({id:t,source:e,skillSlug:n,version:r}){return f(m,{method:"GET",url:"/api/skills/gallery/install/stream",query:{id:t,source:e,skillSlug:n,version:r}})}},X=class{static getApiVaults(){return f(m,{method:"GET",url:"/api/vaults"})}static postApiVaults({requestBody:t}){return f(m,{method:"POST",url:"/api/vaults",body:t,mediaType:"application/json",errors:{400:"Bad Request",500:"Internal Server Error"}})}static putApiVaults({id:t,requestBody:e}){return f(m,{method:"PUT",url:"/api/vaults/{id}",path:{id:t},body:e,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static deleteApiVaults({id:t,deleteLocalFiles:e=!1}){return f(m,{method:"DELETE",url:"/api/vaults/{id}",path:{id:t},query:{deleteLocalFiles:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFiles({id:t,path:e}){return f(m,{method:"GET",url:"/api/vaults/{id}/files",path:{id:t},query:{path:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static getApiVaultsFilesContent({id:t,path:e}){return f(m,{method:"GET",url:"/api/vaults/{id}/files/content",path:{id:t},query:{path:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}};function He(){return{listSessions:t=>D.getApiSessions(t),getSession:t=>D.getApiSessions1({sessionId:t}),createProposalSession:t=>D.postApiSessions({requestBody:t}),createChatSession:t=>D.postApiSessionsChat({requestBody:t}),createAutoTaskSession:t=>D.postApiSessionsAutoTask({requestBody:t}),updateSession:(t,e)=>D.putApiSessions({sessionId:t,requestBody:e}),deleteSession:(t,e)=>D.deleteApiSessions({sessionId:t,deleteFiles:e}),sendMessage:(t,e)=>D.postApiSessionsMessages({sessionId:t,requestBody:e}),optimizeProposal:(t,e)=>D.postApiSessionsOptimizeProposal({sessionId:t,requestBody:e}),generateProposal:(t,e)=>D.postApiSessionsGenerateProposal({sessionId:t,requestBody:e}),executeProposal:(t,e)=>D.postApiSessionsExecuteProposal({sessionId:t,requestBody:e}),archiveProposal:(t,e)=>D.postApiSessionsArchive({sessionId:t,requestBody:e}),completeProposal:t=>D.postApiSessionsComplete({sessionId:t}),submitAnnotations:(t,e)=>D.postApiSessionsAnnotations({sessionId:t,requestBody:e}),listProjects:()=>Ve.getApiDataAggregation(),createProject:t=>ut.postApiProject({requestBody:t}),updateProject:(t,e)=>ut.putApiProject({id:t,requestBody:e}),deleteProject:t=>ut.deleteApiProject({id:t}),listPlans:()=>W.getApiScheduledPlans(),getPlan:t=>W.getApiScheduledPlans1({id:t}),createPlan:t=>W.postApiScheduledPlans({requestBody:t}),updatePlan:(t,e)=>W.putApiScheduledPlans({id:t,requestBody:e}),deletePlan:t=>W.deleteApiScheduledPlans({id:t}),runPlan:t=>W.postApiScheduledPlansRun({id:t}),startPlan:t=>W.postApiScheduledPlansStart({id:t}),listVaults:()=>X.getApiVaults(),createVault:t=>X.postApiVaults({requestBody:t}),updateVault:(t,e)=>X.putApiVaults({id:t,requestBody:e}),deleteVault:(t,e)=>X.deleteApiVaults({id:t,deleteLocalFiles:e}),listVaultFiles:(t,e)=>X.getApiVaultsFiles({id:t,path:e}),previewVaultFile:(t,e)=>X.getApiVaultsFilesContent({id:t,path:e}),archiveChat:t=>D.postApiSessionsArchiveChat({sessionId:t}),listLocalSkills:()=>F.getApiSkillsLocal(),uninstallLocalSkill:t=>F.postApiSkillsLocalUninstall({requestBody:t}),searchSkillGallery:t=>F.getApiSkillsGallery({query:t}),getSkillGalleryDetail:(t,e)=>F.getApiSkillsGalleryDetail({id:t,source:e}),installGallerySkill:t=>F.postApiSkillsGalleryInstall({requestBody:t}),listTrustedSkillProviders:()=>F.getApiSkillsProvidersTrusted(),upsertTrustedSkillProvider:t=>F.postApiSkillsProvidersTrusted({requestBody:t}),deleteTrustedSkillProvider:t=>F.deleteApiSkillsProvidersTrusted({requestBody:t}),resetTrustedSkillProviders:()=>F.postApiSkillsProvidersTrustedReset()}}function b(t){const e=t?.trim();return e||void 0}function x(t,e){const n=b(t);if(!n)throw new j(`${e} is required.`);return n}function Rt(t){const e=t?.map(n=>b(n)).filter(Boolean);return e&&e.length>0?e:void 0}function qt(t=process.env,e={stdout:n=>{process.stdout.write(n)},stderr:n=>{process.stderr.write(n)}}){return{api:He(),env:t,io:e}}function Re(t){return t.option("--base-url <url>",'Backend API base URL. Overrides HAGI_API_BASE_URL and the "baseUrl" config file entry.').option("--token <token>","Bearer token for backend API calls. Overrides HAGI_API_TOKEN.").option("--lang <lang>","Accept-Language value for backend API calls. Overrides HAGI_API_LANG.")}function O(t){return t.option("--json","Emit deterministic JSON instead of human-readable text.")}function S(t,e){const n=t.optsWithGlobals();return{api:e.api,env:e.env,io:e.io,outputJson:n.json===!0,runtime:Ce({baseUrl:n.baseUrl,token:n.token,lang:n.lang},e.env)}}function qe(t,e){O(t.command("create").description("Create an AutoTask session through the dedicated generated endpoint.")).requiredOption("--title <title>","AutoTask session title.").requiredOption("--project-id <id>","Owning project id.").requiredOption("--prompt-id <id>","Prompt template id.").option("--message <text>","Optional custom message override.").option("--preset-id <id>","Optional preset id.").option("--repository-path <path>","Optional MonoSpecs repository path.").option("--project-ids <ids...>","Optional extra project ids for multi-project flows.").option("--need-push","Request push after commit creation when supported.").option("--target-branch-mode <mode>","Optional target branch mode.").option("--target-branch-name <name>","Optional custom target branch name.").option("--script-key <key>","Optional stable scenario script key.").option("--hero-id <id>","Optional preferred hero id.").option("--target-type <type>","Optional target type for the AutoTask session.").option("--vault-id <id>","Optional vault id for the AutoTask session.").action(async function(r){if(r.targetBranchName&&r.targetBranchMode!=="new-custom")throw new j("--target-branch-name requires --target-branch-mode new-custom.");if(r.targetBranchMode==="new-custom"&&!b(r.targetBranchName))throw new j("--target-branch-name is required when --target-branch-mode is new-custom.");const i=S(this,e),s={title:x(r.title,"--title"),projectId:x(r.projectId,"--project-id"),promptId:x(r.promptId,"--prompt-id"),message:b(r.message),presetId:b(r.presetId),repositoryPath:b(r.repositoryPath),projectIds:Rt(r.projectIds),needPush:r.needPush?!0:void 0,targetBranchMode:b(r.targetBranchMode),targetBranchName:b(r.targetBranchName),scriptKey:b(r.scriptKey),heroId:b(r.heroId),targetType:b(r.targetType),vaultId:b(r.vaultId)},a=M(await i.api.createAutoTaskSession(s));if(i.outputJson){i.io.stdout(A({session:a,promptId:s.promptId,requested:s}));return}i.io.stdout(`AutoTask session created
38
+ ${Q(a,[["promptId",s.promptId],["repositoryPath",s.repositoryPath],["targetBranchMode",s.targetBranchMode],["targetBranchName",s.targetBranchName],["scriptKey",s.scriptKey],["heroId",s.heroId]])}`)})}var rt=(function(t){return t.CLAUDE_CODE_CLI="ClaudeCodeCli",t.CODEX_CLI="CodexCli",t.GIT_HUB_COPILOT="GitHubCopilot",t.CODEBUDDY_CLI="CodebuddyCli",t.OPEN_CODE_CLI="OpenCodeCli",t.IFLOW_CLI="IFlowCli",t.HERMES_CLI="HermesCli",t.QODER_CLI="QoderCli",t.KIRO_CLI="KiroCli",t.KIMI_CLI="KimiCli",t.GEMINI_CLI="GeminiCli",t.DEEP_AGENTS_CLI="DeepAgentsCli",t})({}),vt=(function(t){return t.READONLY="Readonly",t.EDIT="Edit",t})({});function Fe(t,e){O(t.command("send").description("Send a follow-up message to an AutoTask session.")).requiredOption("--session-id <id>","AutoTask session id.").requiredOption("--content <text>","Message content.").addOption(new U("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new U("--executor-type <type>","Executor override for this message.").choices(Object.values(rt))).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:x(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(ht("AutoTask message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Le(t,e){const n=t.command("autotask").description("Manage AutoTask sessions.");qe(n,e),Fe(n,e)}function Ge(t,e){O(t.command("archive").description("Archive a chat session through the dedicated chat archive endpoint.")).requiredOption("--session-id <id>","Chat session id to archive.").action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.archiveChat(s);if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message}));return}i.io.stdout(`Chat archived
39
+ sessionId ${s}
40
+ message ${a.message}
41
+ `)})}function Ue(t,e){O(t.command("create").description("Create a normal chat session.")).requiredOption("--title <title>","Chat session title.").requiredOption("--project-id <id>","Owning project id.").option("--hero-id <id>","Optional bound hero id.").addOption(new U("--executor-type <type>","Optional executor override.").choices(Object.values(rt))).action(async function(r){const i=S(this,e),s=M(await i.api.createChatSession({title:x(r.title,"--title"),projectId:x(r.projectId,"--project-id"),heroId:b(r.heroId),executorType:r.executorType}));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Chat session created
42
+ ${Q(s)}`)})}function Be(t,e){O(t.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.deleteSession(s,!1);if(i.outputJson){i.io.stdout(A({sessionId:s,deleted:!0,message:a.message}));return}i.io.stdout(`Chat deleted
43
+ sessionId ${s}
44
+ message ${a.message}
45
+ `)})}var yt=(function(t){return t.CHAT="Chat",t.PROPOSAL="Proposal",t})({});function Me(t,e){O(t.command("list").description("List normal chat sessions.")).action(async function(r){if(r.projectId&&r.projectIds?.length)throw new j("Use either --project-id or --project-ids, not both.");const i=S(this,e),s=jt(await i.api.listSessions({type:yt.CHAT,projectId:b(r.projectId),projectIds:Rt(r.projectIds),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout($t("Chat sessions",s.sessions))}).option("--project-id <id>","Filter chat sessions by a single project id.").option("--project-ids <ids...>","Filter chat sessions by multiple project ids.").option("--active-only","Only return non-archived chat sessions.").option("--include-archived","Include archived chat sessions.")}function We(t,e){O(t.command("send").description("Send a follow-up message to a chat session.")).requiredOption("--session-id <id>","Chat session id.").requiredOption("--content <text>","Message content.").addOption(new U("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new U("--executor-type <type>","Executor override for this message.").choices(Object.values(rt))).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:x(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(ht("Chat message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Je(t,e){const n=t.command("chat").description("Manage normal chat sessions.");Me(n,e),Ue(n,e),Ge(n,e),Be(n,e),We(n,e)}function q(t){const e=t?.trim();return e||void 0}function Ft(t){if(!t)return"";const e=q(t.mode);if(e==="once")return["once",q(t.runAt)].filter(Boolean).join(" ");const n=q(t.repeat?.rule)??e??"";return[n,n==="weekly"?(t.repeat?.weekdays??[]).map(r=>r.trim().slice(0,3).toLowerCase()).join(","):void 0,q(t.timeOfDay),q(t.timeZone)].filter(Boolean).join(" ")}function z(t){return{id:q(t.id)??"",type:q(t.type)??"",name:q(t.name)??"",enabled:t.enabled===!0,state:q(t.state)??"",nextRunAt:q(t.nextRunAt)??null,schedule:t.schedule,agentPool:t.agentPool,payload:t.payload}}function ze(t){return{plans:t.map(z)}}function Ke(t){return t.length===0?`No scheduled plans found.
46
+ `:`Plans (${t.length})
47
+ ${B([{header:"ID",value:e=>e.id},{header:"Type",value:e=>e.type},{header:"Name",value:e=>e.name},{header:"Enabled",value:e=>e.enabled?"yes":"no"},{header:"State",value:e=>e.state},{header:"Next Run",value:e=>e.nextRunAt??"-"},{header:"Schedule",value:e=>Ft(e.schedule)}],t)}
48
+ `}function et(t){return H([["id",t.id],["type",t.type],["name",t.name],["enabled",t.enabled?"yes":"no"],["state",t.state],["nextRun",t.nextRunAt??"-"],["schedule",Ft(t.schedule)]])}function Qe(t){return{planId:t,deleted:!0}}function Xe(t){return`Plan deleted
49
+ ${H([["planId",t.planId],["deleted",String(t.deleted)]])}`}function Ye(t){return{planId:q(t.planId)??"",accepted:!0}}function Ze(t){return`Plan run accepted
50
+ ${H([["planId",t.planId],["accepted",String(t.accepted)]])}`}async function ti(){const t=[];for await(const e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}async function At(t){const e=t.trim();if(!e)throw new j("Provide --input <file> or --input - for stdin.");const n=e==="-"?await ti():await(0,le.readFile)(e,"utf8");try{return JSON.parse(n)}catch(r){throw new j(`Invalid JSON input from ${e}: ${r instanceof Error?r.message:String(r)}`)}}var ei=["id","createdAt","updatedAt","state","nextRunAt"];async function Lt(t){let e;try{e=await At(t)}catch(n){throw n instanceof j?n:new j(`Cannot read plan input from ${t}: ${n instanceof Error?n.message:String(n)}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new j(`Plan input from ${t} must be a JSON object.`);return e}function ot(t){const e={...t};for(const n of ei)delete e[n];return e}function ii(t){return{strategy:"random",agents:[{heroId:t}]}}function Gt(t){return{...t.name!==void 0?{name:t.name}:{},...t.heroId!==void 0?{agentPool:ii(t.heroId)}:{},...t.enabled!==void 0?{enabled:t.enabled}:{}}}function Ut(t,e){return{...ot(t),...ot(e)}}function si(t,e){O(t.command("create").description("Create a scheduled plan from a JSON document. Plans are enabled unless --disabled or the document says otherwise.")).requiredOption("--input <file|->","Plan JSON file path, or - to read from stdin.").option("--name <name>","Plan name. Overrides the document name.").option("--hero-id <id>","Hero for a single-agent pool. Replaces the document agent pool.").option("--disabled","Create the plan disabled. Overrides the document enabled value.").action(async function(r){const i=S(this,e),s=ot(await Lt(r.input)),a=z(await i.api.createPlan({enabled:!0,...s,...Gt({name:b(r.name),heroId:b(r.heroId),enabled:r.disabled?!1:void 0})}));if(i.outputJson){i.io.stdout(A({plan:a}));return}i.io.stdout(`Plan created
51
+ ${et(a)}`)})}function oi(t,e){O(t.command("delete").description("Delete a scheduled plan by id.")).requiredOption("--id <id>","Plan id to delete.").action(async function(r){const i=S(this,e),s=x(r.id,"--id");await i.api.deletePlan(s);const a=Qe(s);if(i.outputJson){i.io.stdout(A(a));return}i.io.stdout(Xe(a))})}async function Bt(t,e,n){const r=await t.api.getPlan(e);return z(r).enabled===n?{view:z(r),changed:!1}:{view:z(await t.api.updatePlan(e,Ut(r,{enabled:n}))),changed:!0}}function ni(t,e){O(t.command("disable").description("Disable a scheduled plan. Nothing is sent when it is already disabled.")).requiredOption("--id <id>","Plan id to disable.").action(async function(r){const i=S(this,e),{view:s,changed:a}=await Bt(i,x(r.id,"--id"),!1);if(i.outputJson){i.io.stdout(A({plan:s,changed:a}));return}i.io.stdout(`${a?"Plan disabled":"Plan was already disabled"}
52
+ ${et(s)}`)})}function ri(t,e){O(t.command("enable").description("Enable a scheduled plan. Nothing is sent when it is already enabled.")).requiredOption("--id <id>","Plan id to enable.").action(async function(r){const i=S(this,e),{view:s,changed:a}=await Bt(i,x(r.id,"--id"),!0);if(i.outputJson){i.io.stdout(A({plan:s,changed:a}));return}i.io.stdout(`${a?"Plan enabled":"Plan was already enabled"}
53
+ ${et(s)}`)})}function ai(t,e){O(t.command("get").description("Show one scheduled plan, including its schedule, agent pool and payload in --json mode.")).requiredOption("--id <id>","Plan id to read.").action(async function(r){const i=S(this,e),s=z(await i.api.getPlan(x(r.id,"--id")));if(i.outputJson){i.io.stdout(A({plan:s}));return}i.io.stdout(et(s))})}function li(t,e){O(t.command("list").description("List scheduled plans with their state, next run time and schedule.")).action(async function(){const r=S(this,e),i=ze(await r.api.listPlans());if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(Ke(i.plans))})}function ui(t,e){O(t.command("run").description("Run a scheduled plan now from its stored inputs. The schedule is not changed.")).requiredOption("--id <id>","Plan id to run.").option("--background","Start the run and print the accepted plan id without waiting for the session.").action(async function(r){const i=S(this,e),s=x(r.id,"--id");if(r.background){const u=Ye(await i.api.startPlan(s));if(i.outputJson){i.io.stdout(A(u));return}i.io.stdout(Ze(u));return}const a=M(await i.api.runPlan(s));if(i.outputJson){i.io.stdout(A({session:a}));return}i.io.stdout(`Plan run created a session
54
+ ${Q(a)}`)})}function di(t,e){O(t.command("update").description("Update a scheduled plan. The current plan is read first and only the given fields change.")).requiredOption("--id <id>","Plan id to update.").option("--input <file|->","JSON document whose top-level fields replace the same fields of the plan.").option("--name <name>","Updated plan name.").option("--hero-id <id>","Hero for a single-agent pool. Replaces the agent pool.").option("--enabled","Enable the plan.").option("--disabled","Disable the plan.").action(async function(r){const i=x(r.id,"--id"),s=b(r.input),a=b(r.name),u=b(r.heroId);if(r.enabled&&r.disabled)throw new j("Pass either --enabled or --disabled, not both.");const h=r.enabled?!0:r.disabled?!1:void 0;if(!s&&!a&&!u&&h===void 0)throw new j("Provide at least one change: --input, --name, --enabled, --disabled, or --hero-id.");const v=s?ot(await Lt(s)):{},_=S(this,e),P=await _.api.getPlan(i),w=z(await _.api.updatePlan(i,Ut(P,{...v,...Gt({name:a,heroId:u,enabled:h})})));if(_.outputJson){_.io.stdout(A({plan:w}));return}_.io.stdout(`Plan updated
55
+ ${et(w)}`)})}function ci(t,e){const n=t.command("plan").description("Manage scheduled plans: saved proposal or HagiTask inputs that run on a schedule.");li(n,e),ai(n,e),si(n,e),di(n,e),ri(n,e),ni(n,e),oi(n,e),ui(n,e)}function J(t){const e=t?.trim();return e||void 0}function Ot(t){return{id:J(t.id)??"",name:J(t.name)??"",path:J(t.path)??"",description:J(t.description),isMonoSpecs:t.isMonoSpecs===!0,monoSpecsVersion:J(t.monoSpecsVersion),monoSpecsRepoDirectory:J(t.monoSpecsRepoDirectory),monoSpecsCommitWhenArchive:typeof t.monoSpecsCommitWhenArchive=="boolean"?t.monoSpecsCommitWhenArchive:void 0,hasError:"hasError"in t?t.hasError===!0:!1,error:"error"in t?J(t.error):void 0}}function Mt(t){return{projects:(t??[]).map(Ot)}}function pi(t){return t.length===0?`No projects found.
56
+ `:`Projects (${t.length})
57
+ ${B([{header:"Project ID",value:e=>e.id},{header:"Name",value:e=>e.name},{header:"Path",value:e=>e.path},{header:"MonoSpecs",value:e=>e.isMonoSpecs?"yes":"no"},{header:"Error",value:e=>e.hasError?"yes":"no"}],t)}
58
+ `}function Wt(t,e=[]){return H([["id",t.id],["name",t.name],["path",t.path],["description",t.description],["isMonoSpecs",String(t.isMonoSpecs)],["monoSpecsVersion",t.monoSpecsVersion],["monoSpecsRepoDirectory",t.monoSpecsRepoDirectory],["monoSpecsCommitWhenArchive",typeof t.monoSpecsCommitWhenArchive=="boolean"?String(t.monoSpecsCommitWhenArchive):void 0],["hasError",String(t.hasError)],["error",t.error],...e])}function hi(t,e){O(t.command("create").description("Create a project through the generated project client.")).requiredOption("--name <name>","Project display name.").requiredOption("--path <path>","Project root path.").option("--description <text>","Optional project description.").action(async function(r){const i=S(this,e),s=Ot(await i.api.createProject({name:x(r.name,"--name"),path:x(r.path,"--path"),description:b(r.description)}));if(i.outputJson){i.io.stdout(A({project:s}));return}i.io.stdout(`Project created
59
+ ${Wt(s)}`)})}function mi(t,e){O(t.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(r){const i=S(this,e),s=r.id.trim();if(await i.api.deleteProject(s),i.outputJson){i.io.stdout(A({projectId:s,deleted:!0}));return}i.io.stdout(`Project deleted
60
+ projectId ${s}
61
+ `)})}function fi(t,e){O(t.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const r=S(this,e),i=Mt((await r.api.listProjects()).projects);if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(pi(i.projects))})}function gi(t,e){O(t.command("update").description("Update a project by merging provided fields into the aggregation snapshot.")).requiredOption("--id <id>","Project id to update.").option("--name <name>","Updated project name.").option("--path <path>","Updated project path.").option("--description <text>","Updated project description.").option("--clear-description","Clear the stored description.").action(async function(r){if(!r.name&&!r.path&&!r.description&&!r.clearDescription)throw new j("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(r.description&&r.clearDescription)throw new j("Use either --description or --clear-description, not both.");const i=S(this,e),s=r.id.trim(),a=Mt((await i.api.listProjects()).projects).projects.find(h=>h.id===s);if(!a)throw new mt(404,`Project ${s} was not found in the aggregation snapshot.`);const u=Ot(await i.api.updateProject(s,{name:b(r.name)??a.name,path:b(r.path)??a.path,description:r.clearDescription?null:b(r.description)??a.description??null}));if(i.outputJson){i.io.stdout(A({project:u}));return}i.io.stdout(`Project updated
62
+ ${Wt(u)}`)})}function vi(t,e){const n=t.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");fi(n,e),hi(n,e),gi(n,e),mi(n,e)}function yi(t,e){if(!e||typeof e!="object"||Array.isArray(e))throw new j("Annotation input must be a JSON object.");const n=e;if(!Array.isArray(n.files))throw new j("Annotation input must include a files array.");const r=typeof n.totalAnnotations=="number"?n.totalAnnotations:n.files.length,i=typeof n.submittedAt=="string"&&n.submittedAt.trim()?n.submittedAt:new Date().toISOString();return{...n,sessionId:t,totalAnnotations:r,submittedAt:i,files:n.files}}function Ai(t,e){O(t.command("annotate").description("Submit proposal annotations from structured JSON input.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=yi(s,await At(r.input)),u=await i.api.submitAnnotations(s,a);if(i.outputJson){i.io.stdout(A({sessionId:s,message:u.message,annotationCount:u.annotationCount??a.totalAnnotations,fileCount:u.fileCount??a.files.length}));return}i.io.stdout(`Proposal annotations submitted
63
+ sessionId ${s}
64
+ message ${u.message}
65
+ annotationCount ${u.annotationCount??a.totalAnnotations}
66
+ fileCount ${u.fileCount??a.files.length}
67
+ `)})}function Oi(t,e){O(t.command("archive").description("Archive a proposal session through the explicit archive endpoint.")).requiredOption("--session-id <id>","Proposal session id to archive.").option("--hero-id <id>","Optional hero override for archiving.").action(async function(r){const i=S(this,e),s=M(await i.api.archiveProposal(r.sessionId.trim(),{heroId:b(r.heroId)}));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Proposal archive started
68
+ ${Q(s)}`)})}function Si(t,e){O(t.command("complete").description("Mark a proposal session as completed through the dedicated completion endpoint.")).requiredOption("--session-id <id>","Proposal session id to complete.").action(async function(r){const i=S(this,e),s=M(await i.api.completeProposal(r.sessionId.trim()));if(i.outputJson){i.io.stdout(A({session:s}));return}i.io.stdout(`Proposal completed
69
+ ${Q(s)}`)})}function Ci(t){return M(t)}function bi(t){return jt(t)}function _i(t){return $t("Proposal sessions",t)}function Pi(t,e=[]){return Q(t,e)}var Jt="New Proposal";function wi(t){const e=b(t.title);if(e)return e;if(t.defaultTitle)return Jt;throw new j("Provide --title or pass --default-title to use the placeholder proposal title.")}function Ei(t,e){O(t.command("create").description("Create a proposal session only. This command does not trigger later lifecycle APIs.")).requiredOption("--project-id <id>","Project id that owns the new proposal session.").requiredOption("--chief-complaint <text>","Proposal chief complaint to store on the new session.").option("--original-chief-complaint <text>","Optional raw chief complaint text to keep alongside the stitched content.").option("--title <title>","Explicit proposal session title.").option("--default-title",`Mark the title as the placeholder title (${Jt}).`).option("--enable-independent-workspace","Request an independent workspace for the proposal session.").option("--base-branch <branch>","Optional base branch for the independent workspace.").action(async function(r){const i=S(this,e),s=wi(r),a=Ci(await i.api.createProposalSession({title:s,chiefComplaint:r.chiefComplaint.trim(),originalChiefComplaint:b(r.originalChiefComplaint),type:yt.PROPOSAL,projectId:r.projectId.trim(),enableIndependentWorkspace:r.enableIndependentWorkspace?!0:void 0,baseBranch:b(r.baseBranch),isDefaultTitle:!!r.defaultTitle})),u=`hagi proposal optimize-description --session-id ${a.sessionId} --description "<description>"`;if(i.outputJson){i.io.stdout(A({session:a,nextCommand:u}));return}i.io.stdout(`Proposal session created
70
+ ${Pi(a,[["next",u]])}`)})}function Ti(t,e){O(t.command("execute").description("Start proposal execution only. This command maps to the execute-proposal backend action.")).requiredOption("--session-id <id>","Proposal session id to execute.").option("--hero-id <id>","Optional hero override for the execute stage.").action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=b(r.heroId),u=await i.api.executeProposal(s,{heroId:a});if(i.outputJson){i.io.stdout(A({sessionId:s,message:u.message,requested:{heroId:a}}));return}i.io.stdout(`Proposal execution started
71
+ sessionId ${s}
72
+ message ${u.message}
73
+ `)})}var ct=["zh-CN","zh-Hant","en-US","ja-JP","ko-KR","de-DE","fr-FR","es-ES","pt-BR","ru-RU"];function Ii(t){if(t.enableExploreMode&&t.disableExploreMode)throw new j("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(t.enableExploreMode)return!0;if(t.disableExploreMode)return!1}function xi(t){const e=t.trim();if(!ct.includes(e))throw new j(`--proposal-content-language must be one of: ${ct.join(", ")}.`);return e}function ki(t,e){O(t.command("generate").description("Start proposal generation only. This command does not execute the proposal.")).requiredOption("--session-id <id>","Proposal session id to generate.").requiredOption("--proposal-content-language <language>",`Language of the generated proposal content (${ct.join(", ")}).`).option("--enable-explore-mode","Explicitly enable explore mode for proposal generation.").option("--disable-explore-mode","Explicitly disable explore mode for proposal generation.").option("--hero-id <id>","Optional hero override for the generate stage.").action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=Ii(r),u=xi(r.proposalContentLanguage),h=await i.api.generateProposal(s,{enableExploreMode:a,heroId:b(r.heroId),proposalContentLanguage:u}),v=`hagi proposal execute --session-id ${s}`;if(i.outputJson){i.io.stdout(A({sessionId:s,message:h.message,requested:{enableExploreMode:a,heroId:b(r.heroId),proposalContentLanguage:u},nextCommand:v}));return}i.io.stdout(`Proposal generation started
74
+ sessionId ${s}
75
+ message ${h.message}
76
+ next Wait for the session to reach Reviewing, then run ${v}
77
+ `)})}function ji(t,e){O(t.command("list").description("List proposal sessions from the backend Sessions API.")).option("--project-id <id>","Filter proposal sessions by a single project id.").option("--project-ids <ids...>","Filter proposal sessions by multiple project ids.").option("--active-only","Only return non-archived proposal sessions.").option("--include-archived","Include archived proposal sessions in the result set.").action(async function(r){if(r.projectId&&r.projectIds?.length)throw new j("Use either --project-id or --project-ids, not both.");const i=S(this,e),s=bi(await i.api.listSessions({type:yt.PROPOSAL,projectId:b(r.projectId),projectIds:r.projectIds?.map(b).filter(Boolean),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(_i(s.sessions))})}function $i(t,e){const n=e.summary,r=e.result,i=r?.validation?.isValid===!0,s=n?.appliedTitle||r?.optimizedTitle||"",a=n?.appliedProposalName||r?.optimizedProposalName||"",u=r?.validation?.diagnostics??[],h=[i?"Proposal optimized":"Proposal optimization returned diagnostics",`sessionId ${t}`,`title ${s}`,`proposalName ${a}`,`valid ${i?"yes":"no"}`];for(const v of u)h.push(`diagnostic ${v.code??"UNKNOWN"}: ${v.message??""}`.trimEnd());return i&&h.push(`next hagi proposal generate --session-id ${t}`),`${h.join(`
78
+ `)}
79
+ `}function Ni(t,e){O(t.command("optimize-description").description("Optimize the proposal description, title, and name in one backend step.")).requiredOption("--session-id <id>","Proposal session id to optimize.").requiredOption("--description <text>","Description text to optimize.").option("--title <title>","Current title snapshot. The session title is used when omitted.").option("--default-title","Treat the current title as the placeholder title.").option("--optimization-direction <text>","Optional optimization direction for AI guidance.").option("--original-chief-complaint <text>","Optional original chief complaint to keep as context.").action(async function(r){const i=S(this,e),s=x(r.sessionId,"--session-id"),a=await i.api.optimizeProposal(s,{description:x(r.description,"--description"),title:b(r.title),isDefaultTitle:r.defaultTitle?!0:void 0,optimizationDirection:b(r.optimizationDirection),originalChiefComplaint:b(r.originalChiefComplaint)});if(i.outputJson){i.io.stdout(A({sessionId:s,...a}));return}i.io.stdout($i(s,a))})}function Di(t,e){O(t.command("send").description("Send a follow-up message to a proposal session.")).requiredOption("--session-id <id>","Proposal session id.").requiredOption("--content <text>","Message content.").addOption(new U("--mode <mode>","Message mode override.").choices(Object.values(vt))).addOption(new U("--executor-type <type>","Executor override for this message.").choices(Object.values(rt))).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.sendMessage(s,{content:x(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(A({sessionId:s,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(ht("Proposal message sent",s,a,[["mode",r.mode],["executorType",r.executorType]]))})}function Vi(t,e){O(t.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new U("--status <status>","Target session status.").choices(Object.values(xt)).makeOptionMandatory()).action(async function(r){const i=S(this,e),s=r.sessionId.trim(),a=await i.api.getSession(s);await i.api.updateSession(s,{title:a.title,description:a.description,status:r.status,metadata:a.metadata});const u=M({...a,status:r.status});if(i.outputJson){i.io.stdout(A({session:u}));return}i.io.stdout(`Proposal status updated
80
+ ${Q(u)}`)})}function Hi(t,e){const n=t.command("proposal").description("Manage proposal sessions through backend session APIs.");ji(n,e),Ei(n,e),Ni(n,e),ki(n,e),Ai(n,e),Ti(n,e),Oi(n,e),Vi(n,e),Si(n,e),Di(n,e)}function Z(t){return t?"yes":"no"}function Ri(t){return t&&t.length>0?t.join(", "):"-"}function qi(t){const e=t.items??[];return e.length===0?`No local skills installed.
81
+ `:`Local skills (${e.length})
82
+ ${B([{header:"Name",value:n=>n.name??"-"},{header:"Scope",value:n=>n.scope??"-"},{header:"Agents",value:n=>Ri(n.agents)},{header:"Path",value:n=>n.path??"-"}],e)}
83
+ `}function Fi(t){return H([["skillName",t.skillName??void 0],["status",t.status??void 0],["message",t.userMessage??void 0],["diagnostic",t.diagnosticMessage??void 0]])}function Li(t){const e=t.items??[];return e.length===0?`No gallery skills found.
84
+ `:`Gallery skills (${e.length})
85
+ ${B([{header:"ID",value:n=>n.id??"-"},{header:"Source",value:n=>n.source??"-"},{header:"Installs",value:n=>String(n.installs??0)},{header:"Trusted",value:n=>Z(n.isTrustedSource)}],e)}
86
+ `}function Gi(t){const e=t.trustedProvider;return H([["id",t.id??void 0],["source",t.source??void 0],["skillSlug",t.skillSlug??void 0],["installable",Z(t.isInstallable)],["description",t.description??void 0],["repository",t.repositoryFullName??t.repositoryName??void 0],["repositoryUrl",t.repositoryUrl??void 0],["defaultBranch",t.repositoryDefaultBranch??void 0],["trustedSource",Z(t.isTrustedSource)],["trustedProvider",e?`${e.displayName??e.providerId??"-"}`:void 0],["installReference",t.installReference??void 0],["installCommand",t.installCommandPreview??void 0],["installVersion",t.installVersion??void 0],["installHint",t.installHint??void 0]])}function Ui(t){return H([["installReference",t.installReference??void 0],["normalizedSkillKey",t.normalizedSkillKey??void 0],["version",t.version??void 0],["status",t.status??void 0],["message",t.userMessage??void 0],["diagnostic",t.diagnosticMessage??void 0],["commandPreview",t.commandPreview??void 0]])}function st(t){const e=t.items??[];return e.length===0?`No trusted providers (directory version ${t.version??0}).
87
+ `:`Trusted providers (${e.length}, directory version ${t.version??0})
88
+ ${B([{header:"Provider ID",value:n=>n.providerId??"-"},{header:"Name",value:n=>n.displayName??"-"},{header:"Enabled",value:n=>Z(n.isEnabled)},{header:"Preset",value:n=>Z(n.isPreset)},{header:"Rules",value:n=>String(n.ruleCount??0)}],e)}
89
+ `}function Bi(t,e){const n=t.command("gallery").description("Search the skill gallery, read skill details, and start managed installs.");O(n.command("search").description("Search the skill gallery by keyword.")).option("--query <query>","Keyword to search for. Omit to list the gallery.").action(async function(i){const s=S(this,e),a=await s.api.searchSkillGallery(b(i.query));if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Li(a))}),O(n.command("detail").description("Show one gallery skill with installability, trust, and repository details.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").action(async function(i){const s=S(this,e),a=await s.api.getSkillGalleryDetail(x(i.id,"--id"),x(i.source,"--source"));if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Gi(a))}),O(n.command("install").description("Start a managed install of one gallery skill.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").requiredOption("--skill-slug <slug>","Skill slug inside the source repository.").option("--version <version>","Optional version token to install.").action(async function(i){const s=S(this,e),a=await s.api.installGallerySkill({id:x(i.id,"--id"),source:x(i.source,"--source"),skillSlug:x(i.skillSlug,"--skill-slug"),version:b(i.version)});if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Ui(a))})}function Mi(t,e){const n=t.command("local").description("List and uninstall globally installed local skills.");O(n.command("list").description("List installed local skills with their managed install metadata.")).action(async function(){const i=S(this,e),s=await i.api.listLocalSkills();if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(qi(s))}),O(n.command("uninstall").description("Uninstall one managed local skill by name.")).requiredOption("--skill-name <name>","Local skill name to uninstall.").action(async function(i){const s=S(this,e),a=await s.api.uninstallLocalSkill({skillName:x(i.skillName,"--skill-name")});if(s.outputJson){s.io.stdout(A(a));return}s.io.stdout(Fi(a))})}async function Wi(t,e){const n=await At(t);if(!n||typeof n!="object"||Array.isArray(n))throw new j(`${e} must be a JSON object.`);return n}function Ji(t,e){const n=t.command("trusted").description("Manage the trusted skill provider directory.");O(n.command("list").description("List trusted skill providers.")).action(async function(){const i=S(this,e),s=await i.api.listTrustedSkillProviders();if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(st(s))}),O(n.command("upsert").description("Create or update a trusted provider from a JSON document.")).requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(i){const s=S(this,e),a=await Wi(x(i.input,"--input"),"Trusted provider input"),u=await s.api.upsertTrustedSkillProvider(a);if(s.outputJson){s.io.stdout(A(u));return}s.io.stdout(st(u))}),O(n.command("delete").description("Delete one trusted provider by id.")).requiredOption("--provider-id <id>","Trusted provider id to delete.").action(async function(i){const s=S(this,e),a={providerId:x(i.providerId,"--provider-id")},u=await s.api.deleteTrustedSkillProvider(a);if(s.outputJson){s.io.stdout(A(u));return}s.io.stdout(st(u))}),O(n.command("reset").description("Reset trusted providers to the backend defaults.")).action(async function(){const i=S(this,e),s=await i.api.resetTrustedSkillProviders();if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(st(s))})}function zi(t,e){const n=t.command("skills").description("Manage local skills, the skill gallery, and trusted providers.");Mi(n,e),Bi(n,e),Ji(n,e)}function I(t){const e=t?.trim();return e||void 0}function Ki(t){return{severity:I(t.severity)??"",code:I(t.code)??"",message:I(t.message)??"",relativePath:I(t.relativePath)}}function St(t){return{id:I(t.id)??"",name:I(t.name)??"",type:I(t.type)??"",physicalPath:I(t.physicalPath)??"",gitUrl:I(t.gitUrl),createdAtUtc:I(t.createdAtUtc),updatedAtUtc:I(t.updatedAtUtc),bootstrapDiagnostics:(t.bootstrapDiagnostics??[]).map(Ki)}}function zt(t){return{generatedAtUtc:I(t.generatedAtUtc),vaults:(t.items??[]).map(St)}}function Qi(t){return t.length===0?`No vaults found.
90
+ `:`Vaults (${t.length})
91
+ ${B([{header:"Vault ID",value:e=>e.id},{header:"Type",value:e=>e.type},{header:"Name",value:e=>e.name},{header:"Path",value:e=>e.physicalPath}],t)}
92
+ `}function Kt(t,e=[]){return H([["id",t.id],["name",t.name],["type",t.type],["physicalPath",t.physicalPath],["gitUrl",t.gitUrl],["createdAtUtc",t.createdAtUtc],["updatedAtUtc",t.updatedAtUtc],["bootstrapDiagnostics",String(t.bootstrapDiagnostics.length)],...e])}function Xi(t){return{relativePath:I(t.relativePath)??"",fileName:I(t.fileName)??"",isDirectory:t.isDirectory===!0,extension:I(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:I(t.lastModifiedUtc),previewSupported:t.previewSupported===!0}}function Yi(t){return{vaultId:I(t.id)??"",deleted:t.deleted===!0,deleteLocalFilesRequested:t.deleteLocalFilesRequested===!0,localFilesDeletionStatus:I(t.localFilesDeletionStatus),localFilesDeleted:t.localFilesDeleted===!0}}function Zi(t){return`Vault deleted
93
+ ${H([["vaultId",t.vaultId],["deleted",String(t.deleted)],["deleteLocalFilesRequested",String(t.deleteLocalFilesRequested)],["localFilesDeletionStatus",t.localFilesDeletionStatus],["localFilesDeleted",String(t.localFilesDeleted)]])}`}function ts(t){return{vaultId:I(t.vaultId)??"",vaultName:I(t.vaultName)??"",physicalPath:I(t.physicalPath)??"",status:I(t.status)??"",errorCode:I(t.errorCode),message:I(t.message),isTruncated:t.isTruncated===!0,totalFileCount:typeof t.totalFileCount=="number"?t.totalFileCount:0,items:(t.items??[]).map(Xi)}}function es(t){const e=H([["vaultId",t.vaultId],["vaultName",t.vaultName],["physicalPath",t.physicalPath],["status",t.status],["errorCode",t.errorCode],["message",t.message],["isTruncated",String(t.isTruncated)],["totalFileCount",String(t.totalFileCount)]]);return t.items.length===0?`Vault files
94
+ ${e}No files found.
95
+ `:`Vault files
96
+ ${e}${B([{header:"Relative Path",value:n=>n.relativePath},{header:"Directory",value:n=>n.isDirectory?"yes":"no"},{header:"Extension",value:n=>n.extension},{header:"Size",value:n=>String(n.sizeBytes)},{header:"Preview",value:n=>n.previewSupported?"yes":"no"}],t.items)}
97
+ `}function is(t){return{vaultId:I(t.vaultId)??"",vaultName:I(t.vaultName)??"",physicalPath:I(t.physicalPath)??"",relativePath:I(t.relativePath)??"",fileName:I(t.fileName)??"",extension:I(t.extension)??"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,lastModifiedUtc:I(t.lastModifiedUtc),status:I(t.status)??"",errorCode:I(t.errorCode),message:I(t.message),previewSupported:t.previewSupported===!0,contentTruncated:t.contentTruncated===!0,content:I(t.content)}}function ss(t){const e=H([["vaultId",t.vaultId],["vaultName",t.vaultName],["physicalPath",t.physicalPath],["relativePath",t.relativePath],["fileName",t.fileName],["extension",t.extension],["sizeBytes",String(t.sizeBytes)],["lastModifiedUtc",t.lastModifiedUtc],["status",t.status],["errorCode",t.errorCode],["message",t.message],["previewSupported",String(t.previewSupported)],["contentTruncated",String(t.contentTruncated)]]);if(!t.content)return`Vault file preview
98
+ ${e}`;const n=t.content.endsWith(`
99
+ `)?"":`
100
+ `;return`Vault file preview
101
+ ${e}content
102
+ -------
103
+ ${t.content}${n}`}function os(t,e){O(t.command("create").description("Create a vault through the generated vault client.")).requiredOption("--name <name>","Vault display name.").requiredOption("--type <type>","Vault type, such as folder, obsidian, or coderef.").requiredOption("--physical-path <path>","Vault physical path.").option("--git-url <url>","Optional git remote URL for git-backed vaults.").action(async function(r){const i=S(this,e),s=St(await i.api.createVault({name:x(r.name,"--name"),type:x(r.type,"--type"),physicalPath:x(r.physicalPath,"--physical-path"),gitUrl:b(r.gitUrl)}));if(i.outputJson){i.io.stdout(A({vault:s}));return}i.io.stdout(`Vault created
104
+ ${Kt(s)}`)})}function ns(t,e){O(t.command("delete").description("Delete a vault by id and optionally request local file cleanup.")).requiredOption("--id <id>","Vault id to delete.").option("--delete-local-files","Request backend deletion of local vault files.").action(async function(r){const i=S(this,e),s=Yi(await i.api.deleteVault(x(r.id,"--id"),r.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(Zi(s))})}function rs(t,e){O(t.command("list").description("List files under a registered vault path.")).requiredOption("--id <id>","Vault id to browse.").option("--path <path>","Optional relative path under the vault root.").action(async function(r){const i=S(this,e),s=ts(await i.api.listVaultFiles(x(r.id,"--id"),b(r.path)));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(es(s))})}function as(t,e){O(t.command("preview").description("Preview supported file content from a registered vault.")).requiredOption("--id <id>","Vault id to browse.").requiredOption("--path <path>","Relative file path to preview.").action(async function(r){const i=S(this,e),s=is(await i.api.previewVaultFile(x(r.id,"--id"),x(r.path,"--path")));if(i.outputJson){i.io.stdout(A(s));return}i.io.stdout(ss(s))})}function ls(t,e){O(t.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const r=S(this,e),i=zt(await r.api.listVaults());if(r.outputJson){r.io.stdout(A(i));return}r.io.stdout(Qi(i.vaults))})}function us(t,e){O(t.command("update").description("Update a vault by merging provided fields into the current vault snapshot.")).requiredOption("--id <id>","Vault id to update.").option("--name <name>","Updated vault display name.").option("--type <type>","Updated vault type.").option("--physical-path <path>","Updated vault physical path.").option("--git-url <url>","Updated git remote URL.").action(async function(r){const i=b(r.name),s=b(r.type),a=b(r.physicalPath),u=b(r.gitUrl);if(!i&&!s&&!a&&!u)throw new j("Provide at least one field to update: --name, --type, --physical-path, or --git-url.");const h=S(this,e),v=x(r.id,"--id"),_=zt(await h.api.listVaults()).vaults.find(w=>w.id===v);if(!_)throw new mt(404,`Vault ${v} was not found in the latest vault snapshot.`);const P=St(await h.api.updateVault(v,{name:i??_.name,type:s??_.type,physicalPath:a??_.physicalPath,gitUrl:u??_.gitUrl??null}));if(h.outputJson){h.io.stdout(A({vault:P}));return}h.io.stdout(`Vault updated
105
+ ${Kt(P)}`)})}function ds(t,e){const n=t.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");ls(n,e),os(n,e),us(n,e),ns(n,e);const r=n.command("files").description("Browse registered vault files and preview supported content.");rs(r,e),as(r,e)}function cs(t){return t.includes("--json")}function Qt(t=qt(),e=!1){const n=new me;return n.name("hagi").description("HagiCode CLI for project, proposal, vault, chat, AutoTask, and scheduled plan management.").showHelpAfterError().exitOverride(),n.configureOutput({writeOut:r=>{t.io.stdout(r)},writeErr:r=>{e||t.io.stderr(r)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),Re(n),vi(n,t),Hi(n,t),ds(n,t),Je(n,t),Le(n,t),ci(n,t),zi(n,t),n}function ps(t,e,n){return t.exitCode===0||t.code==="commander.helpDisplayed"||t.code==="commander.version"?0:(n&&e.io.stderr(Dt({exitCode:V.USAGE,message:t.message},{json:!0})),V.USAGE)}async function hs(t=process.argv,e=qt()){const n=cs(t),r=Qt(e,n);try{return await r.parseAsync([...t]),0}catch(i){if(i instanceof he)return ps(i,e,n);const s=ge(i,{baseUrl:be()});return e.io.stderr(Dt(s,{json:n})),s.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return V}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return Qt}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return hs}});
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-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}
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./chunks/main-OnauE7J3.js");s.runCli().then(e=>{e!==0&&(process.exitCode=e)}).catch(e=>{const n=e instanceof Error?e.stack??e.message:String(e);process.stderr.write(`${n}
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-CL02Q4Mn.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/main-OnauE7J3.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.18.1.f7fa085",
3
+ "version": "0.1.0-dev.20.1.7843819",
4
4
  "description": "HagiCode CLI for project, proposal, vault, chat, and AutoTask management.",
5
5
  "homepage": "https://github.com/HagiCode-org/cli#readme",
6
6
  "bugs": {
@@ -1,94 +0,0 @@
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}});