@controlvector/cv-agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/bundle.cjs +4822 -0
  2. package/dist/bundle.cjs.map +7 -0
  3. package/dist/commands/agent-git.d.ts +59 -0
  4. package/dist/commands/agent-git.d.ts.map +1 -0
  5. package/dist/commands/agent-git.js +234 -0
  6. package/dist/commands/agent-git.js.map +1 -0
  7. package/dist/commands/agent.d.ts +20 -0
  8. package/dist/commands/agent.d.ts.map +1 -0
  9. package/dist/commands/agent.js +506 -0
  10. package/dist/commands/agent.js.map +1 -0
  11. package/dist/commands/auth.d.ts +8 -0
  12. package/dist/commands/auth.d.ts.map +1 -0
  13. package/dist/commands/auth.js +104 -0
  14. package/dist/commands/auth.js.map +1 -0
  15. package/dist/commands/remote.d.ts +8 -0
  16. package/dist/commands/remote.d.ts.map +1 -0
  17. package/dist/commands/remote.js +100 -0
  18. package/dist/commands/remote.js.map +1 -0
  19. package/dist/commands/status.d.ts +8 -0
  20. package/dist/commands/status.d.ts.map +1 -0
  21. package/dist/commands/status.js +75 -0
  22. package/dist/commands/status.js.map +1 -0
  23. package/dist/commands/task.d.ts +8 -0
  24. package/dist/commands/task.d.ts.map +1 -0
  25. package/dist/commands/task.js +122 -0
  26. package/dist/commands/task.js.map +1 -0
  27. package/dist/index.d.ts +9 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +27 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/utils/api.d.ts +31 -0
  32. package/dist/utils/api.d.ts.map +1 -0
  33. package/dist/utils/api.js +169 -0
  34. package/dist/utils/api.js.map +1 -0
  35. package/dist/utils/config.d.ts +13 -0
  36. package/dist/utils/config.d.ts.map +1 -0
  37. package/dist/utils/config.js +29 -0
  38. package/dist/utils/config.js.map +1 -0
  39. package/dist/utils/credentials.d.ts +46 -0
  40. package/dist/utils/credentials.d.ts.map +1 -0
  41. package/dist/utils/credentials.js +176 -0
  42. package/dist/utils/credentials.js.map +1 -0
  43. package/dist/utils/display.d.ts +8 -0
  44. package/dist/utils/display.d.ts.map +1 -0
  45. package/dist/utils/display.js +50 -0
  46. package/dist/utils/display.js.map +1 -0
  47. package/dist/utils/retry.d.ts +5 -0
  48. package/dist/utils/retry.d.ts.map +1 -0
  49. package/dist/utils/retry.js +26 -0
  50. package/dist/utils/retry.js.map +1 -0
  51. package/package.json +38 -0
