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