@hagicode/cli 0.1.0-dev.31.1.bcd050b → 0.1.0-dev.34.1.015c6d4
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 +8 -2
- package/dist/chunks/main-Dp8gzsa8.js +164 -0
- package/dist/cli.js +1 -1
- package/dist/main.js +1 -1
- package/package.json +13 -4
- package/dist/chunks/main-BoZml4AL.js +0 -161
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-Dp8gzsa8.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-Dp8gzsa8.js");exports.createCliApp=e.createCliApp;exports.runCli=e.runCli;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hagicode/cli",
|
|
3
|
-
"version": "0.1.0-dev.
|
|
3
|
+
"version": "0.1.0-dev.34.1.015c6d4",
|
|
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,14 +18,16 @@
|
|
|
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:grpc": "node ./buildTools/generate-grpc.mjs",
|
|
30
|
+
"generate:grpc:check": "node ./buildTools/generate-grpc.mjs --check",
|
|
29
31
|
"generate:api": "node ./buildTools/generate-api.cjs",
|
|
30
32
|
"generate:api:once": "node ./buildTools/generate-api-once.cjs",
|
|
31
33
|
"pack:check": "node ./scripts/verify-package.mjs",
|
|
@@ -33,7 +35,9 @@
|
|
|
33
35
|
"publish:verify-release": "node ./scripts/verify-release-version.mjs",
|
|
34
36
|
"test": "vitest run",
|
|
35
37
|
"test:watch": "vitest",
|
|
36
|
-
"typecheck": "export NODE_OPTIONS=\"${NODE_OPTIONS:-} --max-old-space-size=8192\"; tsc --noEmit -p tsconfig.json"
|
|
38
|
+
"typecheck": "export NODE_OPTIONS=\"${NODE_OPTIONS:-} --max-old-space-size=8192\"; tsc --noEmit -p tsconfig.json",
|
|
39
|
+
"check:registry": "node scripts/check-registry-neutrality.mjs",
|
|
40
|
+
"test:registry": "node --test scripts/check-registry-neutrality.node-test.mjs"
|
|
37
41
|
},
|
|
38
42
|
"keywords": [
|
|
39
43
|
"hagicode",
|
|
@@ -54,9 +58,14 @@
|
|
|
54
58
|
"registry": "https://registry.npmjs.org/"
|
|
55
59
|
},
|
|
56
60
|
"dependencies": {
|
|
61
|
+
"@bufbuild/protobuf": "2.16.0",
|
|
62
|
+
"@connectrpc/connect": "2.2.0",
|
|
63
|
+
"@connectrpc/connect-node": "2.2.0",
|
|
57
64
|
"commander": "^14.0.2"
|
|
58
65
|
},
|
|
59
66
|
"devDependencies": {
|
|
67
|
+
"@bufbuild/buf": "1.73.0",
|
|
68
|
+
"@bufbuild/protoc-gen-es": "2.16.0",
|
|
60
69
|
"@types/node": "^25.0.2",
|
|
61
70
|
"openapi-typescript-codegen": "^0.29.0",
|
|
62
71
|
"rimraf": "^6.1.2",
|
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
var At=Object.create,Le=Object.defineProperty,Ot=Object.getOwnPropertyDescriptor,bt=Object.getOwnPropertyNames,Ct=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty,te=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),wt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(var i=bt(t),o=0,a=i.length,c;o<a;o++)c=i[o],!Pt.call(e,c)&&c!==n&&Le(e,c,{get:(p=>t[p]).bind(null,c),enumerable:!(r=Ot(t,c))||r.enumerable});return e},_t=(e,t,n)=>(n=e!=null?At(Ct(e)):{},wt(t||!e||!e.__esModule?Le(n,"default",{value:e,enumerable:!0}):n,e));let Ne=require("node:path"),Et=require("node:fs"),Tt=require("node:os"),It=require("node:fs/promises");var me=te((e=>{var t=class extends Error{constructor(r,i,o){super(o),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=r,this.nestedError=void 0}},n=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=n})),Ce=te((e=>{var{InvalidArgumentError:t}=me(),n=class{constructor(i,o){switch(this.description=o||"",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,o){return o===this.defaultValue||!Array.isArray(o)?[i]:(o.push(i),o)}default(i,o){return this.defaultValue=i,this.defaultValueDescription=o,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(o,a)=>{if(!this.argChoices.includes(o))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(o,a):o},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function r(i){const o=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+o+">":"["+o+"]"}e.Argument=n,e.humanReadableArgName=r})),Fe=te((e=>{var{humanReadableArgName:t}=Ce(),n=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(i){this.helpWidth=this.helpWidth??i.helpWidth??80}visibleCommands(i){const o=i.commands.filter(c=>!c._hidden),a=i._getHelpCommand();return a&&!a._hidden&&o.push(a),this.sortSubcommands&&o.sort((c,p)=>c.name().localeCompare(p.name())),o}compareOptions(i,o){const a=c=>c.short?c.short.replace(/^-/,""):c.long.replace(/^--/,"");return a(i).localeCompare(a(o))}visibleOptions(i){const o=i.options.filter(c=>!c.hidden),a=i._getHelpOption();if(a&&!a.hidden){const c=a.short&&i._findOption(a.short),p=a.long&&i._findOption(a.long);!c&&!p?o.push(a):a.long&&!p?o.push(i.createOption(a.long,a.description)):a.short&&!c&&o.push(i.createOption(a.short,a.description))}return this.sortOptions&&o.sort(this.compareOptions),o}visibleGlobalOptions(i){if(!this.showGlobalOptions)return[];const o=[];for(let a=i.parent;a;a=a.parent){const c=a.options.filter(p=>!p.hidden);o.push(...c)}return this.sortOptions&&o.sort(this.compareOptions),o}visibleArguments(i){return i._argsDescription&&i.registeredArguments.forEach(o=>{o.description=o.description||i._argsDescription[o.name()]||""}),i.registeredArguments.find(o=>o.description)?i.registeredArguments:[]}subcommandTerm(i){const o=i.registeredArguments.map(a=>t(a)).join(" ");return i._name+(i._aliases[0]?"|"+i._aliases[0]:"")+(i.options.length?" [options]":"")+(o?" "+o:"")}optionTerm(i){return i.flags}argumentTerm(i){return i.name()}longestSubcommandTermLength(i,o){return o.visibleCommands(i).reduce((a,c)=>Math.max(a,this.displayWidth(o.styleSubcommandTerm(o.subcommandTerm(c)))),0)}longestOptionTermLength(i,o){return o.visibleOptions(i).reduce((a,c)=>Math.max(a,this.displayWidth(o.styleOptionTerm(o.optionTerm(c)))),0)}longestGlobalOptionTermLength(i,o){return o.visibleGlobalOptions(i).reduce((a,c)=>Math.max(a,this.displayWidth(o.styleOptionTerm(o.optionTerm(c)))),0)}longestArgumentTermLength(i,o){return o.visibleArguments(i).reduce((a,c)=>Math.max(a,this.displayWidth(o.styleArgumentTerm(o.argumentTerm(c)))),0)}commandUsage(i){let o=i._name;i._aliases[0]&&(o=o+"|"+i._aliases[0]);let a="";for(let c=i.parent;c;c=c.parent)a=c.name()+" "+a;return a+o+" "+i.usage()}commandDescription(i){return i.description()}subcommandDescription(i){return i.summary()||i.description()}optionDescription(i){const o=[];if(i.argChoices&&o.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&(i.required||i.optional||i.isBoolean()&&typeof i.defaultValue=="boolean")&&o.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),i.presetArg!==void 0&&i.optional&&o.push(`preset: ${JSON.stringify(i.presetArg)}`),i.envVar!==void 0&&o.push(`env: ${i.envVar}`),o.length>0){const a=`(${o.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}argumentDescription(i){const o=[];if(i.argChoices&&o.push(`choices: ${i.argChoices.map(a=>JSON.stringify(a)).join(", ")}`),i.defaultValue!==void 0&&o.push(`default: ${i.defaultValueDescription||JSON.stringify(i.defaultValue)}`),o.length>0){const a=`(${o.join(", ")})`;return i.description?`${i.description} ${a}`:a}return i.description}formatItemList(i,o,a){return o.length===0?[]:[a.styleTitle(i),...o,""]}groupItems(i,o,a){const c=new Map;return i.forEach(p=>{const m=a(p);c.has(m)||c.set(m,[])}),o.forEach(p=>{const m=a(p);c.has(m)||c.set(m,[]),c.get(m).push(p)}),c}formatHelp(i,o){const a=o.padWidth(i,o),c=o.helpWidth??80;function p(_,x){return o.formatItem(_,a,x,o)}let m=[`${o.styleTitle("Usage:")} ${o.styleUsage(o.commandUsage(i))}`,""];const b=o.commandDescription(i);b.length>0&&(m=m.concat([o.boxWrap(o.styleCommandDescription(b),c),""]));const C=o.visibleArguments(i).map(_=>p(o.styleArgumentTerm(o.argumentTerm(_)),o.styleArgumentDescription(o.argumentDescription(_))));if(m=m.concat(this.formatItemList("Arguments:",C,o)),this.groupItems(i.options,o.visibleOptions(i),_=>_.helpGroupHeading??"Options:").forEach((_,x)=>{const G=_.map(R=>p(o.styleOptionTerm(o.optionTerm(R)),o.styleOptionDescription(o.optionDescription(R))));m=m.concat(this.formatItemList(x,G,o))}),o.showGlobalOptions){const _=o.visibleGlobalOptions(i).map(x=>p(o.styleOptionTerm(o.optionTerm(x)),o.styleOptionDescription(o.optionDescription(x))));m=m.concat(this.formatItemList("Global Options:",_,o))}return this.groupItems(i.commands,o.visibleCommands(i),_=>_.helpGroup()||"Commands:").forEach((_,x)=>{const G=_.map(R=>p(o.styleSubcommandTerm(o.subcommandTerm(R)),o.styleSubcommandDescription(o.subcommandDescription(R))));m=m.concat(this.formatItemList(x,G,o))}),m.join(`
|
|
2
|
-
`)}displayWidth(i){return r(i).length}styleTitle(i){return i}styleUsage(i){return i.split(" ").map(o=>o==="[options]"?this.styleOptionText(o):o==="[command]"?this.styleSubcommandText(o):o[0]==="["||o[0]==="<"?this.styleArgumentText(o):this.styleCommandText(o)).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(o=>o==="[options]"?this.styleOptionText(o):o[0]==="["||o[0]==="<"?this.styleArgumentText(o):this.styleSubcommandText(o)).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,o){return Math.max(o.longestOptionTermLength(i,o),o.longestGlobalOptionTermLength(i,o),o.longestSubcommandTermLength(i,o),o.longestArgumentTermLength(i,o))}preformatted(i){return/\n[^\S\r\n]/.test(i)}formatItem(i,o,a,c){const m=" ".repeat(2);if(!a)return m+i;const b=i.padEnd(o+i.length-c.displayWidth(i)),C=2,_=(this.helpWidth??80)-o-C-2;let x;return _<this.minWidthToWrap||c.preformatted(a)?x=a:x=c.boxWrap(a,_).replace(/\n/g,`
|
|
3
|
-
`+" ".repeat(o+C)),m+b+" ".repeat(C)+x.replace(/\n/g,`
|
|
4
|
-
${m}`)}boxWrap(i,o){if(o<this.minWidthToWrap)return i;const a=i.split(/\r\n|\n/),c=/[\s]*[^\s]+/g,p=[];return a.forEach(m=>{const b=m.match(c);if(b===null){p.push("");return}let C=[b.shift()],_=this.displayWidth(C[0]);b.forEach(x=>{const G=this.displayWidth(x);if(_+G<=o){C.push(x),_+=G;return}p.push(C.join(""));const R=x.trimStart();C=[R],_=this.displayWidth(R)}),p.push(C.join(""))}),p.join(`
|
|
5
|
-
`)}};function r(i){return i.replace(/\x1b\[\d*(;\d*)*m/g,"")}e.Help=n,e.stripColor=r})),Ge=te((e=>{var{InvalidArgumentError:t}=me(),n=class{constructor(a,c){this.flags=a,this.description=c||"",this.required=a.includes("<"),this.optional=a.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(a),this.mandatory=!1;const p=o(a);this.short=p.shortFlag,this.long=p.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(a,c){return this.defaultValue=a,this.defaultValueDescription=c,this}preset(a){return this.presetArg=a,this}conflicts(a){return this.conflictsWith=this.conflictsWith.concat(a),this}implies(a){let c=a;return typeof a=="string"&&(c={[a]:!0}),this.implied=Object.assign(this.implied||{},c),this}env(a){return this.envVar=a,this}argParser(a){return this.parseArg=a,this}makeOptionMandatory(a=!0){return this.mandatory=!!a,this}hideHelp(a=!0){return this.hidden=!!a,this}_collectValue(a,c){return c===this.defaultValue||!Array.isArray(c)?[a]:(c.push(a),c)}choices(a){return this.argChoices=a.slice(),this.parseArg=(c,p)=>{if(!this.argChoices.includes(c))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(c,p):c},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?i(this.name().replace(/^no-/,"")):i(this.name())}helpGroup(a){return this.helpGroupHeading=a,this}is(a){return this.short===a||this.long===a}isBoolean(){return!this.required&&!this.optional&&!this.negate}},r=class{constructor(a){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,a.forEach(c=>{c.negate?this.negativeOptions.set(c.attributeName(),c):this.positiveOptions.set(c.attributeName(),c)}),this.negativeOptions.forEach((c,p)=>{this.positiveOptions.has(p)&&this.dualOptions.add(p)})}valueFromOption(a,c){const p=c.attributeName();if(!this.dualOptions.has(p))return!0;const m=this.negativeOptions.get(p).presetArg,b=m!==void 0?m:!1;return c.negate===(b===a)}};function i(a){return a.split("-").reduce((c,p)=>c+p[0].toUpperCase()+p.slice(1))}function o(a){let c,p;const m=/^-[^-]$/,b=/^--[^-]/,C=a.split(/[ |,]+/).concat("guard");if(m.test(C[0])&&(c=C.shift()),b.test(C[0])&&(p=C.shift()),!c&&m.test(C[0])&&(c=C.shift()),!c&&b.test(C[0])&&(c=p,p=C.shift()),C[0].startsWith("-")){const _=C[0],x=`option creation failed due to '${_}' in option flags '${a}'`;throw/^-[^-][^-]/.test(_)?new Error(`${x}
|
|
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(_)?new Error(`${x}
|
|
9
|
-
- too many short flags`):b.test(_)?new Error(`${x}
|
|
10
|
-
- too many long flags`):new Error(`${x}
|
|
11
|
-
- unrecognised flag format`)}if(c===void 0&&p===void 0)throw new Error(`option creation failed due to no flags found in '${a}'.`);return{shortFlag:c,longFlag:p}}e.Option=n,e.DualOptions=r})),kt=te((e=>{var t=3;function n(i,o){if(Math.abs(i.length-o.length)>t)return Math.max(i.length,o.length);const a=[];for(let c=0;c<=i.length;c++)a[c]=[c];for(let c=0;c<=o.length;c++)a[0][c]=c;for(let c=1;c<=o.length;c++)for(let p=1;p<=i.length;p++){let m=1;i[p-1]===o[c-1]?m=0:m=1,a[p][c]=Math.min(a[p-1][c]+1,a[p][c-1]+1,a[p-1][c-1]+m),p>1&&c>1&&i[p-1]===o[c-2]&&i[p-2]===o[c-1]&&(a[p][c]=Math.min(a[p][c],a[p-2][c-2]+1))}return a[i.length][o.length]}function r(i,o){if(!o||o.length===0)return"";o=Array.from(new Set(o));const a=i.startsWith("--");a&&(i=i.slice(2),o=o.map(b=>b.slice(2)));let c=[],p=t;const m=.4;return o.forEach(b=>{if(b.length<=1)return;const C=n(i,b),_=Math.max(i.length,b.length);(_-C)/_>m&&(C<p?(p=C,c=[b]):C===p&&c.push(b))}),c.sort((b,C)=>b.localeCompare(C)),a&&(c=c.map(b=>`--${b}`)),c.length>1?`
|
|
12
|
-
(Did you mean one of ${c.join(", ")}?)`:c.length===1?`
|
|
13
|
-
(Did you mean ${c[0]}?)`:""}e.suggestSimilar=r})),jt=te((e=>{var t=require("node:events").EventEmitter,n=require("node:child_process"),r=require("node:path"),i=require("node:fs"),o=require("node:process"),{Argument:a,humanReadableArgName:c}=Ce(),{CommanderError:p}=me(),{Help:m,stripColor:b}=Fe(),{Option:C,DualOptions:_}=Ge(),{suggestSimilar:x}=kt(),G=class Ue extends t{constructor(s){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=s||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:l=>o.stdout.write(l),writeErr:l=>o.stderr.write(l),outputError:(l,u)=>u(l),getOutHelpWidth:()=>o.stdout.isTTY?o.stdout.columns:void 0,getErrHelpWidth:()=>o.stderr.isTTY?o.stderr.columns:void 0,getOutHasColors:()=>z()??(o.stdout.isTTY&&o.stdout.hasColors?.()),getErrHasColors:()=>z()??(o.stderr.isTTY&&o.stderr.hasColors?.()),stripColor:l=>b(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(s){return this._outputConfiguration=s._outputConfiguration,this._helpOption=s._helpOption,this._helpCommand=s._helpCommand,this._helpConfiguration=s._helpConfiguration,this._exitCallback=s._exitCallback,this._storeOptionsAsProperties=s._storeOptionsAsProperties,this._combineFlagAndOptionalValue=s._combineFlagAndOptionalValue,this._allowExcessArguments=s._allowExcessArguments,this._enablePositionalOptions=s._enablePositionalOptions,this._showHelpAfterError=s._showHelpAfterError,this._showSuggestionAfterError=s._showSuggestionAfterError,this}_getCommandAndAncestors(){const s=[];for(let l=this;l;l=l.parent)s.push(l);return s}command(s,l,u){let d=l,h=u;typeof d=="object"&&d!==null&&(h=d,d=null),h=h||{};const[,v,E]=s.match(/([^ ]+) *(.*)/),I=this.createCommand(v);return d&&(I.description(d),I._executableHandler=!0),h.isDefault&&(this._defaultCommandName=I._name),I._hidden=!!(h.noHelp||h.hidden),I._executableFile=h.executableFile||null,E&&I.arguments(E),this._registerCommand(I),I.parent=this,I.copyInheritedSettings(this),d?this:I}createCommand(s){return new Ue(s)}createHelp(){return Object.assign(new m,this.configureHelp())}configureHelp(s){return s===void 0?this._helpConfiguration:(this._helpConfiguration=s,this)}configureOutput(s){return s===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...s},this)}showHelpAfterError(s=!0){return typeof s!="string"&&(s=!!s),this._showHelpAfterError=s,this}showSuggestionAfterError(s=!0){return this._showSuggestionAfterError=!!s,this}addCommand(s,l){if(!s._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
|
-
- specify the name in Command constructor or using .name()`);return l=l||{},l.isDefault&&(this._defaultCommandName=s._name),(l.noHelp||l.hidden)&&(s._hidden=!0),this._registerCommand(s),s.parent=this,s._checkForBrokenPassThrough(),this}createArgument(s,l){return new a(s,l)}argument(s,l,u,d){const h=this.createArgument(s,l);return typeof u=="function"?h.default(d).argParser(u):h.default(u),this.addArgument(h),this}arguments(s){return s.trim().split(/ +/).forEach(l=>{this.argument(l)}),this}addArgument(s){const l=this.registeredArguments.slice(-1)[0];if(l?.variadic)throw new Error(`only the last argument can be variadic '${l.name()}'`);if(s.required&&s.defaultValue!==void 0&&s.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${s.name()}'`);return this.registeredArguments.push(s),this}helpCommand(s,l){if(typeof s=="boolean")return this._addImplicitHelpCommand=s,s&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;const[,u,d]=(s??"help [command]").match(/([^ ]+) *(.*)/),h=l??"display help for command",v=this.createCommand(u);return v.helpOption(!1),d&&v.arguments(d),h&&v.description(h),this._addImplicitHelpCommand=!0,this._helpCommand=v,(s||l)&&this._initCommandGroup(v),this}addHelpCommand(s,l){return typeof s!="object"?(this.helpCommand(s,l),this):(this._addImplicitHelpCommand=!0,this._helpCommand=s,this._initCommandGroup(s),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(s,l){const u=["preSubcommand","preAction","postAction"];if(!u.includes(s))throw new Error(`Unexpected value for event passed to hook : '${s}'.
|
|
15
|
-
Expecting one of '${u.join("', '")}'`);return this._lifeCycleHooks[s]?this._lifeCycleHooks[s].push(l):this._lifeCycleHooks[s]=[l],this}exitOverride(s){return s?this._exitCallback=s:this._exitCallback=l=>{if(l.code!=="commander.executeSubCommandAsync")throw l},this}_exit(s,l,u){this._exitCallback&&this._exitCallback(new p(s,l,u)),o.exit(s)}action(s){const l=u=>{const d=this.registeredArguments.length,h=u.slice(0,d);return this._storeOptionsAsProperties?h[d]=this:h[d]=this.opts(),h.push(this),s.apply(this,h)};return this._actionHandler=l,this}createOption(s,l){return new C(s,l)}_callParseArg(s,l,u,d){try{return s.parseArg(l,u)}catch(h){if(h.code==="commander.invalidArgument"){const v=`${d} ${h.message}`;this.error(v,{exitCode:h.exitCode,code:h.code})}throw h}}_registerOption(s){const l=s.short&&this._findOption(s.short)||s.long&&this._findOption(s.long);if(l){const u=s.long&&this._findOption(s.long)?s.long:s.short;throw new Error(`Cannot add option '${s.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${u}'
|
|
16
|
-
- already used by option '${l.flags}'`)}this._initOptionGroup(s),this.options.push(s)}_registerCommand(s){const l=d=>[d.name()].concat(d.aliases()),u=l(s).find(d=>this._findCommand(d));if(u){const d=l(this._findCommand(u)).join("|"),h=l(s).join("|");throw new Error(`cannot add command '${h}' as already have command '${d}'`)}this._initCommandGroup(s),this.commands.push(s)}addOption(s){this._registerOption(s);const l=s.name(),u=s.attributeName();if(s.negate){const h=s.long.replace(/^--no-/,"--");this._findOption(h)||this.setOptionValueWithSource(u,s.defaultValue===void 0?!0:s.defaultValue,"default")}else s.defaultValue!==void 0&&this.setOptionValueWithSource(u,s.defaultValue,"default");const d=(h,v,E)=>{h==null&&s.presetArg!==void 0&&(h=s.presetArg);const I=this.getOptionValue(u);h!==null&&s.parseArg?h=this._callParseArg(s,h,I,v):h!==null&&s.variadic&&(h=s._collectValue(h,I)),h==null&&(s.negate?h=!1:s.isBoolean()||s.optional?h=!0:h=""),this.setOptionValueWithSource(u,h,E)};return this.on("option:"+l,h=>{d(h,`error: option '${s.flags}' argument '${h}' is invalid.`,"cli")}),s.envVar&&this.on("optionEnv:"+l,h=>{d(h,`error: option '${s.flags}' value '${h}' from env '${s.envVar}' is invalid.`,"env")}),this}_optionEx(s,l,u,d,h){if(typeof l=="object"&&l instanceof C)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const v=this.createOption(l,u);if(v.makeOptionMandatory(!!s.mandatory),typeof d=="function")v.default(h).argParser(d);else if(d instanceof RegExp){const E=d;d=(I,N)=>{const y=E.exec(I);return y?y[0]:N},v.default(h).argParser(d)}else v.default(d);return this.addOption(v)}option(s,l,u,d){return this._optionEx({},s,l,u,d)}requiredOption(s,l,u,d){return this._optionEx({mandatory:!0},s,l,u,d)}combineFlagAndOptionalValue(s=!0){return this._combineFlagAndOptionalValue=!!s,this}allowUnknownOption(s=!0){return this._allowUnknownOption=!!s,this}allowExcessArguments(s=!0){return this._allowExcessArguments=!!s,this}enablePositionalOptions(s=!0){return this._enablePositionalOptions=!!s,this}passThroughOptions(s=!0){return this._passThroughOptions=!!s,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(s=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!s,this}getOptionValue(s){return this._storeOptionsAsProperties?this[s]:this._optionValues[s]}setOptionValue(s,l){return this.setOptionValueWithSource(s,l,void 0)}setOptionValueWithSource(s,l,u){return this._storeOptionsAsProperties?this[s]=l:this._optionValues[s]=l,this._optionValueSources[s]=u,this}getOptionValueSource(s){return this._optionValueSources[s]}getOptionValueSourceWithGlobals(s){let l;return this._getCommandAndAncestors().forEach(u=>{u.getOptionValueSource(s)!==void 0&&(l=u.getOptionValueSource(s))}),l}_prepareUserArgs(s,l){if(s!==void 0&&!Array.isArray(s))throw new Error("first parameter to parse must be array or undefined");if(l=l||{},s===void 0&&l.from===void 0){o.versions?.electron&&(l.from="electron");const d=o.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(l.from="eval")}s===void 0&&(s=o.argv),this.rawArgs=s.slice();let u;switch(l.from){case void 0:case"node":this._scriptPath=s[1],u=s.slice(2);break;case"electron":o.defaultApp?(this._scriptPath=s[1],u=s.slice(2)):u=s.slice(1);break;case"user":u=s.slice(0);break;case"eval":u=s.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",u}parse(s,l){this._prepareForParse();const u=this._prepareUserArgs(s,l);return this._parseCommand([],u),this}async parseAsync(s,l){this._prepareForParse();const u=this._prepareUserArgs(s,l);return await this._parseCommand([],u),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
17
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(s,l,u){if(i.existsSync(s))return;const d=`'${s}' does not exist
|
|
18
|
-
- if '${u}' 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(d)}_executeSubCommand(s,l){l=l.slice();let u=!1;const d=[".js",".ts",".tsx",".mjs",".cjs"];function h(y,k){const H=r.resolve(y,k);if(i.existsSync(H))return H;if(d.includes(r.extname(k)))return;const $e=d.find(St=>i.existsSync(`${H}${St}`));if($e)return`${H}${$e}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let v=s._executableFile||`${this._name}-${s._name}`,E=this._executableDir||"";if(this._scriptPath){let y;try{y=i.realpathSync(this._scriptPath)}catch{y=this._scriptPath}E=r.resolve(r.dirname(y),E)}if(E){let y=h(E,v);if(!y&&!s._executableFile&&this._scriptPath){const k=r.basename(this._scriptPath,r.extname(this._scriptPath));k!==this._name&&(y=h(E,`${k}-${s._name}`))}v=y||v}u=d.includes(r.extname(v));let I;o.platform!=="win32"?u?(l.unshift(v),l=R(o.execArgv).concat(l),I=n.spawn(o.argv[0],l,{stdio:"inherit"})):I=n.spawn(v,l,{stdio:"inherit"}):(this._checkForMissingExecutable(v,E,s._name),l.unshift(v),l=R(o.execArgv).concat(l),I=n.spawn(o.execPath,l,{stdio:"inherit"})),I.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(y=>{o.on(y,()=>{I.killed===!1&&I.exitCode===null&&I.kill(y)})});const N=this._exitCallback;I.on("close",y=>{y=y??1,N?N(new p(y,"commander.executeSubCommandAsync","(close)")):o.exit(y)}),I.on("error",y=>{if(y.code==="ENOENT")this._checkForMissingExecutable(v,E,s._name);else if(y.code==="EACCES")throw new Error(`'${v}' not executable`);if(!N)o.exit(1);else{const k=new p(1,"commander.executeSubCommandAsync","(error)");k.nestedError=y,N(k)}}),this.runningCommand=I}_dispatchSubcommand(s,l,u){const d=this._findCommand(s);d||this.help({error:!0}),d._prepareForParse();let h;return h=this._chainOrCallSubCommandHook(h,d,"preSubcommand"),h=this._chainOrCall(h,()=>{if(d._executableHandler)this._executeSubCommand(d,l.concat(u));else return d._parseCommand(l,u)}),h}_dispatchHelpCommand(s){s||this.help();const l=this._findCommand(s);return l&&!l._executableHandler&&l.help(),this._dispatchSubcommand(s,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((s,l)=>{s.required&&this.args[l]==null&&this.missingArgument(s.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const s=(u,d,h)=>{let v=d;if(d!==null&&u.parseArg){const E=`error: command-argument value '${d}' is invalid for argument '${u.name()}'.`;v=this._callParseArg(u,d,h,E)}return v};this._checkNumberOfArguments();const l=[];this.registeredArguments.forEach((u,d)=>{let h=u.defaultValue;u.variadic?d<this.args.length?(h=this.args.slice(d),u.parseArg&&(h=h.reduce((v,E)=>s(u,E,v),u.defaultValue))):h===void 0&&(h=[]):d<this.args.length&&(h=this.args[d],u.parseArg&&(h=s(u,h,u.defaultValue))),l[d]=h}),this.processedArgs=l}_chainOrCall(s,l){return s?.then&&typeof s.then=="function"?s.then(()=>l()):l()}_chainOrCallHooks(s,l){let u=s;const d=[];return this._getCommandAndAncestors().reverse().filter(h=>h._lifeCycleHooks[l]!==void 0).forEach(h=>{h._lifeCycleHooks[l].forEach(v=>{d.push({hookedCommand:h,callback:v})})}),l==="postAction"&&d.reverse(),d.forEach(h=>{u=this._chainOrCall(u,()=>h.callback(h.hookedCommand,this))}),u}_chainOrCallSubCommandHook(s,l,u){let d=s;return this._lifeCycleHooks[u]!==void 0&&this._lifeCycleHooks[u].forEach(h=>{d=this._chainOrCall(d,()=>h(this,l))}),d}_parseCommand(s,l){const u=this.parseOptions(l);if(this._parseOptionsEnv(),this._parseOptionsImplied(),s=s.concat(u.operands),l=u.unknown,this.args=s.concat(l),s&&this._findCommand(s[0]))return this._dispatchSubcommand(s[0],s.slice(1),l);if(this._getHelpCommand()&&s[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(s[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(l),this._dispatchSubcommand(this._defaultCommandName,s,l);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(u.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const d=()=>{u.unknown.length>0&&this.unknownOption(u.unknown[0])},h=`command:${this.name()}`;if(this._actionHandler){d(),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(h,s,l)})),v=this._chainOrCallHooks(v,"postAction"),v}if(this.parent?.listenerCount(h))d(),this._processArguments(),this.parent.emit(h,s,l);else if(s.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",s,l);this.listenerCount("command:*")?this.emit("command:*",s,l):this.commands.length?this.unknownCommand():(d(),this._processArguments())}else this.commands.length?(d(),this.help({error:!0})):(d(),this._processArguments())}_findCommand(s){if(s)return this.commands.find(l=>l._name===s||l._aliases.includes(s))}_findOption(s){return this.options.find(l=>l.is(s))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(s=>{s.options.forEach(l=>{l.mandatory&&s.getOptionValue(l.attributeName())===void 0&&s.missingMandatoryOptionValue(l)})})}_checkForConflictingLocalOptions(){const s=this.options.filter(l=>{const u=l.attributeName();return this.getOptionValue(u)===void 0?!1:this.getOptionValueSource(u)!=="default"});s.filter(l=>l.conflictsWith.length>0).forEach(l=>{const u=s.find(d=>l.conflictsWith.includes(d.attributeName()));u&&this._conflictingOption(l,u)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(s=>{s._checkForConflictingLocalOptions()})}parseOptions(s){const l=[],u=[];let d=l;function h(y){return y.length>1&&y[0]==="-"}const v=y=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(y)?!this._getCommandAndAncestors().some(k=>k.options.map(H=>H.short).some(H=>/^-\d$/.test(H))):!1;let E=null,I=null,N=0;for(;N<s.length||I;){const y=I??s[N++];if(I=null,y==="--"){d===u&&d.push(y),d.push(...s.slice(N));break}if(E&&(!h(y)||v(y))){this.emit(`option:${E.name()}`,y);continue}if(E=null,h(y)){const k=this._findOption(y);if(k){if(k.required){const H=s[N++];H===void 0&&this.optionMissingArgument(k),this.emit(`option:${k.name()}`,H)}else if(k.optional){let H=null;N<s.length&&(!h(s[N])||v(s[N]))&&(H=s[N++]),this.emit(`option:${k.name()}`,H)}else this.emit(`option:${k.name()}`);E=k.variadic?k:null;continue}}if(y.length>2&&y[0]==="-"&&y[1]!=="-"){const k=this._findOption(`-${y[1]}`);if(k){k.required||k.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${k.name()}`,y.slice(2)):(this.emit(`option:${k.name()}`),I=`-${y.slice(2)}`);continue}}if(/^--[^=]+=/.test(y)){const k=y.indexOf("="),H=this._findOption(y.slice(0,k));if(H&&(H.required||H.optional)){this.emit(`option:${H.name()}`,y.slice(k+1));continue}}if(d===l&&h(y)&&!(this.commands.length===0&&v(y))&&(d=u),(this._enablePositionalOptions||this._passThroughOptions)&&l.length===0&&u.length===0){if(this._findCommand(y)){l.push(y),u.push(...s.slice(N));break}else if(this._getHelpCommand()&&y===this._getHelpCommand().name()){l.push(y,...s.slice(N));break}else if(this._defaultCommandName){u.push(y,...s.slice(N));break}}if(this._passThroughOptions){d.push(y,...s.slice(N));break}d.push(y)}return{operands:l,unknown:u}}opts(){if(this._storeOptionsAsProperties){const s={},l=this.options.length;for(let u=0;u<l;u++){const d=this.options[u].attributeName();s[d]=d===this._versionOptionName?this._version:this[d]}return s}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((s,l)=>Object.assign(s,l.opts()),{})}error(s,l){this._outputConfiguration.outputError(`${s}
|
|
21
|
-
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
22
|
-
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
23
|
-
`),this.outputHelp({error:!0}));const u=l||{},d=u.exitCode||1,h=u.code||"commander.error";this._exit(d,h,s)}_parseOptionsEnv(){this.options.forEach(s=>{if(s.envVar&&s.envVar in o.env){const l=s.attributeName();(this.getOptionValue(l)===void 0||["default","config","env"].includes(this.getOptionValueSource(l)))&&(s.required||s.optional?this.emit(`optionEnv:${s.name()}`,o.env[s.envVar]):this.emit(`optionEnv:${s.name()}`))}})}_parseOptionsImplied(){const s=new _(this.options),l=u=>this.getOptionValue(u)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(u));this.options.filter(u=>u.implied!==void 0&&l(u.attributeName())&&s.valueFromOption(this.getOptionValue(u.attributeName()),u)).forEach(u=>{Object.keys(u.implied).filter(d=>!l(d)).forEach(d=>{this.setOptionValueWithSource(d,u.implied[d],"implied")})})}missingArgument(s){const l=`error: missing required argument '${s}'`;this.error(l,{code:"commander.missingArgument"})}optionMissingArgument(s){const l=`error: option '${s.flags}' argument missing`;this.error(l,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(s){const l=`error: required option '${s.flags}' not specified`;this.error(l,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(s,l){const u=v=>{const E=v.attributeName(),I=this.getOptionValue(E),N=this.options.find(k=>k.negate&&E===k.attributeName()),y=this.options.find(k=>!k.negate&&E===k.attributeName());return N&&(N.presetArg===void 0&&I===!1||N.presetArg!==void 0&&I===N.presetArg)?N:y||v},d=v=>{const E=u(v),I=E.attributeName();return this.getOptionValueSource(I)==="env"?`environment variable '${E.envVar}'`:`option '${E.flags}'`},h=`error: ${d(s)} cannot be used with ${d(l)}`;this.error(h,{code:"commander.conflictingOption"})}unknownOption(s){if(this._allowUnknownOption)return;let l="";if(s.startsWith("--")&&this._showSuggestionAfterError){let d=[],h=this;do{const v=h.createHelp().visibleOptions(h).filter(E=>E.long).map(E=>E.long);d=d.concat(v),h=h.parent}while(h&&!h._enablePositionalOptions);l=x(s,d)}const u=`error: unknown option '${s}'${l}`;this.error(u,{code:"commander.unknownOption"})}_excessArguments(s){if(this._allowExcessArguments)return;const l=this.registeredArguments.length,u=l===1?"":"s",d=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${l} argument${u} but got ${s.length}.`;this.error(d,{code:"commander.excessArguments"})}unknownCommand(){const s=this.args[0];let l="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(h=>{d.push(h.name()),h.alias()&&d.push(h.alias())}),l=x(s,d)}const u=`error: unknown command '${s}'${l}`;this.error(u,{code:"commander.unknownCommand"})}version(s,l,u){if(s===void 0)return this._version;this._version=s,l=l||"-V, --version",u=u||"output the version number";const d=this.createOption(l,u);return this._versionOptionName=d.attributeName(),this._registerOption(d),this.on("option:"+d.name(),()=>{this._outputConfiguration.writeOut(`${s}
|
|
24
|
-
`),this._exit(0,"commander.version",s)}),this}description(s,l){return s===void 0&&l===void 0?this._description:(this._description=s,l&&(this._argsDescription=l),this)}summary(s){return s===void 0?this._summary:(this._summary=s,this)}alias(s){if(s===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]),s===l._name)throw new Error("Command alias can't be the same as its name");const u=this.parent?._findCommand(s);if(u){const d=[u.name()].concat(u.aliases()).join("|");throw new Error(`cannot add alias '${s}' to command '${this.name()}' as already have command '${d}'`)}return l._aliases.push(s),this}aliases(s){return s===void 0?this._aliases:(s.forEach(l=>this.alias(l)),this)}usage(s){if(s===void 0){if(this._usage)return this._usage;const l=this.registeredArguments.map(u=>c(u));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?l:[]).join(" ")}return this._usage=s,this}name(s){return s===void 0?this._name:(this._name=s,this)}helpGroup(s){return s===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=s,this)}commandsGroup(s){return s===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=s,this)}optionsGroup(s){return s===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=s,this)}_initOptionGroup(s){this._defaultOptionGroup&&!s.helpGroupHeading&&s.helpGroup(this._defaultOptionGroup)}_initCommandGroup(s){this._defaultCommandGroup&&!s.helpGroup()&&s.helpGroup(this._defaultCommandGroup)}nameFromFilename(s){return this._name=r.basename(s,r.extname(s)),this}executableDir(s){return s===void 0?this._executableDir:(this._executableDir=s,this)}helpInformation(s){const l=this.createHelp(),u=this._getOutputContext(s);l.prepareContext({error:u.error,helpWidth:u.helpWidth,outputHasColors:u.hasColors});const d=l.formatHelp(this,l);return u.hasColors?d:this._outputConfiguration.stripColor(d)}_getOutputContext(s){s=s||{};const l=!!s.error;let u,d,h;return l?(u=E=>this._outputConfiguration.writeErr(E),d=this._outputConfiguration.getErrHasColors(),h=this._outputConfiguration.getErrHelpWidth()):(u=E=>this._outputConfiguration.writeOut(E),d=this._outputConfiguration.getOutHasColors(),h=this._outputConfiguration.getOutHelpWidth()),{error:l,write:E=>(d||(E=this._outputConfiguration.stripColor(E)),u(E)),hasColors:d,helpWidth:h}}outputHelp(s){let l;typeof s=="function"&&(l=s,s=void 0);const u=this._getOutputContext(s),d={error:u.error,write:u.write,command:this};this._getCommandAndAncestors().reverse().forEach(v=>v.emit("beforeAllHelp",d)),this.emit("beforeHelp",d);let h=this.helpInformation({error:u.error});if(l&&(h=l(h),typeof h!="string"&&!Buffer.isBuffer(h)))throw new Error("outputHelp callback must return a string or a Buffer");u.write(h),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",d),this._getCommandAndAncestors().forEach(v=>v.emit("afterAllHelp",d))}helpOption(s,l){return typeof s=="boolean"?(s?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(s??"-h, --help",l??"display help for command"),(s||l)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(s){return this._helpOption=s,this._initOptionGroup(s),this}help(s){this.outputHelp(s);let l=Number(o.exitCode??0);l===0&&s&&typeof s!="function"&&s.error&&(l=1),this._exit(l,"commander.help","(outputHelp)")}addHelpText(s,l){const u=["beforeAll","before","after","afterAll"];if(!u.includes(s))throw new Error(`Unexpected value for position to addHelpText.
|
|
25
|
-
Expecting one of '${u.join("', '")}'`);const d=`${s}Help`;return this.on(d,h=>{let v;typeof l=="function"?v=l({error:h.error,command:h.command}):v=l,v&&h.write(`${v}
|
|
26
|
-
`)}),this}_outputHelpIfRequested(s){const l=this._getHelpOption();l&&s.find(u=>l.is(u))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function R(ve){return ve.map(s=>{if(!s.startsWith("--inspect"))return s;let l,u="127.0.0.1",d="9229",h;return(h=s.match(/^(--inspect(-brk)?)$/))!==null?l=h[1]:(h=s.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(l=h[1],/^\d+$/.test(h[3])?d=h[3]:u=h[3]):(h=s.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(l=h[1],u=h[3],d=h[4]),l&&d!=="0"?`${l}=${u}:${parseInt(d)+1}`:s})}function z(){if(o.env.NO_COLOR||o.env.FORCE_COLOR==="0"||o.env.FORCE_COLOR==="false")return!1;if(o.env.FORCE_COLOR||o.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=G,e.useColor=z})),xt=te((e=>{var{Argument:t}=Ce(),{Command:n}=jt(),{CommanderError:r,InvalidArgumentError:i}=me(),{Help:o}=Fe(),{Option:a}=Ge();e.program=new n,e.createCommand=c=>new n(c),e.createOption=(c,p)=>new a(c,p),e.createArgument=(c,p)=>new t(c,p),e.Command=n,e.Option=a,e.Argument=t,e.Help=o,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i})),$t=_t(xt(),1),{program:bn,createCommand:Cn,createArgument:Pn,createOption:wn,CommanderError:Nt,InvalidArgumentError:_n,InvalidOptionArgumentError:En,Command:Rt,Argument:Tn,Option:X,Help:In}=$t.default;function O(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},de=class extends Error{url;status;statusText;body;request;constructor(e,t,n){super(n),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},q={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},T=class extends Error{constructor(e){super(e),this.name="CliUsageError"}},se=class extends Error{constructor(e){super(e),this.name="CliOperationFailedError"}},ie=class extends Error{status;details;constructor(e,t,n){super(t),this.name="CliHttpError",this.status=e,this.details=n}};function Pe(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function K(e,t){const n=Pe(e)?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Ht(e){return e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ENOTFOUND")||e.includes("Failed to parse URL")}function Re(e){switch(e){case 400:return q.HTTP_BAD_REQUEST;case 401:return q.HTTP_UNAUTHORIZED;case 403:return q.HTTP_FORBIDDEN;case 404:return q.HTTP_NOT_FOUND;case 409:return q.HTTP_CONFLICT;default:return e&&e>=400&&e<500?q.HTTP_CLIENT_ERROR:e&&e>=500?q.HTTP_SERVER_ERROR:q.UNKNOWN}}function Be(e,t={}){if(e instanceof T)return{exitCode:q.USAGE,message:e.message};if(e instanceof se)return{exitCode:q.OPERATION_FAILED,message:e.message};if(e instanceof ie)return{exitCode:Re(e.status),status:e.status,message:e.message,details:e.details};if(e instanceof de){const n=K(e.body,"error")??K(e.body,"message")??e.message,r=Vt(e.body);return{exitCode:Re(e.status),status:e.status,message:r.length>0?[n,...r].join(`
|
|
28
|
-
`):n,errorCode:K(e.body,"errorCode"),correlationId:K(e.body,"correlationId"),details:e.body}}if(e instanceof Error){if(!Ht(e.message))return{exitCode:q.UNKNOWN,message:e.message};const n=t.baseUrl??"the configured backend";return{exitCode:q.TRANSPORT,message:e.message.includes("Failed to parse URL")?`Invalid HagiCode backend base URL: ${n}`:`Cannot reach HagiCode backend at ${n}. Check that the backend is running and the base URL is correct.`}}return{exitCode:q.UNKNOWN,message:String(e)}}function Dt(e){const t=Pe(e)?.errors;return Array.isArray(t)?t.flatMap(n=>{const r=K(n,"field"),i=K(n,"message");return r&&i?[` - ${r}: ${i}`]:[]}):[]}function Vt(e){const t=Pe(e)?.fieldErrors;return Array.isArray(t)?t.flatMap(n=>{const r=K(n,"field"),i=K(n,"message");return r&&i?[` - ${r}: ${i}`]:[]}):[]}function We(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)}
|
|
29
|
-
`;const n=[e.status?`status=${e.status}`:void 0,e.errorCode?`errorCode=${e.errorCode}`:void 0,e.correlationId?`correlationId=${e.correlationId}`:void 0].filter(Boolean),r=n.length>0?` (${n.join(", ")})`:"";return[`${e.message}${r}`,...Dt(e.details)].join(`
|
|
30
|
-
`)+`
|
|
31
|
-
`}function qt(e){return`cli/${e??"unknown"}`}var Mt=qt("0.1.0-dev.31.1.bcd050b"),Lt="--base-url",Ft="HAGI_API_BASE_URL";function J(e){const t=e?.trim();return t||void 0}function Je(e=process.env){return(0,Ne.join)(J(e.XDG_CONFIG_HOME)??(0,Ne.join)((0,Tt.homedir)(),".config"),"hagi","config.json")}function Gt(e=process.env){const t=Je(e);let n;try{n=(0,Et.readFileSync)(t,"utf8")}catch(o){if(o.code==="ENOENT")return;throw new T(`Cannot read CLI config file ${t}: ${o instanceof Error?o.message:String(o)}`)}let r;try{r=JSON.parse(n)}catch{throw new T(`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"?J(i):void 0}function Ut(e={},t=process.env){const n=J(e.baseUrl)??J(t.HAGI_API_BASE_URL)??Gt(t);if(!n)throw new T(`No backend base URL is configured. Set ${Lt} <url>, the ${Ft} environment variable, or "baseUrl" in ${Je(t)}.`);return{baseUrl:n,token:J(e.token)??J(t.HAGI_API_TOKEN),lang:J(e.lang)??J(t.HAGI_API_LANG)}}function Bt(e={},t=process.env){const n=Ut(e,t);return f.BASE=n.baseUrl,f.WITH_CREDENTIALS=!1,f.CREDENTIALS="omit",f.TOKEN=n.token,f.HEADERS={"X-Hagi-Client":Mt,...n.lang?{"Accept-Language":n.lang}:{}},n}function Wt(){return J(f.BASE)}var Jt=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},zt=class{#t;#i;#e;#o;#r;#s;#n;constructor(e){this.#t=!1,this.#i=!1,this.#e=!1,this.#o=[],this.#r=new Promise((t,n)=>{this.#s=t,this.#n=n;const r=a=>{this.#t||this.#i||this.#e||(this.#t=!0,this.#s&&this.#s(a))},i=a=>{this.#t||this.#i||this.#e||(this.#i=!0,this.#n&&this.#n(a))},o=a=>{this.#t||this.#i||this.#e||this.#o.push(a)};return Object.defineProperty(o,"isResolved",{get:()=>this.#t}),Object.defineProperty(o,"isRejected",{get:()=>this.#i}),Object.defineProperty(o,"isCancelled",{get:()=>this.#e}),e(r,i,o)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#r.then(e,t)}catch(e){return this.#r.catch(e)}finally(e){return this.#r.finally(e)}cancel(){if(!(this.#t||this.#i||this.#e)){if(this.#e=!0,this.#o.length)try{for(const e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#n&&this.#n(new Jt("Request aborted"))}}get isCancelled(){return this.#e}},we=e=>e!=null,ae=e=>typeof e=="string",ye=e=>ae(e)&&e!=="",_e=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]),ze=e=>e instanceof FormData,Kt=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Xt=e=>{const t=[],n=(i,o)=>{t.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(o))}`)},r=(i,o)=>{we(o)&&(Array.isArray(o)?o.forEach(a=>{r(i,a)}):typeof o=="object"?Object.entries(o).forEach(([a,c])=>{r(`${i}[${a}]`,c)}):n(i,o))};return Object.entries(e).forEach(([i,o])=>{r(i,o)}),t.length>0?`?${t.join("&")}`:""},Yt=(e,t)=>{const n=e.ENCODE_PATH||encodeURI,r=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(o,a)=>t.path?.hasOwnProperty(a)?n(String(t.path[a])):o),i=`${e.BASE}${r}`;return t.query?`${i}${Xt(t.query)}`:i},Qt=e=>{if(e.formData){const t=new FormData,n=(r,i)=>{ae(i)||_e(i)?t.append(r,i):t.append(r,JSON.stringify(i))};return Object.entries(e.formData).filter(([r,i])=>we(i)).forEach(([r,i])=>{Array.isArray(i)?i.forEach(o=>n(r,o)):n(r,i)}),t}},ce=async(e,t)=>typeof t=="function"?t(e):t,Zt=async(e,t)=>{const[n,r,i,o]=await Promise.all([ce(t,e.TOKEN),ce(t,e.USERNAME),ce(t,e.PASSWORD),ce(t,e.HEADERS)]),a=Object.entries({Accept:"application/json",...o,...t.headers}).filter(([c,p])=>we(p)).reduce((c,[p,m])=>({...c,[p]:String(m)}),{});return ye(n)&&(a.Authorization=`Bearer ${n}`),ye(r)&&ye(i)&&(a.Authorization=`Basic ${Kt(`${r}:${i}`)}`),t.body!==void 0&&(t.mediaType?a["Content-Type"]=t.mediaType:_e(t.body)?a["Content-Type"]=t.body.type||"application/octet-stream":ae(t.body)?a["Content-Type"]="text/plain":ze(t.body)||(a["Content-Type"]="application/json")),new Headers(a)},ei=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):ae(e.body)||_e(e.body)||ze(e.body)?e.body:JSON.stringify(e.body)},ti=async(e,t,n,r,i,o,a)=>{const c=new AbortController,p={headers:o,body:r??i,method:t.method,signal:c.signal};return e.WITH_CREDENTIALS&&(p.credentials=e.CREDENTIALS),a(()=>c.abort()),await fetch(n,p)},ii=(e,t)=>{if(t){const n=e.headers.get(t);if(ae(n))return n}},oi=async e=>{if(e.status!==204)try{const t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(n=>t.toLowerCase().startsWith(n))?await e.json():await e.text()}catch(t){console.error(t)}},ni=(e,t)=>{const n={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(n)throw new de(e,t,n);if(!t.ok)throw new de(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 zt(async(n,r,i)=>{try{const o=Yt(e,t),a=Qt(t),c=ei(t),p=await Zt(e,t);if(!i.isCancelled){const m=await ti(e,t,o,c,a,p,i),b=await oi(m),C=ii(m,t.responseHeader),_={url:o,ok:m.ok,status:m.status,statusText:m.statusText,body:C??b};ni(t,_),n(_.body)}}catch(o){r(o)}}),ri=class{static getApiDataAggregation(){return g(f,{method:"GET",url:"/api/DataAggregation",errors:{400:"Depth parameter is no longer supported"}})}},He=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"}})}},B=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 postApiProjectMonospecsReload({id:e}){return g(f,{method:"POST",url:"/api/Project/{id}/monospecs/reload",path:{id:e},errors:{400:"Bad Request",404:"Not Found",500:"Internal Server Error"}})}static postApiProjectMonospecsRepositoriesClone({id:e,requestBody:t}){return g(f,{method:"POST",url:"/api/Project/{id}/monospecs/repositories/clone",path:{id:e},body:t,mediaType:"application/json",errors:{400:"Bad Request",404:"Not Found",409:"Conflict",500:"Internal Server Error"}})}static deleteApiProjectMonospecsRepositoriesCheckout({id:e,path:t,force:n=!1}){return g(f,{method:"DELETE",url:"/api/Project/{id}/monospecs/repositories/checkout",path:{id:e},query:{path:t,force:n},errors:{400:"Bad Request",404:"Not Found",409:"Conflict",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:n="light"}){return g(f,{method:"GET",url:"/api/Project/{id}/design-md/site-index/{slug}/preview",path:{id:e,slug:t},query:{theme:n},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:n}){return g(f,{method:"GET",url:"/api/Project/{id}/branches/validate",path:{id:e},query:{branchName:t,repositoryPath:n},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"}})}},Q=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"}})}},M=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:n,projectId:r,projectIds:i}){return g(f,{method:"GET",url:"/api/Sessions",query:{type:e,activeOnly:t,includeArchived:n,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:n=50,historyScope:r,order:i="desc"}){return g(f,{method:"GET",url:"/api/Sessions/{sessionId}/messages",path:{sessionId:e},query:{page:t,pageSize:n,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"}})}},W=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:n,version:r}){return g(f,{method:"GET",url:"/api/skills/gallery/install/stream",query:{id:e,source:t,skillSlug:n,version:r}})}},ne=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 si(){return{listSessions:e=>M.getApiSessions(e),getSession:e=>M.getApiSessions1({sessionId:e}),createProposalSession:e=>M.postApiSessions({requestBody:e}),createChatSession:e=>M.postApiSessionsChat({requestBody:e}),createHagiTaskSession:e=>M.postApiSessionsHagitask({requestBody:e}),listHagiTaskSchemas:()=>He.getApiPresetTasksSchemas(),getHagiTaskSchema:e=>He.getApiPresetTasksSchema({presetTaskId:e}),updateSession:(e,t)=>M.putApiSessions({sessionId:e,requestBody:t}),deleteSession:(e,t)=>M.deleteApiSessions({sessionId:e,deleteFiles:t}),sendMessage:(e,t)=>M.postApiSessionsMessages({sessionId:e,requestBody:t}),optimizeProposal:(e,t)=>M.postApiSessionsOptimizeProposal({sessionId:e,requestBody:t}),generateProposal:(e,t)=>M.postApiSessionsGenerateProposal({sessionId:e,requestBody:t}),executeProposal:(e,t)=>M.postApiSessionsExecuteProposal({sessionId:e,requestBody:t}),archiveProposal:(e,t)=>M.postApiSessionsArchive({sessionId:e,requestBody:t}),completeProposal:e=>M.postApiSessionsComplete({sessionId:e}),submitAnnotations:(e,t)=>M.postApiSessionsAnnotations({sessionId:e,requestBody:t}),listProjects:()=>ri.getApiDataAggregation(),createProject:e=>B.postApiProject({requestBody:e}),updateProject:(e,t)=>B.putApiProject({id:e,requestBody:t}),deleteProject:e=>B.deleteApiProject({id:e}),getMonoSpecsManagement:e=>B.getApiProjectMonospecsManagement({id:e}),saveMonoSpecsManagement:(e,t)=>B.putApiProjectMonospecsManagement({id:e,requestBody:t}),initializeMonoSpecsManagement:e=>B.postApiProjectMonospecsInitialize({id:e}),reloadMonoSpecsManagement:e=>B.postApiProjectMonospecsReload({id:e}),validateMonoSpecs:e=>B.postApiProjectValidateMonospecs({requestBody:e}),cloneMonoSpecsRepositories:(e,t)=>B.postApiProjectMonospecsRepositoriesClone({id:e,requestBody:t}),removeMonoSpecsRepositoryCheckout:(e,t,n)=>B.deleteApiProjectMonospecsRepositoriesCheckout({id:e,path:t,force:n}),listPlans:()=>Q.getApiScheduledPlans(),getPlan:e=>Q.getApiScheduledPlans1({id:e}),createPlan:e=>Q.postApiScheduledPlans({requestBody:e}),updatePlan:(e,t)=>Q.putApiScheduledPlans({id:e,requestBody:t}),deletePlan:e=>Q.deleteApiScheduledPlans({id:e}),runPlan:e=>Q.postApiScheduledPlansRun({id:e}),startPlan:e=>Q.postApiScheduledPlansStart({id:e}),listVaults:()=>ne.getApiVaults(),createVault:e=>ne.postApiVaults({requestBody:e}),updateVault:(e,t)=>ne.putApiVaults({id:e,requestBody:t}),deleteVault:(e,t)=>ne.deleteApiVaults({id:e,deleteLocalFiles:t}),listVaultFiles:(e,t)=>ne.getApiVaultsFiles({id:e,path:t}),previewVaultFile:(e,t)=>ne.getApiVaultsFilesContent({id:e,path:t}),archiveChat:e=>M.postApiSessionsArchiveChat({sessionId:e}),listLocalSkills:()=>W.getApiSkillsLocal(),uninstallLocalSkill:e=>W.postApiSkillsLocalUninstall({requestBody:e}),setBuiltInSkillAvailability:e=>W.postApiSkillsLocalBuiltInAvailability({requestBody:e}),searchSkillGallery:e=>W.getApiSkillsGallery({query:e}),getSkillGalleryDetail:(e,t)=>W.getApiSkillsGalleryDetail({id:e,source:t}),installGallerySkill:e=>W.postApiSkillsGalleryInstall({requestBody:e}),listTrustedSkillProviders:()=>W.getApiSkillsProvidersTrusted(),upsertTrustedSkillProvider:e=>W.postApiSkillsProvidersTrusted({requestBody:e}),deleteTrustedSkillProvider:e=>W.deleteApiSkillsProvidersTrusted({requestBody:e}),resetTrustedSkillProviders:()=>W.postApiSkillsProvidersTrustedReset()}}function P(e){const t=e?.trim();return t||void 0}function w(e,t){const n=P(e);if(!n)throw new T(`${t} is required.`);return n}function Ae(e){const t=e?.map(n=>P(n)).filter(Boolean);return t&&t.length>0?t:void 0}function Ke(e=process.env,t={stdout:n=>{process.stdout.write(n)},stderr:n=>{process.stderr.write(n)}}){return{api:si(),env:e,io:t}}function ai(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 S(e){return e.option("--json","Emit deterministic JSON instead of human-readable text.")}function A(e,t){const n=e.optsWithGlobals();return{api:t.api,env:t.env,io:t.io,outputJson:n.json===!0,runtime:Bt({baseUrl:n.baseUrl,token:n.token,lang:n.lang},t.env)}}function li(e,t){S(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=A(this,t),o=r.sessionId.trim(),a=await i.api.archiveChat(o);if(i.outputJson){i.io.stdout(O({sessionId:o,message:a.message}));return}i.io.stdout(`Chat archived
|
|
32
|
-
sessionId ${o}
|
|
33
|
-
message ${a.message}
|
|
34
|
-
`)})}var Xe=(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 Ye(e){return e.replace(/\s+/g," ").trim()}function L(e,t){const n=t.map(o=>e.map(a=>Ye(a.value(o)))),r=e.map((o,a)=>{const c=n.map(p=>p[a].length);return Math.max(o.header.length,...c)}),i=o=>o.map((a,c)=>a.padEnd(r[c])).join(" ").trimEnd();return[i(e.map(o=>o.header)),i(r.map(o=>"-".repeat(o))),...n.map(i)].join(`
|
|
35
|
-
`)}function D(e){const t=e.filter(([,r])=>r!==void 0&&r!==""),n=Math.max(...t.map(([r])=>r.length));return`${t.map(([r,i])=>`${r.padEnd(n)} ${Ye(i??"")}`).join(`
|
|
36
|
-
`)}
|
|
37
|
-
`}function De(e){return typeof e=="string"?e.trim():e?.value?.trim()??""}function Y(e){return{sessionId:De(e.sessionId),title:e.title,type:e.type,status:e.status,projectId:De(e.projectId),proposalName:e.proposalName??void 0,archived:e.status===Xe.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 Qe(e){return{sessions:e.sessions.map(Y)}}function Ze(e,t){return t.length===0?`No ${e.toLowerCase()} found.
|
|
38
|
-
`:`${e} (${t.length})
|
|
39
|
-
${L([{header:"Session ID",value:n=>n.sessionId},{header:"Title",value:n=>n.title},{header:"Status",value:n=>n.status},{header:"Project ID",value:n=>n.projectId},{header:"Archived",value:n=>n.archived?"yes":"no"}],t)}
|
|
40
|
-
`}function oe(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 Ee(e,t,n,r=[]){return`${e}
|
|
41
|
-
${D([["sessionId",t],["message",n.message],...r])}`}var fe=(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 ci(e,t){S(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 X("--executor-type <type>","Optional executor override.").choices(Object.values(fe))).action(async function(r){const i=A(this,t),o=Y(await i.api.createChatSession({title:w(r.title,"--title"),projectId:w(r.projectId,"--project-id"),heroId:P(r.heroId),executorType:r.executorType}));if(i.outputJson){i.io.stdout(O({session:o}));return}i.io.stdout(`Chat session created
|
|
42
|
-
${oe(o)}`)})}function ui(e,t){S(e.command("delete").description("Delete a chat session.")).requiredOption("--session-id <id>","Chat session id to delete.").action(async function(r){const i=A(this,t),o=r.sessionId.trim(),a=await i.api.deleteSession(o,!1);if(i.outputJson){i.io.stdout(O({sessionId:o,deleted:!0,message:a.message}));return}i.io.stdout(`Chat deleted
|
|
43
|
-
sessionId ${o}
|
|
44
|
-
message ${a.message}
|
|
45
|
-
`)})}var Te=(function(e){return e.CHAT="Chat",e.PROPOSAL="Proposal",e})({});function di(e,t){S(e.command("list").description("List normal chat sessions.")).action(async function(r){if(r.projectId&&r.projectIds?.length)throw new T("Use either --project-id or --project-ids, not both.");const i=A(this,t),o=Qe(await i.api.listSessions({type:Te.CHAT,projectId:P(r.projectId),projectIds:Ae(r.projectIds),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(Ze("Chat sessions",o.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 Ie=(function(e){return e.READONLY="Readonly",e.EDIT="Edit",e})({});function pi(e,t){S(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 X("--mode <mode>","Message mode override.").choices(Object.values(Ie))).addOption(new X("--executor-type <type>","Executor override for this message.").choices(Object.values(fe))).action(async function(r){const i=A(this,t),o=r.sessionId.trim(),a=await i.api.sendMessage(o,{content:w(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(O({sessionId:o,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(Ee("Chat message sent",o,a,[["mode",r.mode],["executorType",r.executorType]]))})}function hi(e,t){const n=e.command("chat").description("Manage normal chat sessions.");di(n,t),ci(n,t),li(n,t),ui(n,t),pi(n,t)}async function mi(){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 ge(e){const t=e.trim();if(!t)throw new T("Provide --input <file> or --input - for stdin.");const n=t==="-"?await mi():await(0,It.readFile)(t,"utf8");try{return JSON.parse(n)}catch(r){throw new T(`Invalid JSON input from ${t}: ${r instanceof Error?r.message:String(r)}`)}}var fi=["first","random"];async function gi(e){let t;try{t=await ge(e)}catch(n){throw n instanceof T?n:new T(`Cannot read HagiTask input from ${e}: ${n instanceof Error?n.message:String(n)}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new T(`HagiTask input from ${e} must be a JSON object.`);return t}function vi(e,t,n){if(!t&&!n)throw new T("Provide --task-id or --prompt-id.");if(e.input!==void 0&&!t)throw new T("--input requires --task-id.");if(e.targetBranchName&&e.targetBranchMode!=="new-custom")throw new T("--target-branch-name requires --target-branch-mode new-custom.");if(e.targetBranchMode==="new-custom"&&!P(e.targetBranchName))throw new T("--target-branch-name is required when --target-branch-mode is new-custom.");const r=P(e.heroSelectionMode);if(r&&!fi.includes(r))throw new T("--hero-selection-mode must be first or random.")}function yi(e,t){S(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=P(r.taskId),o=P(r.promptId);vi(r,i,o);const a=r.input!==void 0?await gi(w(r.input,"--input")):void 0,c=A(this,t),p={title:w(r.title,"--title"),projectId:w(r.projectId,"--project-id"),promptId:o,presetTaskId:i,presetTaskLocale:P(r.locale),presetTaskInput:a,message:P(r.message),repositoryPath:P(r.repositoryPath),targetType:P(r.targetType),vaultId:P(r.vaultId),outputVaultId:P(r.outputVaultId),referenceVaultIds:Ae(r.referenceVaultId),editableVaultIds:Ae(r.editableVaultId),heroId:P(r.heroId),heroSelectionMode:P(r.heroSelectionMode),needPush:r.needPush?!0:void 0,pullRebaseBeforePush:r.pullRebase?!0:void 0,targetBranchMode:P(r.targetBranchMode),targetBranchName:P(r.targetBranchName),scriptKey:P(r.scriptKey)},m=Y(await c.api.createHagiTaskSession(p));if(c.outputJson){c.io.stdout(O({session:m,presetTaskId:p.presetTaskId??null,promptId:p.promptId??null,requested:p}));return}c.io.stdout(`HagiTask session created
|
|
46
|
-
${oe(m,[["presetTaskId",p.presetTaskId??void 0],["presetTaskLocale",p.presetTaskLocale??void 0],["promptId",p.promptId??void 0],["repositoryPath",p.repositoryPath??void 0],["targetBranchMode",p.targetBranchMode??void 0],["targetBranchName",p.targetBranchName??void 0],["scriptKey",p.scriptKey??void 0],["heroId",p.heroId??void 0],["heroSelectionMode",p.heroSelectionMode??void 0]])}`)})}var $="-";function Ve(e){return e?"yes":"no"}function qe(e){return e&&e.length>0?e.join(", "):$}function pe(e){if(Array.isArray(e))return e.map(t=>pe(t));if(e&&typeof e=="object"){const t=e;return Object.fromEntries(Object.keys(t).sort().map(n=>[n,pe(t[n])]))}return e}function et(e){return[...e].sort((t,n)=>{const r=t.id??"",i=n.id??"";return r<i?-1:r>i?1:0})}function Si(e){return pe({tasks:et(e)})}function Ai(e){if(e.length===0)return`No HagiTask is available.
|
|
47
|
-
`;const t=et(e);return`HagiTasks (${t.length})
|
|
48
|
-
${L([{header:"ID",value:n=>n.id??$},{header:"Version",value:n=>n.version??$},{header:"Title",value:n=>n.title??$},{header:"Description",value:n=>n.description??$}],t)}
|
|
49
|
-
`}function Oi(e){const t=[];e.origin==="derived"&&t.push(e.producer?`derived by ${e.producer}`:"derived");for(const n of e.aliases??[])n.key&&t.push(`alias ${n.key} (deprecated)`);return e.options&&e.options.length>0&&t.push(`options: ${e.options.map(n=>n.value??"").join(", ")}`),t.length>0?t.join("; "):$}function bi(e){const t=e.id??$,n=[];n.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??[];n.push(`Target scope (default ${e.scope?.defaultTargetType??$})${r.length===0?`
|
|
50
|
-
None.
|
|
51
|
-
`:`
|
|
52
|
-
${L([{header:"ID",value:m=>m.id??$},{header:"Kind",value:m=>m.kind??$},{header:"Selection",value:m=>m.selectionMode??$},{header:"Required",value:m=>Ve(m.required)},{header:"Access",value:m=>qe(m.allowedAccessTypes)},{header:"Input key",value:m=>m.requestKey??$},{header:"Scope key",value:m=>m.scopeRequestKey??$}],r)}
|
|
53
|
-
`}`);const i=e.commands?.commands??[];n.push(`Commands${i.length===0?`
|
|
54
|
-
None.
|
|
55
|
-
`:`
|
|
56
|
-
${L([{header:"ID",value:m=>m.id??$},{header:"Group",value:m=>m.groupId??$},{header:"Label",value:m=>m.label??$},{header:"URL",value:m=>m.url??$}],i)}
|
|
57
|
-
`}`);const o=e.parameters??[];n.push(`Parameters${o.length===0?`
|
|
58
|
-
None.
|
|
59
|
-
`:`
|
|
60
|
-
${L([{header:"Key",value:m=>m.key??$},{header:"Required",value:m=>Ve(m.required)},{header:"Origin",value:m=>m.origin??$},{header:"Type",value:m=>m.valueType??$},{header:"Label",value:m=>m.label??$},{header:"Notes",value:Oi}],o)}
|
|
61
|
-
`}`);const a=e.requirements??[];n.push(`Requirements${a.length===0?`
|
|
62
|
-
None.
|
|
63
|
-
`:`
|
|
64
|
-
${a.map(m=>`- ${m.type??$}: ${m.name??qe(m.names)}`).join(`
|
|
65
|
-
`)}
|
|
66
|
-
`}`);const c=e.scenes?.registrations??[];n.push(`Scenes${c.length===0?`
|
|
67
|
-
None.
|
|
68
|
-
`:`
|
|
69
|
-
${c.map(m=>`- ${m.sceneKey??$}: ${m.title??$}`).join(`
|
|
70
|
-
`)}
|
|
71
|
-
`}`);const p=e.request;return n.push(D([["endpoint",p?`${p.method??$} ${p.path??$}`:void 0],["presetTaskIdField",p?.presetTaskIdField??void 0],["localeField",p?.localeField??void 0],["requiredFields",p?.requiredFields&&p.requiredFields.length>0?p.requiredFields.join(", "):void 0]])),n.push(`Example
|
|
72
|
-
hagi hagitask schema --task-id ${t} --json # full input JSON Schema and example body
|
|
73
|
-
hagi hagitask create --title "<title>" --project-id <project-id> --task-id ${t} --input input.json
|
|
74
|
-
`),n.join(`
|
|
75
|
-
`)}function Ci(e){return pe(e)}function Pi(e,t){S(e.command("list").description("List the active HagiTasks with their id, version, title and description.")).action(async function(){const r=A(this,t),i=await r.api.listHagiTaskSchemas();if(r.outputJson){r.io.stdout(O(Si(i)));return}r.io.stdout(Ai(i))})}function wi(e,t){const n=e&&typeof e=="object"?e[t]:void 0;return typeof n=="string"&&n.trim()?n.trim():void 0}function _i(e){const t=e&&typeof e=="object"?e.diagnostics:void 0;return Array.isArray(t)?t:[]}async function Ei(e,t){try{return await e.getHagiTaskSchema(t)}catch(n){if(n instanceof de&&n.status===404){const r=_i(n.body);if(r.length>0){const i=r.map(o=>{const a=o.path?` (${o.path})`:"";return` - ${o.code??"diagnostic"}: ${o.message??""}${a}`});throw new ie(404,[wi(n.body,"error")??`HagiTask ${t} is not available.`,...i].join(`
|
|
76
|
-
`),n.body)}}throw n}}function Ti(e,t){S(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=w(r.taskId,"--task-id"),o=A(this,t),a=await Ei(o.api,i);if(o.outputJson){o.io.stdout(O(Ci(a)));return}o.io.stdout(bi(a))})}function Ii(e,t){S(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 X("--mode <mode>","Message mode override.").choices(Object.values(Ie))).addOption(new X("--executor-type <type>","Executor override for this message.").choices(Object.values(fe))).action(async function(r){const i=A(this,t),o=r.sessionId.trim(),a=await i.api.sendMessage(o,{content:w(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(O({sessionId:o,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(Ee("HagiTask message sent",o,a,[["mode",r.mode],["executorType",r.executorType]]))})}function ki(e,t){const n=e.command("hagitask").description("Manage HagiTask sessions: list tasks, read a task schema, create a session from it, and send follow-up messages.");Pi(n,t),Ti(n,t),yi(n,t),Ii(n,t)}function U(e){const t=e?.trim();return t||void 0}function tt(e){if(!e)return"";const t=U(e.mode);if(t==="once")return["once",U(e.runAt)].filter(Boolean).join(" ");const n=U(e.repeat?.rule)??t??"";return[n,n==="weekly"?(e.repeat?.weekdays??[]).map(r=>r.trim().slice(0,3).toLowerCase()).join(","):void 0,U(e.timeOfDay),U(e.timeZone)].filter(Boolean).join(" ")}function Z(e){return{id:U(e.id)??"",type:U(e.type)??"",name:U(e.name)??"",enabled:e.enabled===!0,state:U(e.state)??"",nextRunAt:U(e.nextRunAt)??null,schedule:e.schedule,agentPool:e.agentPool,payload:e.payload}}function ji(e){return{plans:e.map(Z)}}function xi(e){return e.length===0?`No scheduled plans found.
|
|
77
|
-
`:`Plans (${e.length})
|
|
78
|
-
${L([{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=>tt(t.schedule)}],e)}
|
|
79
|
-
`}function le(e){return D([["id",e.id],["type",e.type],["name",e.name],["enabled",e.enabled?"yes":"no"],["state",e.state],["nextRun",e.nextRunAt??"-"],["schedule",tt(e.schedule)]])}function $i(e){return{planId:e,deleted:!0}}function Ni(e){return`Plan deleted
|
|
80
|
-
${D([["planId",e.planId],["deleted",String(e.deleted)]])}`}function Ri(e){return{planId:U(e.planId)??"",accepted:!0}}function Hi(e){return`Plan run accepted
|
|
81
|
-
${D([["planId",e.planId],["accepted",String(e.accepted)]])}`}var Di=["id","createdAt","updatedAt","state","nextRunAt"];async function it(e){let t;try{t=await ge(e)}catch(n){throw n instanceof T?n:new T(`Cannot read plan input from ${e}: ${n instanceof Error?n.message:String(n)}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new T(`Plan input from ${e} must be a JSON object.`);return t}function he(e){const t={...e};for(const n of Di)delete t[n];return t}function Vi(e){return{strategy:"random",agents:[{heroId:e}]}}function ot(e){return{...e.name!==void 0?{name:e.name}:{},...e.heroId!==void 0?{agentPool:Vi(e.heroId)}:{},...e.enabled!==void 0?{enabled:e.enabled}:{}}}function nt(e,t){return{...he(e),...he(t)}}function qi(e,t){S(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=A(this,t),o=he(await it(r.input)),a=Z(await i.api.createPlan({enabled:!0,...o,...ot({name:P(r.name),heroId:P(r.heroId),enabled:r.disabled?!1:void 0})}));if(i.outputJson){i.io.stdout(O({plan:a}));return}i.io.stdout(`Plan created
|
|
82
|
-
${le(a)}`)})}function Mi(e,t){S(e.command("delete").description("Delete a scheduled plan by id.")).requiredOption("--id <id>","Plan id to delete.").action(async function(r){const i=A(this,t),o=w(r.id,"--id");await i.api.deletePlan(o);const a=$i(o);if(i.outputJson){i.io.stdout(O(a));return}i.io.stdout(Ni(a))})}async function rt(e,t,n){const r=await e.api.getPlan(t);return Z(r).enabled===n?{view:Z(r),changed:!1}:{view:Z(await e.api.updatePlan(t,nt(r,{enabled:n}))),changed:!0}}function Li(e,t){S(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=A(this,t),{view:o,changed:a}=await rt(i,w(r.id,"--id"),!1);if(i.outputJson){i.io.stdout(O({plan:o,changed:a}));return}i.io.stdout(`${a?"Plan disabled":"Plan was already disabled"}
|
|
83
|
-
${le(o)}`)})}function Fi(e,t){S(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=A(this,t),{view:o,changed:a}=await rt(i,w(r.id,"--id"),!0);if(i.outputJson){i.io.stdout(O({plan:o,changed:a}));return}i.io.stdout(`${a?"Plan enabled":"Plan was already enabled"}
|
|
84
|
-
${le(o)}`)})}function Gi(e,t){S(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=A(this,t),o=Z(await i.api.getPlan(w(r.id,"--id")));if(i.outputJson){i.io.stdout(O({plan:o}));return}i.io.stdout(le(o))})}function Ui(e,t){S(e.command("list").description("List scheduled plans with their state, next run time and schedule.")).action(async function(){const r=A(this,t),i=ji(await r.api.listPlans());if(r.outputJson){r.io.stdout(O(i));return}r.io.stdout(xi(i.plans))})}function Bi(e,t){S(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=A(this,t),o=w(r.id,"--id");if(r.background){const c=Ri(await i.api.startPlan(o));if(i.outputJson){i.io.stdout(O(c));return}i.io.stdout(Hi(c));return}const a=Y(await i.api.runPlan(o));if(i.outputJson){i.io.stdout(O({session:a}));return}i.io.stdout(`Plan run created a session
|
|
85
|
-
${oe(a)}`)})}function Wi(e,t){S(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=w(r.id,"--id"),o=P(r.input),a=P(r.name),c=P(r.heroId);if(r.enabled&&r.disabled)throw new T("Pass either --enabled or --disabled, not both.");const p=r.enabled?!0:r.disabled?!1:void 0;if(!o&&!a&&!c&&p===void 0)throw new T("Provide at least one change: --input, --name, --enabled, --disabled, or --hero-id.");const m=o?he(await it(o)):{},b=A(this,t),C=await b.api.getPlan(i),_=Z(await b.api.updatePlan(i,nt(C,{...m,...ot({name:a,heroId:c,enabled:p})})));if(b.outputJson){b.io.stdout(O({plan:_}));return}b.io.stdout(`Plan updated
|
|
86
|
-
${le(_)}`)})}function Ji(e,t){const n=e.command("plan").description("Manage scheduled plans: saved proposal or HagiTask inputs that run on a schedule.");Ui(n,t),Gi(n,t),qi(n,t),Wi(n,t),Fi(n,t),Li(n,t),Mi(n,t),Bi(n,t)}function F(e){const t=e?.trim();return t||void 0}function ke(e){return{id:F(e.id)??"",name:F(e.name)??"",path:F(e.path)??"",description:F(e.description),isMonoSpecs:e.isMonoSpecs===!0,monoSpecsVersion:F(e.monoSpecsVersion),monoSpecsRepoDirectory:F(e.monoSpecsRepoDirectory),monoSpecsCommitWhenArchive:typeof e.monoSpecsCommitWhenArchive=="boolean"?e.monoSpecsCommitWhenArchive:void 0,hasError:"hasError"in e?e.hasError===!0:!1,error:"error"in e?F(e.error):void 0}}function st(e){return{projects:(e??[]).map(ke)}}function zi(e){return e.length===0?`No projects found.
|
|
87
|
-
`:`Projects (${e.length})
|
|
88
|
-
${L([{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)}
|
|
89
|
-
`}function at(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 Ki(e){return{projectId:F(e.id)??"",name:F(e.name)??"",isMonoSpecs:e.isMonoSpecs===!0,hasError:e.hasError===!0,error:F(e.error),repositories:(e.repositories??[]).map(t=>({name:F(t.name),path:t.path??void 0,displayName:F(t.displayName),type:F(t.type),branch:F(t.branch),isValidGitRepo:typeof t.isValidGitRepo=="boolean"?t.isValidGitRepo:void 0}))}}function Xi(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)]])}
|
|
90
|
-
${e.repositories.length===0?`This project lists no repositories.
|
|
91
|
-
`:`${L([{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)}
|
|
92
|
-
`}`}function Yi(e,t){S(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=A(this,t),o=ke(await i.api.createProject({name:w(r.name,"--name"),path:w(r.path,"--path"),description:P(r.description)}));if(i.outputJson){i.io.stdout(O({project:o}));return}i.io.stdout(`Project created
|
|
93
|
-
${at(o)}`)})}function Qi(e,t){S(e.command("delete").description("Delete a project by id.")).requiredOption("--id <id>","Project id to delete.").action(async function(r){const i=A(this,t),o=r.id.trim();if(await i.api.deleteProject(o),i.outputJson){i.io.stdout(O({projectId:o,deleted:!0}));return}i.io.stdout(`Project deleted
|
|
94
|
-
projectId ${o}
|
|
95
|
-
`)})}function Zi(e,t){S(e.command("list").description("List projects from the aggregation endpoint.")).action(async function(){const r=A(this,t),i=st((await r.api.listProjects()).projects);if(r.outputJson){r.io.stdout(O(i));return}r.io.stdout(zi(i.projects))})}function V(e){const t=e?.trim();return t||void 0}function lt(e){return{key:e.key??"",value:e.value??"",valueKind:e.valueKind??"string"}}function eo(e){const t=e.isValidGitRepo===!0;return{name:V(e.name),code:V(e.code),path:e.path??"",url:V(e.url),displayName:V(e.displayName),type:V(e.type),icon:V(e.icon),optional:e.optional===!0,tags:e.tags??[],metadata:(e.metadata??[]).map(lt),isValidGitRepo:t,branch:t?V(e.branch):void 0,hasUncommittedChanges:e.hasUncommittedChanges===!0,unpushedCommitCount:e.unpushedCommitCount??0,hasTrackingBranch:e.hasTrackingBranch===!0,trackingBranch:V(e.trackingBranch),aheadCount:e.aheadCount??0,behindCount:e.behindCount??0,syncState:t?V(e.syncState):void 0}}function ct(e){return{version:V(e.version)??"",repoDirectory:V(e.repoDirectory)??"",configPath:V(e.configPath)??"",commitWhenArchive:e.commitWhenArchive===!0,yamlPreview:e.yamlPreview??"",metadata:(e.metadata??[]).map(lt),repositories:(e.repositories??[]).map(eo)}}function to(e){return e.isValidGitRepo?[e.branch??"no branch",e.syncState,e.hasUncommittedChanges?"uncommitted changes":void 0].filter(Boolean).join(", "):"missing or not a Git repository"}function ut(e,t={}){return`${D([["version",e.version],["repoDirectory",e.repoDirectory],["configPath",e.configPath],["commitWhenArchive",String(e.commitWhenArchive)]])}
|
|
96
|
-
${e.repositories.length===0?`This document lists no repositories.
|
|
97
|
-
`:`${L([{header:"Path",value:n=>n.path},{header:"Name",value:n=>n.name??""},{header:"Type",value:n=>n.type??""},{header:"URL",value:n=>n.url??""},{header:"Local state",value:n=>to(n)}],e.repositories)}
|
|
98
|
-
`}${t.yaml?`
|
|
99
|
-
YAML
|
|
100
|
-
${e.yamlPreview}${e.yamlPreview.endsWith(`
|
|
101
|
-
`)?"":`
|
|
102
|
-
`}`:""}`}function dt(e){return{results:(e??[]).map(t=>({path:t.path??"",status:t.status??"",message:V(t.message)}))}}function pt(e){return e.results.length===0?`No repositories were selected for cloning.
|
|
103
|
-
`:`${L([{header:"Path",value:t=>t.path},{header:"Status",value:t=>t.status},{header:"Message",value:t=>t.message??""}],e.results)}
|
|
104
|
-
`}function io(e){return{isValid:e.isValid===!0,config:e.config?{version:V(e.config.version),repoDirectory:V(e.config.repoDirectory)}:null,warnings:e.warnings??[],errors:e.errors??[]}}function oo(e){const t=e.isValid?"MonoSpecs configuration is valid.":"MonoSpecs configuration is invalid.",n=D([["version",e.config?.version],["repoDirectory",e.config?.repoDirectory]]),r=e.warnings.map(o=>` - ${o}
|
|
105
|
-
`).join(""),i=e.errors.map(o=>` - ${o}
|
|
106
|
-
`).join("");return[t,n.trimEnd(),e.warnings.length>0?`Warnings:
|
|
107
|
-
${r}`.trimEnd():"",e.errors.length>0?`Errors:
|
|
108
|
-
${i}`.trimEnd():""].filter(Boolean).join(`
|
|
109
|
-
`)+`
|
|
110
|
-
`}function no(e){return{path:e.path??"",removed:e.removed===!0,message:V(e.message)}}function ro(e){const t=e.removed?`Removed checkout ${e.path}`:`Checkout ${e.path} was not removed`;return`${e.message?`${t}
|
|
111
|
-
${e.message}`:t}
|
|
112
|
-
`}function je(e,t,n={}){const r=ct(t);if(e.outputJson){e.io.stdout(O(r));return}const i=n.heading?`${n.heading}
|
|
113
|
-
`:"";e.io.stdout(`${i}${ut(r,{yaml:n.yaml})}`)}function Oe(e,t){return[...t,e]}function re(e){const t=e.trim().replace(/\\/g,"/").replace(/^(\.\/)+/,"").replace(/\/+$/,"");if(!t||t===".")throw new T(`Repository path must name a directory below the project root: "${e}".`);return t}function so(e,t){S(e.command("clone").description("Clone the configured repositories that are missing on the backend host. Exits with code 30 when any clone fails.")).requiredOption("--id <id>","Project id.").option("--path <path>","Configured repository path to clone. Repeatable; omit to clone every missing repository.",Oe,[]).option("--include-optional","Also clone optional repositories when no --path is given.").action(async function(r){const i=r.path.map(re),o=A(this,t),a=w(r.id,"--id"),c=r.includeOptional===!0,p=dt((await o.api.cloneMonoSpecsRepositories(a,i.length>0?{paths:i,includeOptional:c}:{includeOptional:c})).results);o.outputJson?o.io.stdout(O(p)):o.io.stdout(pt(p));const m=p.results.filter(b=>b.status==="failed");if(m.length>0)throw new se(`${m.length} repository clone(s) failed. See the results above.`)})}function ao(e,t){S(e.command("init").description("Initialize the MonoSpecs configuration of a project. An initialized project returns its existing document.")).requiredOption("--id <id>","Project id.").action(async function(r){const i=A(this,t);je(i,await i.api.initializeMonoSpecsManagement(w(r.id,"--id")),{heading:"MonoSpecs configuration initialized."})})}function lo(e,t){S(e.command("reload").description("Reread monospecs.yaml on the backend host and refresh the local Git state of its repositories.")).requiredOption("--id <id>","Project id.").action(async function(r){const i=A(this,t);je(i,await i.api.reloadMonoSpecsManagement(w(r.id,"--id")),{heading:"MonoSpecs configuration reloaded."})})}function co(e,t){S(e.command("remove-checkout").description("Delete the local checkout of one configured repository on the backend host. monospecs.yaml is not changed.")).requiredOption("--id <id>","Project id.").requiredOption("--path <path>","Configured repository path whose local checkout to delete.").option("--force","Delete the checkout even with uncommitted changes, unpushed commits or no upstream branch.").action(async function(r){const i=A(this,t),o=w(r.id,"--id"),a=re(w(r.path,"--path")),c=r.force===!0;let p;try{p=await i.api.removeMonoSpecsRepositoryCheckout(o,a,c)}catch(b){const C=Be(b);throw C.status===409&&!c&&/force/i.test(C.message)?new ie(409,`${C.message}
|
|
114
|
-
Re-run with --force to delete this checkout anyway.`,C.details):b}const m=no(p);i.outputJson?i.io.stdout(O(m)):i.io.stdout(ro(m))})}var uo="--version, --repo-directory, --commit-when-archive, --add-repository, --remove-repository";function po(e){return{name:e.name,code:e.code,path:e.path,url:e.url,displayName:e.displayName,type:e.type,icon:e.icon,optional:e.optional,tags:e.tags,metadata:e.metadata}}function ho(e){return e.split("/").at(-1)??e}function Se(e,t,n){const r=ct(t),i=n?dt(n.results):void 0;if(e.outputJson){e.io.stdout(O(i?{...r,clone:i}:r));return}e.io.stdout(`MonoSpecs configuration saved.
|
|
115
|
-
${ut(r)}`),i&&e.io.stdout(`
|
|
116
|
-
Clone results
|
|
117
|
-
${pt(i)}`)}function mo(e,t){S(e.command("set").description("Change the MonoSpecs metadata or repositories. Reads the document, applies the given options and saves it.")).requiredOption("--id <id>","Project id.").option("--version <value>","MonoSpecs configuration version.").option("--repo-directory <dir>","Repository directory relative to the project root.").option("--commit-when-archive <true|false>","Whether archiving commits the MonoSpecs changes.").option("--add-repository <path>","Configured repository path to add. Repeatable.",Oe,[]).option("--remove-repository <path>","Configured repository path to remove. Repeatable.",Oe,[]).option("--url <url>","Clone URL of the single added repository.").option("--name <name>","Name of the single added repository. Defaults to the last path segment.").option("--display-name <name>","Display name of the single added repository.").option("--type <type>","Type of the single added repository.").option("--clone","Clone the added repositories after saving. Requires at least one --add-repository.").action(async function(r){const i=r.addRepository.map(re),o=r.removeRepository.map(re);if(!(r.version!==void 0||r.repoDirectory!==void 0||r.commitWhenArchive!==void 0)&&i.length===0&&o.length===0)throw new T(`Provide at least one change: ${uo}.`);if(r.clone&&i.length===0)throw new T("--clone requires at least one --add-repository.");const a=[r.url!==void 0?"--url":void 0,r.name!==void 0?"--name":void 0,r.displayName!==void 0?"--display-name":void 0,r.type!==void 0?"--type":void 0].filter(Boolean);if(a.length>0&&i.length!==1)throw new T(`${a.join(", ")} apply to a single --add-repository only.`);let c;if(r.commitWhenArchive!==void 0){if(r.commitWhenArchive!=="true"&&r.commitWhenArchive!=="false")throw new T("--commit-when-archive must be true or false.");c=r.commitWhenArchive==="true"}const p=A(this,t),m=w(r.id,"--id"),b=await p.api.getMonoSpecsManagement(m),C=(b.repositories??[]).map(po);for(const R of o){const z=C.findIndex(ve=>re(ve.path??"")===R);if(z<0)throw new T(`Repository path ${R} is not configured, so it cannot be removed.`);C.splice(z,1)}for(const R of i){if(C.some(z=>re(z.path??"")===R))throw new T(`Repository path ${R} is already configured.`);C.push({name:r.name??ho(R),code:null,path:R,url:r.url??null,displayName:r.displayName??null,type:r.type??null,icon:null,optional:!1,tags:[],metadata:[]})}const _=await p.api.saveMonoSpecsManagement(m,{version:r.version??b.version,repoDirectory:r.repoDirectory??b.repoDirectory,commitWhenArchive:c??b.commitWhenArchive,repositories:C,metadata:b.metadata??[]});if(!r.clone){Se(p,_);return}let x;try{x=(await p.api.cloneMonoSpecsRepositories(m,{paths:i,includeOptional:!1})).results??[]}catch(R){throw Se(p,_),R}Se(p,_,{results:x});const G=x.filter(R=>R.status==="failed");if(G.length>0)throw new se(`The configuration was saved, but ${G.length} repository clone(s) failed. See the clone results above.`)})}function fo(e,t){S(e.command("show").description("Show the MonoSpecs management document of a project, with local Git state per repository.")).requiredOption("--id <id>","Project id.").option("--yaml","Also print the YAML preview in human-readable mode.").action(async function(r){const i=A(this,t);je(i,await i.api.getMonoSpecsManagement(w(r.id,"--id")),{yaml:r.yaml===!0})})}function go(e,t){S(e.command("validate").description("Validate the MonoSpecs configuration of a project. Exits with code 30 when it is invalid.")).requiredOption("--id <id>","Project id.").action(async function(r){const i=A(this,t),o=w(r.id,"--id"),a=((await i.api.listProjects()).projects??[]).find(p=>p.id===o);if(!a?.path)throw new ie(404,`Project ${o} was not found in the aggregation snapshot.`);const c=io(await i.api.validateMonoSpecs({projectPath:a.path}));if(i.outputJson?i.io.stdout(O(c)):i.io.stdout(oo(c)),!c.isValid)throw new se("MonoSpecs configuration is invalid. See the errors above.")})}function vo(e,t){const n=e.command("monospecs").description("Manage the MonoSpecs configuration and the local repository checkouts of a project.");fo(n,t),ao(n,t),mo(n,t),go(n,t),lo(n,t),so(n,t),co(n,t)}function yo(e,t){S(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=A(this,t),o=r.id.trim(),a=((await i.api.listProjects()).projects??[]).find(p=>p.id===o);if(!a)throw new ie(404,`Project ${o} was not found in the aggregation snapshot.`);const c=Ki(a);if(i.outputJson){i.io.stdout(O(c));return}i.io.stdout(Xi(c))})}function So(e,t){S(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 T("Provide at least one field to update: --name, --path, --description, or --clear-description.");if(r.description&&r.clearDescription)throw new T("Use either --description or --clear-description, not both.");const i=A(this,t),o=r.id.trim(),a=st((await i.api.listProjects()).projects).projects.find(p=>p.id===o);if(!a)throw new ie(404,`Project ${o} was not found in the aggregation snapshot.`);const c=ke(await i.api.updateProject(o,{name:P(r.name)??a.name,path:P(r.path)??a.path,description:r.clearDescription?null:P(r.description)??a.description??null}));if(i.outputJson){i.io.stdout(O({project:c}));return}i.io.stdout(`Project updated
|
|
118
|
-
${at(c)}`)})}function Ao(e,t){const n=e.command("project").description("Manage Hagi projects through generated project and aggregation APIs.");Zi(n,t),yo(n,t),Yi(n,t),So(n,t),Qi(n,t),vo(n,t)}function Oo(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new T("Annotation input must be a JSON object.");const n=t;if(!Array.isArray(n.files))throw new T("Annotation input must include a files array.");const r=typeof n.totalAnnotations=="number"?n.totalAnnotations:n.files.length,i=typeof n.submittedAt=="string"&&n.submittedAt.trim()?n.submittedAt:new Date().toISOString();return{...n,sessionId:e,totalAnnotations:r,submittedAt:i,files:n.files}}function bo(e,t){S(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=A(this,t),o=r.sessionId.trim(),a=Oo(o,await ge(r.input)),c=await i.api.submitAnnotations(o,a);if(i.outputJson){i.io.stdout(O({sessionId:o,message:c.message,annotationCount:c.annotationCount??a.totalAnnotations,fileCount:c.fileCount??a.files.length}));return}i.io.stdout(`Proposal annotations submitted
|
|
119
|
-
sessionId ${o}
|
|
120
|
-
message ${c.message}
|
|
121
|
-
annotationCount ${c.annotationCount??a.totalAnnotations}
|
|
122
|
-
fileCount ${c.fileCount??a.files.length}
|
|
123
|
-
`)})}function Co(e,t){S(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=A(this,t),o=Y(await i.api.archiveProposal(r.sessionId.trim(),{heroId:P(r.heroId)}));if(i.outputJson){i.io.stdout(O({session:o}));return}i.io.stdout(`Proposal archive started
|
|
124
|
-
${oe(o)}`)})}function Po(e,t){S(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=A(this,t),o=Y(await i.api.completeProposal(r.sessionId.trim()));if(i.outputJson){i.io.stdout(O({session:o}));return}i.io.stdout(`Proposal completed
|
|
125
|
-
${oe(o)}`)})}function wo(e){return Y(e)}function _o(e){return Qe(e)}function Eo(e){return Ze("Proposal sessions",e)}function To(e,t=[]){return oe(e,t)}var ht="New Proposal";function Io(e){const t=P(e.title);if(t)return t;if(e.defaultTitle)return ht;throw new T("Provide --title or pass --default-title to use the placeholder proposal title.")}function ko(e,t){S(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 (${ht}).`).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=A(this,t),o=Io(r),a=wo(await i.api.createProposalSession({title:o,chiefComplaint:r.chiefComplaint.trim(),originalChiefComplaint:P(r.originalChiefComplaint),type:Te.PROPOSAL,projectId:r.projectId.trim(),enableIndependentWorkspace:r.enableIndependentWorkspace?!0:void 0,baseBranch:P(r.baseBranch),isDefaultTitle:!!r.defaultTitle})),c=`hagi proposal optimize-description --session-id ${a.sessionId} --description "<description>"`;if(i.outputJson){i.io.stdout(O({session:a,nextCommand:c}));return}i.io.stdout(`Proposal session created
|
|
126
|
-
${To(a,[["next",c]])}`)})}function jo(e,t){S(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=A(this,t),o=r.sessionId.trim(),a=P(r.heroId),c=await i.api.executeProposal(o,{heroId:a});if(i.outputJson){i.io.stdout(O({sessionId:o,message:c.message,requested:{heroId:a}}));return}i.io.stdout(`Proposal execution started
|
|
127
|
-
sessionId ${o}
|
|
128
|
-
message ${c.message}
|
|
129
|
-
`)})}var be=["zh-CN","zh-Hant","en-US","ja-JP","ko-KR","de-DE","fr-FR","es-ES","pt-BR","ru-RU"];function xo(e){if(e.enableExploreMode&&e.disableExploreMode)throw new T("Use either --enable-explore-mode or --disable-explore-mode, not both.");if(e.enableExploreMode)return!0;if(e.disableExploreMode)return!1}function $o(e){const t=e.trim();if(!be.includes(t))throw new T(`--proposal-content-language must be one of: ${be.join(", ")}.`);return t}function No(e,t){S(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 (${be.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=A(this,t),o=r.sessionId.trim(),a=xo(r),c=$o(r.proposalContentLanguage),p=await i.api.generateProposal(o,{enableExploreMode:a,heroId:P(r.heroId),proposalContentLanguage:c}),m=`hagi proposal execute --session-id ${o}`;if(i.outputJson){i.io.stdout(O({sessionId:o,message:p.message,requested:{enableExploreMode:a,heroId:P(r.heroId),proposalContentLanguage:c},nextCommand:m}));return}i.io.stdout(`Proposal generation started
|
|
130
|
-
sessionId ${o}
|
|
131
|
-
message ${p.message}
|
|
132
|
-
next Wait for the session to reach Reviewing, then run ${m}
|
|
133
|
-
`)})}function Ro(e,t){S(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 T("Use either --project-id or --project-ids, not both.");const i=A(this,t),o=_o(await i.api.listSessions({type:Te.PROPOSAL,projectId:P(r.projectId),projectIds:r.projectIds?.map(P).filter(Boolean),activeOnly:r.activeOnly?!0:void 0,includeArchived:r.includeArchived?!0:void 0}));if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(Eo(o.sessions))})}function Ho(e,t){const n=t.summary,r=t.result,i=r?.validation?.isValid===!0,o=n?.appliedTitle||r?.optimizedTitle||"",a=n?.appliedProposalName||r?.optimizedProposalName||"",c=r?.validation?.diagnostics??[],p=[i?"Proposal optimized":"Proposal optimization returned diagnostics",`sessionId ${e}`,`title ${o}`,`proposalName ${a}`,`valid ${i?"yes":"no"}`];for(const m of c)p.push(`diagnostic ${m.code??"UNKNOWN"}: ${m.message??""}`.trimEnd());return i&&p.push(`next hagi proposal generate --session-id ${e}`),`${p.join(`
|
|
134
|
-
`)}
|
|
135
|
-
`}function Do(e,t){S(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=A(this,t),o=w(r.sessionId,"--session-id"),a=await i.api.optimizeProposal(o,{description:w(r.description,"--description"),title:P(r.title),isDefaultTitle:r.defaultTitle?!0:void 0,optimizationDirection:P(r.optimizationDirection),originalChiefComplaint:P(r.originalChiefComplaint)});if(i.outputJson){i.io.stdout(O({sessionId:o,...a}));return}i.io.stdout(Ho(o,a))})}function Vo(e,t){S(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 X("--mode <mode>","Message mode override.").choices(Object.values(Ie))).addOption(new X("--executor-type <type>","Executor override for this message.").choices(Object.values(fe))).action(async function(r){const i=A(this,t),o=r.sessionId.trim(),a=await i.api.sendMessage(o,{content:w(r.content,"--content"),mode:r.mode,executorType:r.executorType});if(i.outputJson){i.io.stdout(O({sessionId:o,message:a.message,requested:{mode:r.mode,executorType:r.executorType}}));return}i.io.stdout(Ee("Proposal message sent",o,a,[["mode",r.mode],["executorType",r.executorType]]))})}function qo(e,t){S(e.command("status").description("Update proposal session status through read-before-write merging.")).requiredOption("--session-id <id>","Proposal session id.").addOption(new X("--status <status>","Target session status.").choices(Object.values(Xe)).makeOptionMandatory()).action(async function(r){const i=A(this,t),o=r.sessionId.trim(),a=await i.api.getSession(o);await i.api.updateSession(o,{title:a.title,description:a.description,status:r.status,metadata:a.metadata});const c=Y({...a,status:r.status});if(i.outputJson){i.io.stdout(O({session:c}));return}i.io.stdout(`Proposal status updated
|
|
136
|
-
${oe(c)}`)})}function Mo(e,t){const n=e.command("proposal").description("Manage proposal sessions through backend session APIs.");Ro(n,t),ko(n,t),Do(n,t),No(n,t),bo(n,t),jo(n,t),Co(n,t),qo(n,t),Po(n,t),Vo(n,t)}function ee(e){return e?"yes":"no"}function Lo(e){return e&&e.length>0?e.join(", "):"-"}function mt(e){return e.origin??"user"}function ft(e){return mt(e)==="built-in"}function Fo(e){return ft(e)?ee(e.builtIn?.enabled):"-"}function Go(e){return(ft(e)?e.builtIn?.version:e.managedInstallMetadata?.version)??"-"}function Uo(e){const t=e.items??[];return t.length===0?`No local skills installed.
|
|
137
|
-
`:`Local skills (${t.length})
|
|
138
|
-
${L([{header:"Name",value:n=>n.name??"-"},{header:"Origin",value:mt},{header:"Enabled",value:Fo},{header:"Version",value:Go},{header:"Scope",value:n=>n.scope??"-"},{header:"Agents",value:n=>Lo(n.agents)},{header:"Path",value:n=>n.path??"-"}],t)}
|
|
139
|
-
`}function Bo(e){return D([["skillName",e.skillName??void 0],["status",e.status??void 0],["message",e.userMessage??void 0],["diagnostic",e.diagnosticMessage??void 0]])}function Wo(e){return D([["skillName",e.slug??void 0],["enabled",ee(e.enabled)],["message",e.userMessage??void 0],["diagnostic",e.diagnosticMessage??void 0]])}function Jo(e){const t=e.items??[];return t.length===0?`No gallery skills found.
|
|
140
|
-
`:`Gallery skills (${t.length})
|
|
141
|
-
${L([{header:"ID",value:n=>n.id??"-"},{header:"Source",value:n=>n.source??"-"},{header:"Installs",value:n=>String(n.installs??0)},{header:"Trusted",value:n=>ee(n.isTrustedSource)}],t)}
|
|
142
|
-
`}function zo(e){const t=e.trustedProvider;return D([["id",e.id??void 0],["source",e.source??void 0],["skillSlug",e.skillSlug??void 0],["installable",ee(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",ee(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 Ko(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 ue(e){const t=e.items??[];return t.length===0?`No trusted providers (directory version ${e.version??0}).
|
|
143
|
-
`:`Trusted providers (${t.length}, directory version ${e.version??0})
|
|
144
|
-
${L([{header:"Provider ID",value:n=>n.providerId??"-"},{header:"Name",value:n=>n.displayName??"-"},{header:"Enabled",value:n=>ee(n.isEnabled)},{header:"Preset",value:n=>ee(n.isPreset)},{header:"Rules",value:n=>String(n.ruleCount??0)}],t)}
|
|
145
|
-
`}function Xo(e,t){const n=e.command("gallery").description("Search the skill gallery, read skill details, and start managed installs.");S(n.command("search").description("Search the skill gallery by keyword.")).option("--query <query>","Keyword to search for. Omit to list the gallery.").action(async function(i){const o=A(this,t),a=await o.api.searchSkillGallery(P(i.query));if(o.outputJson){o.io.stdout(O(a));return}o.io.stdout(Jo(a))}),S(n.command("detail").description("Show one gallery skill with installability, trust, and repository details.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").action(async function(i){const o=A(this,t),a=await o.api.getSkillGalleryDetail(w(i.id,"--id"),w(i.source,"--source"));if(o.outputJson){o.io.stdout(O(a));return}o.io.stdout(zo(a))}),S(n.command("install").description("Start a managed install of one gallery skill.")).requiredOption("--id <id>","Gallery skill id.").requiredOption("--source <source>","Gallery skill source.").requiredOption("--skill-slug <slug>","Skill slug inside the source repository.").option("--version <version>","Optional version token to install.").action(async function(i){const o=A(this,t),a=await o.api.installGallerySkill({id:w(i.id,"--id"),source:w(i.source,"--source"),skillSlug:w(i.skillSlug,"--skill-slug"),version:P(i.version)});if(o.outputJson){o.io.stdout(O(a));return}o.io.stdout(Ko(a))})}var Yo="The change applies to agent runs that start afterwards; a run already in progress keeps its skills.";function Me(e,t,n){const r=n?"enable":"disable";S(e.command(r).description(`${n?"Turn on":"Turn off"} one built-in skill by name. ${Yo}`)).requiredOption("--skill-name <name>",`Built-in skill name to ${r}.`).action(async function(o){const a=A(this,t),c=await a.api.setBuiltInSkillAvailability({slug:w(o.skillName,"--skill-name"),enabled:n});if(a.outputJson?a.io.stdout(O(c)):a.io.stdout(Wo(c)),!c.succeeded)throw new se(c.userMessage??`The built-in skill availability was not changed for ${c.slug??o.skillName}.`)})}function Qo(e,t){const n=e.command("local").description("List, enable or disable built-in skills, and uninstall user-installed local skills.");S(n.command("list").description("List installed local skills with their managed install metadata.")).action(async function(){const i=A(this,t),o=await i.api.listLocalSkills();if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(Uo(o))}),Me(n,t,!0),Me(n,t,!1),S(n.command("uninstall").description("Uninstall one user-installed local skill by name. Built-in skills cannot be uninstalled; use `skills local disable --skill-name <name>` to stop one from loading.")).requiredOption("--skill-name <name>","Local skill name to uninstall.").action(async function(i){const o=A(this,t),a=await o.api.uninstallLocalSkill({skillName:w(i.skillName,"--skill-name")});if(o.outputJson){o.io.stdout(O(a));return}o.io.stdout(Bo(a))})}async function Zo(e,t){const n=await ge(e);if(!n||typeof n!="object"||Array.isArray(n))throw new T(`${t} must be a JSON object.`);return n}function en(e,t){const n=e.command("trusted").description("Manage the trusted skill provider directory.");S(n.command("list").description("List trusted skill providers.")).action(async function(){const i=A(this,t),o=await i.api.listTrustedSkillProviders();if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(ue(o))}),S(n.command("upsert").description("Create or update a trusted provider from a JSON document.")).requiredOption("--input <file>","JSON file path, or - to read from stdin.").action(async function(i){const o=A(this,t),a=await Zo(w(i.input,"--input"),"Trusted provider input"),c=await o.api.upsertTrustedSkillProvider(a);if(o.outputJson){o.io.stdout(O(c));return}o.io.stdout(ue(c))}),S(n.command("delete").description("Delete one trusted provider by id.")).requiredOption("--provider-id <id>","Trusted provider id to delete.").action(async function(i){const o=A(this,t),a={providerId:w(i.providerId,"--provider-id")},c=await o.api.deleteTrustedSkillProvider(a);if(o.outputJson){o.io.stdout(O(c));return}o.io.stdout(ue(c))}),S(n.command("reset").description("Reset trusted providers to the backend defaults.")).action(async function(){const i=A(this,t),o=await i.api.resetTrustedSkillProviders();if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(ue(o))})}function tn(e,t){const n=e.command("skills").description("Manage local skills, the skill gallery, and trusted providers.");Qo(n,t),Xo(n,t),en(n,t)}function j(e){const t=e?.trim();return t||void 0}function on(e){return{severity:j(e.severity)??"",code:j(e.code)??"",message:j(e.message)??"",relativePath:j(e.relativePath)}}function xe(e){return{id:j(e.id)??"",name:j(e.name)??"",type:j(e.type)??"",physicalPath:j(e.physicalPath)??"",gitUrl:j(e.gitUrl),createdAtUtc:j(e.createdAtUtc),updatedAtUtc:j(e.updatedAtUtc),bootstrapDiagnostics:(e.bootstrapDiagnostics??[]).map(on)}}function gt(e){return{generatedAtUtc:j(e.generatedAtUtc),vaults:(e.items??[]).map(xe)}}function nn(e){return e.length===0?`No vaults found.
|
|
146
|
-
`:`Vaults (${e.length})
|
|
147
|
-
${L([{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)}
|
|
148
|
-
`}function vt(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 rn(e){return{relativePath:j(e.relativePath)??"",fileName:j(e.fileName)??"",isDirectory:e.isDirectory===!0,extension:j(e.extension)??"",sizeBytes:typeof e.sizeBytes=="number"?e.sizeBytes:0,lastModifiedUtc:j(e.lastModifiedUtc),previewSupported:e.previewSupported===!0}}function sn(e){return{vaultId:j(e.id)??"",deleted:e.deleted===!0,deleteLocalFilesRequested:e.deleteLocalFilesRequested===!0,localFilesDeletionStatus:j(e.localFilesDeletionStatus),localFilesDeleted:e.localFilesDeleted===!0}}function an(e){return`Vault deleted
|
|
149
|
-
${D([["vaultId",e.vaultId],["deleted",String(e.deleted)],["deleteLocalFilesRequested",String(e.deleteLocalFilesRequested)],["localFilesDeletionStatus",e.localFilesDeletionStatus],["localFilesDeleted",String(e.localFilesDeleted)]])}`}function ln(e){return{vaultId:j(e.vaultId)??"",vaultName:j(e.vaultName)??"",physicalPath:j(e.physicalPath)??"",status:j(e.status)??"",errorCode:j(e.errorCode),message:j(e.message),isTruncated:e.isTruncated===!0,totalFileCount:typeof e.totalFileCount=="number"?e.totalFileCount:0,items:(e.items??[]).map(rn)}}function cn(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
|
|
150
|
-
${t}No files found.
|
|
151
|
-
`:`Vault files
|
|
152
|
-
${t}${L([{header:"Relative Path",value:n=>n.relativePath},{header:"Directory",value:n=>n.isDirectory?"yes":"no"},{header:"Extension",value:n=>n.extension},{header:"Size",value:n=>String(n.sizeBytes)},{header:"Preview",value:n=>n.previewSupported?"yes":"no"}],e.items)}
|
|
153
|
-
`}function un(e){return{vaultId:j(e.vaultId)??"",vaultName:j(e.vaultName)??"",physicalPath:j(e.physicalPath)??"",relativePath:j(e.relativePath)??"",fileName:j(e.fileName)??"",extension:j(e.extension)??"",sizeBytes:typeof e.sizeBytes=="number"?e.sizeBytes:0,lastModifiedUtc:j(e.lastModifiedUtc),status:j(e.status)??"",errorCode:j(e.errorCode),message:j(e.message),previewSupported:e.previewSupported===!0,contentTruncated:e.contentTruncated===!0,content:j(e.content)}}function dn(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
|
|
154
|
-
${t}`;const n=e.content.endsWith(`
|
|
155
|
-
`)?"":`
|
|
156
|
-
`;return`Vault file preview
|
|
157
|
-
${t}content
|
|
158
|
-
-------
|
|
159
|
-
${e.content}${n}`}function pn(e,t){S(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=A(this,t),o=xe(await i.api.createVault({name:w(r.name,"--name"),type:w(r.type,"--type"),physicalPath:w(r.physicalPath,"--physical-path"),gitUrl:P(r.gitUrl)}));if(i.outputJson){i.io.stdout(O({vault:o}));return}i.io.stdout(`Vault created
|
|
160
|
-
${vt(o)}`)})}function hn(e,t){S(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=A(this,t),o=sn(await i.api.deleteVault(w(r.id,"--id"),r.deleteLocalFiles===!0));if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(an(o))})}function mn(e,t){S(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=A(this,t),o=ln(await i.api.listVaultFiles(w(r.id,"--id"),P(r.path)));if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(cn(o))})}function fn(e,t){S(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=A(this,t),o=un(await i.api.previewVaultFile(w(r.id,"--id"),w(r.path,"--path")));if(i.outputJson){i.io.stdout(O(o));return}i.io.stdout(dn(o))})}function gn(e,t){S(e.command("list").description("List registered vaults through the generated vault client.")).action(async function(){const r=A(this,t),i=gt(await r.api.listVaults());if(r.outputJson){r.io.stdout(O(i));return}r.io.stdout(nn(i.vaults))})}function vn(e,t){S(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=P(r.name),o=P(r.type),a=P(r.physicalPath),c=P(r.gitUrl);if(!i&&!o&&!a&&!c)throw new T("Provide at least one field to update: --name, --type, --physical-path, or --git-url.");const p=A(this,t),m=w(r.id,"--id"),b=gt(await p.api.listVaults()).vaults.find(_=>_.id===m);if(!b)throw new ie(404,`Vault ${m} was not found in the latest vault snapshot.`);const C=xe(await p.api.updateVault(m,{name:i??b.name,type:o??b.type,physicalPath:a??b.physicalPath,gitUrl:c??b.gitUrl??null}));if(p.outputJson){p.io.stdout(O({vault:C}));return}p.io.stdout(`Vault updated
|
|
161
|
-
${vt(C)}`)})}function yn(e,t){const n=e.command("vault").description("Manage Hagi vaults and vault file browsing through generated backend APIs.");gn(n,t),pn(n,t),vn(n,t),hn(n,t);const r=n.command("files").description("Browse registered vault files and preview supported content.");mn(r,t),fn(r,t)}function Sn(e){return e.includes("--json")}function yt(e=Ke(),t=!1){const n=new Rt;return n.name("hagi").description("HagiCode CLI for project, proposal, vault, chat, HagiTask, and scheduled plan management.").showHelpAfterError().exitOverride(),n.configureOutput({writeOut:r=>{e.io.stdout(r)},writeErr:r=>{t||e.io.stderr(r)},getOutHelpWidth:()=>100,getErrHelpWidth:()=>100}),ai(n),Ao(n,e),Mo(n,e),yn(n,e),hi(n,e),ki(n,e),Ji(n,e),tn(n,e),n}function An(e,t,n){return e.exitCode===0||e.code==="commander.helpDisplayed"||e.code==="commander.version"?0:(n&&t.io.stderr(We({exitCode:q.USAGE,message:e.message},{json:!0})),q.USAGE)}async function On(e=process.argv,t=Ke()){const n=Sn(e),r=yt(t,n);try{return await r.parseAsync([...e]),0}catch(i){if(i instanceof Nt)return An(i,t,n);const o=Be(i,{baseUrl:Wt()});return t.io.stderr(We(o,{json:n})),o.exitCode}}Object.defineProperty(exports,"EXIT_CODES",{enumerable:!0,get:function(){return q}});Object.defineProperty(exports,"createCliApp",{enumerable:!0,get:function(){return yt}});Object.defineProperty(exports,"runCli",{enumerable:!0,get:function(){return On}});
|