@@ -0,0 +1,4822 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // node_modules/commander/lib/error.js
30
+ var require_error = __commonJS({
31
+ "node_modules/commander/lib/error.js"(exports2) {
32
+ var CommanderError2 = class extends Error {
33
+ /**
34
+ * Constructs the CommanderError class
35
+ * @param {number} exitCode suggested exit code which could be used with process.exit
36
+ * @param {string} code an id string representing the error
37
+ * @param {string} message human-readable description of the error
38
+ */
39
+ constructor(exitCode, code, message) {
40
+ super(message);
41
+ Error.captureStackTrace(this, this.constructor);
42
+ this.name = this.constructor.name;
43
+ this.code = code;
44
+ this.exitCode = exitCode;
45
+ this.nestedError = void 0;
46
+ }
47
+ };
48
+ var InvalidArgumentError2 = class extends CommanderError2 {
49
+ /**
50
+ * Constructs the InvalidArgumentError class
51
+ * @param {string} [message] explanation of why argument is invalid
52
+ */
53
+ constructor(message) {
54
+ super(1, "commander.invalidArgument", message);
55
+ Error.captureStackTrace(this, this.constructor);
56
+ this.name = this.constructor.name;
57
+ }
58
+ };
59
+ exports2.CommanderError = CommanderError2;
60
+ exports2.InvalidArgumentError = InvalidArgumentError2;
61
+ }
62
+ });
63
+
64
+ // node_modules/commander/lib/argument.js
65
+ var require_argument = __commonJS({
66
+ "node_modules/commander/lib/argument.js"(exports2) {
67
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
68
+ var Argument2 = class {
69
+ /**
70
+ * Initialize a new command argument with the given name and description.
71
+ * The default is that the argument is required, and you can explicitly
72
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
73
+ *
74
+ * @param {string} name
75
+ * @param {string} [description]
76
+ */
77
+ constructor(name, description) {
78
+ this.description = description || "";
79
+ this.variadic = false;
80
+ this.parseArg = void 0;
81
+ this.defaultValue = void 0;
82
+ this.defaultValueDescription = void 0;
83
+ this.argChoices = void 0;
84
+ switch (name[0]) {
85
+ case "<":
86
+ this.required = true;
87
+ this._name = name.slice(1, -1);
88
+ break;
89
+ case "[":
90
+ this.required = false;
91
+ this._name = name.slice(1, -1);
92
+ break;
93
+ default:
94
+ this.required = true;
95
+ this._name = name;
96
+ break;
97
+ }
98
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
99
+ this.variadic = true;
100
+ this._name = this._name.slice(0, -3);
101
+ }
102
+ }
103
+ /**
104
+ * Return argument name.
105
+ *
106
+ * @return {string}
107
+ */
108
+ name() {
109
+ return this._name;
110
+ }
111
+ /**
112
+ * @package
113
+ */
114
+ _concatValue(value, previous) {
115
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
116
+ return [value];
117
+ }
118
+ return previous.concat(value);
119
+ }
120
+ /**
121
+ * Set the default value, and optionally supply the description to be displayed in the help.
122
+ *
123
+ * @param {*} value
124
+ * @param {string} [description]
125
+ * @return {Argument}
126
+ */
127
+ default(value, description) {
128
+ this.defaultValue = value;
129
+ this.defaultValueDescription = description;
130
+ return this;
131
+ }
132
+ /**
133
+ * Set the custom handler for processing CLI command arguments into argument values.
134
+ *
135
+ * @param {Function} [fn]
136
+ * @return {Argument}
137
+ */
138
+ argParser(fn) {
139
+ this.parseArg = fn;
140
+ return this;
141
+ }
142
+ /**
143
+ * Only allow argument value to be one of choices.
144
+ *
145
+ * @param {string[]} values
146
+ * @return {Argument}
147
+ */
148
+ choices(values) {
149
+ this.argChoices = values.slice();
150
+ this.parseArg = (arg, previous) => {
151
+ if (!this.argChoices.includes(arg)) {
152
+ throw new InvalidArgumentError2(
153
+ `Allowed choices are ${this.argChoices.join(", ")}.`
154
+ );
155
+ }
156
+ if (this.variadic) {
157
+ return this._concatValue(arg, previous);
158
+ }
159
+ return arg;
160
+ };
161
+ return this;
162
+ }
163
+ /**
164
+ * Make argument required.
165
+ *
166
+ * @returns {Argument}
167
+ */
168
+ argRequired() {
169
+ this.required = true;
170
+ return this;
171
+ }
172
+ /**
173
+ * Make argument optional.
174
+ *
175
+ * @returns {Argument}
176
+ */
177
+ argOptional() {
178
+ this.required = false;
179
+ return this;
180
+ }
181
+ };
182
+ function humanReadableArgName(arg) {
183
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
184
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
185
+ }
186
+ exports2.Argument = Argument2;
187
+ exports2.humanReadableArgName = humanReadableArgName;
188
+ }
189
+ });
190
+
191
+ // node_modules/commander/lib/help.js
192
+ var require_help = __commonJS({
193
+ "node_modules/commander/lib/help.js"(exports2) {
194
+ var { humanReadableArgName } = require_argument();
195
+ var Help2 = class {
196
+ constructor() {
197
+ this.helpWidth = void 0;
198
+ this.sortSubcommands = false;
199
+ this.sortOptions = false;
200
+ this.showGlobalOptions = false;
201
+ }
202
+ /**
203
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
204
+ *
205
+ * @param {Command} cmd
206
+ * @returns {Command[]}
207
+ */
208
+ visibleCommands(cmd) {
209
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
210
+ const helpCommand = cmd._getHelpCommand();
211
+ if (helpCommand && !helpCommand._hidden) {
212
+ visibleCommands.push(helpCommand);
213
+ }
214
+ if (this.sortSubcommands) {
215
+ visibleCommands.sort((a, b) => {
216
+ return a.name().localeCompare(b.name());
217
+ });
218
+ }
219
+ return visibleCommands;
220
+ }
221
+ /**
222
+ * Compare options for sort.
223
+ *
224
+ * @param {Option} a
225
+ * @param {Option} b
226
+ * @returns {number}
227
+ */
228
+ compareOptions(a, b) {
229
+ const getSortKey = (option) => {
230
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
231
+ };
232
+ return getSortKey(a).localeCompare(getSortKey(b));
233
+ }
234
+ /**
235
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
236
+ *
237
+ * @param {Command} cmd
238
+ * @returns {Option[]}
239
+ */
240
+ visibleOptions(cmd) {
241
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
242
+ const helpOption = cmd._getHelpOption();
243
+ if (helpOption && !helpOption.hidden) {
244
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
245
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
246
+ if (!removeShort && !removeLong) {
247
+ visibleOptions.push(helpOption);
248
+ } else if (helpOption.long && !removeLong) {
249
+ visibleOptions.push(
250
+ cmd.createOption(helpOption.long, helpOption.description)
251
+ );
252
+ } else if (helpOption.short && !removeShort) {
253
+ visibleOptions.push(
254
+ cmd.createOption(helpOption.short, helpOption.description)
255
+ );
256
+ }
257
+ }
258
+ if (this.sortOptions) {
259
+ visibleOptions.sort(this.compareOptions);
260
+ }
261
+ return visibleOptions;
262
+ }
263
+ /**
264
+ * Get an array of the visible global options. (Not including help.)
265
+ *
266
+ * @param {Command} cmd
267
+ * @returns {Option[]}
268
+ */
269
+ visibleGlobalOptions(cmd) {
270
+ if (!this.showGlobalOptions) return [];
271
+ const globalOptions = [];
272
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
273
+ const visibleOptions = ancestorCmd.options.filter(
274
+ (option) => !option.hidden
275
+ );
276
+ globalOptions.push(...visibleOptions);
277
+ }
278
+ if (this.sortOptions) {
279
+ globalOptions.sort(this.compareOptions);
280
+ }
281
+ return globalOptions;
282
+ }
283
+ /**
284
+ * Get an array of the arguments if any have a description.
285
+ *
286
+ * @param {Command} cmd
287
+ * @returns {Argument[]}
288
+ */
289
+ visibleArguments(cmd) {
290
+ if (cmd._argsDescription) {
291
+ cmd.registeredArguments.forEach((argument) => {
292
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
293
+ });
294
+ }
295
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
296
+ return cmd.registeredArguments;
297
+ }
298
+ return [];
299
+ }
300
+ /**
301
+ * Get the command term to show in the list of subcommands.
302
+ *
303
+ * @param {Command} cmd
304
+ * @returns {string}
305
+ */
306
+ subcommandTerm(cmd) {
307
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
308
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
309
+ (args ? " " + args : "");
310
+ }
311
+ /**
312
+ * Get the option term to show in the list of options.
313
+ *
314
+ * @param {Option} option
315
+ * @returns {string}
316
+ */
317
+ optionTerm(option) {
318
+ return option.flags;
319
+ }
320
+ /**
321
+ * Get the argument term to show in the list of arguments.
322
+ *
323
+ * @param {Argument} argument
324
+ * @returns {string}
325
+ */
326
+ argumentTerm(argument) {
327
+ return argument.name();
328
+ }
329
+ /**
330
+ * Get the longest command term length.
331
+ *
332
+ * @param {Command} cmd
333
+ * @param {Help} helper
334
+ * @returns {number}
335
+ */
336
+ longestSubcommandTermLength(cmd, helper) {
337
+ return helper.visibleCommands(cmd).reduce((max, command) => {
338
+ return Math.max(max, helper.subcommandTerm(command).length);
339
+ }, 0);
340
+ }
341
+ /**
342
+ * Get the longest option term length.
343
+ *
344
+ * @param {Command} cmd
345
+ * @param {Help} helper
346
+ * @returns {number}
347
+ */
348
+ longestOptionTermLength(cmd, helper) {
349
+ return helper.visibleOptions(cmd).reduce((max, option) => {
350
+ return Math.max(max, helper.optionTerm(option).length);
351
+ }, 0);
352
+ }
353
+ /**
354
+ * Get the longest global option term length.
355
+ *
356
+ * @param {Command} cmd
357
+ * @param {Help} helper
358
+ * @returns {number}
359
+ */
360
+ longestGlobalOptionTermLength(cmd, helper) {
361
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
362
+ return Math.max(max, helper.optionTerm(option).length);
363
+ }, 0);
364
+ }
365
+ /**
366
+ * Get the longest argument term length.
367
+ *
368
+ * @param {Command} cmd
369
+ * @param {Help} helper
370
+ * @returns {number}
371
+ */
372
+ longestArgumentTermLength(cmd, helper) {
373
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
374
+ return Math.max(max, helper.argumentTerm(argument).length);
375
+ }, 0);
376
+ }
377
+ /**
378
+ * Get the command usage to be displayed at the top of the built-in help.
379
+ *
380
+ * @param {Command} cmd
381
+ * @returns {string}
382
+ */
383
+ commandUsage(cmd) {
384
+ let cmdName = cmd._name;
385
+ if (cmd._aliases[0]) {
386
+ cmdName = cmdName + "|" + cmd._aliases[0];
387
+ }
388
+ let ancestorCmdNames = "";
389
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
390
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
391
+ }
392
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
393
+ }
394
+ /**
395
+ * Get the description for the command.
396
+ *
397
+ * @param {Command} cmd
398
+ * @returns {string}
399
+ */
400
+ commandDescription(cmd) {
401
+ return cmd.description();
402
+ }
403
+ /**
404
+ * Get the subcommand summary to show in the list of subcommands.
405
+ * (Fallback to description for backwards compatibility.)
406
+ *
407
+ * @param {Command} cmd
408
+ * @returns {string}
409
+ */
410
+ subcommandDescription(cmd) {
411
+ return cmd.summary() || cmd.description();
412
+ }
413
+ /**
414
+ * Get the option description to show in the list of options.
415
+ *
416
+ * @param {Option} option
417
+ * @return {string}
418
+ */
419
+ optionDescription(option) {
420
+ const extraInfo = [];
421
+ if (option.argChoices) {
422
+ extraInfo.push(
423
+ // use stringify to match the display of the default value
424
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
425
+ );
426
+ }
427
+ if (option.defaultValue !== void 0) {
428
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
429
+ if (showDefault) {
430
+ extraInfo.push(
431
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
432
+ );
433
+ }
434
+ }
435
+ if (option.presetArg !== void 0 && option.optional) {
436
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
437
+ }
438
+ if (option.envVar !== void 0) {
439
+ extraInfo.push(`env: ${option.envVar}`);
440
+ }
441
+ if (extraInfo.length > 0) {
442
+ return `${option.description} (${extraInfo.join(", ")})`;
443
+ }
444
+ return option.description;
445
+ }
446
+ /**
447
+ * Get the argument description to show in the list of arguments.
448
+ *
449
+ * @param {Argument} argument
450
+ * @return {string}
451
+ */
452
+ argumentDescription(argument) {
453
+ const extraInfo = [];
454
+ if (argument.argChoices) {
455
+ extraInfo.push(
456
+ // use stringify to match the display of the default value
457
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
458
+ );
459
+ }
460
+ if (argument.defaultValue !== void 0) {
461
+ extraInfo.push(
462
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
463
+ );
464
+ }
465
+ if (extraInfo.length > 0) {
466
+ const extraDescripton = `(${extraInfo.join(", ")})`;
467
+ if (argument.description) {
468
+ return `${argument.description} ${extraDescripton}`;
469
+ }
470
+ return extraDescripton;
471
+ }
472
+ return argument.description;
473
+ }
474
+ /**
475
+ * Generate the built-in help text.
476
+ *
477
+ * @param {Command} cmd
478
+ * @param {Help} helper
479
+ * @returns {string}
480
+ */
481
+ formatHelp(cmd, helper) {
482
+ const termWidth = helper.padWidth(cmd, helper);
483
+ const helpWidth = helper.helpWidth || 80;
484
+ const itemIndentWidth = 2;
485
+ const itemSeparatorWidth = 2;
486
+ function formatItem(term, description) {
487
+ if (description) {
488
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
489
+ return helper.wrap(
490
+ fullText,
491
+ helpWidth - itemIndentWidth,
492
+ termWidth + itemSeparatorWidth
493
+ );
494
+ }
495
+ return term;
496
+ }
497
+ function formatList(textArray) {
498
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
499
+ }
500
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
501
+ const commandDescription = helper.commandDescription(cmd);
502
+ if (commandDescription.length > 0) {
503
+ output = output.concat([
504
+ helper.wrap(commandDescription, helpWidth, 0),
505
+ ""
506
+ ]);
507
+ }
508
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
509
+ return formatItem(
510
+ helper.argumentTerm(argument),
511
+ helper.argumentDescription(argument)
512
+ );
513
+ });
514
+ if (argumentList.length > 0) {
515
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
516
+ }
517
+ const optionList = helper.visibleOptions(cmd).map((option) => {
518
+ return formatItem(
519
+ helper.optionTerm(option),
520
+ helper.optionDescription(option)
521
+ );
522
+ });
523
+ if (optionList.length > 0) {
524
+ output = output.concat(["Options:", formatList(optionList), ""]);
525
+ }
526
+ if (this.showGlobalOptions) {
527
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
528
+ return formatItem(
529
+ helper.optionTerm(option),
530
+ helper.optionDescription(option)
531
+ );
532
+ });
533
+ if (globalOptionList.length > 0) {
534
+ output = output.concat([
535
+ "Global Options:",
536
+ formatList(globalOptionList),
537
+ ""
538
+ ]);
539
+ }
540
+ }
541
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
542
+ return formatItem(
543
+ helper.subcommandTerm(cmd2),
544
+ helper.subcommandDescription(cmd2)
545
+ );
546
+ });
547
+ if (commandList.length > 0) {
548
+ output = output.concat(["Commands:", formatList(commandList), ""]);
549
+ }
550
+ return output.join("\n");
551
+ }
552
+ /**
553
+ * Calculate the pad width from the maximum term length.
554
+ *
555
+ * @param {Command} cmd
556
+ * @param {Help} helper
557
+ * @returns {number}
558
+ */
559
+ padWidth(cmd, helper) {
560
+ return Math.max(
561
+ helper.longestOptionTermLength(cmd, helper),
562
+ helper.longestGlobalOptionTermLength(cmd, helper),
563
+ helper.longestSubcommandTermLength(cmd, helper),
564
+ helper.longestArgumentTermLength(cmd, helper)
565
+ );
566
+ }
567
+ /**
568
+ * Wrap the given string to width characters per line, with lines after the first indented.
569
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
570
+ *
571
+ * @param {string} str
572
+ * @param {number} width
573
+ * @param {number} indent
574
+ * @param {number} [minColumnWidth=40]
575
+ * @return {string}
576
+ *
577
+ */
578
+ wrap(str, width, indent, minColumnWidth = 40) {
579
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
580
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
581
+ if (str.match(manualIndent)) return str;
582
+ const columnWidth = width - indent;
583
+ if (columnWidth < minColumnWidth) return str;
584
+ const leadingStr = str.slice(0, indent);
585
+ const columnText = str.slice(indent).replace("\r\n", "\n");
586
+ const indentString = " ".repeat(indent);
587
+ const zeroWidthSpace = "\u200B";
588
+ const breaks = `\\s${zeroWidthSpace}`;
589
+ const regex = new RegExp(
590
+ `
591
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
592
+ "g"
593
+ );
594
+ const lines = columnText.match(regex) || [];
595
+ return leadingStr + lines.map((line, i) => {
596
+ if (line === "\n") return "";
597
+ return (i > 0 ? indentString : "") + line.trimEnd();
598
+ }).join("\n");
599
+ }
600
+ };
601
+ exports2.Help = Help2;
602
+ }
603
+ });
604
+
605
+ // node_modules/commander/lib/option.js
606
+ var require_option = __commonJS({
607
+ "node_modules/commander/lib/option.js"(exports2) {
608
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
609
+ var Option2 = class {
610
+ /**
611
+ * Initialize a new `Option` with the given `flags` and `description`.
612
+ *
613
+ * @param {string} flags
614
+ * @param {string} [description]
615
+ */
616
+ constructor(flags, description) {
617
+ this.flags = flags;
618
+ this.description = description || "";
619
+ this.required = flags.includes("<");
620
+ this.optional = flags.includes("[");
621
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
622
+ this.mandatory = false;
623
+ const optionFlags = splitOptionFlags(flags);
624
+ this.short = optionFlags.shortFlag;
625
+ this.long = optionFlags.longFlag;
626
+ this.negate = false;
627
+ if (this.long) {
628
+ this.negate = this.long.startsWith("--no-");
629
+ }
630
+ this.defaultValue = void 0;
631
+ this.defaultValueDescription = void 0;
632
+ this.presetArg = void 0;
633
+ this.envVar = void 0;
634
+ this.parseArg = void 0;
635
+ this.hidden = false;
636
+ this.argChoices = void 0;
637
+ this.conflictsWith = [];
638
+ this.implied = void 0;
639
+ }
640
+ /**
641
+ * Set the default value, and optionally supply the description to be displayed in the help.
642
+ *
643
+ * @param {*} value
644
+ * @param {string} [description]
645
+ * @return {Option}
646
+ */
647
+ default(value, description) {
648
+ this.defaultValue = value;
649
+ this.defaultValueDescription = description;
650
+ return this;
651
+ }
652
+ /**
653
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
654
+ * The custom processing (parseArg) is called.
655
+ *
656
+ * @example
657
+ * new Option('--color').default('GREYSCALE').preset('RGB');
658
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
659
+ *
660
+ * @param {*} arg
661
+ * @return {Option}
662
+ */
663
+ preset(arg) {
664
+ this.presetArg = arg;
665
+ return this;
666
+ }
667
+ /**
668
+ * Add option name(s) that conflict with this option.
669
+ * An error will be displayed if conflicting options are found during parsing.
670
+ *
671
+ * @example
672
+ * new Option('--rgb').conflicts('cmyk');
673
+ * new Option('--js').conflicts(['ts', 'jsx']);
674
+ *
675
+ * @param {(string | string[])} names
676
+ * @return {Option}
677
+ */
678
+ conflicts(names) {
679
+ this.conflictsWith = this.conflictsWith.concat(names);
680
+ return this;
681
+ }
682
+ /**
683
+ * Specify implied option values for when this option is set and the implied options are not.
684
+ *
685
+ * The custom processing (parseArg) is not called on the implied values.
686
+ *
687
+ * @example
688
+ * program
689
+ * .addOption(new Option('--log', 'write logging information to file'))
690
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
691
+ *
692
+ * @param {object} impliedOptionValues
693
+ * @return {Option}
694
+ */
695
+ implies(impliedOptionValues) {
696
+ let newImplied = impliedOptionValues;
697
+ if (typeof impliedOptionValues === "string") {
698
+ newImplied = { [impliedOptionValues]: true };
699
+ }
700
+ this.implied = Object.assign(this.implied || {}, newImplied);
701
+ return this;
702
+ }
703
+ /**
704
+ * Set environment variable to check for option value.
705
+ *
706
+ * An environment variable is only used if when processed the current option value is
707
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
708
+ *
709
+ * @param {string} name
710
+ * @return {Option}
711
+ */
712
+ env(name) {
713
+ this.envVar = name;
714
+ return this;
715
+ }
716
+ /**
717
+ * Set the custom handler for processing CLI option arguments into option values.
718
+ *
719
+ * @param {Function} [fn]
720
+ * @return {Option}
721
+ */
722
+ argParser(fn) {
723
+ this.parseArg = fn;
724
+ return this;
725
+ }
726
+ /**
727
+ * Whether the option is mandatory and must have a value after parsing.
728
+ *
729
+ * @param {boolean} [mandatory=true]
730
+ * @return {Option}
731
+ */
732
+ makeOptionMandatory(mandatory = true) {
733
+ this.mandatory = !!mandatory;
734
+ return this;
735
+ }
736
+ /**
737
+ * Hide option in help.
738
+ *
739
+ * @param {boolean} [hide=true]
740
+ * @return {Option}
741
+ */
742
+ hideHelp(hide = true) {
743
+ this.hidden = !!hide;
744
+ return this;
745
+ }
746
+ /**
747
+ * @package
748
+ */
749
+ _concatValue(value, previous) {
750
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
751
+ return [value];
752
+ }
753
+ return previous.concat(value);
754
+ }
755
+ /**
756
+ * Only allow option value to be one of choices.
757
+ *
758
+ * @param {string[]} values
759
+ * @return {Option}
760
+ */
761
+ choices(values) {
762
+ this.argChoices = values.slice();
763
+ this.parseArg = (arg, previous) => {
764
+ if (!this.argChoices.includes(arg)) {
765
+ throw new InvalidArgumentError2(
766
+ `Allowed choices are ${this.argChoices.join(", ")}.`
767
+ );
768
+ }
769
+ if (this.variadic) {
770
+ return this._concatValue(arg, previous);
771
+ }
772
+ return arg;
773
+ };
774
+ return this;
775
+ }
776
+ /**
777
+ * Return option name.
778
+ *
779
+ * @return {string}
780
+ */
781
+ name() {
782
+ if (this.long) {
783
+ return this.long.replace(/^--/, "");
784
+ }
785
+ return this.short.replace(/^-/, "");
786
+ }
787
+ /**
788
+ * Return option name, in a camelcase format that can be used
789
+ * as a object attribute key.
790
+ *
791
+ * @return {string}
792
+ */
793
+ attributeName() {
794
+ return camelcase(this.name().replace(/^no-/, ""));
795
+ }
796
+ /**
797
+ * Check if `arg` matches the short or long flag.
798
+ *
799
+ * @param {string} arg
800
+ * @return {boolean}
801
+ * @package
802
+ */
803
+ is(arg) {
804
+ return this.short === arg || this.long === arg;
805
+ }
806
+ /**
807
+ * Return whether a boolean option.
808
+ *
809
+ * Options are one of boolean, negated, required argument, or optional argument.
810
+ *
811
+ * @return {boolean}
812
+ * @package
813
+ */
814
+ isBoolean() {
815
+ return !this.required && !this.optional && !this.negate;
816
+ }
817
+ };
818
+ var DualOptions = class {
819
+ /**
820
+ * @param {Option[]} options
821
+ */
822
+ constructor(options) {
823
+ this.positiveOptions = /* @__PURE__ */ new Map();
824
+ this.negativeOptions = /* @__PURE__ */ new Map();
825
+ this.dualOptions = /* @__PURE__ */ new Set();
826
+ options.forEach((option) => {
827
+ if (option.negate) {
828
+ this.negativeOptions.set(option.attributeName(), option);
829
+ } else {
830
+ this.positiveOptions.set(option.attributeName(), option);
831
+ }
832
+ });
833
+ this.negativeOptions.forEach((value, key) => {
834
+ if (this.positiveOptions.has(key)) {
835
+ this.dualOptions.add(key);
836
+ }
837
+ });
838
+ }
839
+ /**
840
+ * Did the value come from the option, and not from possible matching dual option?
841
+ *
842
+ * @param {*} value
843
+ * @param {Option} option
844
+ * @returns {boolean}
845
+ */
846
+ valueFromOption(value, option) {
847
+ const optionKey = option.attributeName();
848
+ if (!this.dualOptions.has(optionKey)) return true;
849
+ const preset = this.negativeOptions.get(optionKey).presetArg;
850
+ const negativeValue = preset !== void 0 ? preset : false;
851
+ return option.negate === (negativeValue === value);
852
+ }
853
+ };
854
+ function camelcase(str) {
855
+ return str.split("-").reduce((str2, word) => {
856
+ return str2 + word[0].toUpperCase() + word.slice(1);
857
+ });
858
+ }
859
+ function splitOptionFlags(flags) {
860
+ let shortFlag;
861
+ let longFlag;
862
+ const flagParts = flags.split(/[ |,]+/);
863
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
864
+ shortFlag = flagParts.shift();
865
+ longFlag = flagParts.shift();
866
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
867
+ shortFlag = longFlag;
868
+ longFlag = void 0;
869
+ }
870
+ return { shortFlag, longFlag };
871
+ }
872
+ exports2.Option = Option2;
873
+ exports2.DualOptions = DualOptions;
874
+ }
875
+ });
876
+
877
+ // node_modules/commander/lib/suggestSimilar.js
878
+ var require_suggestSimilar = __commonJS({
879
+ "node_modules/commander/lib/suggestSimilar.js"(exports2) {
880
+ var maxDistance = 3;
881
+ function editDistance(a, b) {
882
+ if (Math.abs(a.length - b.length) > maxDistance)
883
+ return Math.max(a.length, b.length);
884
+ const d = [];
885
+ for (let i = 0; i <= a.length; i++) {
886
+ d[i] = [i];
887
+ }
888
+ for (let j = 0; j <= b.length; j++) {
889
+ d[0][j] = j;
890
+ }
891
+ for (let j = 1; j <= b.length; j++) {
892
+ for (let i = 1; i <= a.length; i++) {
893
+ let cost = 1;
894
+ if (a[i - 1] === b[j - 1]) {
895
+ cost = 0;
896
+ } else {
897
+ cost = 1;
898
+ }
899
+ d[i][j] = Math.min(
900
+ d[i - 1][j] + 1,
901
+ // deletion
902
+ d[i][j - 1] + 1,
903
+ // insertion
904
+ d[i - 1][j - 1] + cost
905
+ // substitution
906
+ );
907
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
908
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
909
+ }
910
+ }
911
+ }
912
+ return d[a.length][b.length];
913
+ }
914
+ function suggestSimilar(word, candidates) {
915
+ if (!candidates || candidates.length === 0) return "";
916
+ candidates = Array.from(new Set(candidates));
917
+ const searchingOptions = word.startsWith("--");
918
+ if (searchingOptions) {
919
+ word = word.slice(2);
920
+ candidates = candidates.map((candidate) => candidate.slice(2));
921
+ }
922
+ let similar = [];
923
+ let bestDistance = maxDistance;
924
+ const minSimilarity = 0.4;
925
+ candidates.forEach((candidate) => {
926
+ if (candidate.length <= 1) return;
927
+ const distance = editDistance(word, candidate);
928
+ const length = Math.max(word.length, candidate.length);
929
+ const similarity = (length - distance) / length;
930
+ if (similarity > minSimilarity) {
931
+ if (distance < bestDistance) {
932
+ bestDistance = distance;
933
+ similar = [candidate];
934
+ } else if (distance === bestDistance) {
935
+ similar.push(candidate);
936
+ }
937
+ }
938
+ });
939
+ similar.sort((a, b) => a.localeCompare(b));
940
+ if (searchingOptions) {
941
+ similar = similar.map((candidate) => `--${candidate}`);
942
+ }
943
+ if (similar.length > 1) {
944
+ return `
945
+ (Did you mean one of ${similar.join(", ")}?)`;
946
+ }
947
+ if (similar.length === 1) {
948
+ return `
949
+ (Did you mean ${similar[0]}?)`;
950
+ }
951
+ return "";
952
+ }
953
+ exports2.suggestSimilar = suggestSimilar;
954
+ }
955
+ });
956
+
957
+ // node_modules/commander/lib/command.js
958
+ var require_command = __commonJS({
959
+ "node_modules/commander/lib/command.js"(exports2) {
960
+ var EventEmitter = require("node:events").EventEmitter;
961
+ var childProcess = require("node:child_process");
962
+ var path = require("node:path");
963
+ var fs2 = require("node:fs");
964
+ var process3 = require("node:process");
965
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
966
+ var { CommanderError: CommanderError2 } = require_error();
967
+ var { Help: Help2 } = require_help();
968
+ var { Option: Option2, DualOptions } = require_option();
969
+ var { suggestSimilar } = require_suggestSimilar();
970
+ var Command2 = class _Command extends EventEmitter {
971
+ /**
972
+ * Initialize a new `Command`.
973
+ *
974
+ * @param {string} [name]
975
+ */
976
+ constructor(name) {
977
+ super();
978
+ this.commands = [];
979
+ this.options = [];
980
+ this.parent = null;
981
+ this._allowUnknownOption = false;
982
+ this._allowExcessArguments = true;
983
+ this.registeredArguments = [];
984
+ this._args = this.registeredArguments;
985
+ this.args = [];
986
+ this.rawArgs = [];
987
+ this.processedArgs = [];
988
+ this._scriptPath = null;
989
+ this._name = name || "";
990
+ this._optionValues = {};
991
+ this._optionValueSources = {};
992
+ this._storeOptionsAsProperties = false;
993
+ this._actionHandler = null;
994
+ this._executableHandler = false;
995
+ this._executableFile = null;
996
+ this._executableDir = null;
997
+ this._defaultCommandName = null;
998
+ this._exitCallback = null;
999
+ this._aliases = [];
1000
+ this._combineFlagAndOptionalValue = true;
1001
+ this._description = "";
1002
+ this._summary = "";
1003
+ this._argsDescription = void 0;
1004
+ this._enablePositionalOptions = false;
1005
+ this._passThroughOptions = false;
1006
+ this._lifeCycleHooks = {};
1007
+ this._showHelpAfterError = false;
1008
+ this._showSuggestionAfterError = true;
1009
+ this._outputConfiguration = {
1010
+ writeOut: (str) => process3.stdout.write(str),
1011
+ writeErr: (str) => process3.stderr.write(str),
1012
+ getOutHelpWidth: () => process3.stdout.isTTY ? process3.stdout.columns : void 0,
1013
+ getErrHelpWidth: () => process3.stderr.isTTY ? process3.stderr.columns : void 0,
1014
+ outputError: (str, write) => write(str)
1015
+ };
1016
+ this._hidden = false;
1017
+ this._helpOption = void 0;
1018
+ this._addImplicitHelpCommand = void 0;
1019
+ this._helpCommand = void 0;
1020
+ this._helpConfiguration = {};
1021
+ }
1022
+ /**
1023
+ * Copy settings that are useful to have in common across root command and subcommands.
1024
+ *
1025
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1026
+ *
1027
+ * @param {Command} sourceCommand
1028
+ * @return {Command} `this` command for chaining
1029
+ */
1030
+ copyInheritedSettings(sourceCommand) {
1031
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1032
+ this._helpOption = sourceCommand._helpOption;
1033
+ this._helpCommand = sourceCommand._helpCommand;
1034
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1035
+ this._exitCallback = sourceCommand._exitCallback;
1036
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1037
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1038
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1039
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1040
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1041
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1042
+ return this;
1043
+ }
1044
+ /**
1045
+ * @returns {Command[]}
1046
+ * @private
1047
+ */
1048
+ _getCommandAndAncestors() {
1049
+ const result = [];
1050
+ for (let command = this; command; command = command.parent) {
1051
+ result.push(command);
1052
+ }
1053
+ return result;
1054
+ }
1055
+ /**
1056
+ * Define a command.
1057
+ *
1058
+ * There are two styles of command: pay attention to where to put the description.
1059
+ *
1060
+ * @example
1061
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1062
+ * program
1063
+ * .command('clone <source> [destination]')
1064
+ * .description('clone a repository into a newly created directory')
1065
+ * .action((source, destination) => {
1066
+ * console.log('clone command called');
1067
+ * });
1068
+ *
1069
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1070
+ * program
1071
+ * .command('start <service>', 'start named service')
1072
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1073
+ *
1074
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1075
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1076
+ * @param {object} [execOpts] - configuration options (for executable)
1077
+ * @return {Command} returns new command for action handler, or `this` for executable command
1078
+ */
1079
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1080
+ let desc = actionOptsOrExecDesc;
1081
+ let opts = execOpts;
1082
+ if (typeof desc === "object" && desc !== null) {
1083
+ opts = desc;
1084
+ desc = null;
1085
+ }
1086
+ opts = opts || {};
1087
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1088
+ const cmd = this.createCommand(name);
1089
+ if (desc) {
1090
+ cmd.description(desc);
1091
+ cmd._executableHandler = true;
1092
+ }
1093
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1094
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1095
+ cmd._executableFile = opts.executableFile || null;
1096
+ if (args) cmd.arguments(args);
1097
+ this._registerCommand(cmd);
1098
+ cmd.parent = this;
1099
+ cmd.copyInheritedSettings(this);
1100
+ if (desc) return this;
1101
+ return cmd;
1102
+ }
1103
+ /**
1104
+ * Factory routine to create a new unattached command.
1105
+ *
1106
+ * See .command() for creating an attached subcommand, which uses this routine to
1107
+ * create the command. You can override createCommand to customise subcommands.
1108
+ *
1109
+ * @param {string} [name]
1110
+ * @return {Command} new command
1111
+ */
1112
+ createCommand(name) {
1113
+ return new _Command(name);
1114
+ }
1115
+ /**
1116
+ * You can customise the help with a subclass of Help by overriding createHelp,
1117
+ * or by overriding Help properties using configureHelp().
1118
+ *
1119
+ * @return {Help}
1120
+ */
1121
+ createHelp() {
1122
+ return Object.assign(new Help2(), this.configureHelp());
1123
+ }
1124
+ /**
1125
+ * You can customise the help by overriding Help properties using configureHelp(),
1126
+ * or with a subclass of Help by overriding createHelp().
1127
+ *
1128
+ * @param {object} [configuration] - configuration options
1129
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1130
+ */
1131
+ configureHelp(configuration) {
1132
+ if (configuration === void 0) return this._helpConfiguration;
1133
+ this._helpConfiguration = configuration;
1134
+ return this;
1135
+ }
1136
+ /**
1137
+ * The default output goes to stdout and stderr. You can customise this for special
1138
+ * applications. You can also customise the display of errors by overriding outputError.
1139
+ *
1140
+ * The configuration properties are all functions:
1141
+ *
1142
+ * // functions to change where being written, stdout and stderr
1143
+ * writeOut(str)
1144
+ * writeErr(str)
1145
+ * // matching functions to specify width for wrapping help
1146
+ * getOutHelpWidth()
1147
+ * getErrHelpWidth()
1148
+ * // functions based on what is being written out
1149
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1150
+ *
1151
+ * @param {object} [configuration] - configuration options
1152
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1153
+ */
1154
+ configureOutput(configuration) {
1155
+ if (configuration === void 0) return this._outputConfiguration;
1156
+ Object.assign(this._outputConfiguration, configuration);
1157
+ return this;
1158
+ }
1159
+ /**
1160
+ * Display the help or a custom message after an error occurs.
1161
+ *
1162
+ * @param {(boolean|string)} [displayHelp]
1163
+ * @return {Command} `this` command for chaining
1164
+ */
1165
+ showHelpAfterError(displayHelp = true) {
1166
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1167
+ this._showHelpAfterError = displayHelp;
1168
+ return this;
1169
+ }
1170
+ /**
1171
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1172
+ *
1173
+ * @param {boolean} [displaySuggestion]
1174
+ * @return {Command} `this` command for chaining
1175
+ */
1176
+ showSuggestionAfterError(displaySuggestion = true) {
1177
+ this._showSuggestionAfterError = !!displaySuggestion;
1178
+ return this;
1179
+ }
1180
+ /**
1181
+ * Add a prepared subcommand.
1182
+ *
1183
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1184
+ *
1185
+ * @param {Command} cmd - new subcommand
1186
+ * @param {object} [opts] - configuration options
1187
+ * @return {Command} `this` command for chaining
1188
+ */
1189
+ addCommand(cmd, opts) {
1190
+ if (!cmd._name) {
1191
+ throw new Error(`Command passed to .addCommand() must have a name
1192
+ - specify the name in Command constructor or using .name()`);
1193
+ }
1194
+ opts = opts || {};
1195
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1196
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1197
+ this._registerCommand(cmd);
1198
+ cmd.parent = this;
1199
+ cmd._checkForBrokenPassThrough();
1200
+ return this;
1201
+ }
1202
+ /**
1203
+ * Factory routine to create a new unattached argument.
1204
+ *
1205
+ * See .argument() for creating an attached argument, which uses this routine to
1206
+ * create the argument. You can override createArgument to return a custom argument.
1207
+ *
1208
+ * @param {string} name
1209
+ * @param {string} [description]
1210
+ * @return {Argument} new argument
1211
+ */
1212
+ createArgument(name, description) {
1213
+ return new Argument2(name, description);
1214
+ }
1215
+ /**
1216
+ * Define argument syntax for command.
1217
+ *
1218
+ * The default is that the argument is required, and you can explicitly
1219
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1220
+ *
1221
+ * @example
1222
+ * program.argument('<input-file>');
1223
+ * program.argument('[output-file]');
1224
+ *
1225
+ * @param {string} name
1226
+ * @param {string} [description]
1227
+ * @param {(Function|*)} [fn] - custom argument processing function
1228
+ * @param {*} [defaultValue]
1229
+ * @return {Command} `this` command for chaining
1230
+ */
1231
+ argument(name, description, fn, defaultValue) {
1232
+ const argument = this.createArgument(name, description);
1233
+ if (typeof fn === "function") {
1234
+ argument.default(defaultValue).argParser(fn);
1235
+ } else {
1236
+ argument.default(fn);
1237
+ }
1238
+ this.addArgument(argument);
1239
+ return this;
1240
+ }
1241
+ /**
1242
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1243
+ *
1244
+ * See also .argument().
1245
+ *
1246
+ * @example
1247
+ * program.arguments('<cmd> [env]');
1248
+ *
1249
+ * @param {string} names
1250
+ * @return {Command} `this` command for chaining
1251
+ */
1252
+ arguments(names) {
1253
+ names.trim().split(/ +/).forEach((detail) => {
1254
+ this.argument(detail);
1255
+ });
1256
+ return this;
1257
+ }
1258
+ /**
1259
+ * Define argument syntax for command, adding a prepared argument.
1260
+ *
1261
+ * @param {Argument} argument
1262
+ * @return {Command} `this` command for chaining
1263
+ */
1264
+ addArgument(argument) {
1265
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1266
+ if (previousArgument && previousArgument.variadic) {
1267
+ throw new Error(
1268
+ `only the last argument can be variadic '${previousArgument.name()}'`
1269
+ );
1270
+ }
1271
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1272
+ throw new Error(
1273
+ `a default value for a required argument is never used: '${argument.name()}'`
1274
+ );
1275
+ }
1276
+ this.registeredArguments.push(argument);
1277
+ return this;
1278
+ }
1279
+ /**
1280
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1281
+ *
1282
+ * @example
1283
+ * program.helpCommand('help [cmd]');
1284
+ * program.helpCommand('help [cmd]', 'show help');
1285
+ * program.helpCommand(false); // suppress default help command
1286
+ * program.helpCommand(true); // add help command even if no subcommands
1287
+ *
1288
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1289
+ * @param {string} [description] - custom description
1290
+ * @return {Command} `this` command for chaining
1291
+ */
1292
+ helpCommand(enableOrNameAndArgs, description) {
1293
+ if (typeof enableOrNameAndArgs === "boolean") {
1294
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1295
+ return this;
1296
+ }
1297
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1298
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1299
+ const helpDescription = description ?? "display help for command";
1300
+ const helpCommand = this.createCommand(helpName);
1301
+ helpCommand.helpOption(false);
1302
+ if (helpArgs) helpCommand.arguments(helpArgs);
1303
+ if (helpDescription) helpCommand.description(helpDescription);
1304
+ this._addImplicitHelpCommand = true;
1305
+ this._helpCommand = helpCommand;
1306
+ return this;
1307
+ }
1308
+ /**
1309
+ * Add prepared custom help command.
1310
+ *
1311
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1312
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1313
+ * @return {Command} `this` command for chaining
1314
+ */
1315
+ addHelpCommand(helpCommand, deprecatedDescription) {
1316
+ if (typeof helpCommand !== "object") {
1317
+ this.helpCommand(helpCommand, deprecatedDescription);
1318
+ return this;
1319
+ }
1320
+ this._addImplicitHelpCommand = true;
1321
+ this._helpCommand = helpCommand;
1322
+ return this;
1323
+ }
1324
+ /**
1325
+ * Lazy create help command.
1326
+ *
1327
+ * @return {(Command|null)}
1328
+ * @package
1329
+ */
1330
+ _getHelpCommand() {
1331
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1332
+ if (hasImplicitHelpCommand) {
1333
+ if (this._helpCommand === void 0) {
1334
+ this.helpCommand(void 0, void 0);
1335
+ }
1336
+ return this._helpCommand;
1337
+ }
1338
+ return null;
1339
+ }
1340
+ /**
1341
+ * Add hook for life cycle event.
1342
+ *
1343
+ * @param {string} event
1344
+ * @param {Function} listener
1345
+ * @return {Command} `this` command for chaining
1346
+ */
1347
+ hook(event, listener) {
1348
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1349
+ if (!allowedValues.includes(event)) {
1350
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1351
+ Expecting one of '${allowedValues.join("', '")}'`);
1352
+ }
1353
+ if (this._lifeCycleHooks[event]) {
1354
+ this._lifeCycleHooks[event].push(listener);
1355
+ } else {
1356
+ this._lifeCycleHooks[event] = [listener];
1357
+ }
1358
+ return this;
1359
+ }
1360
+ /**
1361
+ * Register callback to use as replacement for calling process.exit.
1362
+ *
1363
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1364
+ * @return {Command} `this` command for chaining
1365
+ */
1366
+ exitOverride(fn) {
1367
+ if (fn) {
1368
+ this._exitCallback = fn;
1369
+ } else {
1370
+ this._exitCallback = (err) => {
1371
+ if (err.code !== "commander.executeSubCommandAsync") {
1372
+ throw err;
1373
+ } else {
1374
+ }
1375
+ };
1376
+ }
1377
+ return this;
1378
+ }
1379
+ /**
1380
+ * Call process.exit, and _exitCallback if defined.
1381
+ *
1382
+ * @param {number} exitCode exit code for using with process.exit
1383
+ * @param {string} code an id string representing the error
1384
+ * @param {string} message human-readable description of the error
1385
+ * @return never
1386
+ * @private
1387
+ */
1388
+ _exit(exitCode, code, message) {
1389
+ if (this._exitCallback) {
1390
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1391
+ }
1392
+ process3.exit(exitCode);
1393
+ }
1394
+ /**
1395
+ * Register callback `fn` for the command.
1396
+ *
1397
+ * @example
1398
+ * program
1399
+ * .command('serve')
1400
+ * .description('start service')
1401
+ * .action(function() {
1402
+ * // do work here
1403
+ * });
1404
+ *
1405
+ * @param {Function} fn
1406
+ * @return {Command} `this` command for chaining
1407
+ */
1408
+ action(fn) {
1409
+ const listener = (args) => {
1410
+ const expectedArgsCount = this.registeredArguments.length;
1411
+ const actionArgs = args.slice(0, expectedArgsCount);
1412
+ if (this._storeOptionsAsProperties) {
1413
+ actionArgs[expectedArgsCount] = this;
1414
+ } else {
1415
+ actionArgs[expectedArgsCount] = this.opts();
1416
+ }
1417
+ actionArgs.push(this);
1418
+ return fn.apply(this, actionArgs);
1419
+ };
1420
+ this._actionHandler = listener;
1421
+ return this;
1422
+ }
1423
+ /**
1424
+ * Factory routine to create a new unattached option.
1425
+ *
1426
+ * See .option() for creating an attached option, which uses this routine to
1427
+ * create the option. You can override createOption to return a custom option.
1428
+ *
1429
+ * @param {string} flags
1430
+ * @param {string} [description]
1431
+ * @return {Option} new option
1432
+ */
1433
+ createOption(flags, description) {
1434
+ return new Option2(flags, description);
1435
+ }
1436
+ /**
1437
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1438
+ *
1439
+ * @param {(Option | Argument)} target
1440
+ * @param {string} value
1441
+ * @param {*} previous
1442
+ * @param {string} invalidArgumentMessage
1443
+ * @private
1444
+ */
1445
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1446
+ try {
1447
+ return target.parseArg(value, previous);
1448
+ } catch (err) {
1449
+ if (err.code === "commander.invalidArgument") {
1450
+ const message = `${invalidArgumentMessage} ${err.message}`;
1451
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1452
+ }
1453
+ throw err;
1454
+ }
1455
+ }
1456
+ /**
1457
+ * Check for option flag conflicts.
1458
+ * Register option if no conflicts found, or throw on conflict.
1459
+ *
1460
+ * @param {Option} option
1461
+ * @private
1462
+ */
1463
+ _registerOption(option) {
1464
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1465
+ if (matchingOption) {
1466
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1467
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1468
+ - already used by option '${matchingOption.flags}'`);
1469
+ }
1470
+ this.options.push(option);
1471
+ }
1472
+ /**
1473
+ * Check for command name and alias conflicts with existing commands.
1474
+ * Register command if no conflicts found, or throw on conflict.
1475
+ *
1476
+ * @param {Command} command
1477
+ * @private
1478
+ */
1479
+ _registerCommand(command) {
1480
+ const knownBy = (cmd) => {
1481
+ return [cmd.name()].concat(cmd.aliases());
1482
+ };
1483
+ const alreadyUsed = knownBy(command).find(
1484
+ (name) => this._findCommand(name)
1485
+ );
1486
+ if (alreadyUsed) {
1487
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1488
+ const newCmd = knownBy(command).join("|");
1489
+ throw new Error(
1490
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1491
+ );
1492
+ }
1493
+ this.commands.push(command);
1494
+ }
1495
+ /**
1496
+ * Add an option.
1497
+ *
1498
+ * @param {Option} option
1499
+ * @return {Command} `this` command for chaining
1500
+ */
1501
+ addOption(option) {
1502
+ this._registerOption(option);
1503
+ const oname = option.name();
1504
+ const name = option.attributeName();
1505
+ if (option.negate) {
1506
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1507
+ if (!this._findOption(positiveLongFlag)) {
1508
+ this.setOptionValueWithSource(
1509
+ name,
1510
+ option.defaultValue === void 0 ? true : option.defaultValue,
1511
+ "default"
1512
+ );
1513
+ }
1514
+ } else if (option.defaultValue !== void 0) {
1515
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1516
+ }
1517
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1518
+ if (val == null && option.presetArg !== void 0) {
1519
+ val = option.presetArg;
1520
+ }
1521
+ const oldValue = this.getOptionValue(name);
1522
+ if (val !== null && option.parseArg) {
1523
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1524
+ } else if (val !== null && option.variadic) {
1525
+ val = option._concatValue(val, oldValue);
1526
+ }
1527
+ if (val == null) {
1528
+ if (option.negate) {
1529
+ val = false;
1530
+ } else if (option.isBoolean() || option.optional) {
1531
+ val = true;
1532
+ } else {
1533
+ val = "";
1534
+ }
1535
+ }
1536
+ this.setOptionValueWithSource(name, val, valueSource);
1537
+ };
1538
+ this.on("option:" + oname, (val) => {
1539
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1540
+ handleOptionValue(val, invalidValueMessage, "cli");
1541
+ });
1542
+ if (option.envVar) {
1543
+ this.on("optionEnv:" + oname, (val) => {
1544
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1545
+ handleOptionValue(val, invalidValueMessage, "env");
1546
+ });
1547
+ }
1548
+ return this;
1549
+ }
1550
+ /**
1551
+ * Internal implementation shared by .option() and .requiredOption()
1552
+ *
1553
+ * @return {Command} `this` command for chaining
1554
+ * @private
1555
+ */
1556
+ _optionEx(config, flags, description, fn, defaultValue) {
1557
+ if (typeof flags === "object" && flags instanceof Option2) {
1558
+ throw new Error(
1559
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1560
+ );
1561
+ }
1562
+ const option = this.createOption(flags, description);
1563
+ option.makeOptionMandatory(!!config.mandatory);
1564
+ if (typeof fn === "function") {
1565
+ option.default(defaultValue).argParser(fn);
1566
+ } else if (fn instanceof RegExp) {
1567
+ const regex = fn;
1568
+ fn = (val, def) => {
1569
+ const m = regex.exec(val);
1570
+ return m ? m[0] : def;
1571
+ };
1572
+ option.default(defaultValue).argParser(fn);
1573
+ } else {
1574
+ option.default(fn);
1575
+ }
1576
+ return this.addOption(option);
1577
+ }
1578
+ /**
1579
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1580
+ *
1581
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1582
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1583
+ *
1584
+ * See the README for more details, and see also addOption() and requiredOption().
1585
+ *
1586
+ * @example
1587
+ * program
1588
+ * .option('-p, --pepper', 'add pepper')
1589
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1590
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1591
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1592
+ *
1593
+ * @param {string} flags
1594
+ * @param {string} [description]
1595
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1596
+ * @param {*} [defaultValue]
1597
+ * @return {Command} `this` command for chaining
1598
+ */
1599
+ option(flags, description, parseArg, defaultValue) {
1600
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1601
+ }
1602
+ /**
1603
+ * Add a required option which must have a value after parsing. This usually means
1604
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1605
+ *
1606
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1607
+ *
1608
+ * @param {string} flags
1609
+ * @param {string} [description]
1610
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1611
+ * @param {*} [defaultValue]
1612
+ * @return {Command} `this` command for chaining
1613
+ */
1614
+ requiredOption(flags, description, parseArg, defaultValue) {
1615
+ return this._optionEx(
1616
+ { mandatory: true },
1617
+ flags,
1618
+ description,
1619
+ parseArg,
1620
+ defaultValue
1621
+ );
1622
+ }
1623
+ /**
1624
+ * Alter parsing of short flags with optional values.
1625
+ *
1626
+ * @example
1627
+ * // for `.option('-f,--flag [value]'):
1628
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1629
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1630
+ *
1631
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1632
+ * @return {Command} `this` command for chaining
1633
+ */
1634
+ combineFlagAndOptionalValue(combine = true) {
1635
+ this._combineFlagAndOptionalValue = !!combine;
1636
+ return this;
1637
+ }
1638
+ /**
1639
+ * Allow unknown options on the command line.
1640
+ *
1641
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1642
+ * @return {Command} `this` command for chaining
1643
+ */
1644
+ allowUnknownOption(allowUnknown = true) {
1645
+ this._allowUnknownOption = !!allowUnknown;
1646
+ return this;
1647
+ }
1648
+ /**
1649
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1650
+ *
1651
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1652
+ * @return {Command} `this` command for chaining
1653
+ */
1654
+ allowExcessArguments(allowExcess = true) {
1655
+ this._allowExcessArguments = !!allowExcess;
1656
+ return this;
1657
+ }
1658
+ /**
1659
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1660
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1661
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1662
+ *
1663
+ * @param {boolean} [positional]
1664
+ * @return {Command} `this` command for chaining
1665
+ */
1666
+ enablePositionalOptions(positional = true) {
1667
+ this._enablePositionalOptions = !!positional;
1668
+ return this;
1669
+ }
1670
+ /**
1671
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1672
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1673
+ * positional options to have been enabled on the program (parent commands).
1674
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1675
+ *
1676
+ * @param {boolean} [passThrough] for unknown options.
1677
+ * @return {Command} `this` command for chaining
1678
+ */
1679
+ passThroughOptions(passThrough = true) {
1680
+ this._passThroughOptions = !!passThrough;
1681
+ this._checkForBrokenPassThrough();
1682
+ return this;
1683
+ }
1684
+ /**
1685
+ * @private
1686
+ */
1687
+ _checkForBrokenPassThrough() {
1688
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1689
+ throw new Error(
1690
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1691
+ );
1692
+ }
1693
+ }
1694
+ /**
1695
+ * Whether to store option values as properties on command object,
1696
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1697
+ *
1698
+ * @param {boolean} [storeAsProperties=true]
1699
+ * @return {Command} `this` command for chaining
1700
+ */
1701
+ storeOptionsAsProperties(storeAsProperties = true) {
1702
+ if (this.options.length) {
1703
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1704
+ }
1705
+ if (Object.keys(this._optionValues).length) {
1706
+ throw new Error(
1707
+ "call .storeOptionsAsProperties() before setting option values"
1708
+ );
1709
+ }
1710
+ this._storeOptionsAsProperties = !!storeAsProperties;
1711
+ return this;
1712
+ }
1713
+ /**
1714
+ * Retrieve option value.
1715
+ *
1716
+ * @param {string} key
1717
+ * @return {object} value
1718
+ */
1719
+ getOptionValue(key) {
1720
+ if (this._storeOptionsAsProperties) {
1721
+ return this[key];
1722
+ }
1723
+ return this._optionValues[key];
1724
+ }
1725
+ /**
1726
+ * Store option value.
1727
+ *
1728
+ * @param {string} key
1729
+ * @param {object} value
1730
+ * @return {Command} `this` command for chaining
1731
+ */
1732
+ setOptionValue(key, value) {
1733
+ return this.setOptionValueWithSource(key, value, void 0);
1734
+ }
1735
+ /**
1736
+ * Store option value and where the value came from.
1737
+ *
1738
+ * @param {string} key
1739
+ * @param {object} value
1740
+ * @param {string} source - expected values are default/config/env/cli/implied
1741
+ * @return {Command} `this` command for chaining
1742
+ */
1743
+ setOptionValueWithSource(key, value, source) {
1744
+ if (this._storeOptionsAsProperties) {
1745
+ this[key] = value;
1746
+ } else {
1747
+ this._optionValues[key] = value;
1748
+ }
1749
+ this._optionValueSources[key] = source;
1750
+ return this;
1751
+ }
1752
+ /**
1753
+ * Get source of option value.
1754
+ * Expected values are default | config | env | cli | implied
1755
+ *
1756
+ * @param {string} key
1757
+ * @return {string}
1758
+ */
1759
+ getOptionValueSource(key) {
1760
+ return this._optionValueSources[key];
1761
+ }
1762
+ /**
1763
+ * Get source of option value. See also .optsWithGlobals().
1764
+ * Expected values are default | config | env | cli | implied
1765
+ *
1766
+ * @param {string} key
1767
+ * @return {string}
1768
+ */
1769
+ getOptionValueSourceWithGlobals(key) {
1770
+ let source;
1771
+ this._getCommandAndAncestors().forEach((cmd) => {
1772
+ if (cmd.getOptionValueSource(key) !== void 0) {
1773
+ source = cmd.getOptionValueSource(key);
1774
+ }
1775
+ });
1776
+ return source;
1777
+ }
1778
+ /**
1779
+ * Get user arguments from implied or explicit arguments.
1780
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1781
+ *
1782
+ * @private
1783
+ */
1784
+ _prepareUserArgs(argv, parseOptions) {
1785
+ if (argv !== void 0 && !Array.isArray(argv)) {
1786
+ throw new Error("first parameter to parse must be array or undefined");
1787
+ }
1788
+ parseOptions = parseOptions || {};
1789
+ if (argv === void 0 && parseOptions.from === void 0) {
1790
+ if (process3.versions?.electron) {
1791
+ parseOptions.from = "electron";
1792
+ }
1793
+ const execArgv = process3.execArgv ?? [];
1794
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1795
+ parseOptions.from = "eval";
1796
+ }
1797
+ }
1798
+ if (argv === void 0) {
1799
+ argv = process3.argv;
1800
+ }
1801
+ this.rawArgs = argv.slice();
1802
+ let userArgs;
1803
+ switch (parseOptions.from) {
1804
+ case void 0:
1805
+ case "node":
1806
+ this._scriptPath = argv[1];
1807
+ userArgs = argv.slice(2);
1808
+ break;
1809
+ case "electron":
1810
+ if (process3.defaultApp) {
1811
+ this._scriptPath = argv[1];
1812
+ userArgs = argv.slice(2);
1813
+ } else {
1814
+ userArgs = argv.slice(1);
1815
+ }
1816
+ break;
1817
+ case "user":
1818
+ userArgs = argv.slice(0);
1819
+ break;
1820
+ case "eval":
1821
+ userArgs = argv.slice(1);
1822
+ break;
1823
+ default:
1824
+ throw new Error(
1825
+ `unexpected parse option { from: '${parseOptions.from}' }`
1826
+ );
1827
+ }
1828
+ if (!this._name && this._scriptPath)
1829
+ this.nameFromFilename(this._scriptPath);
1830
+ this._name = this._name || "program";
1831
+ return userArgs;
1832
+ }
1833
+ /**
1834
+ * Parse `argv`, setting options and invoking commands when defined.
1835
+ *
1836
+ * Use parseAsync instead of parse if any of your action handlers are async.
1837
+ *
1838
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1839
+ *
1840
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1841
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1842
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1843
+ * - `'user'`: just user arguments
1844
+ *
1845
+ * @example
1846
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1847
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1848
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1849
+ *
1850
+ * @param {string[]} [argv] - optional, defaults to process.argv
1851
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1852
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1853
+ * @return {Command} `this` command for chaining
1854
+ */
1855
+ parse(argv, parseOptions) {
1856
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1857
+ this._parseCommand([], userArgs);
1858
+ return this;
1859
+ }
1860
+ /**
1861
+ * Parse `argv`, setting options and invoking commands when defined.
1862
+ *
1863
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1864
+ *
1865
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1866
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1867
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1868
+ * - `'user'`: just user arguments
1869
+ *
1870
+ * @example
1871
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1872
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1873
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1874
+ *
1875
+ * @param {string[]} [argv]
1876
+ * @param {object} [parseOptions]
1877
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1878
+ * @return {Promise}
1879
+ */
1880
+ async parseAsync(argv, parseOptions) {
1881
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1882
+ await this._parseCommand([], userArgs);
1883
+ return this;
1884
+ }
1885
+ /**
1886
+ * Execute a sub-command executable.
1887
+ *
1888
+ * @private
1889
+ */
1890
+ _executeSubCommand(subcommand, args) {
1891
+ args = args.slice();
1892
+ let launchWithNode = false;
1893
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1894
+ function findFile(baseDir, baseName) {
1895
+ const localBin = path.resolve(baseDir, baseName);
1896
+ if (fs2.existsSync(localBin)) return localBin;
1897
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1898
+ const foundExt = sourceExt.find(
1899
+ (ext) => fs2.existsSync(`${localBin}${ext}`)
1900
+ );
1901
+ if (foundExt) return `${localBin}${foundExt}`;
1902
+ return void 0;
1903
+ }
1904
+ this._checkForMissingMandatoryOptions();
1905
+ this._checkForConflictingOptions();
1906
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1907
+ let executableDir = this._executableDir || "";
1908
+ if (this._scriptPath) {
1909
+ let resolvedScriptPath;
1910
+ try {
1911
+ resolvedScriptPath = fs2.realpathSync(this._scriptPath);
1912
+ } catch (err) {
1913
+ resolvedScriptPath = this._scriptPath;
1914
+ }
1915
+ executableDir = path.resolve(
1916
+ path.dirname(resolvedScriptPath),
1917
+ executableDir
1918
+ );
1919
+ }
1920
+ if (executableDir) {
1921
+ let localFile = findFile(executableDir, executableFile);
1922
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1923
+ const legacyName = path.basename(
1924
+ this._scriptPath,
1925
+ path.extname(this._scriptPath)
1926
+ );
1927
+ if (legacyName !== this._name) {
1928
+ localFile = findFile(
1929
+ executableDir,
1930
+ `${legacyName}-${subcommand._name}`
1931
+ );
1932
+ }
1933
+ }
1934
+ executableFile = localFile || executableFile;
1935
+ }
1936
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1937
+ let proc;
1938
+ if (process3.platform !== "win32") {
1939
+ if (launchWithNode) {
1940
+ args.unshift(executableFile);
1941
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
1942
+ proc = childProcess.spawn(process3.argv[0], args, { stdio: "inherit" });
1943
+ } else {
1944
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1945
+ }
1946
+ } else {
1947
+ args.unshift(executableFile);
1948
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
1949
+ proc = childProcess.spawn(process3.execPath, args, { stdio: "inherit" });
1950
+ }
1951
+ if (!proc.killed) {
1952
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1953
+ signals.forEach((signal) => {
1954
+ process3.on(signal, () => {
1955
+ if (proc.killed === false && proc.exitCode === null) {
1956
+ proc.kill(signal);
1957
+ }
1958
+ });
1959
+ });
1960
+ }
1961
+ const exitCallback = this._exitCallback;
1962
+ proc.on("close", (code) => {
1963
+ code = code ?? 1;
1964
+ if (!exitCallback) {
1965
+ process3.exit(code);
1966
+ } else {
1967
+ exitCallback(
1968
+ new CommanderError2(
1969
+ code,
1970
+ "commander.executeSubCommandAsync",
1971
+ "(close)"
1972
+ )
1973
+ );
1974
+ }
1975
+ });
1976
+ proc.on("error", (err) => {
1977
+ if (err.code === "ENOENT") {
1978
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1979
+ const executableMissing = `'${executableFile}' does not exist
1980
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1981
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1982
+ - ${executableDirMessage}`;
1983
+ throw new Error(executableMissing);
1984
+ } else if (err.code === "EACCES") {
1985
+ throw new Error(`'${executableFile}' not executable`);
1986
+ }
1987
+ if (!exitCallback) {
1988
+ process3.exit(1);
1989
+ } else {
1990
+ const wrappedError = new CommanderError2(
1991
+ 1,
1992
+ "commander.executeSubCommandAsync",
1993
+ "(error)"
1994
+ );
1995
+ wrappedError.nestedError = err;
1996
+ exitCallback(wrappedError);
1997
+ }
1998
+ });
1999
+ this.runningCommand = proc;
2000
+ }
2001
+ /**
2002
+ * @private
2003
+ */
2004
+ _dispatchSubcommand(commandName, operands, unknown) {
2005
+ const subCommand = this._findCommand(commandName);
2006
+ if (!subCommand) this.help({ error: true });
2007
+ let promiseChain;
2008
+ promiseChain = this._chainOrCallSubCommandHook(
2009
+ promiseChain,
2010
+ subCommand,
2011
+ "preSubcommand"
2012
+ );
2013
+ promiseChain = this._chainOrCall(promiseChain, () => {
2014
+ if (subCommand._executableHandler) {
2015
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2016
+ } else {
2017
+ return subCommand._parseCommand(operands, unknown);
2018
+ }
2019
+ });
2020
+ return promiseChain;
2021
+ }
2022
+ /**
2023
+ * Invoke help directly if possible, or dispatch if necessary.
2024
+ * e.g. help foo
2025
+ *
2026
+ * @private
2027
+ */
2028
+ _dispatchHelpCommand(subcommandName) {
2029
+ if (!subcommandName) {
2030
+ this.help();
2031
+ }
2032
+ const subCommand = this._findCommand(subcommandName);
2033
+ if (subCommand && !subCommand._executableHandler) {
2034
+ subCommand.help();
2035
+ }
2036
+ return this._dispatchSubcommand(
2037
+ subcommandName,
2038
+ [],
2039
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2040
+ );
2041
+ }
2042
+ /**
2043
+ * Check this.args against expected this.registeredArguments.
2044
+ *
2045
+ * @private
2046
+ */
2047
+ _checkNumberOfArguments() {
2048
+ this.registeredArguments.forEach((arg, i) => {
2049
+ if (arg.required && this.args[i] == null) {
2050
+ this.missingArgument(arg.name());
2051
+ }
2052
+ });
2053
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2054
+ return;
2055
+ }
2056
+ if (this.args.length > this.registeredArguments.length) {
2057
+ this._excessArguments(this.args);
2058
+ }
2059
+ }
2060
+ /**
2061
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2062
+ *
2063
+ * @private
2064
+ */
2065
+ _processArguments() {
2066
+ const myParseArg = (argument, value, previous) => {
2067
+ let parsedValue = value;
2068
+ if (value !== null && argument.parseArg) {
2069
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2070
+ parsedValue = this._callParseArg(
2071
+ argument,
2072
+ value,
2073
+ previous,
2074
+ invalidValueMessage
2075
+ );
2076
+ }
2077
+ return parsedValue;
2078
+ };
2079
+ this._checkNumberOfArguments();
2080
+ const processedArgs = [];
2081
+ this.registeredArguments.forEach((declaredArg, index) => {
2082
+ let value = declaredArg.defaultValue;
2083
+ if (declaredArg.variadic) {
2084
+ if (index < this.args.length) {
2085
+ value = this.args.slice(index);
2086
+ if (declaredArg.parseArg) {
2087
+ value = value.reduce((processed, v) => {
2088
+ return myParseArg(declaredArg, v, processed);
2089
+ }, declaredArg.defaultValue);
2090
+ }
2091
+ } else if (value === void 0) {
2092
+ value = [];
2093
+ }
2094
+ } else if (index < this.args.length) {
2095
+ value = this.args[index];
2096
+ if (declaredArg.parseArg) {
2097
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2098
+ }
2099
+ }
2100
+ processedArgs[index] = value;
2101
+ });
2102
+ this.processedArgs = processedArgs;
2103
+ }
2104
+ /**
2105
+ * Once we have a promise we chain, but call synchronously until then.
2106
+ *
2107
+ * @param {(Promise|undefined)} promise
2108
+ * @param {Function} fn
2109
+ * @return {(Promise|undefined)}
2110
+ * @private
2111
+ */
2112
+ _chainOrCall(promise, fn) {
2113
+ if (promise && promise.then && typeof promise.then === "function") {
2114
+ return promise.then(() => fn());
2115
+ }
2116
+ return fn();
2117
+ }
2118
+ /**
2119
+ *
2120
+ * @param {(Promise|undefined)} promise
2121
+ * @param {string} event
2122
+ * @return {(Promise|undefined)}
2123
+ * @private
2124
+ */
2125
+ _chainOrCallHooks(promise, event) {
2126
+ let result = promise;
2127
+ const hooks = [];
2128
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2129
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2130
+ hooks.push({ hookedCommand, callback });
2131
+ });
2132
+ });
2133
+ if (event === "postAction") {
2134
+ hooks.reverse();
2135
+ }
2136
+ hooks.forEach((hookDetail) => {
2137
+ result = this._chainOrCall(result, () => {
2138
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2139
+ });
2140
+ });
2141
+ return result;
2142
+ }
2143
+ /**
2144
+ *
2145
+ * @param {(Promise|undefined)} promise
2146
+ * @param {Command} subCommand
2147
+ * @param {string} event
2148
+ * @return {(Promise|undefined)}
2149
+ * @private
2150
+ */
2151
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2152
+ let result = promise;
2153
+ if (this._lifeCycleHooks[event] !== void 0) {
2154
+ this._lifeCycleHooks[event].forEach((hook) => {
2155
+ result = this._chainOrCall(result, () => {
2156
+ return hook(this, subCommand);
2157
+ });
2158
+ });
2159
+ }
2160
+ return result;
2161
+ }
2162
+ /**
2163
+ * Process arguments in context of this command.
2164
+ * Returns action result, in case it is a promise.
2165
+ *
2166
+ * @private
2167
+ */
2168
+ _parseCommand(operands, unknown) {
2169
+ const parsed = this.parseOptions(unknown);
2170
+ this._parseOptionsEnv();
2171
+ this._parseOptionsImplied();
2172
+ operands = operands.concat(parsed.operands);
2173
+ unknown = parsed.unknown;
2174
+ this.args = operands.concat(unknown);
2175
+ if (operands && this._findCommand(operands[0])) {
2176
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2177
+ }
2178
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2179
+ return this._dispatchHelpCommand(operands[1]);
2180
+ }
2181
+ if (this._defaultCommandName) {
2182
+ this._outputHelpIfRequested(unknown);
2183
+ return this._dispatchSubcommand(
2184
+ this._defaultCommandName,
2185
+ operands,
2186
+ unknown
2187
+ );
2188
+ }
2189
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2190
+ this.help({ error: true });
2191
+ }
2192
+ this._outputHelpIfRequested(parsed.unknown);
2193
+ this._checkForMissingMandatoryOptions();
2194
+ this._checkForConflictingOptions();
2195
+ const checkForUnknownOptions = () => {
2196
+ if (parsed.unknown.length > 0) {
2197
+ this.unknownOption(parsed.unknown[0]);
2198
+ }
2199
+ };
2200
+ const commandEvent = `command:${this.name()}`;
2201
+ if (this._actionHandler) {
2202
+ checkForUnknownOptions();
2203
+ this._processArguments();
2204
+ let promiseChain;
2205
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2206
+ promiseChain = this._chainOrCall(
2207
+ promiseChain,
2208
+ () => this._actionHandler(this.processedArgs)
2209
+ );
2210
+ if (this.parent) {
2211
+ promiseChain = this._chainOrCall(promiseChain, () => {
2212
+ this.parent.emit(commandEvent, operands, unknown);
2213
+ });
2214
+ }
2215
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2216
+ return promiseChain;
2217
+ }
2218
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2219
+ checkForUnknownOptions();
2220
+ this._processArguments();
2221
+ this.parent.emit(commandEvent, operands, unknown);
2222
+ } else if (operands.length) {
2223
+ if (this._findCommand("*")) {
2224
+ return this._dispatchSubcommand("*", operands, unknown);
2225
+ }
2226
+ if (this.listenerCount("command:*")) {
2227
+ this.emit("command:*", operands, unknown);
2228
+ } else if (this.commands.length) {
2229
+ this.unknownCommand();
2230
+ } else {
2231
+ checkForUnknownOptions();
2232
+ this._processArguments();
2233
+ }
2234
+ } else if (this.commands.length) {
2235
+ checkForUnknownOptions();
2236
+ this.help({ error: true });
2237
+ } else {
2238
+ checkForUnknownOptions();
2239
+ this._processArguments();
2240
+ }
2241
+ }
2242
+ /**
2243
+ * Find matching command.
2244
+ *
2245
+ * @private
2246
+ * @return {Command | undefined}
2247
+ */
2248
+ _findCommand(name) {
2249
+ if (!name) return void 0;
2250
+ return this.commands.find(
2251
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2252
+ );
2253
+ }
2254
+ /**
2255
+ * Return an option matching `arg` if any.
2256
+ *
2257
+ * @param {string} arg
2258
+ * @return {Option}
2259
+ * @package
2260
+ */
2261
+ _findOption(arg) {
2262
+ return this.options.find((option) => option.is(arg));
2263
+ }
2264
+ /**
2265
+ * Display an error message if a mandatory option does not have a value.
2266
+ * Called after checking for help flags in leaf subcommand.
2267
+ *
2268
+ * @private
2269
+ */
2270
+ _checkForMissingMandatoryOptions() {
2271
+ this._getCommandAndAncestors().forEach((cmd) => {
2272
+ cmd.options.forEach((anOption) => {
2273
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2274
+ cmd.missingMandatoryOptionValue(anOption);
2275
+ }
2276
+ });
2277
+ });
2278
+ }
2279
+ /**
2280
+ * Display an error message if conflicting options are used together in this.
2281
+ *
2282
+ * @private
2283
+ */
2284
+ _checkForConflictingLocalOptions() {
2285
+ const definedNonDefaultOptions = this.options.filter((option) => {
2286
+ const optionKey = option.attributeName();
2287
+ if (this.getOptionValue(optionKey) === void 0) {
2288
+ return false;
2289
+ }
2290
+ return this.getOptionValueSource(optionKey) !== "default";
2291
+ });
2292
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2293
+ (option) => option.conflictsWith.length > 0
2294
+ );
2295
+ optionsWithConflicting.forEach((option) => {
2296
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2297
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2298
+ );
2299
+ if (conflictingAndDefined) {
2300
+ this._conflictingOption(option, conflictingAndDefined);
2301
+ }
2302
+ });
2303
+ }
2304
+ /**
2305
+ * Display an error message if conflicting options are used together.
2306
+ * Called after checking for help flags in leaf subcommand.
2307
+ *
2308
+ * @private
2309
+ */
2310
+ _checkForConflictingOptions() {
2311
+ this._getCommandAndAncestors().forEach((cmd) => {
2312
+ cmd._checkForConflictingLocalOptions();
2313
+ });
2314
+ }
2315
+ /**
2316
+ * Parse options from `argv` removing known options,
2317
+ * and return argv split into operands and unknown arguments.
2318
+ *
2319
+ * Examples:
2320
+ *
2321
+ * argv => operands, unknown
2322
+ * --known kkk op => [op], []
2323
+ * op --known kkk => [op], []
2324
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2325
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2326
+ *
2327
+ * @param {string[]} argv
2328
+ * @return {{operands: string[], unknown: string[]}}
2329
+ */
2330
+ parseOptions(argv) {
2331
+ const operands = [];
2332
+ const unknown = [];
2333
+ let dest = operands;
2334
+ const args = argv.slice();
2335
+ function maybeOption(arg) {
2336
+ return arg.length > 1 && arg[0] === "-";
2337
+ }
2338
+ let activeVariadicOption = null;
2339
+ while (args.length) {
2340
+ const arg = args.shift();
2341
+ if (arg === "--") {
2342
+ if (dest === unknown) dest.push(arg);
2343
+ dest.push(...args);
2344
+ break;
2345
+ }
2346
+ if (activeVariadicOption && !maybeOption(arg)) {
2347
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2348
+ continue;
2349
+ }
2350
+ activeVariadicOption = null;
2351
+ if (maybeOption(arg)) {
2352
+ const option = this._findOption(arg);
2353
+ if (option) {
2354
+ if (option.required) {
2355
+ const value = args.shift();
2356
+ if (value === void 0) this.optionMissingArgument(option);
2357
+ this.emit(`option:${option.name()}`, value);
2358
+ } else if (option.optional) {
2359
+ let value = null;
2360
+ if (args.length > 0 && !maybeOption(args[0])) {
2361
+ value = args.shift();
2362
+ }
2363
+ this.emit(`option:${option.name()}`, value);
2364
+ } else {
2365
+ this.emit(`option:${option.name()}`);
2366
+ }
2367
+ activeVariadicOption = option.variadic ? option : null;
2368
+ continue;
2369
+ }
2370
+ }
2371
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2372
+ const option = this._findOption(`-${arg[1]}`);
2373
+ if (option) {
2374
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2375
+ this.emit(`option:${option.name()}`, arg.slice(2));
2376
+ } else {
2377
+ this.emit(`option:${option.name()}`);
2378
+ args.unshift(`-${arg.slice(2)}`);
2379
+ }
2380
+ continue;
2381
+ }
2382
+ }
2383
+ if (/^--[^=]+=/.test(arg)) {
2384
+ const index = arg.indexOf("=");
2385
+ const option = this._findOption(arg.slice(0, index));
2386
+ if (option && (option.required || option.optional)) {
2387
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2388
+ continue;
2389
+ }
2390
+ }
2391
+ if (maybeOption(arg)) {
2392
+ dest = unknown;
2393
+ }
2394
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2395
+ if (this._findCommand(arg)) {
2396
+ operands.push(arg);
2397
+ if (args.length > 0) unknown.push(...args);
2398
+ break;
2399
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2400
+ operands.push(arg);
2401
+ if (args.length > 0) operands.push(...args);
2402
+ break;
2403
+ } else if (this._defaultCommandName) {
2404
+ unknown.push(arg);
2405
+ if (args.length > 0) unknown.push(...args);
2406
+ break;
2407
+ }
2408
+ }
2409
+ if (this._passThroughOptions) {
2410
+ dest.push(arg);
2411
+ if (args.length > 0) dest.push(...args);
2412
+ break;
2413
+ }
2414
+ dest.push(arg);
2415
+ }
2416
+ return { operands, unknown };
2417
+ }
2418
+ /**
2419
+ * Return an object containing local option values as key-value pairs.
2420
+ *
2421
+ * @return {object}
2422
+ */
2423
+ opts() {
2424
+ if (this._storeOptionsAsProperties) {
2425
+ const result = {};
2426
+ const len = this.options.length;
2427
+ for (let i = 0; i < len; i++) {
2428
+ const key = this.options[i].attributeName();
2429
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2430
+ }
2431
+ return result;
2432
+ }
2433
+ return this._optionValues;
2434
+ }
2435
+ /**
2436
+ * Return an object containing merged local and global option values as key-value pairs.
2437
+ *
2438
+ * @return {object}
2439
+ */
2440
+ optsWithGlobals() {
2441
+ return this._getCommandAndAncestors().reduce(
2442
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2443
+ {}
2444
+ );
2445
+ }
2446
+ /**
2447
+ * Display error message and exit (or call exitOverride).
2448
+ *
2449
+ * @param {string} message
2450
+ * @param {object} [errorOptions]
2451
+ * @param {string} [errorOptions.code] - an id string representing the error
2452
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2453
+ */
2454
+ error(message, errorOptions) {
2455
+ this._outputConfiguration.outputError(
2456
+ `${message}
2457
+ `,
2458
+ this._outputConfiguration.writeErr
2459
+ );
2460
+ if (typeof this._showHelpAfterError === "string") {
2461
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2462
+ `);
2463
+ } else if (this._showHelpAfterError) {
2464
+ this._outputConfiguration.writeErr("\n");
2465
+ this.outputHelp({ error: true });
2466
+ }
2467
+ const config = errorOptions || {};
2468
+ const exitCode = config.exitCode || 1;
2469
+ const code = config.code || "commander.error";
2470
+ this._exit(exitCode, code, message);
2471
+ }
2472
+ /**
2473
+ * Apply any option related environment variables, if option does
2474
+ * not have a value from cli or client code.
2475
+ *
2476
+ * @private
2477
+ */
2478
+ _parseOptionsEnv() {
2479
+ this.options.forEach((option) => {
2480
+ if (option.envVar && option.envVar in process3.env) {
2481
+ const optionKey = option.attributeName();
2482
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2483
+ this.getOptionValueSource(optionKey)
2484
+ )) {
2485
+ if (option.required || option.optional) {
2486
+ this.emit(`optionEnv:${option.name()}`, process3.env[option.envVar]);
2487
+ } else {
2488
+ this.emit(`optionEnv:${option.name()}`);
2489
+ }
2490
+ }
2491
+ }
2492
+ });
2493
+ }
2494
+ /**
2495
+ * Apply any implied option values, if option is undefined or default value.
2496
+ *
2497
+ * @private
2498
+ */
2499
+ _parseOptionsImplied() {
2500
+ const dualHelper = new DualOptions(this.options);
2501
+ const hasCustomOptionValue = (optionKey) => {
2502
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2503
+ };
2504
+ this.options.filter(
2505
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2506
+ this.getOptionValue(option.attributeName()),
2507
+ option
2508
+ )
2509
+ ).forEach((option) => {
2510
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2511
+ this.setOptionValueWithSource(
2512
+ impliedKey,
2513
+ option.implied[impliedKey],
2514
+ "implied"
2515
+ );
2516
+ });
2517
+ });
2518
+ }
2519
+ /**
2520
+ * Argument `name` is missing.
2521
+ *
2522
+ * @param {string} name
2523
+ * @private
2524
+ */
2525
+ missingArgument(name) {
2526
+ const message = `error: missing required argument '${name}'`;
2527
+ this.error(message, { code: "commander.missingArgument" });
2528
+ }
2529
+ /**
2530
+ * `Option` is missing an argument.
2531
+ *
2532
+ * @param {Option} option
2533
+ * @private
2534
+ */
2535
+ optionMissingArgument(option) {
2536
+ const message = `error: option '${option.flags}' argument missing`;
2537
+ this.error(message, { code: "commander.optionMissingArgument" });
2538
+ }
2539
+ /**
2540
+ * `Option` does not have a value, and is a mandatory option.
2541
+ *
2542
+ * @param {Option} option
2543
+ * @private
2544
+ */
2545
+ missingMandatoryOptionValue(option) {
2546
+ const message = `error: required option '${option.flags}' not specified`;
2547
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2548
+ }
2549
+ /**
2550
+ * `Option` conflicts with another option.
2551
+ *
2552
+ * @param {Option} option
2553
+ * @param {Option} conflictingOption
2554
+ * @private
2555
+ */
2556
+ _conflictingOption(option, conflictingOption) {
2557
+ const findBestOptionFromValue = (option2) => {
2558
+ const optionKey = option2.attributeName();
2559
+ const optionValue = this.getOptionValue(optionKey);
2560
+ const negativeOption = this.options.find(
2561
+ (target) => target.negate && optionKey === target.attributeName()
2562
+ );
2563
+ const positiveOption = this.options.find(
2564
+ (target) => !target.negate && optionKey === target.attributeName()
2565
+ );
2566
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2567
+ return negativeOption;
2568
+ }
2569
+ return positiveOption || option2;
2570
+ };
2571
+ const getErrorMessage = (option2) => {
2572
+ const bestOption = findBestOptionFromValue(option2);
2573
+ const optionKey = bestOption.attributeName();
2574
+ const source = this.getOptionValueSource(optionKey);
2575
+ if (source === "env") {
2576
+ return `environment variable '${bestOption.envVar}'`;
2577
+ }
2578
+ return `option '${bestOption.flags}'`;
2579
+ };
2580
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2581
+ this.error(message, { code: "commander.conflictingOption" });
2582
+ }
2583
+ /**
2584
+ * Unknown option `flag`.
2585
+ *
2586
+ * @param {string} flag
2587
+ * @private
2588
+ */
2589
+ unknownOption(flag) {
2590
+ if (this._allowUnknownOption) return;
2591
+ let suggestion = "";
2592
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2593
+ let candidateFlags = [];
2594
+ let command = this;
2595
+ do {
2596
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2597
+ candidateFlags = candidateFlags.concat(moreFlags);
2598
+ command = command.parent;
2599
+ } while (command && !command._enablePositionalOptions);
2600
+ suggestion = suggestSimilar(flag, candidateFlags);
2601
+ }
2602
+ const message = `error: unknown option '${flag}'${suggestion}`;
2603
+ this.error(message, { code: "commander.unknownOption" });
2604
+ }
2605
+ /**
2606
+ * Excess arguments, more than expected.
2607
+ *
2608
+ * @param {string[]} receivedArgs
2609
+ * @private
2610
+ */
2611
+ _excessArguments(receivedArgs) {
2612
+ if (this._allowExcessArguments) return;
2613
+ const expected = this.registeredArguments.length;
2614
+ const s = expected === 1 ? "" : "s";
2615
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2616
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2617
+ this.error(message, { code: "commander.excessArguments" });
2618
+ }
2619
+ /**
2620
+ * Unknown command.
2621
+ *
2622
+ * @private
2623
+ */
2624
+ unknownCommand() {
2625
+ const unknownName = this.args[0];
2626
+ let suggestion = "";
2627
+ if (this._showSuggestionAfterError) {
2628
+ const candidateNames = [];
2629
+ this.createHelp().visibleCommands(this).forEach((command) => {
2630
+ candidateNames.push(command.name());
2631
+ if (command.alias()) candidateNames.push(command.alias());
2632
+ });
2633
+ suggestion = suggestSimilar(unknownName, candidateNames);
2634
+ }
2635
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2636
+ this.error(message, { code: "commander.unknownCommand" });
2637
+ }
2638
+ /**
2639
+ * Get or set the program version.
2640
+ *
2641
+ * This method auto-registers the "-V, --version" option which will print the version number.
2642
+ *
2643
+ * You can optionally supply the flags and description to override the defaults.
2644
+ *
2645
+ * @param {string} [str]
2646
+ * @param {string} [flags]
2647
+ * @param {string} [description]
2648
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2649
+ */
2650
+ version(str, flags, description) {
2651
+ if (str === void 0) return this._version;
2652
+ this._version = str;
2653
+ flags = flags || "-V, --version";
2654
+ description = description || "output the version number";
2655
+ const versionOption = this.createOption(flags, description);
2656
+ this._versionOptionName = versionOption.attributeName();
2657
+ this._registerOption(versionOption);
2658
+ this.on("option:" + versionOption.name(), () => {
2659
+ this._outputConfiguration.writeOut(`${str}
2660
+ `);
2661
+ this._exit(0, "commander.version", str);
2662
+ });
2663
+ return this;
2664
+ }
2665
+ /**
2666
+ * Set the description.
2667
+ *
2668
+ * @param {string} [str]
2669
+ * @param {object} [argsDescription]
2670
+ * @return {(string|Command)}
2671
+ */
2672
+ description(str, argsDescription) {
2673
+ if (str === void 0 && argsDescription === void 0)
2674
+ return this._description;
2675
+ this._description = str;
2676
+ if (argsDescription) {
2677
+ this._argsDescription = argsDescription;
2678
+ }
2679
+ return this;
2680
+ }
2681
+ /**
2682
+ * Set the summary. Used when listed as subcommand of parent.
2683
+ *
2684
+ * @param {string} [str]
2685
+ * @return {(string|Command)}
2686
+ */
2687
+ summary(str) {
2688
+ if (str === void 0) return this._summary;
2689
+ this._summary = str;
2690
+ return this;
2691
+ }
2692
+ /**
2693
+ * Set an alias for the command.
2694
+ *
2695
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2696
+ *
2697
+ * @param {string} [alias]
2698
+ * @return {(string|Command)}
2699
+ */
2700
+ alias(alias) {
2701
+ if (alias === void 0) return this._aliases[0];
2702
+ let command = this;
2703
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2704
+ command = this.commands[this.commands.length - 1];
2705
+ }
2706
+ if (alias === command._name)
2707
+ throw new Error("Command alias can't be the same as its name");
2708
+ const matchingCommand = this.parent?._findCommand(alias);
2709
+ if (matchingCommand) {
2710
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2711
+ throw new Error(
2712
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2713
+ );
2714
+ }
2715
+ command._aliases.push(alias);
2716
+ return this;
2717
+ }
2718
+ /**
2719
+ * Set aliases for the command.
2720
+ *
2721
+ * Only the first alias is shown in the auto-generated help.
2722
+ *
2723
+ * @param {string[]} [aliases]
2724
+ * @return {(string[]|Command)}
2725
+ */
2726
+ aliases(aliases) {
2727
+ if (aliases === void 0) return this._aliases;
2728
+ aliases.forEach((alias) => this.alias(alias));
2729
+ return this;
2730
+ }
2731
+ /**
2732
+ * Set / get the command usage `str`.
2733
+ *
2734
+ * @param {string} [str]
2735
+ * @return {(string|Command)}
2736
+ */
2737
+ usage(str) {
2738
+ if (str === void 0) {
2739
+ if (this._usage) return this._usage;
2740
+ const args = this.registeredArguments.map((arg) => {
2741
+ return humanReadableArgName(arg);
2742
+ });
2743
+ return [].concat(
2744
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2745
+ this.commands.length ? "[command]" : [],
2746
+ this.registeredArguments.length ? args : []
2747
+ ).join(" ");
2748
+ }
2749
+ this._usage = str;
2750
+ return this;
2751
+ }
2752
+ /**
2753
+ * Get or set the name of the command.
2754
+ *
2755
+ * @param {string} [str]
2756
+ * @return {(string|Command)}
2757
+ */
2758
+ name(str) {
2759
+ if (str === void 0) return this._name;
2760
+ this._name = str;
2761
+ return this;
2762
+ }
2763
+ /**
2764
+ * Set the name of the command from script filename, such as process.argv[1],
2765
+ * or require.main.filename, or __filename.
2766
+ *
2767
+ * (Used internally and public although not documented in README.)
2768
+ *
2769
+ * @example
2770
+ * program.nameFromFilename(require.main.filename);
2771
+ *
2772
+ * @param {string} filename
2773
+ * @return {Command}
2774
+ */
2775
+ nameFromFilename(filename) {
2776
+ this._name = path.basename(filename, path.extname(filename));
2777
+ return this;
2778
+ }
2779
+ /**
2780
+ * Get or set the directory for searching for executable subcommands of this command.
2781
+ *
2782
+ * @example
2783
+ * program.executableDir(__dirname);
2784
+ * // or
2785
+ * program.executableDir('subcommands');
2786
+ *
2787
+ * @param {string} [path]
2788
+ * @return {(string|null|Command)}
2789
+ */
2790
+ executableDir(path2) {
2791
+ if (path2 === void 0) return this._executableDir;
2792
+ this._executableDir = path2;
2793
+ return this;
2794
+ }
2795
+ /**
2796
+ * Return program help documentation.
2797
+ *
2798
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2799
+ * @return {string}
2800
+ */
2801
+ helpInformation(contextOptions) {
2802
+ const helper = this.createHelp();
2803
+ if (helper.helpWidth === void 0) {
2804
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2805
+ }
2806
+ return helper.formatHelp(this, helper);
2807
+ }
2808
+ /**
2809
+ * @private
2810
+ */
2811
+ _getHelpContext(contextOptions) {
2812
+ contextOptions = contextOptions || {};
2813
+ const context = { error: !!contextOptions.error };
2814
+ let write;
2815
+ if (context.error) {
2816
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2817
+ } else {
2818
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2819
+ }
2820
+ context.write = contextOptions.write || write;
2821
+ context.command = this;
2822
+ return context;
2823
+ }
2824
+ /**
2825
+ * Output help information for this command.
2826
+ *
2827
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2828
+ *
2829
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2830
+ */
2831
+ outputHelp(contextOptions) {
2832
+ let deprecatedCallback;
2833
+ if (typeof contextOptions === "function") {
2834
+ deprecatedCallback = contextOptions;
2835
+ contextOptions = void 0;
2836
+ }
2837
+ const context = this._getHelpContext(contextOptions);
2838
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2839
+ this.emit("beforeHelp", context);
2840
+ let helpInformation = this.helpInformation(context);
2841
+ if (deprecatedCallback) {
2842
+ helpInformation = deprecatedCallback(helpInformation);
2843
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2844
+ throw new Error("outputHelp callback must return a string or a Buffer");
2845
+ }
2846
+ }
2847
+ context.write(helpInformation);
2848
+ if (this._getHelpOption()?.long) {
2849
+ this.emit(this._getHelpOption().long);
2850
+ }
2851
+ this.emit("afterHelp", context);
2852
+ this._getCommandAndAncestors().forEach(
2853
+ (command) => command.emit("afterAllHelp", context)
2854
+ );
2855
+ }
2856
+ /**
2857
+ * You can pass in flags and a description to customise the built-in help option.
2858
+ * Pass in false to disable the built-in help option.
2859
+ *
2860
+ * @example
2861
+ * program.helpOption('-?, --help' 'show help'); // customise
2862
+ * program.helpOption(false); // disable
2863
+ *
2864
+ * @param {(string | boolean)} flags
2865
+ * @param {string} [description]
2866
+ * @return {Command} `this` command for chaining
2867
+ */
2868
+ helpOption(flags, description) {
2869
+ if (typeof flags === "boolean") {
2870
+ if (flags) {
2871
+ this._helpOption = this._helpOption ?? void 0;
2872
+ } else {
2873
+ this._helpOption = null;
2874
+ }
2875
+ return this;
2876
+ }
2877
+ flags = flags ?? "-h, --help";
2878
+ description = description ?? "display help for command";
2879
+ this._helpOption = this.createOption(flags, description);
2880
+ return this;
2881
+ }
2882
+ /**
2883
+ * Lazy create help option.
2884
+ * Returns null if has been disabled with .helpOption(false).
2885
+ *
2886
+ * @returns {(Option | null)} the help option
2887
+ * @package
2888
+ */
2889
+ _getHelpOption() {
2890
+ if (this._helpOption === void 0) {
2891
+ this.helpOption(void 0, void 0);
2892
+ }
2893
+ return this._helpOption;
2894
+ }
2895
+ /**
2896
+ * Supply your own option to use for the built-in help option.
2897
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2898
+ *
2899
+ * @param {Option} option
2900
+ * @return {Command} `this` command for chaining
2901
+ */
2902
+ addHelpOption(option) {
2903
+ this._helpOption = option;
2904
+ return this;
2905
+ }
2906
+ /**
2907
+ * Output help information and exit.
2908
+ *
2909
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2910
+ *
2911
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2912
+ */
2913
+ help(contextOptions) {
2914
+ this.outputHelp(contextOptions);
2915
+ let exitCode = process3.exitCode || 0;
2916
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2917
+ exitCode = 1;
2918
+ }
2919
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2920
+ }
2921
+ /**
2922
+ * Add additional text to be displayed with the built-in help.
2923
+ *
2924
+ * Position is 'before' or 'after' to affect just this command,
2925
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2926
+ *
2927
+ * @param {string} position - before or after built-in help
2928
+ * @param {(string | Function)} text - string to add, or a function returning a string
2929
+ * @return {Command} `this` command for chaining
2930
+ */
2931
+ addHelpText(position, text) {
2932
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2933
+ if (!allowedValues.includes(position)) {
2934
+ throw new Error(`Unexpected value for position to addHelpText.
2935
+ Expecting one of '${allowedValues.join("', '")}'`);
2936
+ }
2937
+ const helpEvent = `${position}Help`;
2938
+ this.on(helpEvent, (context) => {
2939
+ let helpStr;
2940
+ if (typeof text === "function") {
2941
+ helpStr = text({ error: context.error, command: context.command });
2942
+ } else {
2943
+ helpStr = text;
2944
+ }
2945
+ if (helpStr) {
2946
+ context.write(`${helpStr}
2947
+ `);
2948
+ }
2949
+ });
2950
+ return this;
2951
+ }
2952
+ /**
2953
+ * Output help information if help flags specified
2954
+ *
2955
+ * @param {Array} args - array of options to search for help flags
2956
+ * @private
2957
+ */
2958
+ _outputHelpIfRequested(args) {
2959
+ const helpOption = this._getHelpOption();
2960
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2961
+ if (helpRequested) {
2962
+ this.outputHelp();
2963
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2964
+ }
2965
+ }
2966
+ };
2967
+ function incrementNodeInspectorPort(args) {
2968
+ return args.map((arg) => {
2969
+ if (!arg.startsWith("--inspect")) {
2970
+ return arg;
2971
+ }
2972
+ let debugOption;
2973
+ let debugHost = "127.0.0.1";
2974
+ let debugPort = "9229";
2975
+ let match;
2976
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2977
+ debugOption = match[1];
2978
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2979
+ debugOption = match[1];
2980
+ if (/^\d+$/.test(match[3])) {
2981
+ debugPort = match[3];
2982
+ } else {
2983
+ debugHost = match[3];
2984
+ }
2985
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2986
+ debugOption = match[1];
2987
+ debugHost = match[3];
2988
+ debugPort = match[4];
2989
+ }
2990
+ if (debugOption && debugPort !== "0") {
2991
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2992
+ }
2993
+ return arg;
2994
+ });
2995
+ }
2996
+ exports2.Command = Command2;
2997
+ }
2998
+ });
2999
+
3000
+ // node_modules/commander/index.js
3001
+ var require_commander = __commonJS({
3002
+ "node_modules/commander/index.js"(exports2) {
3003
+ var { Argument: Argument2 } = require_argument();
3004
+ var { Command: Command2 } = require_command();
3005
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3006
+ var { Help: Help2 } = require_help();
3007
+ var { Option: Option2 } = require_option();
3008
+ exports2.program = new Command2();
3009
+ exports2.createCommand = (name) => new Command2(name);
3010
+ exports2.createOption = (flags, description) => new Option2(flags, description);
3011
+ exports2.createArgument = (name, description) => new Argument2(name, description);
3012
+ exports2.Command = Command2;
3013
+ exports2.Option = Option2;
3014
+ exports2.Argument = Argument2;
3015
+ exports2.Help = Help2;
3016
+ exports2.CommanderError = CommanderError2;
3017
+ exports2.InvalidArgumentError = InvalidArgumentError2;
3018
+ exports2.InvalidOptionArgumentError = InvalidArgumentError2;
3019
+ }
3020
+ });
3021
+
3022
+ // node_modules/commander/esm.mjs
3023
+ var import_index = __toESM(require_commander(), 1);
3024
+ var {
3025
+ program,
3026
+ createCommand,
3027
+ createArgument,
3028
+ createOption,
3029
+ CommanderError,
3030
+ InvalidArgumentError,
3031
+ InvalidOptionArgumentError,
3032
+ // deprecated old name
3033
+ Command,
3034
+ Argument,
3035
+ Option,
3036
+ Help
3037
+ } = import_index.default;
3038
+
3039
+ // src/commands/agent.ts
3040
+ var import_node_child_process2 = require("node:child_process");
3041
+
3042
+ // node_modules/chalk/source/vendor/ansi-styles/index.js
3043
+ var ANSI_BACKGROUND_OFFSET = 10;
3044
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
3045
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
3046
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
3047
+ var styles = {
3048
+ modifier: {
3049
+ reset: [0, 0],
3050
+ // 21 isn't widely supported and 22 does the same thing
3051
+ bold: [1, 22],
3052
+ dim: [2, 22],
3053
+ italic: [3, 23],
3054
+ underline: [4, 24],
3055
+ overline: [53, 55],
3056
+ inverse: [7, 27],
3057
+ hidden: [8, 28],
3058
+ strikethrough: [9, 29]
3059
+ },
3060
+ color: {
3061
+ black: [30, 39],
3062
+ red: [31, 39],
3063
+ green: [32, 39],
3064
+ yellow: [33, 39],
3065
+ blue: [34, 39],
3066
+ magenta: [35, 39],
3067
+ cyan: [36, 39],
3068
+ white: [37, 39],
3069
+ // Bright color
3070
+ blackBright: [90, 39],
3071
+ gray: [90, 39],
3072
+ // Alias of `blackBright`
3073
+ grey: [90, 39],
3074
+ // Alias of `blackBright`
3075
+ redBright: [91, 39],
3076
+ greenBright: [92, 39],
3077
+ yellowBright: [93, 39],
3078
+ blueBright: [94, 39],
3079
+ magentaBright: [95, 39],
3080
+ cyanBright: [96, 39],
3081
+ whiteBright: [97, 39]
3082
+ },
3083
+ bgColor: {
3084
+ bgBlack: [40, 49],
3085
+ bgRed: [41, 49],
3086
+ bgGreen: [42, 49],
3087
+ bgYellow: [43, 49],
3088
+ bgBlue: [44, 49],
3089
+ bgMagenta: [45, 49],
3090
+ bgCyan: [46, 49],
3091
+ bgWhite: [47, 49],
3092
+ // Bright color
3093
+ bgBlackBright: [100, 49],
3094
+ bgGray: [100, 49],
3095
+ // Alias of `bgBlackBright`
3096
+ bgGrey: [100, 49],
3097
+ // Alias of `bgBlackBright`
3098
+ bgRedBright: [101, 49],
3099
+ bgGreenBright: [102, 49],
3100
+ bgYellowBright: [103, 49],
3101
+ bgBlueBright: [104, 49],
3102
+ bgMagentaBright: [105, 49],
3103
+ bgCyanBright: [106, 49],
3104
+ bgWhiteBright: [107, 49]
3105
+ }
3106
+ };
3107
+ var modifierNames = Object.keys(styles.modifier);
3108
+ var foregroundColorNames = Object.keys(styles.color);
3109
+ var backgroundColorNames = Object.keys(styles.bgColor);
3110
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
3111
+ function assembleStyles() {
3112
+ const codes = /* @__PURE__ */ new Map();
3113
+ for (const [groupName, group] of Object.entries(styles)) {
3114
+ for (const [styleName, style] of Object.entries(group)) {
3115
+ styles[styleName] = {
3116
+ open: `\x1B[${style[0]}m`,
3117
+ close: `\x1B[${style[1]}m`
3118
+ };
3119
+ group[styleName] = styles[styleName];
3120
+ codes.set(style[0], style[1]);
3121
+ }
3122
+ Object.defineProperty(styles, groupName, {
3123
+ value: group,
3124
+ enumerable: false
3125
+ });
3126
+ }
3127
+ Object.defineProperty(styles, "codes", {
3128
+ value: codes,
3129
+ enumerable: false
3130
+ });
3131
+ styles.color.close = "\x1B[39m";
3132
+ styles.bgColor.close = "\x1B[49m";
3133
+ styles.color.ansi = wrapAnsi16();
3134
+ styles.color.ansi256 = wrapAnsi256();
3135
+ styles.color.ansi16m = wrapAnsi16m();
3136
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
3137
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
3138
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
3139
+ Object.defineProperties(styles, {
3140
+ rgbToAnsi256: {
3141
+ value(red, green, blue) {
3142
+ if (red === green && green === blue) {
3143
+ if (red < 8) {
3144
+ return 16;
3145
+ }
3146
+ if (red > 248) {
3147
+ return 231;
3148
+ }
3149
+ return Math.round((red - 8) / 247 * 24) + 232;
3150
+ }
3151
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
3152
+ },
3153
+ enumerable: false
3154
+ },
3155
+ hexToRgb: {
3156
+ value(hex) {
3157
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
3158
+ if (!matches) {
3159
+ return [0, 0, 0];
3160
+ }
3161
+ let [colorString] = matches;
3162
+ if (colorString.length === 3) {
3163
+ colorString = [...colorString].map((character) => character + character).join("");
3164
+ }
3165
+ const integer = Number.parseInt(colorString, 16);
3166
+ return [
3167
+ /* eslint-disable no-bitwise */
3168
+ integer >> 16 & 255,
3169
+ integer >> 8 & 255,
3170
+ integer & 255
3171
+ /* eslint-enable no-bitwise */
3172
+ ];
3173
+ },
3174
+ enumerable: false
3175
+ },
3176
+ hexToAnsi256: {
3177
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
3178
+ enumerable: false
3179
+ },
3180
+ ansi256ToAnsi: {
3181
+ value(code) {
3182
+ if (code < 8) {
3183
+ return 30 + code;
3184
+ }
3185
+ if (code < 16) {
3186
+ return 90 + (code - 8);
3187
+ }
3188
+ let red;
3189
+ let green;
3190
+ let blue;
3191
+ if (code >= 232) {
3192
+ red = ((code - 232) * 10 + 8) / 255;
3193
+ green = red;
3194
+ blue = red;
3195
+ } else {
3196
+ code -= 16;
3197
+ const remainder = code % 36;
3198
+ red = Math.floor(code / 36) / 5;
3199
+ green = Math.floor(remainder / 6) / 5;
3200
+ blue = remainder % 6 / 5;
3201
+ }
3202
+ const value = Math.max(red, green, blue) * 2;
3203
+ if (value === 0) {
3204
+ return 30;
3205
+ }
3206
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
3207
+ if (value === 2) {
3208
+ result += 60;
3209
+ }
3210
+ return result;
3211
+ },
3212
+ enumerable: false
3213
+ },
3214
+ rgbToAnsi: {
3215
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
3216
+ enumerable: false
3217
+ },
3218
+ hexToAnsi: {
3219
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
3220
+ enumerable: false
3221
+ }
3222
+ });
3223
+ return styles;
3224
+ }
3225
+ var ansiStyles = assembleStyles();
3226
+ var ansi_styles_default = ansiStyles;
3227
+
3228
+ // node_modules/chalk/source/vendor/supports-color/index.js
3229
+ var import_node_process = __toESM(require("node:process"), 1);
3230
+ var import_node_os = __toESM(require("node:os"), 1);
3231
+ var import_node_tty = __toESM(require("node:tty"), 1);
3232
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
3233
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3234
+ const position = argv.indexOf(prefix + flag);
3235
+ const terminatorPosition = argv.indexOf("--");
3236
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
3237
+ }
3238
+ var { env } = import_node_process.default;
3239
+ var flagForceColor;
3240
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
3241
+ flagForceColor = 0;
3242
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
3243
+ flagForceColor = 1;
3244
+ }
3245
+ function envForceColor() {
3246
+ if ("FORCE_COLOR" in env) {
3247
+ if (env.FORCE_COLOR === "true") {
3248
+ return 1;
3249
+ }
3250
+ if (env.FORCE_COLOR === "false") {
3251
+ return 0;
3252
+ }
3253
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
3254
+ }
3255
+ }
3256
+ function translateLevel(level) {
3257
+ if (level === 0) {
3258
+ return false;
3259
+ }
3260
+ return {
3261
+ level,
3262
+ hasBasic: true,
3263
+ has256: level >= 2,
3264
+ has16m: level >= 3
3265
+ };
3266
+ }
3267
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
3268
+ const noFlagForceColor = envForceColor();
3269
+ if (noFlagForceColor !== void 0) {
3270
+ flagForceColor = noFlagForceColor;
3271
+ }
3272
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
3273
+ if (forceColor === 0) {
3274
+ return 0;
3275
+ }
3276
+ if (sniffFlags) {
3277
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
3278
+ return 3;
3279
+ }
3280
+ if (hasFlag("color=256")) {
3281
+ return 2;
3282
+ }
3283
+ }
3284
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
3285
+ return 1;
3286
+ }
3287
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
3288
+ return 0;
3289
+ }
3290
+ const min = forceColor || 0;
3291
+ if (env.TERM === "dumb") {
3292
+ return min;
3293
+ }
3294
+ if (import_node_process.default.platform === "win32") {
3295
+ const osRelease = import_node_os.default.release().split(".");
3296
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
3297
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
3298
+ }
3299
+ return 1;
3300
+ }
3301
+ if ("CI" in env) {
3302
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
3303
+ return 3;
3304
+ }
3305
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
3306
+ return 1;
3307
+ }
3308
+ return min;
3309
+ }
3310
+ if ("TEAMCITY_VERSION" in env) {
3311
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
3312
+ }
3313
+ if (env.COLORTERM === "truecolor") {
3314
+ return 3;
3315
+ }
3316
+ if (env.TERM === "xterm-kitty") {
3317
+ return 3;
3318
+ }
3319
+ if (env.TERM === "xterm-ghostty") {
3320
+ return 3;
3321
+ }
3322
+ if (env.TERM === "wezterm") {
3323
+ return 3;
3324
+ }
3325
+ if ("TERM_PROGRAM" in env) {
3326
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
3327
+ switch (env.TERM_PROGRAM) {
3328
+ case "iTerm.app": {
3329
+ return version >= 3 ? 3 : 2;
3330
+ }
3331
+ case "Apple_Terminal": {
3332
+ return 2;
3333
+ }
3334
+ }
3335
+ }
3336
+ if (/-256(color)?$/i.test(env.TERM)) {
3337
+ return 2;
3338
+ }
3339
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
3340
+ return 1;
3341
+ }
3342
+ if ("COLORTERM" in env) {
3343
+ return 1;
3344
+ }
3345
+ return min;
3346
+ }
3347
+ function createSupportsColor(stream, options = {}) {
3348
+ const level = _supportsColor(stream, {
3349
+ streamIsTTY: stream && stream.isTTY,
3350
+ ...options
3351
+ });
3352
+ return translateLevel(level);
3353
+ }
3354
+ var supportsColor = {
3355
+ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
3356
+ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
3357
+ };
3358
+ var supports_color_default = supportsColor;
3359
+
3360
+ // node_modules/chalk/source/utilities.js
3361
+ function stringReplaceAll(string, substring, replacer) {
3362
+ let index = string.indexOf(substring);
3363
+ if (index === -1) {
3364
+ return string;
3365
+ }
3366
+ const substringLength = substring.length;
3367
+ let endIndex = 0;
3368
+ let returnValue = "";
3369
+ do {
3370
+ returnValue += string.slice(endIndex, index) + substring + replacer;
3371
+ endIndex = index + substringLength;
3372
+ index = string.indexOf(substring, endIndex);
3373
+ } while (index !== -1);
3374
+ returnValue += string.slice(endIndex);
3375
+ return returnValue;
3376
+ }
3377
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
3378
+ let endIndex = 0;
3379
+ let returnValue = "";
3380
+ do {
3381
+ const gotCR = string[index - 1] === "\r";
3382
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
3383
+ endIndex = index + 1;
3384
+ index = string.indexOf("\n", endIndex);
3385
+ } while (index !== -1);
3386
+ returnValue += string.slice(endIndex);
3387
+ return returnValue;
3388
+ }
3389
+
3390
+ // node_modules/chalk/source/index.js
3391
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
3392
+ var GENERATOR = Symbol("GENERATOR");
3393
+ var STYLER = Symbol("STYLER");
3394
+ var IS_EMPTY = Symbol("IS_EMPTY");
3395
+ var levelMapping = [
3396
+ "ansi",
3397
+ "ansi",
3398
+ "ansi256",
3399
+ "ansi16m"
3400
+ ];
3401
+ var styles2 = /* @__PURE__ */ Object.create(null);
3402
+ var applyOptions = (object, options = {}) => {
3403
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
3404
+ throw new Error("The `level` option should be an integer from 0 to 3");
3405
+ }
3406
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
3407
+ object.level = options.level === void 0 ? colorLevel : options.level;
3408
+ };
3409
+ var chalkFactory = (options) => {
3410
+ const chalk2 = (...strings) => strings.join(" ");
3411
+ applyOptions(chalk2, options);
3412
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
3413
+ return chalk2;
3414
+ };
3415
+ function createChalk(options) {
3416
+ return chalkFactory(options);
3417
+ }
3418
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
3419
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
3420
+ styles2[styleName] = {
3421
+ get() {
3422
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
3423
+ Object.defineProperty(this, styleName, { value: builder });
3424
+ return builder;
3425
+ }
3426
+ };
3427
+ }
3428
+ styles2.visible = {
3429
+ get() {
3430
+ const builder = createBuilder(this, this[STYLER], true);
3431
+ Object.defineProperty(this, "visible", { value: builder });
3432
+ return builder;
3433
+ }
3434
+ };
3435
+ var getModelAnsi = (model, level, type, ...arguments_) => {
3436
+ if (model === "rgb") {
3437
+ if (level === "ansi16m") {
3438
+ return ansi_styles_default[type].ansi16m(...arguments_);
3439
+ }
3440
+ if (level === "ansi256") {
3441
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
3442
+ }
3443
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
3444
+ }
3445
+ if (model === "hex") {
3446
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
3447
+ }
3448
+ return ansi_styles_default[type][model](...arguments_);
3449
+ };
3450
+ var usedModels = ["rgb", "hex", "ansi256"];
3451
+ for (const model of usedModels) {
3452
+ styles2[model] = {
3453
+ get() {
3454
+ const { level } = this;
3455
+ return function(...arguments_) {
3456
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
3457
+ return createBuilder(this, styler, this[IS_EMPTY]);
3458
+ };
3459
+ }
3460
+ };
3461
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
3462
+ styles2[bgModel] = {
3463
+ get() {
3464
+ const { level } = this;
3465
+ return function(...arguments_) {
3466
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
3467
+ return createBuilder(this, styler, this[IS_EMPTY]);
3468
+ };
3469
+ }
3470
+ };
3471
+ }
3472
+ var proto = Object.defineProperties(() => {
3473
+ }, {
3474
+ ...styles2,
3475
+ level: {
3476
+ enumerable: true,
3477
+ get() {
3478
+ return this[GENERATOR].level;
3479
+ },
3480
+ set(level) {
3481
+ this[GENERATOR].level = level;
3482
+ }
3483
+ }
3484
+ });
3485
+ var createStyler = (open, close, parent) => {
3486
+ let openAll;
3487
+ let closeAll;
3488
+ if (parent === void 0) {
3489
+ openAll = open;
3490
+ closeAll = close;
3491
+ } else {
3492
+ openAll = parent.openAll + open;
3493
+ closeAll = close + parent.closeAll;
3494
+ }
3495
+ return {
3496
+ open,
3497
+ close,
3498
+ openAll,
3499
+ closeAll,
3500
+ parent
3501
+ };
3502
+ };
3503
+ var createBuilder = (self, _styler, _isEmpty) => {
3504
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
3505
+ Object.setPrototypeOf(builder, proto);
3506
+ builder[GENERATOR] = self;
3507
+ builder[STYLER] = _styler;
3508
+ builder[IS_EMPTY] = _isEmpty;
3509
+ return builder;
3510
+ };
3511
+ var applyStyle = (self, string) => {
3512
+ if (self.level <= 0 || !string) {
3513
+ return self[IS_EMPTY] ? "" : string;
3514
+ }
3515
+ let styler = self[STYLER];
3516
+ if (styler === void 0) {
3517
+ return string;
3518
+ }
3519
+ const { openAll, closeAll } = styler;
3520
+ if (string.includes("\x1B")) {
3521
+ while (styler !== void 0) {
3522
+ string = stringReplaceAll(string, styler.close, styler.open);
3523
+ styler = styler.parent;
3524
+ }
3525
+ }
3526
+ const lfIndex = string.indexOf("\n");
3527
+ if (lfIndex !== -1) {
3528
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
3529
+ }
3530
+ return openAll + string + closeAll;
3531
+ };
3532
+ Object.defineProperties(createChalk.prototype, styles2);
3533
+ var chalk = createChalk();
3534
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
3535
+ var source_default = chalk;
3536
+
3537
+ // src/utils/credentials.ts
3538
+ var import_fs = require("fs");
3539
+ var import_os = require("os");
3540
+ var import_path = require("path");
3541
+ var os2 = __toESM(require("os"));
3542
+ var CREDENTIAL_PATHS = [
3543
+ (0, import_path.join)((0, import_os.homedir)(), ".config", "cv-hub", "credentials"),
3544
+ "/root/.config/cv-hub/credentials"
3545
+ ];
3546
+ async function findCredentialFile() {
3547
+ for (const p of CREDENTIAL_PATHS) {
3548
+ try {
3549
+ await import_fs.promises.access(p);
3550
+ return p;
3551
+ } catch {
3552
+ continue;
3553
+ }
3554
+ }
3555
+ return null;
3556
+ }
3557
+ async function readCredentials() {
3558
+ const credPath = await findCredentialFile();
3559
+ if (!credPath) {
3560
+ return {};
3561
+ }
3562
+ try {
3563
+ const content = await import_fs.promises.readFile(credPath, "utf-8");
3564
+ return parseCredentials(content);
3565
+ } catch {
3566
+ return {};
3567
+ }
3568
+ }
3569
+ function parseCredentials(content) {
3570
+ const result = {};
3571
+ for (const line of content.split("\n")) {
3572
+ const trimmed = line.trim();
3573
+ if (!trimmed || trimmed.startsWith("#")) continue;
3574
+ const eqIdx = trimmed.indexOf("=");
3575
+ if (eqIdx === -1) continue;
3576
+ const key = trimmed.slice(0, eqIdx).trim();
3577
+ const value = trimmed.slice(eqIdx + 1).trim();
3578
+ result[key] = value;
3579
+ }
3580
+ return result;
3581
+ }
3582
+ async function writeCredentialField(key, value) {
3583
+ let credPath = await findCredentialFile();
3584
+ if (!credPath) {
3585
+ credPath = CREDENTIAL_PATHS[0];
3586
+ await import_fs.promises.mkdir((0, import_path.dirname)(credPath), { recursive: true });
3587
+ await import_fs.promises.writeFile(credPath, `${key}=${value}
3588
+ `, { mode: 384 });
3589
+ return credPath;
3590
+ }
3591
+ let content;
3592
+ try {
3593
+ content = await import_fs.promises.readFile(credPath, "utf-8");
3594
+ } catch {
3595
+ content = "";
3596
+ }
3597
+ const lines = content.split("\n");
3598
+ let found = false;
3599
+ for (let i = 0; i < lines.length; i++) {
3600
+ const trimmed = lines[i].trim();
3601
+ if (trimmed.startsWith("#") || !trimmed) continue;
3602
+ const eqIdx = trimmed.indexOf("=");
3603
+ if (eqIdx === -1) continue;
3604
+ const lineKey = trimmed.slice(0, eqIdx).trim();
3605
+ if (lineKey === key) {
3606
+ lines[i] = `${key}=${value}`;
3607
+ found = true;
3608
+ break;
3609
+ }
3610
+ }
3611
+ if (!found) {
3612
+ if (content.length > 0 && !content.endsWith("\n")) {
3613
+ lines.push("");
3614
+ }
3615
+ lines.push(`${key}=${value}`);
3616
+ }
3617
+ let newContent = lines.join("\n");
3618
+ if (!newContent.endsWith("\n")) {
3619
+ newContent += "\n";
3620
+ }
3621
+ await import_fs.promises.writeFile(credPath, newContent, { mode: 384 });
3622
+ return credPath;
3623
+ }
3624
+ async function getMachineName() {
3625
+ const creds = await readCredentials();
3626
+ const raw = creds.CV_HUB_MACHINE_NAME || os2.hostname();
3627
+ return cleanMachineName(raw);
3628
+ }
3629
+ function cleanMachineName(name) {
3630
+ return name.trim().toLowerCase().replace(/\s+/g, "-");
3631
+ }
3632
+
3633
+ // src/utils/api.ts
3634
+ async function apiCall(creds, method, path, body) {
3635
+ const url = `${creds.CV_HUB_API}${path}`;
3636
+ const headers = {
3637
+ "Authorization": `Bearer ${creds.CV_HUB_PAT}`,
3638
+ "Content-Type": "application/json"
3639
+ };
3640
+ return fetch(url, {
3641
+ method,
3642
+ headers,
3643
+ body: body ? JSON.stringify(body) : void 0
3644
+ });
3645
+ }
3646
+ async function registerExecutor(creds, machineName, workingDir) {
3647
+ const hostname2 = (await import("node:os")).hostname();
3648
+ const res = await apiCall(creds, "POST", "/api/v1/executors", {
3649
+ name: `cva:${machineName}`,
3650
+ machine_name: machineName,
3651
+ type: "claude_code",
3652
+ workspace_root: workingDir,
3653
+ capabilities: {
3654
+ tools: ["bash", "read", "write", "edit", "glob", "grep"],
3655
+ maxConcurrentTasks: 1
3656
+ }
3657
+ });
3658
+ if (!res.ok) {
3659
+ const err = await res.text();
3660
+ throw new Error(`Failed to register executor: ${res.status} ${err}`);
3661
+ }
3662
+ const data = await res.json();
3663
+ return { id: data.executor.id, name: data.executor.name };
3664
+ }
3665
+ async function markOffline(creds, executorId) {
3666
+ await apiCall(creds, "POST", `/api/v1/executors/${executorId}/offline`).catch(() => {
3667
+ });
3668
+ }
3669
+ async function pollForTask(creds, executorId) {
3670
+ const res = await apiCall(creds, "POST", `/api/v1/executors/${executorId}/poll`);
3671
+ if (!res.ok) throw new Error(`Poll failed: ${res.status}`);
3672
+ const data = await res.json();
3673
+ return data.task || null;
3674
+ }
3675
+ async function startTask(creds, executorId, taskId) {
3676
+ const res = await apiCall(creds, "POST", `/api/v1/executors/${executorId}/tasks/${taskId}/start`);
3677
+ if (!res.ok) throw new Error(`Start failed: ${res.status}`);
3678
+ }
3679
+ async function completeTask(creds, executorId, taskId, result) {
3680
+ const res = await apiCall(creds, "POST", `/api/v1/executors/${executorId}/tasks/${taskId}/complete`, result);
3681
+ if (!res.ok) throw new Error(`Complete failed: ${res.status}`);
3682
+ }
3683
+ async function failTask(creds, executorId, taskId, error) {
3684
+ const res = await apiCall(creds, "POST", `/api/v1/executors/${executorId}/tasks/${taskId}/fail`, { error });
3685
+ if (!res.ok) throw new Error(`Fail failed: ${res.status}`);
3686
+ }
3687
+ async function sendHeartbeat(creds, executorId, taskId, message) {
3688
+ await apiCall(creds, "POST", `/api/v1/executors/${executorId}/heartbeat`).catch(() => {
3689
+ });
3690
+ if (taskId) {
3691
+ const body = message ? { message, log_type: "heartbeat" } : void 0;
3692
+ await apiCall(creds, "POST", `/api/v1/executors/${executorId}/tasks/${taskId}/heartbeat`, body).catch(() => {
3693
+ });
3694
+ }
3695
+ }
3696
+ async function sendTaskLog(creds, executorId, taskId, logType, message, details, progressPct) {
3697
+ await apiCall(creds, "POST", `/api/v1/executors/${executorId}/tasks/${taskId}/log`, {
3698
+ log_type: logType,
3699
+ message,
3700
+ ...details ? { details } : {},
3701
+ ...progressPct !== void 0 ? { progress_pct: progressPct } : {}
3702
+ }).catch(() => {
3703
+ });
3704
+ }
3705
+ async function createTaskPrompt(creds, executorId, taskId, promptText, promptType = "approval", options, context) {
3706
+ const res = await apiCall(creds, "POST", `/api/v1/executors/${executorId}/tasks/${taskId}/prompt`, {
3707
+ type: promptType,
3708
+ text: promptText,
3709
+ ...options ? { options } : {},
3710
+ ...context ? { context } : {}
3711
+ });
3712
+ if (!res.ok) throw new Error(`Create prompt failed: ${res.status}`);
3713
+ return await res.json();
3714
+ }
3715
+ async function pollPromptResponse(creds, executorId, taskId, promptId) {
3716
+ const res = await apiCall(creds, "GET", `/api/v1/executors/${executorId}/tasks/${taskId}/prompts/${promptId}`);
3717
+ if (!res.ok) throw new Error(`Poll prompt failed: ${res.status}`);
3718
+ const data = await res.json();
3719
+ return { response: data.response ?? null };
3720
+ }
3721
+ async function listExecutors(creds) {
3722
+ const res = await apiCall(creds, "GET", "/api/v1/executors");
3723
+ if (!res.ok) throw new Error(`List executors failed: ${res.status}`);
3724
+ const data = await res.json();
3725
+ return data.executors || [];
3726
+ }
3727
+ async function listTasks(creds, status) {
3728
+ const qs = status ? `?status=${encodeURIComponent(status)}` : "";
3729
+ const res = await apiCall(creds, "GET", `/api/v1/tasks${qs}`);
3730
+ if (!res.ok) throw new Error(`List tasks failed: ${res.status}`);
3731
+ const data = await res.json();
3732
+ return data.tasks || [];
3733
+ }
3734
+ async function getTask(creds, taskId) {
3735
+ const res = await apiCall(creds, "GET", `/api/v1/tasks/${taskId}`);
3736
+ if (!res.ok) throw new Error(`Get task failed: ${res.status}`);
3737
+ const data = await res.json();
3738
+ return data.task;
3739
+ }
3740
+ async function getTaskLogs(creds, taskId) {
3741
+ const res = await apiCall(creds, "GET", `/api/v1/tasks/${taskId}/logs`);
3742
+ if (!res.ok) throw new Error(`Get task logs failed: ${res.status}`);
3743
+ const data = await res.json();
3744
+ return data.logs || [];
3745
+ }
3746
+ async function createRepo(creds, name, description) {
3747
+ const res = await apiCall(creds, "POST", "/api/v1/repos", {
3748
+ name,
3749
+ ...description ? { description } : {}
3750
+ });
3751
+ if (!res.ok) {
3752
+ const err = await res.text();
3753
+ throw new Error(`Create repo failed: ${res.status} ${err}`);
3754
+ }
3755
+ return await res.json();
3756
+ }
3757
+
3758
+ // src/commands/agent-git.ts
3759
+ var import_node_child_process = require("node:child_process");
3760
+ function gitExec(cmd, cwd) {
3761
+ try {
3762
+ return (0, import_node_child_process.execSync)(cmd, { cwd, encoding: "utf-8", timeout: 1e4 }).trim();
3763
+ } catch {
3764
+ return null;
3765
+ }
3766
+ }
3767
+ function capturePreTaskState(cwd) {
3768
+ return {
3769
+ headSha: gitExec("git rev-parse HEAD", cwd),
3770
+ branch: gitExec("git rev-parse --abbrev-ref HEAD", cwd),
3771
+ remote: gitExec("git remote get-url origin", cwd),
3772
+ workingDir: cwd
3773
+ };
3774
+ }
3775
+ function capturePostTaskState(cwd, preState) {
3776
+ const headSha = gitExec("git rev-parse HEAD", cwd);
3777
+ const branch = gitExec("git rev-parse --abbrev-ref HEAD", cwd);
3778
+ let filesAdded = [];
3779
+ let filesModified = [];
3780
+ let filesDeleted = [];
3781
+ let linesAdded = 0;
3782
+ let linesDeleted = 0;
3783
+ let commitMessages = [];
3784
+ if (preState.headSha && headSha && preState.headSha !== headSha) {
3785
+ const diffOutput = gitExec(
3786
+ `git diff --name-status ${preState.headSha}..${headSha}`,
3787
+ cwd
3788
+ );
3789
+ if (diffOutput) {
3790
+ for (const line of diffOutput.split("\n")) {
3791
+ const [status, ...pathParts] = line.split(" ");
3792
+ const filepath = pathParts.join(" ");
3793
+ if (!filepath) continue;
3794
+ if (status === "A") filesAdded.push(filepath);
3795
+ else if (status === "M") filesModified.push(filepath);
3796
+ else if (status === "D") filesDeleted.push(filepath);
3797
+ else if (status?.startsWith("R")) {
3798
+ filesDeleted.push(pathParts[0]);
3799
+ if (pathParts[1]) filesAdded.push(pathParts[1]);
3800
+ }
3801
+ }
3802
+ }
3803
+ const statOutput = gitExec(
3804
+ `git diff --shortstat ${preState.headSha}..${headSha}`,
3805
+ cwd
3806
+ );
3807
+ if (statOutput) {
3808
+ const addMatch = statOutput.match(/(\d+) insertion/);
3809
+ const delMatch = statOutput.match(/(\d+) deletion/);
3810
+ linesAdded = addMatch ? parseInt(addMatch[1], 10) : 0;
3811
+ linesDeleted = delMatch ? parseInt(delMatch[1], 10) : 0;
3812
+ }
3813
+ const logOutput = gitExec(
3814
+ `git log --oneline ${preState.headSha}..${headSha}`,
3815
+ cwd
3816
+ );
3817
+ if (logOutput) {
3818
+ commitMessages = logOutput.split("\n").filter(Boolean);
3819
+ }
3820
+ } else if (!preState.headSha && headSha) {
3821
+ const allFiles = gitExec("git ls-files", cwd);
3822
+ if (allFiles) {
3823
+ filesAdded = allFiles.split("\n").filter(Boolean);
3824
+ }
3825
+ } else {
3826
+ const statusOutput = gitExec("git status --porcelain", cwd);
3827
+ if (statusOutput) {
3828
+ for (const line of statusOutput.split("\n")) {
3829
+ const status = line.substring(0, 2).trim();
3830
+ const filepath = line.substring(3);
3831
+ if (!filepath) continue;
3832
+ if (status === "??" || status === "A") filesAdded.push(filepath);
3833
+ else if (status === "M") filesModified.push(filepath);
3834
+ else if (status === "D") filesDeleted.push(filepath);
3835
+ }
3836
+ }
3837
+ }
3838
+ let pushStatus = "not_pushed";
3839
+ let pushRemote = null;
3840
+ const remote = gitExec("git remote get-url origin", cwd);
3841
+ if (!remote) {
3842
+ pushStatus = "no_remote";
3843
+ } else {
3844
+ pushRemote = remote;
3845
+ if (headSha && branch) {
3846
+ const remoteRef = gitExec(`git ls-remote origin ${branch}`, cwd);
3847
+ if (remoteRef && remoteRef.includes(headSha)) {
3848
+ pushStatus = "success";
3849
+ }
3850
+ }
3851
+ }
3852
+ return {
3853
+ headSha,
3854
+ branch,
3855
+ filesAdded,
3856
+ filesModified,
3857
+ filesDeleted,
3858
+ linesAdded,
3859
+ linesDeleted,
3860
+ commitMessages,
3861
+ pushStatus,
3862
+ pushRemote
3863
+ };
3864
+ }
3865
+ function buildCompletionPayload(exitCode, preState, postState, startTime) {
3866
+ const durationSec = Math.floor((Date.now() - startTime) / 1e3);
3867
+ const durationStr = durationSec >= 60 ? `${Math.floor(durationSec / 60)}m ${durationSec % 60}s` : `${durationSec}s`;
3868
+ const totalChanged = postState.filesAdded.length + postState.filesModified.length + postState.filesDeleted.length;
3869
+ const parts = [`Completed in ${durationStr}.`];
3870
+ if (totalChanged > 0) {
3871
+ parts.push(
3872
+ `${totalChanged} file(s) changed (+${postState.linesAdded}/-${postState.linesDeleted}).`
3873
+ );
3874
+ } else {
3875
+ parts.push("No file changes detected.");
3876
+ }
3877
+ if (postState.headSha && postState.headSha !== preState.headSha) {
3878
+ parts.push(`Commit: ${postState.headSha.substring(0, 8)}`);
3879
+ }
3880
+ if (postState.pushStatus === "success") {
3881
+ parts.push("Pushed to remote.");
3882
+ } else if (postState.pushStatus === "not_pushed") {
3883
+ parts.push("Not pushed to remote.");
3884
+ }
3885
+ return {
3886
+ summary: parts.join(" "),
3887
+ commit: {
3888
+ sha: postState.headSha,
3889
+ branch: postState.branch,
3890
+ remote: postState.pushRemote,
3891
+ push_status: postState.pushStatus,
3892
+ messages: postState.commitMessages
3893
+ },
3894
+ files: {
3895
+ added: postState.filesAdded,
3896
+ modified: postState.filesModified,
3897
+ deleted: postState.filesDeleted,
3898
+ total_changed: totalChanged
3899
+ },
3900
+ stats: {
3901
+ lines_added: postState.linesAdded,
3902
+ lines_deleted: postState.linesDeleted,
3903
+ duration_seconds: durationSec
3904
+ },
3905
+ exit_code: exitCode
3906
+ };
3907
+ }
3908
+ function verifyGitRemote(cwd, task, gitHost) {
3909
+ if (!task.owner || !task.repo) return null;
3910
+ const expectedRemote = `https://${gitHost}/${task.owner}/${task.repo}.git`;
3911
+ const currentRemote = gitExec("git remote get-url origin", cwd);
3912
+ if (!currentRemote) {
3913
+ try {
3914
+ (0, import_node_child_process.execSync)(`git remote add origin ${expectedRemote}`, { cwd, timeout: 5e3 });
3915
+ } catch {
3916
+ }
3917
+ return { remoteName: "origin", remoteUrl: expectedRemote };
3918
+ }
3919
+ if (currentRemote === expectedRemote) {
3920
+ return { remoteName: "origin", remoteUrl: expectedRemote };
3921
+ }
3922
+ if (currentRemote.includes(gitHost)) {
3923
+ try {
3924
+ (0, import_node_child_process.execSync)(`git remote set-url origin ${expectedRemote}`, { cwd, timeout: 5e3 });
3925
+ } catch {
3926
+ }
3927
+ return { remoteName: "origin", remoteUrl: expectedRemote };
3928
+ }
3929
+ const cvRemote = gitExec("git remote get-url cv-hub", cwd);
3930
+ if (!cvRemote) {
3931
+ try {
3932
+ (0, import_node_child_process.execSync)(`git remote add cv-hub ${expectedRemote}`, { cwd, timeout: 5e3 });
3933
+ } catch {
3934
+ }
3935
+ } else if (cvRemote !== expectedRemote) {
3936
+ try {
3937
+ (0, import_node_child_process.execSync)(`git remote set-url cv-hub ${expectedRemote}`, { cwd, timeout: 5e3 });
3938
+ } catch {
3939
+ }
3940
+ }
3941
+ return { remoteName: "cv-hub", remoteUrl: expectedRemote };
3942
+ }
3943
+
3944
+ // src/utils/display.ts
3945
+ function formatDuration(ms) {
3946
+ const s = Math.floor(ms / 1e3);
3947
+ if (s < 60) return `${s}s`;
3948
+ const m = Math.floor(s / 60);
3949
+ const rem = s % 60;
3950
+ if (m < 60) return `${m}m ${rem}s`;
3951
+ const h = Math.floor(m / 60);
3952
+ return `${h}h ${m % 60}m`;
3953
+ }
3954
+ function setTerminalTitle(title) {
3955
+ if (process.stdout.isTTY) {
3956
+ process.stdout.write(`\x1B]0;${title}\x07`);
3957
+ }
3958
+ }
3959
+ function printBanner(status, elapsed, changedFiles, commitSha) {
3960
+ const color = status === "COMPLETED" ? source_default.green : status === "ABORTED" ? source_default.yellow : source_default.red;
3961
+ const icon = status === "COMPLETED" ? "\u2705" : status === "ABORTED" ? "\u23F9" : "\u274C";
3962
+ console.log(color("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"));
3963
+ console.log(color(`\u2502 ${icon} ${status.padEnd(57)}\u2502`));
3964
+ console.log(color(`\u2502 Duration: ${elapsed.padEnd(49)}\u2502`));
3965
+ if (changedFiles.length > 0) {
3966
+ const shown = changedFiles.slice(0, 3);
3967
+ const fileStr = shown.join(", ") + (changedFiles.length > 3 ? ` and ${changedFiles.length - 3} more` : "");
3968
+ console.log(color(`\u2502 Files: ${fileStr.substring(0, 51).padEnd(51)}\u2502`));
3969
+ }
3970
+ if (commitSha) {
3971
+ console.log(color(`\u2502 Commit: ${commitSha.substring(0, 8).padEnd(51)}\u2502`));
3972
+ }
3973
+ console.log(color("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"));
3974
+ }
3975
+ function updateStatusLine(idle, poll, completedCount, failedCount) {
3976
+ const line = `\r${source_default.cyan("\u{1F504}")} Listening... (${idle} idle) | Last poll: ${poll} ago | Completed: ${completedCount} | Failed: ${failedCount}`;
3977
+ process.stdout.write(`\r\x1B[K${line}`);
3978
+ }
3979
+
3980
+ // src/utils/retry.ts
3981
+ async function withRetry(fn, label, maxRetries = 3) {
3982
+ for (let i = 0; i < maxRetries; i++) {
3983
+ try {
3984
+ return await fn();
3985
+ } catch (err) {
3986
+ if (i === maxRetries - 1) throw err;
3987
+ const delay = (i + 1) * 5;
3988
+ console.log(`
3989
+ ${source_default.yellow("\u26A0")} ${label} failed, retrying in ${delay}s... (${err.message})`);
3990
+ await new Promise((r) => setTimeout(r, delay * 1e3));
3991
+ }
3992
+ }
3993
+ throw new Error("unreachable");
3994
+ }
3995
+
3996
+ // src/commands/agent.ts
3997
+ function buildClaudePrompt(task) {
3998
+ let prompt = "";
3999
+ prompt += `You are executing a task dispatched from Claude.ai via CV-Hub.
4000
+
4001
+ `;
4002
+ prompt += `## Task: ${task.title}
4003
+ `;
4004
+ prompt += `Task ID: ${task.id}
4005
+ `;
4006
+ prompt += `Priority: ${task.priority}
4007
+ `;
4008
+ if (task.branch) prompt += `Branch: ${task.branch}
4009
+ `;
4010
+ if (task.file_paths?.length) prompt += `Focus files: ${task.file_paths.join(", ")}
4011
+ `;
4012
+ prompt += `
4013
+ `;
4014
+ if (task.description) {
4015
+ prompt += task.description;
4016
+ } else if (task.input?.description) {
4017
+ prompt += task.input.description;
4018
+ }
4019
+ if (task.input?.context) {
4020
+ prompt += `
4021
+
4022
+ ## Context
4023
+ ${task.input.context}`;
4024
+ }
4025
+ if (task.input?.instructions?.length) {
4026
+ prompt += `
4027
+
4028
+ ## Instructions
4029
+ `;
4030
+ task.input.instructions.forEach((i, idx) => {
4031
+ prompt += `${idx + 1}. ${i}
4032
+ `;
4033
+ });
4034
+ }
4035
+ if (task.input?.constraints?.length) {
4036
+ prompt += `
4037
+
4038
+ ## Constraints
4039
+ `;
4040
+ task.input.constraints.forEach((c) => {
4041
+ prompt += `- ${c}
4042
+ `;
4043
+ });
4044
+ }
4045
+ if (task.owner && task.repo) {
4046
+ prompt += `
4047
+
4048
+ ## Git Remote Instructions
4049
+ `;
4050
+ prompt += `This repository has a \`cvhub\` remote pointing to CV-Hub.
4051
+ `;
4052
+ prompt += `When committing and pushing, push to the \`cvhub\` remote:
4053
+ `;
4054
+ prompt += ` git push cvhub <branch>
4055
+ `;
4056
+ prompt += `
4057
+ `;
4058
+ prompt += `IMPORTANT: Use only standard \`git\` commands. Do NOT use \`cv\`, \`cva\`, or \`cv-git\` commands.
4059
+ `;
4060
+ }
4061
+ prompt += `
4062
+
4063
+ ---
4064
+ `;
4065
+ prompt += `When complete, provide a brief summary of what you accomplished.
4066
+ `;
4067
+ return prompt;
4068
+ }
4069
+ var _activeChild = null;
4070
+ var _sigintCount = 0;
4071
+ var _sigintTimer = null;
4072
+ var _signalHandlerInstalled = false;
4073
+ function installSignalHandlers(getState, cleanup) {
4074
+ if (_signalHandlerInstalled) return;
4075
+ _signalHandlerInstalled = true;
4076
+ process.on("SIGINT", async () => {
4077
+ if (!_activeChild) {
4078
+ console.log("\n" + source_default.gray("Agent stopped."));
4079
+ await cleanup();
4080
+ process.exit(0);
4081
+ }
4082
+ _sigintCount++;
4083
+ if (_sigintCount === 1) {
4084
+ console.log(`
4085
+ ${source_default.yellow("!")} Press Ctrl+C again within 3s to abort task.`);
4086
+ _sigintTimer = setTimeout(() => {
4087
+ _sigintCount = 0;
4088
+ }, 3e3);
4089
+ return;
4090
+ }
4091
+ if (_sigintTimer) clearTimeout(_sigintTimer);
4092
+ console.log(`
4093
+ ${source_default.red("X")} Aborting task...`);
4094
+ try {
4095
+ _activeChild.kill("SIGKILL");
4096
+ } catch {
4097
+ }
4098
+ _activeChild = null;
4099
+ _sigintCount = 0;
4100
+ });
4101
+ process.on("SIGTERM", async () => {
4102
+ console.log(`
4103
+ ${source_default.gray("Received SIGTERM, shutting down...")}`);
4104
+ if (_activeChild) {
4105
+ try {
4106
+ _activeChild.kill("SIGKILL");
4107
+ } catch {
4108
+ }
4109
+ _activeChild = null;
4110
+ }
4111
+ await cleanup();
4112
+ process.exit(0);
4113
+ });
4114
+ }
4115
+ var ALLOWED_TOOLS = [
4116
+ "Bash(*)",
4117
+ "Read(*)",
4118
+ "Write(*)",
4119
+ "Edit(*)",
4120
+ "Glob(*)",
4121
+ "Grep(*)",
4122
+ "WebFetch(*)",
4123
+ "WebSearch(*)",
4124
+ "NotebookEdit(*)",
4125
+ "TodoWrite(*)"
4126
+ ];
4127
+ var PERMISSION_PATTERNS = [
4128
+ /Allow .+ to .+\? \(y\/n\)/,
4129
+ /Do you want to proceed\? \(y\/n\)/,
4130
+ /\? \(y\/n\)/
4131
+ ];
4132
+ async function launchAutoApproveMode(prompt, options) {
4133
+ return new Promise((resolve, reject) => {
4134
+ const args = ["-p", prompt, "--allowedTools", ...ALLOWED_TOOLS];
4135
+ const child = (0, import_node_child_process2.spawn)("claude", args, {
4136
+ cwd: options.cwd,
4137
+ stdio: ["inherit", "inherit", "pipe"],
4138
+ env: { ...process.env }
4139
+ });
4140
+ _activeChild = child;
4141
+ let stderr = "";
4142
+ child.stderr?.on("data", (data) => {
4143
+ const text = data.toString();
4144
+ stderr += text;
4145
+ process.stderr.write(data);
4146
+ });
4147
+ child.on("close", (code, signal) => {
4148
+ _activeChild = null;
4149
+ if (signal === "SIGKILL") {
4150
+ resolve({ exitCode: 137, stderr });
4151
+ } else {
4152
+ resolve({ exitCode: code ?? 1, stderr });
4153
+ }
4154
+ });
4155
+ child.on("error", (err) => {
4156
+ _activeChild = null;
4157
+ reject(err);
4158
+ });
4159
+ });
4160
+ }
4161
+ async function launchRelayMode(prompt, options) {
4162
+ return new Promise((resolve, reject) => {
4163
+ const child = (0, import_node_child_process2.spawn)("claude", [], {
4164
+ cwd: options.cwd,
4165
+ stdio: ["pipe", "pipe", "pipe"],
4166
+ env: { ...process.env }
4167
+ });
4168
+ _activeChild = child;
4169
+ let stderr = "";
4170
+ let stdoutBuffer = "";
4171
+ child.stdin?.write(prompt + "\n");
4172
+ child.stdout?.on("data", async (data) => {
4173
+ const text = data.toString();
4174
+ process.stdout.write(data);
4175
+ stdoutBuffer += text;
4176
+ for (const pattern of PERMISSION_PATTERNS) {
4177
+ const match = stdoutBuffer.match(pattern);
4178
+ if (match) {
4179
+ const promptText = match[0];
4180
+ stdoutBuffer = "";
4181
+ try {
4182
+ await sendTaskLog(
4183
+ options.creds,
4184
+ options.executorId,
4185
+ options.taskId,
4186
+ "info",
4187
+ `Permission prompt: ${promptText}`,
4188
+ { prompt_text: promptText }
4189
+ );
4190
+ const { prompt_id } = await createTaskPrompt(
4191
+ options.creds,
4192
+ options.executorId,
4193
+ options.taskId,
4194
+ promptText,
4195
+ "approval",
4196
+ ["y", "n"]
4197
+ );
4198
+ const timeoutMs = 5 * 60 * 1e3;
4199
+ const startPoll = Date.now();
4200
+ let answered = false;
4201
+ while (Date.now() - startPoll < timeoutMs) {
4202
+ await new Promise((r) => setTimeout(r, 2e3));
4203
+ try {
4204
+ const { response } = await pollPromptResponse(
4205
+ options.creds,
4206
+ options.executorId,
4207
+ options.taskId,
4208
+ prompt_id
4209
+ );
4210
+ if (response !== null) {
4211
+ const answer = response.toLowerCase().startsWith("y") ? "y" : "n";
4212
+ child.stdin?.write(answer + "\n");
4213
+ answered = true;
4214
+ console.log(source_default.gray(` [relay] User responded: ${answer}`));
4215
+ break;
4216
+ }
4217
+ } catch {
4218
+ }
4219
+ }
4220
+ if (!answered) {
4221
+ child.stdin?.write("n\n");
4222
+ console.log(source_default.yellow(` [relay] Prompt timed out, denying.`));
4223
+ }
4224
+ } catch (err) {
4225
+ child.stdin?.write("n\n");
4226
+ console.log(source_default.yellow(` [relay] Prompt relay error: ${err.message}, denying.`));
4227
+ }
4228
+ break;
4229
+ }
4230
+ }
4231
+ if (stdoutBuffer.length > 2048) {
4232
+ stdoutBuffer = stdoutBuffer.slice(-1024);
4233
+ }
4234
+ });
4235
+ child.stderr?.on("data", (data) => {
4236
+ const text = data.toString();
4237
+ stderr += text;
4238
+ process.stderr.write(data);
4239
+ });
4240
+ child.on("close", (code, signal) => {
4241
+ _activeChild = null;
4242
+ if (signal === "SIGKILL") {
4243
+ resolve({ exitCode: 137, stderr });
4244
+ } else {
4245
+ resolve({ exitCode: code ?? 1, stderr });
4246
+ }
4247
+ });
4248
+ child.on("error", (err) => {
4249
+ _activeChild = null;
4250
+ reject(err);
4251
+ });
4252
+ });
4253
+ }
4254
+ async function runAgent(options) {
4255
+ const creds = await readCredentials();
4256
+ if (!creds.CV_HUB_API) {
4257
+ creds.CV_HUB_API = "https://api.hub.controlvector.io";
4258
+ }
4259
+ if (!creds.CV_HUB_PAT) {
4260
+ console.log();
4261
+ console.log(source_default.red("Not authenticated.") + " Run " + source_default.cyan("cva auth login") + " first.");
4262
+ console.log();
4263
+ console.log(source_default.bold("Quick setup:"));
4264
+ console.log(` ${source_default.cyan("cva auth login")} # Authenticate`);
4265
+ console.log(` ${source_default.cyan("cd ~/project/my-project")} # Go to your project`);
4266
+ console.log(` ${source_default.cyan("cva agent")} # Start listening`);
4267
+ console.log();
4268
+ process.exit(1);
4269
+ }
4270
+ try {
4271
+ (0, import_node_child_process2.execSync)("claude --version", { stdio: "pipe", timeout: 5e3 });
4272
+ } catch {
4273
+ console.log();
4274
+ console.log(source_default.red("Claude Code CLI not found.") + " Install it first:");
4275
+ console.log(` ${source_default.cyan("npm install -g @anthropic-ai/claude-code")}`);
4276
+ console.log();
4277
+ process.exit(1);
4278
+ }
4279
+ const machineName = options.machine || await getMachineName();
4280
+ const pollInterval = Math.max(3, parseInt(options.pollInterval, 10)) * 1e3;
4281
+ const workingDir = options.workingDir;
4282
+ if (!options.machine) {
4283
+ const credCheck = await readCredentials();
4284
+ if (!credCheck.CV_HUB_MACHINE_NAME) {
4285
+ console.log();
4286
+ console.log(source_default.yellow("!") + ` No machine name set. Registering as "${source_default.bold(machineName)}".`);
4287
+ console.log(source_default.gray(` Use --machine <name> to override.`));
4288
+ console.log();
4289
+ }
4290
+ }
4291
+ const executor = await withRetry(
4292
+ () => registerExecutor(creds, machineName, workingDir),
4293
+ "Executor registration"
4294
+ );
4295
+ const mode = options.autoApprove ? "auto-approve" : "relay";
4296
+ console.log();
4297
+ console.log(source_default.bold("CVA \u2014 CV-Hub Agent"));
4298
+ console.log(` Machine: ${source_default.cyan(machineName)}`);
4299
+ console.log(` Executor: ${source_default.gray(executor.id)}`);
4300
+ console.log(` API: ${source_default.gray(creds.CV_HUB_API)}`);
4301
+ console.log(` Dir: ${source_default.gray(workingDir)}`);
4302
+ console.log(` Polling: every ${options.pollInterval}s`);
4303
+ console.log(` Mode: ${source_default.cyan(mode)}`);
4304
+ console.log(` Ctrl+C to stop`);
4305
+ console.log();
4306
+ console.log(source_default.cyan("Listening for tasks..."));
4307
+ console.log();
4308
+ const state = {
4309
+ executorId: executor.id,
4310
+ currentTaskId: null,
4311
+ completedCount: 0,
4312
+ failedCount: 0,
4313
+ lastPoll: Date.now(),
4314
+ lastTaskEnd: Date.now(),
4315
+ running: true
4316
+ };
4317
+ installSignalHandlers(
4318
+ () => state,
4319
+ async () => {
4320
+ state.running = false;
4321
+ await markOffline(creds, state.executorId);
4322
+ }
4323
+ );
4324
+ while (state.running) {
4325
+ try {
4326
+ const task = await withRetry(
4327
+ () => pollForTask(creds, state.executorId),
4328
+ "Task poll"
4329
+ );
4330
+ state.lastPoll = Date.now();
4331
+ if (task) {
4332
+ await executeTask(task, state, creds, options);
4333
+ } else {
4334
+ updateStatusLine(
4335
+ formatDuration(Date.now() - state.lastTaskEnd),
4336
+ formatDuration(Date.now() - state.lastPoll),
4337
+ state.completedCount,
4338
+ state.failedCount
4339
+ );
4340
+ }
4341
+ } catch (err) {
4342
+ console.log(`
4343
+ ${source_default.red("!")} Error: ${err.message}`);
4344
+ }
4345
+ await new Promise((r) => setTimeout(r, pollInterval));
4346
+ }
4347
+ }
4348
+ async function executeTask(task, state, creds, options) {
4349
+ const startTime = Date.now();
4350
+ state.currentTaskId = task.id;
4351
+ process.stdout.write("\r\x1B[K");
4352
+ console.log(source_default.bold("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"));
4353
+ console.log(source_default.bold(`\u2502 Task: ${(task.title || "").substring(0, 53).padEnd(53)}\u2502`));
4354
+ console.log(source_default.bold(`\u2502 ID: ${task.id.padEnd(55)}\u2502`));
4355
+ console.log(source_default.bold(`\u2502 Priority: ${task.priority.padEnd(49)}\u2502`));
4356
+ console.log(source_default.bold("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"));
4357
+ console.log();
4358
+ try {
4359
+ await startTask(creds, state.executorId, task.id);
4360
+ setTerminalTitle(`cva: ${task.title} (starting...)`);
4361
+ sendTaskLog(creds, state.executorId, task.id, "lifecycle", "Task started, launching Claude Code");
4362
+ } catch (err) {
4363
+ console.log(source_default.red(`Failed to start task: ${err.message}`));
4364
+ state.currentTaskId = null;
4365
+ return;
4366
+ }
4367
+ const heartbeatTimer = setInterval(async () => {
4368
+ try {
4369
+ const elapsed = formatDuration(Date.now() - startTime);
4370
+ setTerminalTitle(`cva: ${task.title} (${elapsed})`);
4371
+ await sendHeartbeat(creds, state.executorId, task.id, `Claude Code running (${elapsed} elapsed)`);
4372
+ } catch {
4373
+ }
4374
+ }, 3e4);
4375
+ let timeoutTimer;
4376
+ if (task.timeout_at) {
4377
+ const timeoutMs = new Date(task.timeout_at).getTime() - Date.now();
4378
+ if (timeoutMs > 0) {
4379
+ timeoutTimer = setTimeout(() => {
4380
+ console.log(`
4381
+ ${source_default.red("Timeout")} Task timed out after ${formatDuration(timeoutMs)}`);
4382
+ }, timeoutMs);
4383
+ }
4384
+ }
4385
+ const preGitState = capturePreTaskState(options.workingDir);
4386
+ const gitHost = (creds.CV_HUB_API || "https://api.hub.controlvector.io").replace(/^https?:\/\//, "").replace(/^api\./, "git.");
4387
+ const remoteInfo = verifyGitRemote(options.workingDir, task, gitHost);
4388
+ if (remoteInfo) {
4389
+ console.log(source_default.gray(` Git remote: ${remoteInfo.remoteName} -> ${remoteInfo.remoteUrl}`));
4390
+ }
4391
+ const prompt = buildClaudePrompt(task);
4392
+ try {
4393
+ const mode = options.autoApprove ? "auto-approve" : "relay";
4394
+ console.log(source_default.cyan("Launching Claude Code") + ` (${mode} mode)...`);
4395
+ if (options.autoApprove) {
4396
+ console.log(source_default.gray(" Allowed tools: ") + ALLOWED_TOOLS.join(", "));
4397
+ }
4398
+ console.log(source_default.gray("-".repeat(60)));
4399
+ let result;
4400
+ if (options.autoApprove) {
4401
+ result = await launchAutoApproveMode(prompt, { cwd: options.workingDir });
4402
+ } else {
4403
+ result = await launchRelayMode(prompt, {
4404
+ cwd: options.workingDir,
4405
+ creds,
4406
+ executorId: state.executorId,
4407
+ taskId: task.id
4408
+ });
4409
+ }
4410
+ console.log(source_default.gray("\n" + "-".repeat(60)));
4411
+ const postGitState = capturePostTaskState(options.workingDir, preGitState);
4412
+ const payload = buildCompletionPayload(result.exitCode, preGitState, postGitState, startTime);
4413
+ const elapsed = formatDuration(Date.now() - startTime);
4414
+ const allChangedFiles = [
4415
+ ...postGitState.filesAdded,
4416
+ ...postGitState.filesModified,
4417
+ ...postGitState.filesDeleted
4418
+ ];
4419
+ if (result.exitCode === 0) {
4420
+ if (allChangedFiles.length > 0) {
4421
+ sendTaskLog(
4422
+ creds,
4423
+ state.executorId,
4424
+ task.id,
4425
+ "git",
4426
+ `${allChangedFiles.length} file(s) changed (+${postGitState.linesAdded}/-${postGitState.linesDeleted})`,
4427
+ { added: postGitState.filesAdded.slice(0, 10), modified: postGitState.filesModified.slice(0, 10), deleted: postGitState.filesDeleted.slice(0, 10) }
4428
+ );
4429
+ }
4430
+ sendTaskLog(
4431
+ creds,
4432
+ state.executorId,
4433
+ task.id,
4434
+ "lifecycle",
4435
+ `Claude Code completed successfully (${elapsed})`,
4436
+ void 0,
4437
+ 100
4438
+ );
4439
+ console.log();
4440
+ printBanner("COMPLETED", elapsed, allChangedFiles, postGitState.headSha);
4441
+ await withRetry(
4442
+ () => completeTask(creds, state.executorId, task.id, payload),
4443
+ "Report completion"
4444
+ );
4445
+ state.completedCount++;
4446
+ console.log(source_default.gray(" Reported to CV-Hub."));
4447
+ } else if (result.exitCode === 137) {
4448
+ sendTaskLog(
4449
+ creds,
4450
+ state.executorId,
4451
+ task.id,
4452
+ "lifecycle",
4453
+ "Task aborted by user (Ctrl+C)"
4454
+ );
4455
+ console.log();
4456
+ printBanner("ABORTED", elapsed, [], null);
4457
+ try {
4458
+ await failTask(creds, state.executorId, task.id, "Aborted by user (Ctrl+C)");
4459
+ } catch {
4460
+ }
4461
+ state.failedCount++;
4462
+ } else {
4463
+ const stderrTail = result.stderr.trim().slice(-500);
4464
+ sendTaskLog(
4465
+ creds,
4466
+ state.executorId,
4467
+ task.id,
4468
+ "lifecycle",
4469
+ `Claude Code exited with code ${result.exitCode} (${elapsed})`,
4470
+ stderrTail ? { stderr_tail: stderrTail } : void 0
4471
+ );
4472
+ console.log();
4473
+ printBanner("FAILED", elapsed, allChangedFiles, postGitState.headSha);
4474
+ const errorDetail = result.stderr.trim() ? `${result.stderr.trim().slice(-1500)}
4475
+
4476
+ Exit code ${result.exitCode} after ${elapsed}.` : `Claude Code exited with code ${result.exitCode} after ${elapsed}.`;
4477
+ await withRetry(
4478
+ () => failTask(creds, state.executorId, task.id, errorDetail),
4479
+ "Report failure"
4480
+ );
4481
+ state.failedCount++;
4482
+ }
4483
+ } catch (err) {
4484
+ console.log(`
4485
+ ${source_default.red("!")} Task error: ${err.message}`);
4486
+ sendTaskLog(
4487
+ creds,
4488
+ state.executorId,
4489
+ task.id,
4490
+ "error",
4491
+ `Agent error: ${err.message}`
4492
+ );
4493
+ try {
4494
+ await failTask(creds, state.executorId, task.id, err.message);
4495
+ } catch {
4496
+ }
4497
+ state.failedCount++;
4498
+ } finally {
4499
+ clearInterval(heartbeatTimer);
4500
+ if (timeoutTimer) clearTimeout(timeoutTimer);
4501
+ state.currentTaskId = null;
4502
+ state.lastTaskEnd = Date.now();
4503
+ }
4504
+ setTerminalTitle("cva: listening...");
4505
+ console.log();
4506
+ console.log(source_default.cyan("Listening for tasks..."));
4507
+ console.log();
4508
+ }
4509
+ function agentCommand() {
4510
+ const cmd = new Command("agent");
4511
+ cmd.description("Listen for tasks dispatched from Claude.ai and execute them with Claude Code");
4512
+ cmd.option("--machine <name>", "Machine name override");
4513
+ cmd.option("--poll-interval <seconds>", "How often to check for tasks", "5");
4514
+ cmd.option("--working-dir <path>", "Working directory for Claude Code", process.cwd());
4515
+ cmd.option("--auto-approve", "Pre-approve all tool permissions (uses -p mode)", false);
4516
+ cmd.action(async (opts) => {
4517
+ await runAgent(opts);
4518
+ });
4519
+ return cmd;
4520
+ }
4521
+
4522
+ // src/commands/auth.ts
4523
+ async function authLogin(opts) {
4524
+ const token = opts.token || await promptForToken();
4525
+ const apiUrl = opts.apiUrl || "https://api.hub.controlvector.io";
4526
+ console.log(source_default.gray("Validating token..."));
4527
+ try {
4528
+ const res = await fetch(`${apiUrl}/api/v1/user/me`, {
4529
+ headers: { "Authorization": `Bearer ${token}` }
4530
+ });
4531
+ if (!res.ok) {
4532
+ console.log(source_default.red("Invalid token.") + ` API returned ${res.status}`);
4533
+ process.exit(1);
4534
+ }
4535
+ const data = await res.json();
4536
+ const username = data.user?.username || data.user?.email || "unknown";
4537
+ await writeCredentialField("CV_HUB_PAT", token);
4538
+ await writeCredentialField("CV_HUB_API", apiUrl);
4539
+ console.log(source_default.green("Authenticated") + ` as ${source_default.bold(username)}`);
4540
+ console.log(source_default.gray(`Token saved to ~/.config/cv-hub/credentials`));
4541
+ } catch (err) {
4542
+ console.log(source_default.red("Connection failed:") + ` ${err.message}`);
4543
+ process.exit(1);
4544
+ }
4545
+ }
4546
+ async function promptForToken() {
4547
+ const readline = await import("node:readline");
4548
+ const rl = readline.createInterface({
4549
+ input: process.stdin,
4550
+ output: process.stdout
4551
+ });
4552
+ return new Promise((resolve) => {
4553
+ rl.question("Enter your CV-Hub PAT token: ", (answer) => {
4554
+ rl.close();
4555
+ const token = answer.trim();
4556
+ if (!token) {
4557
+ console.log(source_default.red("No token provided."));
4558
+ process.exit(1);
4559
+ }
4560
+ resolve(token);
4561
+ });
4562
+ });
4563
+ }
4564
+ async function authStatus() {
4565
+ const creds = await readCredentials();
4566
+ if (!creds.CV_HUB_PAT) {
4567
+ console.log(source_default.yellow("Not authenticated.") + " Run " + source_default.cyan("cva auth login") + " first.");
4568
+ return;
4569
+ }
4570
+ const apiUrl = creds.CV_HUB_API || "https://api.hub.controlvector.io";
4571
+ const maskedToken = creds.CV_HUB_PAT.substring(0, 8) + "..." + creds.CV_HUB_PAT.slice(-4);
4572
+ console.log(`API: ${source_default.cyan(apiUrl)}`);
4573
+ console.log(`Token: ${source_default.gray(maskedToken)}`);
4574
+ try {
4575
+ const res = await fetch(`${apiUrl}/api/v1/user/me`, {
4576
+ headers: { "Authorization": `Bearer ${creds.CV_HUB_PAT}` }
4577
+ });
4578
+ if (res.ok) {
4579
+ const data = await res.json();
4580
+ const username = data.user?.username || data.user?.email || "unknown";
4581
+ console.log(`User: ${source_default.green(username)}`);
4582
+ console.log(`Status: ${source_default.green("valid")}`);
4583
+ } else {
4584
+ console.log(`Status: ${source_default.red("invalid")} (${res.status})`);
4585
+ }
4586
+ } catch (err) {
4587
+ console.log(`Status: ${source_default.red("unreachable")} (${err.message})`);
4588
+ }
4589
+ }
4590
+ function authCommand() {
4591
+ const cmd = new Command("auth");
4592
+ cmd.description("Manage CV-Hub authentication");
4593
+ cmd.command("login").description("Authenticate with CV-Hub using a PAT token").option("--token <token>", "PAT token (or enter interactively)").option("--api-url <url>", "CV-Hub API URL", "https://api.hub.controlvector.io").action(authLogin);
4594
+ cmd.command("status").description("Show current authentication status").action(authStatus);
4595
+ return cmd;
4596
+ }
4597
+
4598
+ // src/commands/remote.ts
4599
+ var import_node_child_process3 = require("node:child_process");
4600
+ function getGitHost(apiUrl) {
4601
+ return apiUrl.replace(/^https?:\/\//, "").replace(/^api\./, "git.");
4602
+ }
4603
+ async function remoteAdd(ownerRepo) {
4604
+ const creds = await readCredentials();
4605
+ const apiUrl = creds.CV_HUB_API || "https://api.hub.controlvector.io";
4606
+ const gitHost = getGitHost(apiUrl);
4607
+ const [owner, repo] = ownerRepo.split("/");
4608
+ if (!owner || !repo) {
4609
+ console.log(source_default.red("Invalid format.") + " Use: cva remote add <owner>/<repo>");
4610
+ process.exit(1);
4611
+ }
4612
+ const remoteUrl = `https://${gitHost}/${owner}/${repo}.git`;
4613
+ try {
4614
+ const existing = (0, import_node_child_process3.execSync)("git remote get-url cvhub", { encoding: "utf-8", timeout: 5e3 }).trim();
4615
+ if (existing === remoteUrl) {
4616
+ console.log(source_default.gray(`Remote 'cvhub' already set to ${remoteUrl}`));
4617
+ return;
4618
+ }
4619
+ (0, import_node_child_process3.execSync)(`git remote set-url cvhub ${remoteUrl}`, { timeout: 5e3 });
4620
+ console.log(source_default.green("Updated") + ` remote 'cvhub' -> ${remoteUrl}`);
4621
+ } catch {
4622
+ try {
4623
+ (0, import_node_child_process3.execSync)(`git remote add cvhub ${remoteUrl}`, { timeout: 5e3 });
4624
+ console.log(source_default.green("Added") + ` remote 'cvhub' -> ${remoteUrl}`);
4625
+ } catch (err) {
4626
+ console.log(source_default.red("Failed to add remote:") + ` ${err.message}`);
4627
+ process.exit(1);
4628
+ }
4629
+ }
4630
+ }
4631
+ async function remoteSetup(ownerRepo) {
4632
+ const creds = await readCredentials();
4633
+ if (!creds.CV_HUB_PAT) {
4634
+ console.log(source_default.red("Not authenticated.") + " Run " + source_default.cyan("cva auth login") + " first.");
4635
+ process.exit(1);
4636
+ }
4637
+ if (!creds.CV_HUB_API) {
4638
+ creds.CV_HUB_API = "https://api.hub.controlvector.io";
4639
+ }
4640
+ const [owner, repo] = ownerRepo.split("/");
4641
+ if (!owner || !repo) {
4642
+ console.log(source_default.red("Invalid format.") + " Use: cva remote setup <owner>/<repo>");
4643
+ process.exit(1);
4644
+ }
4645
+ console.log(source_default.gray(`Creating repository ${ownerRepo} on CV-Hub...`));
4646
+ try {
4647
+ await createRepo(creds, repo);
4648
+ console.log(source_default.green("Created") + ` repository ${ownerRepo}`);
4649
+ } catch (err) {
4650
+ if (err.message.includes("409") || err.message.includes("already exists")) {
4651
+ console.log(source_default.gray(`Repository ${ownerRepo} already exists.`));
4652
+ } else {
4653
+ console.log(source_default.red("Failed to create repo:") + ` ${err.message}`);
4654
+ process.exit(1);
4655
+ }
4656
+ }
4657
+ await remoteAdd(ownerRepo);
4658
+ }
4659
+ function remoteCommand() {
4660
+ const cmd = new Command("remote");
4661
+ cmd.description("Manage CV-Hub git remotes");
4662
+ cmd.command("add <owner/repo>").description("Add cvhub remote to current git repo").action(remoteAdd);
4663
+ cmd.command("setup <owner/repo>").description("Create repo on CV-Hub and add cvhub remote").action(remoteSetup);
4664
+ return cmd;
4665
+ }
4666
+
4667
+ // src/commands/task.ts
4668
+ async function taskList(opts) {
4669
+ const creds = await readCredentials();
4670
+ if (!creds.CV_HUB_PAT) {
4671
+ console.log(source_default.red("Not authenticated.") + " Run " + source_default.cyan("cva auth login") + " first.");
4672
+ process.exit(1);
4673
+ }
4674
+ if (!creds.CV_HUB_API) creds.CV_HUB_API = "https://api.hub.controlvector.io";
4675
+ try {
4676
+ const tasks = await listTasks(creds, opts.status);
4677
+ if (tasks.length === 0) {
4678
+ console.log(source_default.gray("No tasks found."));
4679
+ return;
4680
+ }
4681
+ const statusColors = {
4682
+ pending: source_default.yellow,
4683
+ assigned: source_default.blue,
4684
+ running: source_default.cyan,
4685
+ completed: source_default.green,
4686
+ failed: source_default.red,
4687
+ cancelled: source_default.gray,
4688
+ waiting_for_input: source_default.magenta
4689
+ };
4690
+ for (const t of tasks) {
4691
+ const colorFn = statusColors[t.status] || source_default.white;
4692
+ const status = colorFn(t.status.padEnd(18));
4693
+ const title = (t.title || "").substring(0, 50);
4694
+ const id = source_default.gray(t.id.substring(0, 8));
4695
+ const age = t.created_at ? source_default.gray(timeSince(new Date(t.created_at))) : "";
4696
+ console.log(`${id} ${status} ${title} ${age}`);
4697
+ }
4698
+ console.log(source_default.gray(`
4699
+ ${tasks.length} task(s)`));
4700
+ } catch (err) {
4701
+ console.log(source_default.red("Failed:") + ` ${err.message}`);
4702
+ process.exit(1);
4703
+ }
4704
+ }
4705
+ async function taskLogs(taskId) {
4706
+ const creds = await readCredentials();
4707
+ if (!creds.CV_HUB_PAT) {
4708
+ console.log(source_default.red("Not authenticated.") + " Run " + source_default.cyan("cva auth login") + " first.");
4709
+ process.exit(1);
4710
+ }
4711
+ if (!creds.CV_HUB_API) creds.CV_HUB_API = "https://api.hub.controlvector.io";
4712
+ try {
4713
+ const logs = await getTaskLogs(creds, taskId);
4714
+ if (logs.length === 0) {
4715
+ console.log(source_default.gray("No logs found. Showing task detail:"));
4716
+ const task = await getTask(creds, taskId);
4717
+ console.log(JSON.stringify(task, null, 2));
4718
+ return;
4719
+ }
4720
+ const typeColors = {
4721
+ lifecycle: source_default.blue,
4722
+ heartbeat: source_default.gray,
4723
+ progress: source_default.cyan,
4724
+ git: source_default.green,
4725
+ error: source_default.red,
4726
+ info: source_default.white
4727
+ };
4728
+ for (const log of logs) {
4729
+ const colorFn = typeColors[log.log_type] || source_default.white;
4730
+ const type = colorFn(`[${log.log_type}]`.padEnd(14));
4731
+ const time = source_default.gray(new Date(log.created_at).toLocaleTimeString());
4732
+ const pct = log.progress_pct !== null && log.progress_pct !== void 0 ? source_default.yellow(` ${log.progress_pct}%`) : "";
4733
+ console.log(`${time} ${type} ${log.message}${pct}`);
4734
+ }
4735
+ } catch (err) {
4736
+ console.log(source_default.red("Failed:") + ` ${err.message}`);
4737
+ process.exit(1);
4738
+ }
4739
+ }
4740
+ function timeSince(date) {
4741
+ const seconds = Math.floor((Date.now() - date.getTime()) / 1e3);
4742
+ if (seconds < 60) return `${seconds}s ago`;
4743
+ const minutes = Math.floor(seconds / 60);
4744
+ if (minutes < 60) return `${minutes}m ago`;
4745
+ const hours = Math.floor(minutes / 60);
4746
+ if (hours < 24) return `${hours}h ago`;
4747
+ const days = Math.floor(hours / 24);
4748
+ return `${days}d ago`;
4749
+ }
4750
+ function taskCommand() {
4751
+ const cmd = new Command("task");
4752
+ cmd.description("View tasks and task logs");
4753
+ cmd.command("list").description("List tasks").option("--status <status>", "Filter by status (e.g. running,completed)").action(taskList);
4754
+ cmd.command("logs <taskId>").description("View logs for a task").action(taskLogs);
4755
+ return cmd;
4756
+ }
4757
+
4758
+ // src/commands/status.ts
4759
+ async function showStatus() {
4760
+ const creds = await readCredentials();
4761
+ if (!creds.CV_HUB_PAT) {
4762
+ console.log(source_default.red("Not authenticated.") + " Run " + source_default.cyan("cva auth login") + " first.");
4763
+ process.exit(1);
4764
+ }
4765
+ if (!creds.CV_HUB_API) creds.CV_HUB_API = "https://api.hub.controlvector.io";
4766
+ try {
4767
+ const executors = await listExecutors(creds);
4768
+ if (executors.length === 0) {
4769
+ console.log(source_default.gray("No executors registered."));
4770
+ return;
4771
+ }
4772
+ const statusColors = {
4773
+ online: source_default.green,
4774
+ offline: source_default.gray,
4775
+ busy: source_default.yellow,
4776
+ error: source_default.red
4777
+ };
4778
+ console.log(source_default.bold("Executors:"));
4779
+ console.log();
4780
+ for (const e of executors) {
4781
+ const colorFn = statusColors[e.status] || source_default.white;
4782
+ const status = colorFn(e.status.padEnd(10));
4783
+ const name = source_default.cyan(e.name || e.machine_name || "unknown");
4784
+ const id = source_default.gray(e.id.substring(0, 8));
4785
+ const heartbeat = e.last_heartbeat_at ? source_default.gray(`last seen ${timeSince2(new Date(e.last_heartbeat_at))}`) : source_default.gray("never");
4786
+ const workspace = e.workspace_root ? source_default.gray(` | ${e.workspace_root}`) : "";
4787
+ console.log(` ${id} ${status} ${name} ${heartbeat}${workspace}`);
4788
+ }
4789
+ console.log(source_default.gray(`
4790
+ ${executors.length} executor(s)`));
4791
+ } catch (err) {
4792
+ console.log(source_default.red("Failed:") + ` ${err.message}`);
4793
+ process.exit(1);
4794
+ }
4795
+ }
4796
+ function timeSince2(date) {
4797
+ const seconds = Math.floor((Date.now() - date.getTime()) / 1e3);
4798
+ if (seconds < 60) return `${seconds}s ago`;
4799
+ const minutes = Math.floor(seconds / 60);
4800
+ if (minutes < 60) return `${minutes}m ago`;
4801
+ const hours = Math.floor(minutes / 60);
4802
+ if (hours < 24) return `${hours}h ago`;
4803
+ const days = Math.floor(hours / 24);
4804
+ return `${days}d ago`;
4805
+ }
4806
+ function statusCommand() {
4807
+ const cmd = new Command("status");
4808
+ cmd.description("Show registered executors and their status");
4809
+ cmd.action(showStatus);
4810
+ return cmd;
4811
+ }
4812
+
4813
+ // src/index.ts
4814
+ var program2 = new Command();
4815
+ program2.name("cva").description("CV-Hub Agent \u2014 bridges Claude Code with CV-Hub task dispatch").version("0.1.0");
4816
+ program2.addCommand(agentCommand());
4817
+ program2.addCommand(authCommand());
4818
+ program2.addCommand(remoteCommand());
4819
+ program2.addCommand(taskCommand());
4820
+ program2.addCommand(statusCommand());
4821
+ program2.parse(process.argv);
4822
+ //# sourceMappingURL=bundle.cjs.map