@caddis/cli 0.4.75 → 0.4.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -51,8 +51,8 @@ var require_error = __commonJS({
51
51
  * @param {string} code an id string representing the error
52
52
  * @param {string} message human-readable description of the error
53
53
  */
54
- constructor(exitCode, code, message) {
55
- super(message);
54
+ constructor(exitCode, code, message3) {
55
+ super(message3);
56
56
  Error.captureStackTrace(this, this.constructor);
57
57
  this.name = this.constructor.name;
58
58
  this.code = code;
@@ -65,8 +65,8 @@ var require_error = __commonJS({
65
65
  * Constructs the InvalidArgumentError class
66
66
  * @param {string} [message] explanation of why argument is invalid
67
67
  */
68
- constructor(message) {
69
- super(1, "commander.invalidArgument", message);
68
+ constructor(message3) {
69
+ super(1, "commander.invalidArgument", message3);
70
70
  Error.captureStackTrace(this, this.constructor);
71
71
  this.name = this.constructor.name;
72
72
  }
@@ -639,8 +639,8 @@ var require_help = __commonJS({
639
639
  * @param {string} str
640
640
  * @returns {number}
641
641
  */
642
- displayWidth(str) {
643
- return stripColor(str).length;
642
+ displayWidth(str3) {
643
+ return stripColor(str3).length;
644
644
  }
645
645
  /**
646
646
  * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
@@ -648,11 +648,11 @@ var require_help = __commonJS({
648
648
  * @param {string} str
649
649
  * @returns {string}
650
650
  */
651
- styleTitle(str) {
652
- return str;
651
+ styleTitle(str3) {
652
+ return str3;
653
653
  }
654
- styleUsage(str) {
655
- return str.split(" ").map((word) => {
654
+ styleUsage(str3) {
655
+ return str3.split(" ").map((word) => {
656
656
  if (word === "[options]") return this.styleOptionText(word);
657
657
  if (word === "[command]") return this.styleSubcommandText(word);
658
658
  if (word[0] === "[" || word[0] === "<")
@@ -660,46 +660,46 @@ var require_help = __commonJS({
660
660
  return this.styleCommandText(word);
661
661
  }).join(" ");
662
662
  }
663
- styleCommandDescription(str) {
664
- return this.styleDescriptionText(str);
663
+ styleCommandDescription(str3) {
664
+ return this.styleDescriptionText(str3);
665
665
  }
666
- styleOptionDescription(str) {
667
- return this.styleDescriptionText(str);
666
+ styleOptionDescription(str3) {
667
+ return this.styleDescriptionText(str3);
668
668
  }
669
- styleSubcommandDescription(str) {
670
- return this.styleDescriptionText(str);
669
+ styleSubcommandDescription(str3) {
670
+ return this.styleDescriptionText(str3);
671
671
  }
672
- styleArgumentDescription(str) {
673
- return this.styleDescriptionText(str);
672
+ styleArgumentDescription(str3) {
673
+ return this.styleDescriptionText(str3);
674
674
  }
675
- styleDescriptionText(str) {
676
- return str;
675
+ styleDescriptionText(str3) {
676
+ return str3;
677
677
  }
678
- styleOptionTerm(str) {
679
- return this.styleOptionText(str);
678
+ styleOptionTerm(str3) {
679
+ return this.styleOptionText(str3);
680
680
  }
681
- styleSubcommandTerm(str) {
682
- return str.split(" ").map((word) => {
681
+ styleSubcommandTerm(str3) {
682
+ return str3.split(" ").map((word) => {
683
683
  if (word === "[options]") return this.styleOptionText(word);
684
684
  if (word[0] === "[" || word[0] === "<")
685
685
  return this.styleArgumentText(word);
686
686
  return this.styleSubcommandText(word);
687
687
  }).join(" ");
688
688
  }
689
- styleArgumentTerm(str) {
690
- return this.styleArgumentText(str);
689
+ styleArgumentTerm(str3) {
690
+ return this.styleArgumentText(str3);
691
691
  }
692
- styleOptionText(str) {
693
- return str;
692
+ styleOptionText(str3) {
693
+ return str3;
694
694
  }
695
- styleArgumentText(str) {
696
- return str;
695
+ styleArgumentText(str3) {
696
+ return str3;
697
697
  }
698
- styleSubcommandText(str) {
699
- return str;
698
+ styleSubcommandText(str3) {
699
+ return str3;
700
700
  }
701
- styleCommandText(str) {
702
- return str;
701
+ styleCommandText(str3) {
702
+ return str3;
703
703
  }
704
704
  /**
705
705
  * Calculate the pad width from the maximum term length.
@@ -722,8 +722,8 @@ var require_help = __commonJS({
722
722
  * @param {string} str
723
723
  * @returns {boolean}
724
724
  */
725
- preformatted(str) {
726
- return /\n[^\S\r\n]/.test(str);
725
+ preformatted(str3) {
726
+ return /\n[^\S\r\n]/.test(str3);
727
727
  }
728
728
  /**
729
729
  * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
@@ -769,9 +769,9 @@ ${itemIndentStr}`);
769
769
  * @param {number} width
770
770
  * @returns {string}
771
771
  */
772
- boxWrap(str, width) {
773
- if (width < this.minWidthToWrap) return str;
774
- const rawLines = str.split(/\r\n|\n/);
772
+ boxWrap(str3, width) {
773
+ if (width < this.minWidthToWrap) return str3;
774
+ const rawLines = str3.split(/\r\n|\n/);
775
775
  const chunkPattern = /[\s]*[^\s]+/g;
776
776
  const wrappedLines = [];
777
777
  rawLines.forEach((line2) => {
@@ -799,9 +799,9 @@ ${itemIndentStr}`);
799
799
  return wrappedLines.join("\n");
800
800
  }
801
801
  };
802
- function stripColor(str) {
802
+ function stripColor(str3) {
803
803
  const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
804
- return str.replace(sgrPattern, "");
804
+ return str3.replace(sgrPattern, "");
805
805
  }
806
806
  exports.Help = Help2;
807
807
  exports.stripColor = stripColor;
@@ -1073,9 +1073,9 @@ var require_option = __commonJS({
1073
1073
  return option.negate === (negativeValue === value);
1074
1074
  }
1075
1075
  };
1076
- function camelcase(str) {
1077
- return str.split("-").reduce((str2, word) => {
1078
- return str2 + word[0].toUpperCase() + word.slice(1);
1076
+ function camelcase(str3) {
1077
+ return str3.split("-").reduce((str4, word) => {
1078
+ return str4 + word[0].toUpperCase() + word.slice(1);
1079
1079
  });
1080
1080
  }
1081
1081
  function splitOptionFlags(flags) {
@@ -1209,7 +1209,7 @@ var require_command = __commonJS({
1209
1209
  "use strict";
1210
1210
  var EventEmitter = __require("events").EventEmitter;
1211
1211
  var childProcess = __require("child_process");
1212
- var path7 = __require("path");
1212
+ var path19 = __require("path");
1213
1213
  var fs = __require("fs");
1214
1214
  var process3 = __require("process");
1215
1215
  var { Argument: Argument2, humanReadableArgName } = require_argument();
@@ -1258,14 +1258,14 @@ var require_command = __commonJS({
1258
1258
  this._showSuggestionAfterError = true;
1259
1259
  this._savedState = null;
1260
1260
  this._outputConfiguration = {
1261
- writeOut: (str) => process3.stdout.write(str),
1262
- writeErr: (str) => process3.stderr.write(str),
1263
- outputError: (str, write) => write(str),
1261
+ writeOut: (str3) => process3.stdout.write(str3),
1262
+ writeErr: (str3) => process3.stderr.write(str3),
1263
+ outputError: (str3, write) => write(str3),
1264
1264
  getOutHelpWidth: () => process3.stdout.isTTY ? process3.stdout.columns : void 0,
1265
1265
  getErrHelpWidth: () => process3.stderr.isTTY ? process3.stderr.columns : void 0,
1266
1266
  getOutHasColors: () => useColor() ?? (process3.stdout.isTTY && process3.stdout.hasColors?.()),
1267
1267
  getErrHasColors: () => useColor() ?? (process3.stderr.isTTY && process3.stderr.hasColors?.()),
1268
- stripColor: (str) => stripColor(str)
1268
+ stripColor: (str3) => stripColor(str3)
1269
1269
  };
1270
1270
  this._hidden = false;
1271
1271
  this._helpOption = void 0;
@@ -1654,9 +1654,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
1654
1654
  * @return never
1655
1655
  * @private
1656
1656
  */
1657
- _exit(exitCode, code, message) {
1657
+ _exit(exitCode, code, message3) {
1658
1658
  if (this._exitCallback) {
1659
- this._exitCallback(new CommanderError2(exitCode, code, message));
1659
+ this._exitCallback(new CommanderError2(exitCode, code, message3));
1660
1660
  }
1661
1661
  process3.exit(exitCode);
1662
1662
  }
@@ -1716,8 +1716,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
1716
1716
  return target.parseArg(value, previous);
1717
1717
  } catch (err) {
1718
1718
  if (err.code === "commander.invalidArgument") {
1719
- const message = `${invalidArgumentMessage} ${err.message}`;
1720
- this.error(message, { exitCode: err.exitCode, code: err.code });
1719
+ const message3 = `${invalidArgumentMessage} ${err.message}`;
1720
+ this.error(message3, { exitCode: err.exitCode, code: err.code });
1721
1721
  }
1722
1722
  throw err;
1723
1723
  }
@@ -2222,9 +2222,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2222
2222
  let launchWithNode = false;
2223
2223
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2224
2224
  function findFile(baseDir, baseName) {
2225
- const localBin = path7.resolve(baseDir, baseName);
2225
+ const localBin = path19.resolve(baseDir, baseName);
2226
2226
  if (fs.existsSync(localBin)) return localBin;
2227
- if (sourceExt.includes(path7.extname(baseName))) return void 0;
2227
+ if (sourceExt.includes(path19.extname(baseName))) return void 0;
2228
2228
  const foundExt = sourceExt.find(
2229
2229
  (ext) => fs.existsSync(`${localBin}${ext}`)
2230
2230
  );
@@ -2242,17 +2242,17 @@ Expecting one of '${allowedValues.join("', '")}'`);
2242
2242
  } catch {
2243
2243
  resolvedScriptPath = this._scriptPath;
2244
2244
  }
2245
- executableDir = path7.resolve(
2246
- path7.dirname(resolvedScriptPath),
2245
+ executableDir = path19.resolve(
2246
+ path19.dirname(resolvedScriptPath),
2247
2247
  executableDir
2248
2248
  );
2249
2249
  }
2250
2250
  if (executableDir) {
2251
2251
  let localFile = findFile(executableDir, executableFile);
2252
2252
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
2253
- const legacyName = path7.basename(
2253
+ const legacyName = path19.basename(
2254
2254
  this._scriptPath,
2255
- path7.extname(this._scriptPath)
2255
+ path19.extname(this._scriptPath)
2256
2256
  );
2257
2257
  if (legacyName !== this._name) {
2258
2258
  localFile = findFile(
@@ -2263,7 +2263,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2263
2263
  }
2264
2264
  executableFile = localFile || executableFile;
2265
2265
  }
2266
- launchWithNode = sourceExt.includes(path7.extname(executableFile));
2266
+ launchWithNode = sourceExt.includes(path19.extname(executableFile));
2267
2267
  let proc;
2268
2268
  if (process3.platform !== "win32") {
2269
2269
  if (launchWithNode) {
@@ -2793,9 +2793,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2793
2793
  * @param {string} [errorOptions.code] - an id string representing the error
2794
2794
  * @param {number} [errorOptions.exitCode] - used with process.exit
2795
2795
  */
2796
- error(message, errorOptions) {
2796
+ error(message3, errorOptions) {
2797
2797
  this._outputConfiguration.outputError(
2798
- `${message}
2798
+ `${message3}
2799
2799
  `,
2800
2800
  this._outputConfiguration.writeErr
2801
2801
  );
@@ -2809,7 +2809,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2809
2809
  const config = errorOptions || {};
2810
2810
  const exitCode = config.exitCode || 1;
2811
2811
  const code = config.code || "commander.error";
2812
- this._exit(exitCode, code, message);
2812
+ this._exit(exitCode, code, message3);
2813
2813
  }
2814
2814
  /**
2815
2815
  * Apply any option related environment variables, if option does
@@ -2865,8 +2865,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2865
2865
  * @private
2866
2866
  */
2867
2867
  missingArgument(name) {
2868
- const message = `error: missing required argument '${name}'`;
2869
- this.error(message, { code: "commander.missingArgument" });
2868
+ const message3 = `error: missing required argument '${name}'`;
2869
+ this.error(message3, { code: "commander.missingArgument" });
2870
2870
  }
2871
2871
  /**
2872
2872
  * `Option` is missing an argument.
@@ -2875,8 +2875,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2875
2875
  * @private
2876
2876
  */
2877
2877
  optionMissingArgument(option) {
2878
- const message = `error: option '${option.flags}' argument missing`;
2879
- this.error(message, { code: "commander.optionMissingArgument" });
2878
+ const message3 = `error: option '${option.flags}' argument missing`;
2879
+ this.error(message3, { code: "commander.optionMissingArgument" });
2880
2880
  }
2881
2881
  /**
2882
2882
  * `Option` does not have a value, and is a mandatory option.
@@ -2885,8 +2885,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2885
2885
  * @private
2886
2886
  */
2887
2887
  missingMandatoryOptionValue(option) {
2888
- const message = `error: required option '${option.flags}' not specified`;
2889
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2888
+ const message3 = `error: required option '${option.flags}' not specified`;
2889
+ this.error(message3, { code: "commander.missingMandatoryOptionValue" });
2890
2890
  }
2891
2891
  /**
2892
2892
  * `Option` conflicts with another option.
@@ -2919,8 +2919,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2919
2919
  }
2920
2920
  return `option '${bestOption.flags}'`;
2921
2921
  };
2922
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2923
- this.error(message, { code: "commander.conflictingOption" });
2922
+ const message3 = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2923
+ this.error(message3, { code: "commander.conflictingOption" });
2924
2924
  }
2925
2925
  /**
2926
2926
  * Unknown option `flag`.
@@ -2941,8 +2941,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2941
2941
  } while (command && !command._enablePositionalOptions);
2942
2942
  suggestion = suggestSimilar(flag, candidateFlags);
2943
2943
  }
2944
- const message = `error: unknown option '${flag}'${suggestion}`;
2945
- this.error(message, { code: "commander.unknownOption" });
2944
+ const message3 = `error: unknown option '${flag}'${suggestion}`;
2945
+ this.error(message3, { code: "commander.unknownOption" });
2946
2946
  }
2947
2947
  /**
2948
2948
  * Excess arguments, more than expected.
@@ -2955,8 +2955,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2955
2955
  const expected = this.registeredArguments.length;
2956
2956
  const s = expected === 1 ? "" : "s";
2957
2957
  const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2958
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2959
- this.error(message, { code: "commander.excessArguments" });
2958
+ const message3 = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2959
+ this.error(message3, { code: "commander.excessArguments" });
2960
2960
  }
2961
2961
  /**
2962
2962
  * Unknown command.
@@ -2974,8 +2974,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
2974
2974
  });
2975
2975
  suggestion = suggestSimilar(unknownName, candidateNames);
2976
2976
  }
2977
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2978
- this.error(message, { code: "commander.unknownCommand" });
2977
+ const message3 = `error: unknown command '${unknownName}'${suggestion}`;
2978
+ this.error(message3, { code: "commander.unknownCommand" });
2979
2979
  }
2980
2980
  /**
2981
2981
  * Get or set the program version.
@@ -2989,18 +2989,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
2989
2989
  * @param {string} [description]
2990
2990
  * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2991
2991
  */
2992
- version(str, flags, description) {
2993
- if (str === void 0) return this._version;
2994
- this._version = str;
2992
+ version(str3, flags, description) {
2993
+ if (str3 === void 0) return this._version;
2994
+ this._version = str3;
2995
2995
  flags = flags || "-V, --version";
2996
2996
  description = description || "output the version number";
2997
2997
  const versionOption = this.createOption(flags, description);
2998
2998
  this._versionOptionName = versionOption.attributeName();
2999
2999
  this._registerOption(versionOption);
3000
3000
  this.on("option:" + versionOption.name(), () => {
3001
- this._outputConfiguration.writeOut(`${str}
3001
+ this._outputConfiguration.writeOut(`${str3}
3002
3002
  `);
3003
- this._exit(0, "commander.version", str);
3003
+ this._exit(0, "commander.version", str3);
3004
3004
  });
3005
3005
  return this;
3006
3006
  }
@@ -3011,10 +3011,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
3011
3011
  * @param {object} [argsDescription]
3012
3012
  * @return {(string|Command)}
3013
3013
  */
3014
- description(str, argsDescription) {
3015
- if (str === void 0 && argsDescription === void 0)
3014
+ description(str3, argsDescription) {
3015
+ if (str3 === void 0 && argsDescription === void 0)
3016
3016
  return this._description;
3017
- this._description = str;
3017
+ this._description = str3;
3018
3018
  if (argsDescription) {
3019
3019
  this._argsDescription = argsDescription;
3020
3020
  }
@@ -3026,9 +3026,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3026
3026
  * @param {string} [str]
3027
3027
  * @return {(string|Command)}
3028
3028
  */
3029
- summary(str) {
3030
- if (str === void 0) return this._summary;
3031
- this._summary = str;
3029
+ summary(str3) {
3030
+ if (str3 === void 0) return this._summary;
3031
+ this._summary = str3;
3032
3032
  return this;
3033
3033
  }
3034
3034
  /**
@@ -3076,8 +3076,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
3076
3076
  * @param {string} [str]
3077
3077
  * @return {(string|Command)}
3078
3078
  */
3079
- usage(str) {
3080
- if (str === void 0) {
3079
+ usage(str3) {
3080
+ if (str3 === void 0) {
3081
3081
  if (this._usage) return this._usage;
3082
3082
  const args = this.registeredArguments.map((arg) => {
3083
3083
  return humanReadableArgName(arg);
@@ -3088,7 +3088,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3088
3088
  this.registeredArguments.length ? args : []
3089
3089
  ).join(" ");
3090
3090
  }
3091
- this._usage = str;
3091
+ this._usage = str3;
3092
3092
  return this;
3093
3093
  }
3094
3094
  /**
@@ -3097,9 +3097,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3097
3097
  * @param {string} [str]
3098
3098
  * @return {(string|Command)}
3099
3099
  */
3100
- name(str) {
3101
- if (str === void 0) return this._name;
3102
- this._name = str;
3100
+ name(str3) {
3101
+ if (str3 === void 0) return this._name;
3102
+ this._name = str3;
3103
3103
  return this;
3104
3104
  }
3105
3105
  /**
@@ -3178,7 +3178,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3178
3178
  * @return {Command}
3179
3179
  */
3180
3180
  nameFromFilename(filename) {
3181
- this._name = path7.basename(filename, path7.extname(filename));
3181
+ this._name = path19.basename(filename, path19.extname(filename));
3182
3182
  return this;
3183
3183
  }
3184
3184
  /**
@@ -3192,9 +3192,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3192
3192
  * @param {string} [path]
3193
3193
  * @return {(string|null|Command)}
3194
3194
  */
3195
- executableDir(path8) {
3196
- if (path8 === void 0) return this._executableDir;
3197
- this._executableDir = path8;
3195
+ executableDir(path20) {
3196
+ if (path20 === void 0) return this._executableDir;
3197
+ this._executableDir = path20;
3198
3198
  return this;
3199
3199
  }
3200
3200
  /**
@@ -3233,17 +3233,17 @@ Expecting one of '${allowedValues.join("', '")}'`);
3233
3233
  let hasColors;
3234
3234
  let helpWidth;
3235
3235
  if (error) {
3236
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
3236
+ baseWrite = (str3) => this._outputConfiguration.writeErr(str3);
3237
3237
  hasColors = this._outputConfiguration.getErrHasColors();
3238
3238
  helpWidth = this._outputConfiguration.getErrHelpWidth();
3239
3239
  } else {
3240
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
3240
+ baseWrite = (str3) => this._outputConfiguration.writeOut(str3);
3241
3241
  hasColors = this._outputConfiguration.getOutHasColors();
3242
3242
  helpWidth = this._outputConfiguration.getOutHelpWidth();
3243
3243
  }
3244
- const write = (str) => {
3245
- if (!hasColors) str = this._outputConfiguration.stripColor(str);
3246
- return baseWrite(str);
3244
+ const write = (str3) => {
3245
+ if (!hasColors) str3 = this._outputConfiguration.stripColor(str3);
3246
+ return baseWrite(str3);
3247
3247
  };
3248
3248
  return { error, write, hasColors, helpWidth };
3249
3249
  }
@@ -4874,10 +4874,10 @@ function keysFilePath(env) {
4874
4874
  const expanded = expandHome(configured);
4875
4875
  return isAbsolute(expanded) ? expanded : expanded;
4876
4876
  }
4877
- function parseKeysFile(path7) {
4877
+ function parseKeysFile(path19) {
4878
4878
  let text;
4879
4879
  try {
4880
- text = readFileSync3(path7, "utf8");
4880
+ text = readFileSync3(path19, "utf8");
4881
4881
  } catch {
4882
4882
  return {};
4883
4883
  }
@@ -4959,8 +4959,8 @@ async function probeKey(baseUrl, model, apiKey) {
4959
4959
  }
4960
4960
  return { ok: false, rejected: false, detail: `could not validate (HTTP ${res.status})` };
4961
4961
  } catch (error) {
4962
- const message = error instanceof Error ? error.message : String(error);
4963
- return { ok: false, rejected: false, detail: `could not validate (${message})` };
4962
+ const message3 = error instanceof Error ? error.message : String(error);
4963
+ return { ok: false, rejected: false, detail: `could not validate (${message3})` };
4964
4964
  } finally {
4965
4965
  clearTimeout(timer);
4966
4966
  }
@@ -4989,18 +4989,18 @@ function upsertKeyLines(existing, updates) {
4989
4989
  if (!text.endsWith("\n")) text += "\n";
4990
4990
  return text;
4991
4991
  }
4992
- function restrictPermissions(path7) {
4992
+ function restrictPermissions(path19) {
4993
4993
  if (process.platform === "win32") return null;
4994
4994
  try {
4995
- chmodSync(path7, 384);
4995
+ chmodSync(path19, 384);
4996
4996
  return null;
4997
4997
  } catch (error) {
4998
4998
  return error instanceof Error ? error.message : String(error);
4999
4999
  }
5000
5000
  }
5001
5001
  async function keys(options = {}) {
5002
- const path7 = keysFilePath(process.env);
5003
- const fileKeys = parseKeysFile(path7);
5002
+ const path19 = keysFilePath(process.env);
5003
+ const fileKeys = parseKeysFile(path19);
5004
5004
  const names = Object.keys(PROVIDERS).sort();
5005
5005
  const current = names.map((name) => {
5006
5006
  const preset = PROVIDERS[name];
@@ -5016,7 +5016,7 @@ async function keys(options = {}) {
5016
5016
  if (options.check) {
5017
5017
  const configured = current.filter((entry) => entry.value);
5018
5018
  if (!configured.length) {
5019
- process.stdout.write(`no provider keys configured (looked in $ENV and ${path7})
5019
+ process.stdout.write(`no provider keys configured (looked in $ENV and ${path19})
5020
5020
  `);
5021
5021
  return 1;
5022
5022
  }
@@ -5031,7 +5031,7 @@ async function keys(options = {}) {
5031
5031
  return bad ? 1 : 0;
5032
5032
  }
5033
5033
  Ie("caddis keys");
5034
- process.stdout.write(` keys file: ${path7}
5034
+ process.stdout.write(` keys file: ${path19}
5035
5035
 
5036
5036
  `);
5037
5037
  for (const entry of current) {
@@ -5091,20 +5091,20 @@ async function keys(options = {}) {
5091
5091
  return 0;
5092
5092
  }
5093
5093
  if (options.dryRun) {
5094
- Se(`dry run \u2014 would write ${Object.keys(collected).join(", ")} to ${path7}`);
5094
+ Se(`dry run \u2014 would write ${Object.keys(collected).join(", ")} to ${path19}`);
5095
5095
  return 0;
5096
5096
  }
5097
5097
  let existing = "";
5098
5098
  try {
5099
- existing = readFileSync4(path7, "utf8");
5099
+ existing = readFileSync4(path19, "utf8");
5100
5100
  } catch {
5101
5101
  existing = "";
5102
5102
  }
5103
- mkdirSync2(dirname(path7), { recursive: true });
5104
- writeFileSync(path7, upsertKeyLines(existing, collected), { encoding: "utf8" });
5105
- const permWarning = restrictPermissions(path7);
5103
+ mkdirSync2(dirname(path19), { recursive: true });
5104
+ writeFileSync(path19, upsertKeyLines(existing, collected), { encoding: "utf8" });
5105
+ const permWarning = restrictPermissions(path19);
5106
5106
  process.stdout.write(`
5107
- wrote ${Object.keys(collected).join(", ")} to ${path7}
5107
+ wrote ${Object.keys(collected).join(", ")} to ${path19}
5108
5108
  `);
5109
5109
  if (permWarning) process.stdout.write(color.yellow(` could not set 0600 on the keys file: ${permWarning}
5110
5110
  `));
@@ -5707,6 +5707,2568 @@ var init_status = __esm({
5707
5707
  }
5708
5708
  });
5709
5709
 
5710
+ // src/hub/paths.ts
5711
+ import path7 from "path";
5712
+ function hubDir(home = caddisHome()) {
5713
+ return path7.join(home, ".caddis", "hub");
5714
+ }
5715
+ var configPath, registryPath, keyPath, lockPath;
5716
+ var init_paths = __esm({
5717
+ "src/hub/paths.ts"() {
5718
+ "use strict";
5719
+ init_sessions();
5720
+ configPath = (home) => path7.join(hubDir(home), "config.json");
5721
+ registryPath = (home) => path7.join(hubDir(home), "repos.json");
5722
+ keyPath = (home) => path7.join(hubDir(home), "key");
5723
+ lockPath = (home) => path7.join(hubDir(home), "hub.lock");
5724
+ }
5725
+ });
5726
+
5727
+ // src/hub/autostart.ts
5728
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
5729
+ import path8 from "path";
5730
+ function buildVbs(node, entry) {
5731
+ const q2 = (s) => `""${s.replace(/"/g, '""""')}""`;
5732
+ return `CreateObject("WScript.Shell").Run "${q2(node)} ${q2(entry)} hub serve", 0, False\r
5733
+ `;
5734
+ }
5735
+ function schtasksCreateArgs(vbs) {
5736
+ return ["/Create", "/SC", "ONLOGON", "/RL", "LIMITED", "/TN", TASK_NAME, "/TR", `wscript.exe "${vbs}"`, "/F"];
5737
+ }
5738
+ function buildPlist(node, entry) {
5739
+ const args = [node, entry, "hub", "serve"].map((a) => ` <string>${xml(a)}</string>`).join("\n");
5740
+ return `<?xml version="1.0" encoding="UTF-8"?>
5741
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5742
+ <plist version="1.0">
5743
+ <dict>
5744
+ <key>Label</key>
5745
+ <string>${MAC_LABEL}</string>
5746
+ <key>ProgramArguments</key>
5747
+ <array>
5748
+ ${args}
5749
+ </array>
5750
+ <key>RunAtLoad</key>
5751
+ <true/>
5752
+ </dict>
5753
+ </plist>
5754
+ `;
5755
+ }
5756
+ function desktopArg(a) {
5757
+ const escaped = a.replace(/([`$"\\])/g, "\\$1").replace(/%/g, "%%");
5758
+ return `"${escaped.replace(/\\/g, "\\\\")}"`;
5759
+ }
5760
+ function buildDesktop(node, entry) {
5761
+ const exec = [node, entry, "hub", "serve"].map(desktopArg).join(" ");
5762
+ return `[Desktop Entry]
5763
+ Type=Application
5764
+ Name=caddis hub
5765
+ Exec=${exec}
5766
+ X-GNOME-Autostart-enabled=true
5767
+ NoDisplay=true
5768
+ `;
5769
+ }
5770
+ function writeText(file, text) {
5771
+ mkdirSync3(path8.dirname(file), { recursive: true });
5772
+ writeFileSync2(file, text, "utf8");
5773
+ }
5774
+ async function enableAutostart(deps = {}) {
5775
+ const home = deps.home ?? caddisHome();
5776
+ const node = deps.node ?? process.execPath;
5777
+ const rawEntry = deps.entry ?? process.argv[1];
5778
+ if (!rawEntry) return { ok: false, message: "cannot find the caddis CLI entry script" };
5779
+ const entry = path8.resolve(rawEntry);
5780
+ const runCmd = deps.runCmd ?? defaultRun;
5781
+ const kind = kindOf(deps.platform ?? process.platform);
5782
+ if (kind === "win") {
5783
+ const vbs = vbsPath(home);
5784
+ writeText(vbs, buildVbs(node, entry));
5785
+ const r2 = await runCmd("schtasks", schtasksCreateArgs(vbs));
5786
+ return r2.ok ? { ok: true, message: `caddis hub autostart enabled (logon task ${TASK_NAME})` } : { ok: false, message: `schtasks /Create failed (exit ${r2.code})` };
5787
+ }
5788
+ if (kind === "mac") {
5789
+ const file2 = plistPath(home);
5790
+ writeText(file2, buildPlist(node, entry));
5791
+ const r2 = await runCmd("launchctl", ["load", "-w", file2]);
5792
+ return r2.ok ? { ok: true, message: `caddis hub autostart enabled (${file2})` } : { ok: false, message: `launchctl load failed (exit ${r2.code})` };
5793
+ }
5794
+ const file = desktopPath(home);
5795
+ writeText(file, buildDesktop(node, entry));
5796
+ return { ok: true, message: `caddis hub autostart enabled (${file})` };
5797
+ }
5798
+ async function disableAutostart(deps = {}) {
5799
+ const home = deps.home ?? caddisHome();
5800
+ const runCmd = deps.runCmd ?? defaultRun;
5801
+ const kind = kindOf(deps.platform ?? process.platform);
5802
+ if (kind === "win") {
5803
+ const r2 = await runCmd("schtasks", schtasksDeleteArgs());
5804
+ rmSync3(vbsPath(home), { force: true });
5805
+ return r2.ok ? { ok: true, message: "caddis hub autostart disabled" } : { ok: true, message: "caddis hub autostart was not enabled (no logon task to delete)" };
5806
+ }
5807
+ if (kind === "mac") {
5808
+ const file = plistPath(home);
5809
+ if (existsSync6(file)) await runCmd("launchctl", ["unload", "-w", file]);
5810
+ rmSync3(file, { force: true });
5811
+ return { ok: true, message: "caddis hub autostart disabled" };
5812
+ }
5813
+ rmSync3(desktopPath(home), { force: true });
5814
+ return { ok: true, message: "caddis hub autostart disabled" };
5815
+ }
5816
+ async function autostartStatus(deps = {}) {
5817
+ const home = deps.home ?? caddisHome();
5818
+ const runCmd = deps.runCmd ?? defaultRun;
5819
+ const kind = kindOf(deps.platform ?? process.platform);
5820
+ const enabled = kind === "win" ? (await runCmd("schtasks", schtasksQueryArgs())).ok : existsSync6(kind === "mac" ? plistPath(home) : desktopPath(home));
5821
+ return { ok: enabled, message: enabled ? "caddis hub autostart is enabled" : "caddis hub autostart is not enabled" };
5822
+ }
5823
+ var TASK_NAME, MAC_LABEL, CMD_TIMEOUT_MS, vbsPath, schtasksDeleteArgs, schtasksQueryArgs, xml, plistPath, desktopPath, defaultRun, kindOf;
5824
+ var init_autostart = __esm({
5825
+ "src/hub/autostart.ts"() {
5826
+ "use strict";
5827
+ init_exec();
5828
+ init_sessions();
5829
+ init_paths();
5830
+ TASK_NAME = "caddis-hub";
5831
+ MAC_LABEL = "dev.caddis.hub";
5832
+ CMD_TIMEOUT_MS = 3e4;
5833
+ vbsPath = (home) => path8.join(hubDir(home), "autostart.vbs");
5834
+ schtasksDeleteArgs = () => ["/Delete", "/TN", TASK_NAME, "/F"];
5835
+ schtasksQueryArgs = () => ["/Query", "/TN", TASK_NAME];
5836
+ xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
5837
+ plistPath = (home) => path8.join(home, "Library", "LaunchAgents", `${MAC_LABEL}.plist`);
5838
+ desktopPath = (home) => path8.join(home, ".config", "autostart", `${TASK_NAME}.desktop`);
5839
+ defaultRun = async (cmd, args) => {
5840
+ const r2 = await run(cmd, args, { timeout: CMD_TIMEOUT_MS });
5841
+ return { ok: r2.ok, code: r2.code };
5842
+ };
5843
+ kindOf = (p2) => p2 === "win32" ? "win" : p2 === "darwin" ? "mac" : "linux";
5844
+ }
5845
+ });
5846
+
5847
+ // src/hub/config.ts
5848
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
5849
+ import path9 from "path";
5850
+ import { randomBytes } from "crypto";
5851
+ function defaultConfig() {
5852
+ return { schema: 1, port: DEFAULT_PORT, accounts: {}, pinned: [], hidden: [] };
5853
+ }
5854
+ function defaultRegistry() {
5855
+ return { schema: 1, repos: [] };
5856
+ }
5857
+ function sleepSync(ms) {
5858
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
5859
+ }
5860
+ function renameWithRetry(from, to) {
5861
+ const retryable = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
5862
+ const attempts = isWin() ? 6 : 1;
5863
+ for (let i = 0; ; i++) {
5864
+ try {
5865
+ renameSync2(from, to);
5866
+ return;
5867
+ } catch (e2) {
5868
+ const code = e2.code ?? "";
5869
+ if (i + 1 >= attempts || !retryable.has(code)) throw e2;
5870
+ sleepSync(15 * 2 ** i);
5871
+ }
5872
+ }
5873
+ }
5874
+ function writeJsonAtomic(file, data) {
5875
+ mkdirSync4(path9.dirname(file), { recursive: true, mode: 448 });
5876
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
5877
+ try {
5878
+ writeFileSync3(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 384 });
5879
+ renameWithRetry(tmp, file);
5880
+ } catch (e2) {
5881
+ try {
5882
+ unlinkSync(tmp);
5883
+ } catch {
5884
+ }
5885
+ throw e2;
5886
+ }
5887
+ }
5888
+ function readJson(file, normalize, fallback) {
5889
+ let text;
5890
+ try {
5891
+ text = readFileSync6(file, "utf8");
5892
+ } catch (e2) {
5893
+ if (e2.code === "ENOENT") {
5894
+ const good = lastGood.get(file);
5895
+ return { value: good ?? fallback() };
5896
+ }
5897
+ return failure(file, fallback, `cannot read ${path9.basename(file)}: ${e2.message}`);
5898
+ }
5899
+ try {
5900
+ const value = normalize(JSON.parse(text));
5901
+ lastGood.set(file, value);
5902
+ return { value };
5903
+ } catch (e2) {
5904
+ return failure(file, fallback, `corrupt ${path9.basename(file)}: ${e2.message}`);
5905
+ }
5906
+ }
5907
+ function failure(file, fallback, error) {
5908
+ return { value: lastGood.get(file) ?? fallback(), error };
5909
+ }
5910
+ function normalizeConfig(raw) {
5911
+ if (!isObj(raw)) throw new Error("not a JSON object");
5912
+ const d3 = defaultConfig();
5913
+ const port = raw.port;
5914
+ if (typeof port === "number" && Number.isFinite(port)) d3.port = port;
5915
+ if (isObj(raw.accounts)) {
5916
+ for (const [k3, v2] of Object.entries(raw.accounts)) if (typeof v2 === "string") d3.accounts[k3] = v2;
5917
+ }
5918
+ d3.pinned = strings(raw.pinned);
5919
+ d3.hidden = strings(raw.hidden);
5920
+ return d3;
5921
+ }
5922
+ function normalizeRegistry(raw) {
5923
+ if (!isObj(raw)) throw new Error("not a JSON object");
5924
+ const repos = [];
5925
+ if (Array.isArray(raw.repos)) {
5926
+ for (const r2 of raw.repos) {
5927
+ if (isObj(r2) && typeof r2.path === "string" && typeof r2.added_at === "string") {
5928
+ repos.push({ path: r2.path, added_at: r2.added_at });
5929
+ }
5930
+ }
5931
+ }
5932
+ return { schema: 1, repos };
5933
+ }
5934
+ function readConfig(home) {
5935
+ return readJson(configPath(home), normalizeConfig, defaultConfig);
5936
+ }
5937
+ function readRegistry(home) {
5938
+ return readJson(registryPath(home), normalizeRegistry, defaultRegistry);
5939
+ }
5940
+ function normalizeRepoPath(p2) {
5941
+ const r2 = path9.resolve(p2);
5942
+ const root = path9.parse(r2).root;
5943
+ let out = r2;
5944
+ while (out.length > root.length && /[\/]$/.test(out)) out = out.slice(0, -1);
5945
+ return out;
5946
+ }
5947
+ function addRepos(paths, home) {
5948
+ const cur = readRegistry(home);
5949
+ if (cur.error) return cur;
5950
+ const seen = new Set(cur.value.repos.map((r2) => repoKey(r2.path)));
5951
+ const repos = [...cur.value.repos];
5952
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5953
+ let changed = false;
5954
+ for (const p2 of paths) {
5955
+ const n = normalizeRepoPath(p2);
5956
+ const k3 = repoKey(n);
5957
+ if (seen.has(k3)) continue;
5958
+ seen.add(k3);
5959
+ repos.push({ path: n, added_at: now });
5960
+ changed = true;
5961
+ }
5962
+ const value = { schema: 1, repos };
5963
+ if (changed) {
5964
+ writeJsonAtomic(registryPath(home), value);
5965
+ lastGood.set(registryPath(home), value);
5966
+ }
5967
+ return { value };
5968
+ }
5969
+ var DEFAULT_PORT, isWin, lastGood, isObj, strings, repoKey;
5970
+ var init_config = __esm({
5971
+ "src/hub/config.ts"() {
5972
+ "use strict";
5973
+ init_paths();
5974
+ DEFAULT_PORT = 47821;
5975
+ isWin = () => process.platform === "win32";
5976
+ lastGood = /* @__PURE__ */ new Map();
5977
+ isObj = (v2) => typeof v2 === "object" && v2 !== null && !Array.isArray(v2);
5978
+ strings = (v2) => Array.isArray(v2) ? v2.filter((x2) => typeof x2 === "string") : [];
5979
+ repoKey = (p2) => isWin() ? p2.toLowerCase() : p2;
5980
+ }
5981
+ });
5982
+
5983
+ // src/hub/keyfile.ts
5984
+ import { chmodSync as chmodSync2, linkSync, mkdirSync as mkdirSync5, readFileSync as readFileSync7, unlinkSync as unlinkSync2, writeFileSync as writeFileSync4 } from "fs";
5985
+ import { randomBytes as randomBytes2 } from "crypto";
5986
+ import path10 from "path";
5987
+ function windowsAccount(env = process.env) {
5988
+ const user = env.USERNAME ?? "";
5989
+ return env.USERDOMAIN ? `${env.USERDOMAIN}\\${user}` : user;
5990
+ }
5991
+ function icaclsArgs(file, account) {
5992
+ return [file, "/inheritance:r", "/grant:r", `${account}:F`];
5993
+ }
5994
+ function removeQuiet(file) {
5995
+ try {
5996
+ unlinkSync2(file);
5997
+ } catch {
5998
+ }
5999
+ }
6000
+ function readKey(file, platform) {
6001
+ let text;
6002
+ try {
6003
+ text = readFileSync7(file, "utf8").trim();
6004
+ } catch (e2) {
6005
+ if (e2.code === "ENOENT") return null;
6006
+ throw e2;
6007
+ }
6008
+ if (!KEY_RE.test(text)) throw new Error(`the hub key file is corrupt: delete ${file} and start again`);
6009
+ if (platform !== "win32") chmodSync2(file, 384);
6010
+ return text;
6011
+ }
6012
+ async function ownerOnly(file, platform, deps) {
6013
+ if (platform !== "win32") {
6014
+ chmodSync2(file, 384);
6015
+ return;
6016
+ }
6017
+ const account = deps.account ?? windowsAccount();
6018
+ if (!account) throw new Error("icacls: cannot find the current user name (USERNAME is not set)");
6019
+ const r2 = await (deps.runCmd ?? run)("icacls", icaclsArgs(file, account), { timeout: ICACLS_TIMEOUT_MS });
6020
+ if (!r2.ok) throw new Error(`icacls could not set the owner-only ACL on the hub key file (exit ${r2.code})`);
6021
+ }
6022
+ async function ensureKey(deps = {}) {
6023
+ const platform = deps.platform ?? process.platform;
6024
+ const file = keyPath(deps.home);
6025
+ const existing = readKey(file, platform);
6026
+ if (existing) return existing;
6027
+ mkdirSync5(path10.dirname(file), { recursive: true, mode: 448 });
6028
+ const key = randomBytes2(32).toString("hex");
6029
+ const tmp = `${file}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
6030
+ try {
6031
+ writeFileSync4(tmp, "", { mode: 384, flag: "wx" });
6032
+ await (deps.setAcl ?? ((f) => ownerOnly(f, platform, deps)))(tmp);
6033
+ writeFileSync4(tmp, key, { flag: "r+" });
6034
+ try {
6035
+ linkSync(tmp, file);
6036
+ } catch (e2) {
6037
+ if (e2.code !== "EEXIST") throw e2;
6038
+ }
6039
+ } finally {
6040
+ removeQuiet(tmp);
6041
+ }
6042
+ const back = readKey(file, platform);
6043
+ if (!back) throw new Error("the hub key file disappeared after create");
6044
+ return back;
6045
+ }
6046
+ var KEY_RE, ICACLS_TIMEOUT_MS;
6047
+ var init_keyfile = __esm({
6048
+ "src/hub/keyfile.ts"() {
6049
+ "use strict";
6050
+ init_paths();
6051
+ init_exec();
6052
+ KEY_RE = /^[0-9a-f]{64}$/;
6053
+ ICACLS_TIMEOUT_MS = 15e3;
6054
+ }
6055
+ });
6056
+
6057
+ // src/hub/lock.ts
6058
+ import { closeSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync8, unlinkSync as unlinkSync3, writeSync } from "fs";
6059
+ import path11 from "path";
6060
+ function readLock(home) {
6061
+ try {
6062
+ const raw = JSON.parse(readFileSync8(lockPath(home), "utf8"));
6063
+ const pid = raw.pid;
6064
+ const port = raw.port;
6065
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return null;
6066
+ if (typeof port !== "number" || !Number.isInteger(port)) return null;
6067
+ const started = typeof raw.started_at === "string" ? raw.started_at : "";
6068
+ const info = { pid, started_at: started, port };
6069
+ if (typeof raw.instance === "string" && /^[0-9a-f]{32}$/.test(raw.instance)) info.instance = raw.instance;
6070
+ return info;
6071
+ } catch {
6072
+ return null;
6073
+ }
6074
+ }
6075
+ function holderAlive(h2, home, alive) {
6076
+ return h2.pid === process.pid ? held.has(lockPath(home)) : alive(h2.pid);
6077
+ }
6078
+ function removeFile(file) {
6079
+ try {
6080
+ unlinkSync3(file);
6081
+ } catch (e2) {
6082
+ if (e2.code !== "ENOENT") throw e2;
6083
+ }
6084
+ }
6085
+ function acquireLock(info, home, alive = pidAlive) {
6086
+ const file = lockPath(home);
6087
+ const live = (h2) => h2 !== null && holderAlive(h2, home, alive);
6088
+ mkdirSync6(path11.dirname(file), { recursive: true, mode: 448 });
6089
+ for (let attempt = 0; attempt < 3; attempt++) {
6090
+ let fd;
6091
+ try {
6092
+ fd = openSync(file, "wx", 384);
6093
+ } catch (e2) {
6094
+ if (e2.code !== "EEXIST") throw e2;
6095
+ const holder2 = readLock(home);
6096
+ if (live(holder2)) return { ok: false, holder: holder2 };
6097
+ const again = readLock(home);
6098
+ if (live(again)) return { ok: false, holder: again };
6099
+ removeFile(file);
6100
+ continue;
6101
+ }
6102
+ try {
6103
+ writeSync(fd, JSON.stringify(info) + "\n");
6104
+ } finally {
6105
+ closeSync(fd);
6106
+ }
6107
+ if (info.pid === process.pid) held.add(file);
6108
+ return { ok: true };
6109
+ }
6110
+ const holder = readLock(home);
6111
+ if (holder) return { ok: false, holder };
6112
+ throw new Error("could not take the hub lock");
6113
+ }
6114
+ function writeLock(info, home) {
6115
+ writeJsonAtomic(lockPath(home), info);
6116
+ }
6117
+ function releaseLock(pid, home) {
6118
+ const cur = readLock(home);
6119
+ if (!cur || cur.pid !== pid) return;
6120
+ if (pid === process.pid) held.delete(lockPath(home));
6121
+ try {
6122
+ removeFile(lockPath(home));
6123
+ } catch {
6124
+ }
6125
+ }
6126
+ function removeLockIf(expected, home) {
6127
+ const cur = readLock(home);
6128
+ if (cur && cur.pid === expected.pid && cur.instance === expected.instance && cur.started_at === expected.started_at) {
6129
+ removeLock(home);
6130
+ }
6131
+ }
6132
+ function removeLock(home) {
6133
+ held.delete(lockPath(home));
6134
+ try {
6135
+ removeFile(lockPath(home));
6136
+ } catch {
6137
+ }
6138
+ }
6139
+ var held;
6140
+ var init_lock = __esm({
6141
+ "src/hub/lock.ts"() {
6142
+ "use strict";
6143
+ init_config();
6144
+ init_paths();
6145
+ init_sessions();
6146
+ held = /* @__PURE__ */ new Set();
6147
+ }
6148
+ });
6149
+
6150
+ // src/hub/restart.ts
6151
+ import { readFileSync as readFileSync9 } from "fs";
6152
+ import path12 from "path";
6153
+ function readInstalledVersion2(packageRoot) {
6154
+ try {
6155
+ const parsed = JSON.parse(readFileSync9(path12.join(packageRoot, "package.json"), "utf8"));
6156
+ return typeof parsed.version === "string" && parsed.version ? parsed.version : null;
6157
+ } catch {
6158
+ return null;
6159
+ }
6160
+ }
6161
+ function createRestarter(deps) {
6162
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r2) => setTimeout(r2, ms)));
6163
+ const now = deps.now ?? Date.now;
6164
+ const waitMs = deps.waitMs ?? RESTART_WAIT_MS;
6165
+ const failed = /* @__PURE__ */ new Set();
6166
+ let busy = false;
6167
+ let cancel = null;
6168
+ async function handOver(version) {
6169
+ deps.log(`caddis hub: version ${deps.currentVersion} -> ${version}; starting the new server`);
6170
+ let child = null;
6171
+ let error = "";
6172
+ try {
6173
+ await deps.closeServer();
6174
+ child = await deps.spawnNew();
6175
+ let exited = false;
6176
+ void child.exited.then(() => {
6177
+ exited = true;
6178
+ });
6179
+ const deadline = now() + waitMs;
6180
+ while (now() < deadline) {
6181
+ await Promise.resolve();
6182
+ if (exited) {
6183
+ error = "the new server exited before it answered";
6184
+ break;
6185
+ }
6186
+ if (await deps.probe(child) === version) {
6187
+ deps.exit(0);
6188
+ return;
6189
+ }
6190
+ await sleep2(POLL_MS);
6191
+ }
6192
+ if (!error) error = `the new server did not answer with version ${version} in ${Math.round(waitMs / 1e3)} s`;
6193
+ } catch (e2) {
6194
+ error = e2 instanceof Error ? e2.message : String(e2);
6195
+ }
6196
+ failed.add(version);
6197
+ deps.log(`caddis hub: restart to ${version} failed (${error}); keeping version ${deps.currentVersion}`);
6198
+ if (child && deps.killChild) {
6199
+ try {
6200
+ await deps.killChild(child);
6201
+ } catch {
6202
+ }
6203
+ }
6204
+ try {
6205
+ await deps.restartOwn();
6206
+ } catch (e2) {
6207
+ deps.log(`caddis hub: could not restart the old server: ${e2 instanceof Error ? e2.message : String(e2)}`);
6208
+ deps.exit(1);
6209
+ }
6210
+ }
6211
+ async function tick() {
6212
+ if (busy) return;
6213
+ busy = true;
6214
+ try {
6215
+ const v2 = deps.readVersion();
6216
+ if (v2 === null || v2 === deps.currentVersion || failed.has(v2)) return;
6217
+ await handOver(v2);
6218
+ } catch (e2) {
6219
+ try {
6220
+ deps.log(`caddis hub: restart check failed: ${e2 instanceof Error ? e2.message : String(e2)}`);
6221
+ } catch {
6222
+ }
6223
+ } finally {
6224
+ busy = false;
6225
+ }
6226
+ }
6227
+ return {
6228
+ start: () => {
6229
+ cancel ??= deps.every(() => void tick(), RESTART_CHECK_MS);
6230
+ },
6231
+ stop: () => {
6232
+ cancel?.();
6233
+ cancel = null;
6234
+ },
6235
+ tick
6236
+ };
6237
+ }
6238
+ var RESTART_CHECK_MS, RESTART_WAIT_MS, POLL_MS;
6239
+ var init_restart = __esm({
6240
+ "src/hub/restart.ts"() {
6241
+ "use strict";
6242
+ RESTART_CHECK_MS = 6e4;
6243
+ RESTART_WAIT_MS = 2e4;
6244
+ POLL_MS = 250;
6245
+ }
6246
+ });
6247
+
6248
+ // src/hub/auth.ts
6249
+ import { createHash, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
6250
+ function randomToken() {
6251
+ return randomBytes3(32).toString("base64url");
6252
+ }
6253
+ function safeEqual(a, b3) {
6254
+ const ha = createHash("sha256").update(a, "utf8").digest();
6255
+ const hb = createHash("sha256").update(b3, "utf8").digest();
6256
+ return timingSafeEqual(ha, hb) && a.length === b3.length;
6257
+ }
6258
+ function hostAllowed(host, port) {
6259
+ if (!host) return false;
6260
+ const h2 = host.toLowerCase();
6261
+ return h2 === `127.0.0.1:${port}` || h2 === `localhost:${port}`;
6262
+ }
6263
+ function originAllowed(origin, port) {
6264
+ if (!origin) return false;
6265
+ return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;
6266
+ }
6267
+ function parseCookies(header) {
6268
+ const out = {};
6269
+ if (!header) return out;
6270
+ for (const part of header.split(";")) {
6271
+ const i = part.indexOf("=");
6272
+ if (i < 1) continue;
6273
+ const name = part.slice(0, i).trim();
6274
+ if (name && !(name in out)) out[name] = part.slice(i + 1).trim();
6275
+ }
6276
+ return out;
6277
+ }
6278
+ var CODE_TTL_MS, MAX_CODES, MAX_SESSIONS, SESSION_IDLE_MS, SESSION_MAX_MS, AuthStore;
6279
+ var init_auth = __esm({
6280
+ "src/hub/auth.ts"() {
6281
+ "use strict";
6282
+ CODE_TTL_MS = 6e4;
6283
+ MAX_CODES = 20;
6284
+ MAX_SESSIONS = 20;
6285
+ SESSION_IDLE_MS = 12 * 60 * 60 * 1e3;
6286
+ SESSION_MAX_MS = 24 * 60 * 60 * 1e3;
6287
+ AuthStore = class {
6288
+ constructor(now = Date.now) {
6289
+ this.now = now;
6290
+ }
6291
+ now;
6292
+ codes = [];
6293
+ sessions = [];
6294
+ /** Mint a single-use code. Expired codes are dropped first; then the oldest goes past the cap. */
6295
+ mintCode() {
6296
+ const t = this.now();
6297
+ this.codes = this.codes.filter((c) => t - c.mintedAt < CODE_TTL_MS);
6298
+ const value = randomToken();
6299
+ this.codes.push({ value, mintedAt: t });
6300
+ while (this.codes.length > MAX_CODES) this.codes.shift();
6301
+ return value;
6302
+ }
6303
+ /** Expiry time of a code minted now, as UTC ISO 8601. */
6304
+ codeExpiresAt() {
6305
+ return new Date(this.now() + CODE_TTL_MS).toISOString();
6306
+ }
6307
+ /**
6308
+ * Swap a code for a new session id. The code is removed before the age check,
6309
+ * so a code is consumed even when this call fails. Returns null on failure.
6310
+ */
6311
+ redeemCode(code) {
6312
+ if (!code) return null;
6313
+ let found;
6314
+ for (const c of this.codes) if (safeEqual(c.value, code)) found = c;
6315
+ if (!found) return null;
6316
+ this.codes = this.codes.filter((c) => c !== found);
6317
+ const age = this.now() - found.mintedAt;
6318
+ if (age < 0 || age >= CODE_TTL_MS) return null;
6319
+ const t = this.now();
6320
+ const s = { id: randomToken(), csrf: randomToken(), tab: randomToken(), createdAt: t, lastSeenAt: t };
6321
+ this.sessions.push(s);
6322
+ while (this.sessions.length > MAX_SESSIONS) this.sessions.shift();
6323
+ return s.id;
6324
+ }
6325
+ /** Remove a code without making a session (a refused /login still uses up its code). */
6326
+ discardCode(code) {
6327
+ if (!code) return;
6328
+ this.codes = this.codes.filter((c) => !safeEqual(c.value, code));
6329
+ }
6330
+ /**
6331
+ * Find a live session and mark it used. A session past the idle TTL or the absolute TTL
6332
+ * is removed and the call returns null.
6333
+ */
6334
+ getSession(id) {
6335
+ return this.findSession(id, null);
6336
+ }
6337
+ /**
6338
+ * As getSession, but the session's tab token must match too (constant time). A wrong or missing token
6339
+ * returns null and does not mark the session used.
6340
+ */
6341
+ getTabSession(id, tab) {
6342
+ return this.findSession(id, tab ?? "");
6343
+ }
6344
+ findSession(id, tab) {
6345
+ if (!id) return null;
6346
+ let found = null;
6347
+ for (const s of this.sessions) if (safeEqual(s.id, id)) found = s;
6348
+ if (!found) return null;
6349
+ if (tab !== null && !safeEqual(found.tab, tab)) return null;
6350
+ const t = this.now();
6351
+ if (t - found.lastSeenAt >= SESSION_IDLE_MS || t - found.createdAt >= SESSION_MAX_MS) {
6352
+ this.sessions = this.sessions.filter((x2) => x2 !== found);
6353
+ return null;
6354
+ }
6355
+ found.lastSeenAt = t;
6356
+ return found;
6357
+ }
6358
+ deleteSession(id) {
6359
+ const s = this.getSession(id);
6360
+ if (s) this.sessions = this.sessions.filter((x2) => x2 !== s);
6361
+ }
6362
+ codeCount() {
6363
+ return this.codes.length;
6364
+ }
6365
+ sessionCount() {
6366
+ return this.sessions.length;
6367
+ }
6368
+ };
6369
+ }
6370
+ });
6371
+
6372
+ // src/hub/server.ts
6373
+ import http from "http";
6374
+ function send(res, status5, body, extra = {}) {
6375
+ const text = JSON.stringify(body);
6376
+ res.writeHead(status5, {
6377
+ "Content-Type": "application/json; charset=utf-8",
6378
+ "Content-Length": Buffer.byteLength(text),
6379
+ ...extra
6380
+ });
6381
+ res.end(text);
6382
+ }
6383
+ function readBody(req) {
6384
+ return new Promise((resolve, reject) => {
6385
+ const declared = Number(req.headers["content-length"] ?? 0);
6386
+ if (declared > MAX_BODY_BYTES) {
6387
+ reject(new BodyTooLarge());
6388
+ return;
6389
+ }
6390
+ const chunks = [];
6391
+ let size = 0;
6392
+ let done = false;
6393
+ req.on("data", (c) => {
6394
+ if (done) return;
6395
+ size += c.length;
6396
+ if (size > MAX_BODY_BYTES) {
6397
+ done = true;
6398
+ reject(new BodyTooLarge());
6399
+ return;
6400
+ }
6401
+ chunks.push(c);
6402
+ });
6403
+ req.on("end", () => {
6404
+ if (!done) resolve(Buffer.concat(chunks));
6405
+ });
6406
+ req.on("error", (e2) => {
6407
+ if (!done) reject(e2);
6408
+ });
6409
+ });
6410
+ }
6411
+ function tooLarge(req, res) {
6412
+ res.on("finish", () => req.socket.destroy());
6413
+ fail(res, 413, "body_too_large");
6414
+ }
6415
+ function keyOk(req, key) {
6416
+ const v2 = req.headers[KEY_HEADER];
6417
+ return typeof v2 === "string" && safeEqual(v2, key);
6418
+ }
6419
+ async function startServer(opts) {
6420
+ const host = opts.host ?? "127.0.0.1";
6421
+ if (host !== "127.0.0.1") throw new Error("the hub server binds 127.0.0.1 only");
6422
+ if (typeof opts.key !== "string" || Buffer.byteLength(opts.key, "utf8") < MIN_KEY_BYTES) {
6423
+ throw new Error(`the hub server key must be at least ${MIN_KEY_BYTES} bytes`);
6424
+ }
6425
+ const auth = new AuthStore(opts.now ?? Date.now);
6426
+ const { key, versions } = opts;
6427
+ let port = opts.port;
6428
+ const sessionOf = (req) => auth.getSession(parseCookies(req.headers.cookie)[SESSION_COOKIE]);
6429
+ const tabSessionOf = (req) => {
6430
+ const tab = req.headers[TAB_HEADER];
6431
+ return auth.getTabSession(parseCookies(req.headers.cookie)[SESSION_COOKIE], typeof tab === "string" ? tab : "");
6432
+ };
6433
+ async function handle(req, res) {
6434
+ res.setHeader("Content-Security-Policy", CSP);
6435
+ res.setHeader("X-Content-Type-Options", "nosniff");
6436
+ res.setHeader("Referrer-Policy", "no-referrer");
6437
+ let url;
6438
+ try {
6439
+ url = new URL(req.url ?? "/", "http://127.0.0.1");
6440
+ } catch {
6441
+ fail(res, 400, "bad_url");
6442
+ return;
6443
+ }
6444
+ const path19 = url.pathname;
6445
+ const method = req.method ?? "GET";
6446
+ if (path19.startsWith("/api/") || path19 === "/login") res.setHeader("Cache-Control", "no-store");
6447
+ if (!hostAllowed(req.headers.host, port)) {
6448
+ if (path19 === "/login") auth.discardCode(url.searchParams.get("code") ?? "");
6449
+ fail(res, 403, "bad_host");
6450
+ return;
6451
+ }
6452
+ if (path19 === "/api/hub/whoami" && method === "GET") {
6453
+ if (!opts.instance) return fail(res, 404, "not_found");
6454
+ return send(res, 200, { instance: opts.instance });
6455
+ }
6456
+ if (path19 === "/api/health" && method === "GET") {
6457
+ if (!keyOk(req, key)) return fail(res, 401, "unauthorized");
6458
+ return send(res, 200, { schema: 1, ok: true, versions });
6459
+ }
6460
+ if (path19 === "/api/hub/code" && method === "POST") {
6461
+ if (!keyOk(req, key)) return fail(res, 401, "unauthorized");
6462
+ try {
6463
+ await readBody(req);
6464
+ } catch (e2) {
6465
+ if (e2 instanceof BodyTooLarge) return tooLarge(req, res);
6466
+ throw e2;
6467
+ }
6468
+ const code = auth.mintCode();
6469
+ return send(res, 200, { schema: 1, code, expires_at: auth.codeExpiresAt() });
6470
+ }
6471
+ if (path19 === "/api/hub/stop" && method === "POST") {
6472
+ if (!keyOk(req, key)) return fail(res, 401, "unauthorized");
6473
+ try {
6474
+ await readBody(req);
6475
+ } catch (e2) {
6476
+ if (e2 instanceof BodyTooLarge) return tooLarge(req, res);
6477
+ throw e2;
6478
+ }
6479
+ res.on("finish", () => opts.onStop?.());
6480
+ return send(res, 200, { schema: 1, ok: true });
6481
+ }
6482
+ if (method !== "GET") {
6483
+ const origin = req.headers.origin;
6484
+ if (!originAllowed(typeof origin === "string" ? origin : void 0, port)) return fail(res, 403, "bad_origin");
6485
+ const session = sessionOf(req);
6486
+ if (!session) return fail(res, 401, "unauthorized");
6487
+ const token = req.headers[CSRF_HEADER];
6488
+ if (typeof token !== "string" || !safeEqual(token, session.csrf)) return fail(res, 403, "bad_csrf");
6489
+ try {
6490
+ await readBody(req);
6491
+ } catch (e2) {
6492
+ if (e2 instanceof BodyTooLarge) return tooLarge(req, res);
6493
+ throw e2;
6494
+ }
6495
+ if (path19 === "/api/logout" && method === "POST") {
6496
+ auth.deleteSession(session.id);
6497
+ return send(res, 200, { schema: 1, ok: true }, {
6498
+ "Set-Cookie": `${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`
6499
+ });
6500
+ }
6501
+ return fail(res, 404, "not_found");
6502
+ }
6503
+ if (path19 === "/") {
6504
+ res.writeHead(200, {
6505
+ "Content-Type": "text/html; charset=utf-8",
6506
+ "Content-Length": Buffer.byteLength(PLACEHOLDER_HTML)
6507
+ });
6508
+ res.end(PLACEHOLDER_HTML);
6509
+ return;
6510
+ }
6511
+ if (path19 === "/login") {
6512
+ const id = auth.redeemCode(url.searchParams.get("code") ?? "");
6513
+ const session = id ? auth.getSession(id) : null;
6514
+ if (!id || !session) return fail(res, 401, "bad_code");
6515
+ res.writeHead(303, {
6516
+ Location: `/#tab=${session.tab}`,
6517
+ "Set-Cookie": `${SESSION_COOKIE}=${id}; HttpOnly; SameSite=Strict; Path=/`,
6518
+ "Content-Length": 0
6519
+ });
6520
+ res.end();
6521
+ return;
6522
+ }
6523
+ if (path19 === "/api/session") {
6524
+ const session = tabSessionOf(req);
6525
+ if (!session) return fail(res, 401, "unauthorized");
6526
+ return send(res, 200, { schema: 1, csrf_token: session.csrf, versions });
6527
+ }
6528
+ if (path19 === "/api/state") {
6529
+ if (!tabSessionOf(req)) return fail(res, 401, "unauthorized");
6530
+ let state;
6531
+ try {
6532
+ state = await opts.getState();
6533
+ } catch {
6534
+ return fail(res, 500, "state_failed");
6535
+ }
6536
+ return send(res, 200, state);
6537
+ }
6538
+ return fail(res, 404, "not_found");
6539
+ }
6540
+ const server = http.createServer((req, res) => {
6541
+ handle(req, res).catch(() => {
6542
+ if (!res.headersSent) fail(res, 500, "internal");
6543
+ else res.destroy();
6544
+ });
6545
+ });
6546
+ server.headersTimeout = 1e4;
6547
+ server.requestTimeout = 15e3;
6548
+ await new Promise((resolve, reject) => {
6549
+ const onError = (e2) => reject(e2);
6550
+ server.once("error", onError);
6551
+ server.listen(opts.port, host, () => {
6552
+ server.off("error", onError);
6553
+ resolve();
6554
+ });
6555
+ });
6556
+ const addr = server.address();
6557
+ port = addr.port;
6558
+ return {
6559
+ port,
6560
+ address: addr.address,
6561
+ close: () => new Promise((resolve) => {
6562
+ server.close(() => resolve());
6563
+ server.closeAllConnections();
6564
+ })
6565
+ };
6566
+ }
6567
+ var SESSION_COOKIE, KEY_HEADER, CSRF_HEADER, TAB_HEADER, MAX_BODY_BYTES, MIN_KEY_BYTES, CSP, PLACEHOLDER_HTML, BodyTooLarge, fail;
6568
+ var init_server = __esm({
6569
+ "src/hub/server.ts"() {
6570
+ "use strict";
6571
+ init_auth();
6572
+ SESSION_COOKIE = "caddis_hub_session";
6573
+ KEY_HEADER = "x-caddis-hub-key";
6574
+ CSRF_HEADER = "x-csrf-token";
6575
+ TAB_HEADER = "x-caddis-hub-tab";
6576
+ MAX_BODY_BYTES = 16 * 1024;
6577
+ MIN_KEY_BYTES = 32;
6578
+ CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
6579
+ PLACEHOLDER_HTML = '<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>caddis hub</title>\n</head>\n<body>\n<h1>caddis hub</h1>\n<p>UI arrives in H2.</p>\n</body>\n</html>\n';
6580
+ BodyTooLarge = class extends Error {
6581
+ };
6582
+ fail = (res, status5, error) => send(res, status5, { schema: 1, error });
6583
+ }
6584
+ });
6585
+
6586
+ // src/hub/bounded.ts
6587
+ function withTimeout(work, ms, what) {
6588
+ let timer;
6589
+ const limit = new Promise((_resolve, reject) => {
6590
+ timer = setTimeout(() => reject(new Error(`${what} did not finish in ${Math.round(ms / 1e3)} s`)), ms);
6591
+ timer.unref();
6592
+ });
6593
+ return Promise.race([work, limit]).finally(() => clearTimeout(timer));
6594
+ }
6595
+ var init_bounded = __esm({
6596
+ "src/hub/bounded.ts"() {
6597
+ "use strict";
6598
+ }
6599
+ });
6600
+
6601
+ // src/hub/spawn.ts
6602
+ import { spawn } from "child_process";
6603
+ function killTree(pid) {
6604
+ if (process.platform === "win32") {
6605
+ try {
6606
+ spawn("taskkill", ["/T", "/F", "/PID", String(pid)], {
6607
+ windowsHide: true,
6608
+ shell: false,
6609
+ stdio: "ignore"
6610
+ }).on("error", () => {
6611
+ });
6612
+ } catch {
6613
+ }
6614
+ return;
6615
+ }
6616
+ try {
6617
+ process.kill(-pid, "SIGKILL");
6618
+ } catch {
6619
+ try {
6620
+ process.kill(pid, "SIGKILL");
6621
+ } catch {
6622
+ }
6623
+ }
6624
+ }
6625
+ function wrapWindowsShim(cmd, args) {
6626
+ if (process.platform !== "win32" || !/\.(cmd|bat)$/i.test(cmd)) return null;
6627
+ if (UNSAFE_PATH.test(cmd)) return { error: `refused: the command path contains an unsafe character: ${cmd}` };
6628
+ for (const a of args) {
6629
+ if (!SAFE_ARG.test(a)) return { error: `refused argument for a .cmd shim: ${JSON.stringify(a)}` };
6630
+ }
6631
+ return { cmd: process.env.ComSpec || "cmd.exe", args: ["/d", "/s", "/c", `""${cmd}"${args.map((a) => ` ${a}`).join("")}"`] };
6632
+ }
6633
+ var DEFAULT_MAX_BYTES, SAFE_ARG, UNSAFE_PATH, spawnBounded;
6634
+ var init_spawn = __esm({
6635
+ "src/hub/spawn.ts"() {
6636
+ "use strict";
6637
+ DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
6638
+ SAFE_ARG = /^[A-Za-z0-9._:/@=-]+$/;
6639
+ UNSAFE_PATH = /["&|<>^%!\r\n]/;
6640
+ spawnBounded = (cmd, args, opts) => new Promise((resolve) => {
6641
+ let verbatim = false;
6642
+ const wrapped = wrapWindowsShim(cmd, args);
6643
+ if (wrapped && "error" in wrapped) {
6644
+ resolve({ ok: false, code: null, stdout: "", stderr: wrapped.error, timedOut: false });
6645
+ return;
6646
+ }
6647
+ if (wrapped) {
6648
+ verbatim = true;
6649
+ cmd = wrapped.cmd;
6650
+ args = wrapped.args;
6651
+ }
6652
+ const cap = opts.maxBytes ?? DEFAULT_MAX_BYTES;
6653
+ let stdout = "";
6654
+ let stderr = "";
6655
+ let timedOut = false;
6656
+ let settled = false;
6657
+ const finish2 = (code, extraErr = "") => {
6658
+ if (settled) return;
6659
+ settled = true;
6660
+ clearTimeout(timer);
6661
+ resolve({
6662
+ ok: code === 0 && !timedOut,
6663
+ code,
6664
+ stdout,
6665
+ stderr: extraErr ? `${stderr}${stderr ? "\n" : ""}${extraErr}` : stderr,
6666
+ timedOut
6667
+ });
6668
+ };
6669
+ let child;
6670
+ try {
6671
+ child = spawn(cmd, args, {
6672
+ cwd: opts.cwd,
6673
+ env: opts.env ? { ...process.env, ...opts.env } : process.env,
6674
+ windowsHide: true,
6675
+ shell: false,
6676
+ // The wrapped command line is already quoted for cmd.exe. Node must not quote it again.
6677
+ windowsVerbatimArguments: verbatim,
6678
+ detached: process.platform !== "win32",
6679
+ stdio: ["ignore", "pipe", "pipe"]
6680
+ });
6681
+ } catch (error) {
6682
+ resolve({
6683
+ ok: false,
6684
+ code: null,
6685
+ stdout: "",
6686
+ stderr: error instanceof Error ? error.message : String(error),
6687
+ timedOut: false
6688
+ });
6689
+ return;
6690
+ }
6691
+ const timer = setTimeout(() => {
6692
+ timedOut = true;
6693
+ if (child.pid !== void 0) killTree(child.pid);
6694
+ setTimeout(() => finish2(null), 2e3).unref();
6695
+ }, opts.timeoutMs);
6696
+ const append = (current, chunk) => {
6697
+ if (current.length >= cap) return current;
6698
+ return (current + chunk.toString("utf8")).slice(0, cap);
6699
+ };
6700
+ child.stdout?.on("data", (c) => {
6701
+ stdout = append(stdout, c);
6702
+ });
6703
+ child.stderr?.on("data", (c) => {
6704
+ stderr = append(stderr, c);
6705
+ });
6706
+ child.on("error", (error) => finish2(null, error.message));
6707
+ child.on("close", (code) => finish2(code));
6708
+ });
6709
+ }
6710
+ });
6711
+
6712
+ // src/hub/sources/agents.ts
6713
+ import { existsSync as existsSync7, readFileSync as readFileSync10, statSync } from "fs";
6714
+ import path13 from "path";
6715
+ function classifyWaiting(waitingFor) {
6716
+ const w2 = (waitingFor ?? "").toLowerCase();
6717
+ if (w2 === "permission prompt" || w2 === "input needed" || w2.includes("question")) return "owner";
6718
+ return "peer";
6719
+ }
6720
+ function repoPathFor(cwd) {
6721
+ if (!cwd) return null;
6722
+ let dir = path13.resolve(cwd);
6723
+ for (; ; ) {
6724
+ const dotGit = path13.join(dir, ".git");
6725
+ if (existsSync7(dotGit)) {
6726
+ if (isDir(dotGit)) return normalizeRepoPath(dir);
6727
+ if (isFile(dotGit)) return commonRoot(dir, dotGit);
6728
+ return null;
6729
+ }
6730
+ const parent = path13.dirname(dir);
6731
+ if (parent === dir) return null;
6732
+ dir = parent;
6733
+ }
6734
+ }
6735
+ function commonRoot(dir, dotGitFile) {
6736
+ try {
6737
+ const m2 = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync10(dotGitFile, "utf8"));
6738
+ if (!m2) return null;
6739
+ const gitdir = path13.resolve(dir, m2[1] ?? "");
6740
+ let common;
6741
+ try {
6742
+ const rel = readFileSync10(path13.join(gitdir, "commondir"), "utf8").trim();
6743
+ if (!rel) return normalizeRepoPath(dir);
6744
+ common = path13.resolve(gitdir, rel);
6745
+ } catch {
6746
+ return normalizeRepoPath(dir);
6747
+ }
6748
+ return normalizeRepoPath(path13.dirname(common));
6749
+ } catch {
6750
+ return null;
6751
+ }
6752
+ }
6753
+ function createAgentsSource(opts = {}) {
6754
+ const now = opts.now ?? Date.now;
6755
+ const spawn2 = opts.spawn ?? spawnBounded;
6756
+ const find2 = opts.findClaude ?? (() => findBin("claude"));
6757
+ const waitingSince = /* @__PURE__ */ new Map();
6758
+ let sessions = null;
6759
+ let lastOkAt = null;
6760
+ let lastError = null;
6761
+ let lastRunOk = false;
6762
+ let running = null;
6763
+ const fail2 = (message3) => {
6764
+ lastError = message3;
6765
+ lastRunOk = false;
6766
+ };
6767
+ const ingest = (parsed) => {
6768
+ if (!Array.isArray(parsed)) return fail2("claude agents output is not a JSON array");
6769
+ const t = now();
6770
+ const byId = /* @__PURE__ */ new Map();
6771
+ const seenWaiting = /* @__PURE__ */ new Set();
6772
+ for (const raw of parsed) {
6773
+ if (!raw || typeof raw !== "object") continue;
6774
+ const e2 = raw;
6775
+ const sessionId = str(e2.sessionId);
6776
+ if (!sessionId) continue;
6777
+ const kind = str(e2.kind) ?? "interactive";
6778
+ const status5 = str(e2.status) ?? str(e2.state) ?? "unknown";
6779
+ if (kind === "background" && status5 === "done") continue;
6780
+ const prior = byId.get(sessionId);
6781
+ if (prior) {
6782
+ prior.copies += 1;
6783
+ continue;
6784
+ }
6785
+ const pid = typeof e2.pid === "number" ? e2.pid : null;
6786
+ const cwd = str(e2.cwd);
6787
+ const isWaiting = status5 === "waiting";
6788
+ const waitingFor = isWaiting ? str(e2.waitingFor) : null;
6789
+ const key = `${pid ?? str(e2.id) ?? kind}:${sessionId}`;
6790
+ let since = null;
6791
+ if (isWaiting) {
6792
+ seenWaiting.add(key);
6793
+ since = waitingSince.get(key) ?? t;
6794
+ waitingSince.set(key, since);
6795
+ }
6796
+ const confirmed = isWaiting && t - (since ?? t) >= WAIT_DEBOUNCE_MS;
6797
+ byId.set(sessionId, {
6798
+ key,
6799
+ pid,
6800
+ session_id: sessionId,
6801
+ name: str(e2.name),
6802
+ kind,
6803
+ cwd,
6804
+ repo_path: repoPathFor(cwd),
6805
+ status: status5,
6806
+ waiting_for: waitingFor,
6807
+ waiting_class: confirmed ? classifyWaiting(waitingFor) : null,
6808
+ waiting_since: since === null ? null : new Date(since).toISOString(),
6809
+ copies: 1
6810
+ });
6811
+ }
6812
+ for (const k3 of [...waitingSince.keys()]) if (!seenWaiting.has(k3)) waitingSince.delete(k3);
6813
+ sessions = [...byId.values()];
6814
+ lastOkAt = t;
6815
+ lastError = null;
6816
+ lastRunOk = true;
6817
+ };
6818
+ const run2 = async () => {
6819
+ const bin = await withTimeout(find2(), FIND_TIMEOUT_MS, "finding claude");
6820
+ if (!bin) return fail2("claude was not found on PATH");
6821
+ const result = await spawn2(bin, ["agents", "--json"], { timeoutMs: RUN_TIMEOUT_MS });
6822
+ if (result.timedOut) return fail2(`claude agents timed out after ${RUN_TIMEOUT_MS / 1e3} s`);
6823
+ if (!result.ok) {
6824
+ const detail2 = (result.stderr || result.stdout).trim().slice(0, 500);
6825
+ return fail2(`claude agents failed (exit ${result.code ?? "none"})${detail2 ? `: ${detail2}` : ""}`);
6826
+ }
6827
+ let parsed;
6828
+ try {
6829
+ parsed = JSON.parse(result.stdout);
6830
+ } catch (error) {
6831
+ return fail2(`claude agents output is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
6832
+ }
6833
+ ingest(parsed);
6834
+ };
6835
+ return {
6836
+ refresh() {
6837
+ if (!running) {
6838
+ running = run2().catch((error) => fail2(error instanceof Error ? error.message : String(error))).finally(() => {
6839
+ running = null;
6840
+ });
6841
+ }
6842
+ return running;
6843
+ },
6844
+ get() {
6845
+ return {
6846
+ ok: lastRunOk,
6847
+ last_ok_at: lastOkAt === null ? null : new Date(lastOkAt).toISOString(),
6848
+ last_error: lastError,
6849
+ stale: lastOkAt === null || now() - lastOkAt > STALE_AFTER_MS2,
6850
+ data: sessions
6851
+ };
6852
+ }
6853
+ };
6854
+ }
6855
+ var STALE_AFTER_MS2, WAIT_DEBOUNCE_MS, RUN_TIMEOUT_MS, FIND_TIMEOUT_MS, isFile, isDir, str;
6856
+ var init_agents = __esm({
6857
+ "src/hub/sources/agents.ts"() {
6858
+ "use strict";
6859
+ init_which();
6860
+ init_bounded();
6861
+ init_spawn();
6862
+ init_config();
6863
+ STALE_AFTER_MS2 = 3 * 6e4;
6864
+ WAIT_DEBOUNCE_MS = 45e3;
6865
+ RUN_TIMEOUT_MS = 1e4;
6866
+ FIND_TIMEOUT_MS = 1e4;
6867
+ isFile = (p2) => {
6868
+ try {
6869
+ return statSync(p2).isFile();
6870
+ } catch {
6871
+ return false;
6872
+ }
6873
+ };
6874
+ isDir = (p2) => {
6875
+ try {
6876
+ return statSync(p2).isDirectory();
6877
+ } catch {
6878
+ return false;
6879
+ }
6880
+ };
6881
+ str = (v2) => typeof v2 === "string" && v2 ? v2 : null;
6882
+ }
6883
+ });
6884
+
6885
+ // src/hub/sources/collector.ts
6886
+ import { existsSync as existsSync8 } from "fs";
6887
+ import os5 from "os";
6888
+ import path14 from "path";
6889
+ function defaultScriptPath() {
6890
+ const name = "caddis_hub_collect.py";
6891
+ const bundle = bundlePath("antigravity-plugin", { requireManifest: false });
6892
+ if (bundle) {
6893
+ const shipped = path14.join(bundle, "scripts", name);
6894
+ if (existsSync8(shipped)) return shipped;
6895
+ }
6896
+ return path14.join(packageInfo().root, "..", "scripts", name);
6897
+ }
6898
+ async function resolvePython() {
6899
+ const py = await find("python");
6900
+ if (py) return { cmd: py, pre: [] };
6901
+ if (process.platform === "win32") {
6902
+ const launcher = await find("py");
6903
+ if (launcher) return { cmd: launcher, pre: ["-3"] };
6904
+ return null;
6905
+ }
6906
+ const py3 = await find("python3");
6907
+ return py3 ? { cmd: py3, pre: [] } : null;
6908
+ }
6909
+ function createCollectorSource(opts) {
6910
+ const now = opts.now ?? Date.now;
6911
+ const spawn2 = opts.spawn ?? spawnBounded;
6912
+ const cache = /* @__PURE__ */ new Map();
6913
+ let spend = null;
6914
+ let guide = null;
6915
+ let schema = COLLECTOR_SCHEMA;
6916
+ let generatedAt = "";
6917
+ let lastOkAt = null;
6918
+ let lastError = null;
6919
+ let updateNeeded = false;
6920
+ let lastRunOk = false;
6921
+ let running = null;
6922
+ const fail2 = (message3) => {
6923
+ lastError = message3;
6924
+ lastRunOk = false;
6925
+ };
6926
+ const ingest = (parsed, wanted) => {
6927
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return fail2("collector output is not a JSON object");
6928
+ const out = parsed;
6929
+ const version = out.schema;
6930
+ if (typeof version !== "number" || !Number.isInteger(version) || version < COLLECTOR_SCHEMA - 1) {
6931
+ return fail2(`collector output has an unusable schema: ${String(version)}`);
6932
+ }
6933
+ if (version > COLLECTOR_SCHEMA) {
6934
+ updateNeeded = true;
6935
+ return fail2(`collector schema ${version} is newer than this hub (${COLLECTOR_SCHEMA}): update the hub`);
6936
+ }
6937
+ if (!Array.isArray(out.repos)) return fail2("collector output has no repos list");
6938
+ updateNeeded = false;
6939
+ schema = version;
6940
+ generatedAt = typeof out.generated_at === "string" ? out.generated_at : "";
6941
+ const keep = new Set(wanted);
6942
+ for (const key of [...cache.keys()]) if (!keep.has(key)) cache.delete(key);
6943
+ for (const entry of out.repos) {
6944
+ if (!entry || typeof entry.path !== "string" || !keep.has(entry.path)) continue;
6945
+ const old = cache.get(entry.path);
6946
+ if (entry.error !== void 0 || entry.fingerprint === void 0) {
6947
+ if (!old || old.error !== void 0) cache.set(entry.path, entry);
6948
+ continue;
6949
+ }
6950
+ if (!old || old.error !== void 0 || old.fingerprint !== entry.fingerprint) cache.set(entry.path, entry);
6951
+ }
6952
+ const keepOrError = (next, old) => {
6953
+ if (!next || typeof next !== "object") return old;
6954
+ const slot = next;
6955
+ if ("error" in slot && old && !("error" in old)) return old;
6956
+ return slot;
6957
+ };
6958
+ spend = keepOrError(out.spend, spend);
6959
+ guide = keepOrError(out.guide, guide);
6960
+ lastOkAt = now();
6961
+ lastError = null;
6962
+ lastRunOk = true;
6963
+ };
6964
+ const run2 = async () => {
6965
+ const repos = opts.repos();
6966
+ let cmd = opts.python;
6967
+ let pre = [];
6968
+ if (!cmd) {
6969
+ const found = await resolvePython();
6970
+ if (!found) return fail2("python was not found (tried python, then py -3)");
6971
+ cmd = found.cmd;
6972
+ pre = found.pre;
6973
+ }
6974
+ const script = opts.scriptPath ?? defaultScriptPath();
6975
+ const args = repos.length ? [...pre, script, "--repos", ...repos, "--json"] : [...pre, script, "--repos", path14.join(os5.tmpdir(), "caddis-hub-no-repos"), "--only", "spend,guide", "--json"];
6976
+ const result = await spawn2(cmd, args, { timeoutMs: RUN_TIMEOUT_MS2 });
6977
+ if (result.timedOut) return fail2(`collector timed out after ${RUN_TIMEOUT_MS2 / 1e3} s`);
6978
+ if (!result.ok) {
6979
+ const detail2 = (result.stderr || result.stdout).trim().slice(0, 500);
6980
+ return fail2(`collector failed (exit ${result.code ?? "none"})${detail2 ? `: ${detail2}` : ""}`);
6981
+ }
6982
+ let parsed;
6983
+ try {
6984
+ parsed = JSON.parse(result.stdout);
6985
+ } catch (error) {
6986
+ return fail2(`collector output is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
6987
+ }
6988
+ ingest(parsed, repos);
6989
+ };
6990
+ return {
6991
+ refresh() {
6992
+ if (!running) {
6993
+ running = run2().catch((error) => fail2(error instanceof Error ? error.message : String(error))).finally(() => {
6994
+ running = null;
6995
+ });
6996
+ }
6997
+ return running;
6998
+ },
6999
+ get() {
7000
+ const hasData = lastOkAt !== null;
7001
+ return {
7002
+ ok: lastRunOk,
7003
+ last_ok_at: lastOkAt === null ? null : new Date(lastOkAt).toISOString(),
7004
+ last_error: lastError,
7005
+ stale: lastOkAt === null || now() - lastOkAt > STALE_AFTER_MS3,
7006
+ update_needed: updateNeeded,
7007
+ data: hasData ? { schema, generated_at: generatedAt, repos: [...cache.values()], spend: spend ?? {}, guide: guide ?? {} } : null
7008
+ };
7009
+ }
7010
+ };
7011
+ }
7012
+ var COLLECTOR_SCHEMA, STALE_AFTER_MS3, RUN_TIMEOUT_MS2, FIND_TIMEOUT_MS2, find;
7013
+ var init_collector = __esm({
7014
+ "src/hub/sources/collector.ts"() {
7015
+ "use strict";
7016
+ init_pkg();
7017
+ init_which();
7018
+ init_bounded();
7019
+ init_spawn();
7020
+ COLLECTOR_SCHEMA = 1;
7021
+ STALE_AFTER_MS3 = 3 * 6e4;
7022
+ RUN_TIMEOUT_MS2 = 6e4;
7023
+ FIND_TIMEOUT_MS2 = 1e4;
7024
+ find = (name) => withTimeout(findBin(name), FIND_TIMEOUT_MS2, `finding ${name}`);
7025
+ }
7026
+ });
7027
+
7028
+ // src/hub/sources/coordinator.ts
7029
+ import { readdirSync as readdirSync3, readFileSync as readFileSync11 } from "fs";
7030
+ import path15 from "path";
7031
+ function stub(repoId, schema) {
7032
+ return {
7033
+ repo_id: repoId,
7034
+ schema,
7035
+ coordinator_session: null,
7036
+ heartbeat_at: null,
7037
+ queue: [],
7038
+ merging_now: null,
7039
+ deploy_checks: [],
7040
+ ledger: [],
7041
+ processed_requests: []
7042
+ };
7043
+ }
7044
+ function parse3(repoId, text) {
7045
+ let raw;
7046
+ try {
7047
+ raw = JSON.parse(text);
7048
+ } catch (e2) {
7049
+ return { error: `corrupt coordinator.json: ${e2.message}` };
7050
+ }
7051
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: "coordinator.json is not a JSON object" };
7052
+ const o2 = raw;
7053
+ const schema = o2.schema;
7054
+ if (typeof schema !== "number" || !Number.isInteger(schema) || schema < COORDINATOR_SCHEMA - 1) {
7055
+ return { error: `coordinator.json has an unusable schema: ${String(schema)}` };
7056
+ }
7057
+ if (schema > COORDINATOR_SCHEMA) {
7058
+ return {
7059
+ newer: stub(repoId, schema),
7060
+ error: `coordinator schema ${schema} is newer than this hub (${COORDINATOR_SCHEMA}): update the hub`
7061
+ };
7062
+ }
7063
+ return {
7064
+ good: {
7065
+ repo_id: repoId,
7066
+ schema,
7067
+ coordinator_session: o2.coordinator_session ?? null,
7068
+ heartbeat_at: typeof o2.heartbeat_at === "string" ? o2.heartbeat_at : null,
7069
+ queue: arr(o2.queue),
7070
+ merging_now: o2.merging_now ?? null,
7071
+ deploy_checks: arr(o2.deploy_checks).slice(-5),
7072
+ ledger: arr(o2.ledger).slice(-20),
7073
+ processed_requests: arr(o2.processed_requests).slice(-20)
7074
+ }
7075
+ };
7076
+ }
7077
+ function hubHome(home) {
7078
+ const override = process.env.CADDIS_HUB_HOME;
7079
+ return override ? override : hubDir(home);
7080
+ }
7081
+ function createCoordinatorSource(opts = {}) {
7082
+ const now = opts.now ?? Date.now;
7083
+ const lastGood2 = /* @__PURE__ */ new Map();
7084
+ const errors = /* @__PURE__ */ new Map();
7085
+ return {
7086
+ refresh() {
7087
+ const root = path15.join(hubHome(opts.home), "repos");
7088
+ let ids = [];
7089
+ try {
7090
+ ids = readdirSync3(root, { withFileTypes: true }).filter((d3) => d3.isDirectory()).map((d3) => d3.name);
7091
+ } catch {
7092
+ }
7093
+ const seen = new Set(ids);
7094
+ for (const id of [...lastGood2.keys()]) if (!seen.has(id)) lastGood2.delete(id);
7095
+ for (const id of [...errors.keys()]) if (!seen.has(id)) errors.delete(id);
7096
+ for (const id of ids) {
7097
+ let text;
7098
+ try {
7099
+ text = readFileSync11(path15.join(root, id, "coordinator.json"), "utf8");
7100
+ } catch (e2) {
7101
+ if (e2.code === "ENOENT") {
7102
+ lastGood2.delete(id);
7103
+ errors.delete(id);
7104
+ } else {
7105
+ if (!lastGood2.has(id)) lastGood2.set(id, stub(id, null));
7106
+ errors.set(id, { error: `cannot read coordinator.json: ${e2.message}`, updateNeeded: false });
7107
+ }
7108
+ continue;
7109
+ }
7110
+ const r2 = parse3(id, text);
7111
+ if (r2.good) {
7112
+ lastGood2.set(id, r2.good);
7113
+ errors.delete(id);
7114
+ continue;
7115
+ }
7116
+ if (!lastGood2.has(id)) lastGood2.set(id, r2.newer ?? stub(id, null));
7117
+ errors.set(id, { error: r2.error ?? "unreadable", updateNeeded: r2.newer !== void 0 });
7118
+ }
7119
+ },
7120
+ get() {
7121
+ const t = now();
7122
+ const out = [];
7123
+ for (const [id, good] of lastGood2) {
7124
+ const ms = good.heartbeat_at ? Date.parse(good.heartbeat_at) : NaN;
7125
+ const age = Number.isNaN(ms) ? null : Math.max(0, Math.floor((t - ms) / 1e3));
7126
+ const err = errors.get(id);
7127
+ out.push({
7128
+ ...good,
7129
+ heartbeat_age_s: age,
7130
+ responding: age !== null && age < RESPONDING_WITHIN_S,
7131
+ error: err?.error ?? null,
7132
+ update_needed: err?.updateNeeded ?? false
7133
+ });
7134
+ }
7135
+ return out.sort((a, b3) => a.repo_id.localeCompare(b3.repo_id));
7136
+ }
7137
+ };
7138
+ }
7139
+ var COORDINATOR_SCHEMA, RESPONDING_WITHIN_S, arr;
7140
+ var init_coordinator = __esm({
7141
+ "src/hub/sources/coordinator.ts"() {
7142
+ "use strict";
7143
+ init_paths();
7144
+ COORDINATOR_SCHEMA = 1;
7145
+ RESPONDING_WITHIN_S = 180;
7146
+ arr = (v2) => Array.isArray(v2) ? v2 : [];
7147
+ }
7148
+ });
7149
+
7150
+ // src/hub/sources/github.ts
7151
+ import { readFileSync as readFileSync12 } from "fs";
7152
+ import path16 from "path";
7153
+ function parseGithubRemote(url) {
7154
+ const m2 = /^(?:https?:\/\/(?:[^@/]+@)?|ssh:\/\/git@|git@)github\.com[/:]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(url.trim());
7155
+ return m2 ? `${m2[1]}/${m2[2]}` : null;
7156
+ }
7157
+ function readOriginUrl(repoDir) {
7158
+ const root = repoPathFor(repoDir);
7159
+ if (!root) return null;
7160
+ let text;
7161
+ try {
7162
+ text = readFileSync12(path16.join(root, ".git", "config"), "utf8");
7163
+ } catch {
7164
+ return null;
7165
+ }
7166
+ let inOrigin = false;
7167
+ for (const line2 of text.split(/\r?\n/)) {
7168
+ const section = /^\s*\[(.+)\]\s*$/.exec(line2);
7169
+ if (section) {
7170
+ inOrigin = /^remote\s+"origin"$/.test(section[1] ?? "");
7171
+ continue;
7172
+ }
7173
+ const kv = inOrigin ? /^\s*url\s*=\s*(.+?)\s*$/.exec(line2) : null;
7174
+ if (kv) return kv[1] ?? null;
7175
+ }
7176
+ return null;
7177
+ }
7178
+ function readRequiredChecks(repoDir) {
7179
+ try {
7180
+ const text = readFileSync12(path16.join(repoDir, ".caddis", "coordinator.md"), "utf8");
7181
+ const m2 = /```json[^\S\r\n]*\r?\n([\s\S]*?)\r?\n[^\S\r\n]*```/.exec(text);
7182
+ if (!m2) return null;
7183
+ const parsed = JSON.parse(m2[1] ?? "");
7184
+ if (!parsed || typeof parsed !== "object") return null;
7185
+ const req = parsed.required_checks;
7186
+ if (!Array.isArray(req) || !req.every((x2) => typeof x2 === "string")) return null;
7187
+ return req;
7188
+ } catch {
7189
+ return null;
7190
+ }
7191
+ }
7192
+ function requiredState(checks, required) {
7193
+ if (required === null) return "unknown";
7194
+ let pending = false;
7195
+ for (const name of required) {
7196
+ const c = checks.find((x2) => x2.name === name);
7197
+ if (!c || c.status !== "completed") pending = true;
7198
+ else if (c.conclusion && FAILED.has(c.conclusion)) return "fail";
7199
+ else if (!c.conclusion || !PASSED.has(c.conclusion)) pending = true;
7200
+ }
7201
+ return pending ? "pending" : "pass";
7202
+ }
7203
+ async function defaultToken(spawn2, account) {
7204
+ const gh = await findGh();
7205
+ if (!gh) return null;
7206
+ const r2 = await spawn2(gh, ["auth", "token", "-u", account], { timeoutMs: TOKEN_TIMEOUT_MS });
7207
+ const token = r2.stdout.trim();
7208
+ return r2.ok && token ? token : null;
7209
+ }
7210
+ function parseAuthStatus(text) {
7211
+ const accounts = [];
7212
+ let active = null;
7213
+ let current = null;
7214
+ for (const line2 of text.split(/\r?\n/)) {
7215
+ const m2 = /Logged in to (\S+) (?:account|as) (\S+)/.exec(line2);
7216
+ if (m2) {
7217
+ current = m2[1] === "github.com" ? m2[2] ?? null : null;
7218
+ if (current && !accounts.includes(current)) accounts.push(current);
7219
+ continue;
7220
+ }
7221
+ if (current && /Active account:\s*true/i.test(line2)) active = current;
7222
+ }
7223
+ if (!active && accounts.length === 1) active = accounts[0] ?? null;
7224
+ return { active, accounts };
7225
+ }
7226
+ async function defaultAuthStatus(spawn2) {
7227
+ const gh = await findGh();
7228
+ if (!gh) return null;
7229
+ const r2 = await spawn2(gh, ["auth", "status", "-h", "github.com"], { timeoutMs: TOKEN_TIMEOUT_MS });
7230
+ if (r2.timedOut) return null;
7231
+ const status5 = parseAuthStatus(`${r2.stdout}
7232
+ ${r2.stderr}`);
7233
+ return status5.accounts.length || r2.ok ? status5 : null;
7234
+ }
7235
+ function accountCandidates(owner, status5, known) {
7236
+ if (!status5) return [known ?? owner];
7237
+ const out = [];
7238
+ const add = (a) => {
7239
+ if (a && !out.includes(a)) out.push(a);
7240
+ };
7241
+ if (known && status5.accounts.includes(known)) add(known);
7242
+ add(status5.accounts.find((a) => a.toLowerCase() === owner.toLowerCase()));
7243
+ add(status5.active);
7244
+ status5.accounts.forEach(add);
7245
+ return out;
7246
+ }
7247
+ function accessError(owner, tried) {
7248
+ const set = `set "accounts": {"${owner}": "<gh user>"} in ~/.caddis/hub/config.json`;
7249
+ if (!tried.length) return `no gh account is logged in: run gh auth login -h github.com, then ${set}`;
7250
+ return `no access with account ${tried.join(", ")}: run gh auth login -h github.com, or ${set}`;
7251
+ }
7252
+ function createGithubSource(opts) {
7253
+ const now = opts.now ?? Date.now;
7254
+ const doFetch = opts.fetch ?? ((url, init2) => fetch(url, init2));
7255
+ const spawn2 = opts.spawn ?? spawnBounded;
7256
+ const getToken = opts.getToken ?? ((account) => defaultToken(spawn2, account));
7257
+ const authStatus = opts.authStatus ?? (opts.getToken ? async () => null : () => defaultAuthStatus(spawn2));
7258
+ const ownerAccount = /* @__PURE__ */ new Map();
7259
+ let etags = /* @__PURE__ */ new Map();
7260
+ let seen = /* @__PURE__ */ new Set();
7261
+ const slots = /* @__PURE__ */ new Map();
7262
+ const rate = /* @__PURE__ */ new Map();
7263
+ let lastOkAt = null;
7264
+ let lastError = null;
7265
+ let lastRunOk = false;
7266
+ let running = null;
7267
+ const noteRate = (account, res) => {
7268
+ const left = res.headers.get("x-ratelimit-remaining");
7269
+ const remaining = Number(left);
7270
+ if (left === null || !Number.isFinite(remaining)) return;
7271
+ const reset = Number(res.headers.get("x-ratelimit-reset"));
7272
+ rate.set(account, {
7273
+ remaining,
7274
+ reset_at: Number.isFinite(reset) && reset > 0 ? new Date(reset * 1e3).toISOString() : null
7275
+ });
7276
+ };
7277
+ const getJson = async (account, token, pathAndQuery) => {
7278
+ const url = `${API}${pathAndQuery}`;
7279
+ const key = `${account}
7280
+ ${url}`;
7281
+ seen.add(key);
7282
+ const cached2 = etags.get(key);
7283
+ const headers = {
7284
+ Authorization: `Bearer ${token}`,
7285
+ Accept: "application/vnd.github+json",
7286
+ "X-GitHub-Api-Version": "2022-11-28",
7287
+ "User-Agent": "caddis-hub"
7288
+ };
7289
+ if (cached2) headers["If-None-Match"] = cached2.etag;
7290
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
7291
+ const res = await withTimeout(doFetch(url, { headers, signal }), FETCH_TIMEOUT_MS + 1e3, "GitHub request");
7292
+ noteRate(account, res);
7293
+ if (res.status === 304) {
7294
+ if (cached2) return cached2.body;
7295
+ throw new HttpError(304, false, "GitHub answered 304 with no cached copy");
7296
+ }
7297
+ if (!res.ok) {
7298
+ const limited = (res.status === 403 || res.status === 429) && (res.headers.get("x-ratelimit-remaining") === "0" || res.headers.get("retry-after") !== null);
7299
+ throw new HttpError(res.status, limited, limited ? "GitHub rate limit reached" : `GitHub answered ${res.status}`);
7300
+ }
7301
+ const body = await withTimeout(res.json(), FETCH_TIMEOUT_MS + 1e3, "GitHub response");
7302
+ const etag = res.headers.get("etag");
7303
+ if (etag) etags.set(key, { etag, body });
7304
+ return body;
7305
+ };
7306
+ const loadRepo = async (repoPath, repo, account, token) => {
7307
+ const required = readRequiredChecks(repoPath);
7308
+ let first;
7309
+ try {
7310
+ first = await getJson(account, token, `/repos/${repo}/pulls?state=open&per_page=50`);
7311
+ } catch (error) {
7312
+ if (error instanceof HttpError && error.status === 404) throw new HttpError(404, false, error.message, true);
7313
+ throw error;
7314
+ }
7315
+ const pulls = list(first);
7316
+ const prs = [];
7317
+ for (const p2 of pulls) {
7318
+ const head = str2(rec(p2.head).sha) ?? "";
7319
+ const byName = /* @__PURE__ */ new Map();
7320
+ if (head) {
7321
+ const body = rec(await getJson(account, token, `/repos/${repo}/commits/${head}/check-runs?per_page=100`));
7322
+ for (const c of list(body.check_runs)) {
7323
+ const name = str2(c.name);
7324
+ if (!name) continue;
7325
+ byName.set(name, {
7326
+ name,
7327
+ status: str2(c.status) ?? "unknown",
7328
+ conclusion: str2(c.conclusion),
7329
+ required: required === null ? null : required.includes(name)
7330
+ });
7331
+ }
7332
+ }
7333
+ const checks = [...byName.values()];
7334
+ prs.push({
7335
+ number: Number(p2.number),
7336
+ title: str2(p2.title) ?? "",
7337
+ head_sha: head,
7338
+ author: str2(rec(p2.user).login),
7339
+ draft: p2.draft === true,
7340
+ updated_at: str2(p2.updated_at),
7341
+ url: str2(p2.html_url) ?? "",
7342
+ checks,
7343
+ required_state: requiredState(checks, required)
7344
+ });
7345
+ }
7346
+ const closed = list(
7347
+ await getJson(account, token, `/repos/${repo}/pulls?state=closed&sort=updated&direction=desc&per_page=20`)
7348
+ );
7349
+ const merged = closed.filter((p2) => str2(p2.merged_at) && str2(p2.merge_commit_sha)).sort((a, b3) => String(b3.merged_at).localeCompare(String(a.merged_at))).slice(0, MERGES_SHOWN);
7350
+ const merges = [];
7351
+ for (const p2 of merged) {
7352
+ const sha = str2(p2.merge_commit_sha) ?? "";
7353
+ const body = rec(await getJson(account, token, `/repos/${repo}/actions/runs?head_sha=${sha}&per_page=10`));
7354
+ merges.push({
7355
+ number: Number(p2.number),
7356
+ title: str2(p2.title) ?? "",
7357
+ merge_sha: sha,
7358
+ merged_at: str2(p2.merged_at) ?? "",
7359
+ runs: list(body.workflow_runs).map((r2) => ({
7360
+ name: str2(r2.name) ?? "",
7361
+ status: str2(r2.status) ?? "unknown",
7362
+ conclusion: str2(r2.conclusion),
7363
+ url: str2(r2.html_url) ?? ""
7364
+ }))
7365
+ });
7366
+ }
7367
+ return { path: repoPath, repo, account, prs, merges };
7368
+ };
7369
+ const run2 = async () => {
7370
+ seen = /* @__PURE__ */ new Set();
7371
+ const limitedAccounts = /* @__PURE__ */ new Set();
7372
+ try {
7373
+ await runRepos(limitedAccounts);
7374
+ } finally {
7375
+ const kept = /* @__PURE__ */ new Map();
7376
+ for (const key of seen) {
7377
+ const entry = etags.get(key);
7378
+ if (entry) kept.set(key, entry);
7379
+ }
7380
+ etags = kept;
7381
+ }
7382
+ };
7383
+ const runRepos = async (limitedAccounts) => {
7384
+ const accounts = opts.accounts();
7385
+ const wanted = opts.repos();
7386
+ const tokens = /* @__PURE__ */ new Map();
7387
+ const errors = [];
7388
+ let loaded = false;
7389
+ let status5;
7390
+ const tokenFor = async (account) => {
7391
+ if (!tokens.has(account)) {
7392
+ tokens.set(account, await withTimeout(getToken(account), TOKEN_TIMEOUT_MS + 5e3, "gh auth token"));
7393
+ }
7394
+ return tokens.get(account) ?? null;
7395
+ };
7396
+ for (const key of [...slots.keys()]) if (!wanted.includes(key)) slots.delete(key);
7397
+ for (const repoPath of wanted) {
7398
+ const url = readOriginUrl(repoPath);
7399
+ const repo = url ? parseGithubRemote(url) : null;
7400
+ if (!repo) {
7401
+ slots.set(repoPath, { path: repoPath, reason: "no github remote" });
7402
+ continue;
7403
+ }
7404
+ const owner = repo.split("/")[0] ?? "";
7405
+ const override = accounts[repo] ?? accounts[owner];
7406
+ let candidates;
7407
+ if (override) {
7408
+ candidates = [override];
7409
+ } else {
7410
+ if (status5 === void 0) {
7411
+ status5 = await withTimeout(authStatus(), TOKEN_TIMEOUT_MS + 5e3, "gh auth status").catch(() => null);
7412
+ }
7413
+ candidates = accountCandidates(owner, status5, ownerAccount.get(owner));
7414
+ }
7415
+ const old = slots.get(repoPath);
7416
+ const tried = [];
7417
+ let settled = false;
7418
+ for (const account of candidates) {
7419
+ if (limitedAccounts.has(account)) {
7420
+ settled = true;
7421
+ break;
7422
+ }
7423
+ tried.push(account);
7424
+ try {
7425
+ const token = await tokenFor(account);
7426
+ if (!token) continue;
7427
+ const slot = await loadRepo(repoPath, repo, account, token);
7428
+ slots.set(repoPath, { ...slot, last_ok_at: new Date(now()).toISOString() });
7429
+ if (!override) ownerAccount.set(owner, account);
7430
+ loaded = true;
7431
+ settled = true;
7432
+ break;
7433
+ } catch (error) {
7434
+ if (error instanceof HttpError && error.access && !error.rateLimited) continue;
7435
+ if (error instanceof HttpError && error.rateLimited) limitedAccounts.add(account);
7436
+ const message3 = error instanceof Error ? error.message : String(error);
7437
+ errors.push(`${repo}: ${message3}`);
7438
+ if (old?.prs !== void 0) {
7439
+ if (!(error instanceof HttpError && error.rateLimited)) slots.set(repoPath, { ...old, error: message3 });
7440
+ } else {
7441
+ slots.set(repoPath, { path: repoPath, repo, account, error: message3 });
7442
+ }
7443
+ settled = true;
7444
+ break;
7445
+ }
7446
+ }
7447
+ if (!settled) {
7448
+ if (!override && ownerAccount.get(owner) !== void 0) ownerAccount.delete(owner);
7449
+ const slot = { path: repoPath, repo, error: accessError(owner, tried) };
7450
+ if (tried[0]) slot.account = tried[0];
7451
+ if (old?.last_ok_at) slot.last_ok_at = old.last_ok_at;
7452
+ slots.set(repoPath, slot);
7453
+ }
7454
+ }
7455
+ lastRunOk = errors.length === 0;
7456
+ lastError = errors.length ? errors.join("; ") : null;
7457
+ if (lastRunOk || loaded) lastOkAt = now();
7458
+ };
7459
+ return {
7460
+ refresh() {
7461
+ if (!running) {
7462
+ running = run2().catch((error) => {
7463
+ lastError = error instanceof Error ? error.message : String(error);
7464
+ lastRunOk = false;
7465
+ }).finally(() => {
7466
+ running = null;
7467
+ });
7468
+ }
7469
+ return running;
7470
+ },
7471
+ get() {
7472
+ return {
7473
+ ok: lastRunOk,
7474
+ last_ok_at: lastOkAt === null ? null : new Date(lastOkAt).toISOString(),
7475
+ last_error: lastError,
7476
+ stale: lastOkAt === null || now() - lastOkAt > STALE_AFTER_MS4,
7477
+ data: lastOkAt === null && slots.size === 0 ? null : { repos: [...slots.values()], rate: Object.fromEntries(rate) }
7478
+ };
7479
+ },
7480
+ nextDelayMs() {
7481
+ for (const r2 of rate.values()) if (r2.remaining < RATE_RESERVE) return SLOW_POLL_MS;
7482
+ return POLL_MS2;
7483
+ }
7484
+ };
7485
+ }
7486
+ var STALE_AFTER_MS4, POLL_MS2, SLOW_POLL_MS, RATE_RESERVE, API, TOKEN_TIMEOUT_MS, FIND_TIMEOUT_MS3, FETCH_TIMEOUT_MS, MERGES_SHOWN, FAILED, PASSED, HttpError, str2, rec, list, findGh;
7487
+ var init_github = __esm({
7488
+ "src/hub/sources/github.ts"() {
7489
+ "use strict";
7490
+ init_which();
7491
+ init_bounded();
7492
+ init_spawn();
7493
+ init_agents();
7494
+ STALE_AFTER_MS4 = 3 * 6e4;
7495
+ POLL_MS2 = 6e4;
7496
+ SLOW_POLL_MS = 5 * 6e4;
7497
+ RATE_RESERVE = 500;
7498
+ API = "https://api.github.com";
7499
+ TOKEN_TIMEOUT_MS = 1e4;
7500
+ FIND_TIMEOUT_MS3 = 1e4;
7501
+ FETCH_TIMEOUT_MS = 15e3;
7502
+ MERGES_SHOWN = 5;
7503
+ FAILED = /* @__PURE__ */ new Set(["failure", "cancelled", "timed_out", "action_required", "startup_failure", "stale"]);
7504
+ PASSED = /* @__PURE__ */ new Set(["success", "neutral", "skipped"]);
7505
+ HttpError = class extends Error {
7506
+ constructor(status5, rateLimited, message3, access = false) {
7507
+ super(message3);
7508
+ this.status = status5;
7509
+ this.rateLimited = rateLimited;
7510
+ this.access = access || status5 === 401 || status5 === 403 && !rateLimited;
7511
+ }
7512
+ status;
7513
+ rateLimited;
7514
+ /** This token cannot see the repo: try the next account. */
7515
+ access;
7516
+ };
7517
+ str2 = (v2) => typeof v2 === "string" && v2 ? v2 : null;
7518
+ rec = (v2) => v2 && typeof v2 === "object" ? v2 : {};
7519
+ list = (v2) => Array.isArray(v2) ? v2.map(rec) : [];
7520
+ findGh = () => withTimeout(findBin("gh"), FIND_TIMEOUT_MS3, "finding gh");
7521
+ }
7522
+ });
7523
+
7524
+ // src/hub/state.ts
7525
+ import { createHash as createHash2 } from "crypto";
7526
+ import { readFileSync as readFileSync13 } from "fs";
7527
+ import path17 from "path";
7528
+ function repoIdFor(nameWithOwner) {
7529
+ return nameWithOwner.trim().toLowerCase().replace(/\//g, "__");
7530
+ }
7531
+ function localRepoId(repoPath) {
7532
+ const norm = process.platform === "win32" ? repoPath.toLowerCase().replace(/\//g, "\\") : repoPath;
7533
+ const digest = createHash2("sha256").update(norm, "utf8").digest("hex").slice(0, 6);
7534
+ return `local__${path17.basename(repoPath)}__${digest}`;
7535
+ }
7536
+ function readPluginVersion(home) {
7537
+ try {
7538
+ const file = path17.join(home, ".claude", "plugins", "installed_plugins.json");
7539
+ const parsed = JSON.parse(readFileSync13(file, "utf8"));
7540
+ for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {
7541
+ if (!key.startsWith("caddis@") || !Array.isArray(entries)) continue;
7542
+ for (const e2 of entries) {
7543
+ const v2 = e2?.version;
7544
+ if (typeof v2 === "string" && v2) return v2;
7545
+ }
7546
+ }
7547
+ } catch {
7548
+ }
7549
+ return null;
7550
+ }
7551
+ function defaultVersions(home) {
7552
+ const pool = bundleManifest().poolVersion;
7553
+ return { hub: packageInfo().version, pool: pool === "unknown" ? null : pool, plugin: readPluginVersion(home) };
7554
+ }
7555
+ function createHub(opts = {}) {
7556
+ const home = opts.home ?? caddisHome();
7557
+ const now = opts.now ?? Date.now;
7558
+ const repoPaths = () => {
7559
+ const cfg = readConfig(home).value;
7560
+ const hidden = new Set(cfg.hidden.map((p2) => repoKey(normalizeRepoPath(p2))));
7561
+ const seen = /* @__PURE__ */ new Set();
7562
+ const out = [];
7563
+ const add = (p2) => {
7564
+ const n = normalizeRepoPath(p2);
7565
+ const k3 = repoKey(n);
7566
+ if (hidden.has(k3) || seen.has(k3)) return;
7567
+ seen.add(k3);
7568
+ out.push(n);
7569
+ };
7570
+ cfg.pinned.forEach(add);
7571
+ readRegistry(home).value.repos.forEach((r2) => add(r2.path));
7572
+ return out;
7573
+ };
7574
+ const collector = opts.collector ?? createCollectorSource({ repos: repoPaths, now });
7575
+ const agents = opts.agents ?? createAgentsSource({ now });
7576
+ const github = opts.github ?? createGithubSource({ repos: repoPaths, accounts: () => readConfig(home).value.accounts, now });
7577
+ const coordinator = opts.coordinator ?? createCoordinatorSource({ home, now });
7578
+ let versionsCache = null;
7579
+ const versions = () => {
7580
+ if (opts.versions) return opts.versions();
7581
+ if (!versionsCache || now() - versionsCache.at > VERSIONS_TTL_MS) {
7582
+ versionsCache = { at: now(), value: defaultVersions(home) };
7583
+ }
7584
+ return versionsCache.value;
7585
+ };
7586
+ const thrown = /* @__PURE__ */ new Map();
7587
+ let coordinatorOkAt = null;
7588
+ const guarded = async (name, run2) => {
7589
+ try {
7590
+ await withTimeout(Promise.resolve().then(run2), REFRESH_CEILING_MS[name], "refresh");
7591
+ thrown.delete(name);
7592
+ if (name === "coordinator") coordinatorOkAt = now();
7593
+ } catch (e2) {
7594
+ thrown.set(name, message(e2));
7595
+ }
7596
+ };
7597
+ const registerSessionRepos = () => {
7598
+ const sessions = agents.get().data ?? [];
7599
+ const paths = sessions.map((s) => s.repo_path).filter((p2) => typeof p2 === "string" && p2 !== "");
7600
+ if (!paths.length) return;
7601
+ try {
7602
+ addRepos(paths, home);
7603
+ } catch {
7604
+ }
7605
+ };
7606
+ const refreshers = {
7607
+ agents: () => guarded("agents", async () => {
7608
+ await agents.refresh();
7609
+ registerSessionRepos();
7610
+ }),
7611
+ collector: () => guarded("collector", () => collector.refresh()),
7612
+ github: () => guarded("github", () => github.refresh()),
7613
+ coordinator: () => guarded("coordinator", () => coordinator.refresh())
7614
+ };
7615
+ const delays = {
7616
+ agents: () => AGENTS_EVERY_MS,
7617
+ collector: () => COLLECTOR_EVERY_MS,
7618
+ github: () => github.nextDelayMs(),
7619
+ coordinator: () => COORDINATOR_EVERY_MS
7620
+ };
7621
+ let running = false;
7622
+ const timers = /* @__PURE__ */ new Map();
7623
+ const schedule = (name, delay) => {
7624
+ if (!running) return;
7625
+ const timer = setTimeout(() => {
7626
+ timers.delete(name);
7627
+ void refreshers[name]().finally(() => {
7628
+ let next = AGENTS_EVERY_MS;
7629
+ try {
7630
+ next = delays[name]();
7631
+ } catch {
7632
+ }
7633
+ schedule(name, next);
7634
+ });
7635
+ }, delay);
7636
+ timer.unref();
7637
+ timers.set(name, timer);
7638
+ };
7639
+ const status5 = (name, s) => {
7640
+ const err = thrown.get(name);
7641
+ const okAt = s.last_ok_at === null ? null : Date.parse(s.last_ok_at);
7642
+ return {
7643
+ ok: s.ok && err === void 0,
7644
+ last_ok_at: s.last_ok_at,
7645
+ last_error: err ?? s.last_error,
7646
+ stale: okAt === null || Number.isNaN(okAt) || now() - okAt > STALE_AFTER_MS5
7647
+ };
7648
+ };
7649
+ const getState = () => {
7650
+ const col = collector.get();
7651
+ const ag = agents.get();
7652
+ const gh = github.get();
7653
+ const coord = coordinator.get();
7654
+ const pinned = new Set(readConfig(home).value.pinned.map((p2) => repoKey(normalizeRepoPath(p2))));
7655
+ const colByPath = new Map((col.data?.repos ?? []).map((r2) => [repoKey(r2.path), r2]));
7656
+ const ghByPath = new Map((gh.data?.repos ?? []).map((r2) => [repoKey(r2.path), r2]));
7657
+ const coordById = new Map(coord.map((c) => [c.repo_id, c]));
7658
+ const repos = repoPaths().map((p2) => {
7659
+ const k3 = repoKey(p2);
7660
+ const c = colByPath.get(k3);
7661
+ const g2 = ghByPath.get(k3) ?? null;
7662
+ const repoId = g2?.repo ? repoIdFor(g2.repo) : g2?.reason === "no github remote" ? localRepoId(p2) : void 0;
7663
+ const out = {
7664
+ path: p2,
7665
+ name: path17.basename(p2),
7666
+ pinned: pinned.has(k3),
7667
+ roadmaps: c?.roadmaps ?? null,
7668
+ plans: c?.plans ?? null,
7669
+ relays: c?.relays ?? null,
7670
+ github: g2,
7671
+ coordinator: repoId ? coordById.get(repoId) ?? null : null
7672
+ };
7673
+ if (repoId) out.repo_id = repoId;
7674
+ if (c?.error !== void 0) out.error = c.error;
7675
+ return out;
7676
+ });
7677
+ const coordOkAt = coordinatorOkAt === null ? null : new Date(coordinatorOkAt).toISOString();
7678
+ return {
7679
+ schema: STATE_SCHEMA,
7680
+ generated_at: new Date(now()).toISOString(),
7681
+ versions: versions(),
7682
+ sources: {
7683
+ collector: status5("collector", col),
7684
+ agents: status5("agents", ag),
7685
+ github: status5("github", gh),
7686
+ coordinator: status5("coordinator", { ok: coordOkAt !== null, last_ok_at: coordOkAt, last_error: null })
7687
+ },
7688
+ update_needed: col.update_needed || coord.some((c) => c.update_needed),
7689
+ repos,
7690
+ sessions: ag.data ?? [],
7691
+ spend: col.data?.spend ?? null,
7692
+ guide: col.data?.guide ?? null
7693
+ };
7694
+ };
7695
+ return {
7696
+ start() {
7697
+ if (running) return;
7698
+ running = true;
7699
+ schedule("coordinator", 0);
7700
+ const first = setTimeout(() => {
7701
+ timers.delete("agents");
7702
+ void refreshers.agents().finally(() => {
7703
+ schedule("agents", AGENTS_EVERY_MS);
7704
+ schedule("collector", 0);
7705
+ schedule("github", 0);
7706
+ });
7707
+ }, 0);
7708
+ first.unref();
7709
+ timers.set("agents", first);
7710
+ },
7711
+ stop() {
7712
+ running = false;
7713
+ for (const timer of timers.values()) clearTimeout(timer);
7714
+ timers.clear();
7715
+ },
7716
+ getState,
7717
+ async refreshAll() {
7718
+ await refreshers.agents();
7719
+ await refreshers.coordinator();
7720
+ await refreshers.collector();
7721
+ await refreshers.github();
7722
+ },
7723
+ repoPaths
7724
+ };
7725
+ }
7726
+ var STATE_SCHEMA, STALE_AFTER_MS5, COLLECTOR_EVERY_MS, AGENTS_EVERY_MS, COORDINATOR_EVERY_MS, VERSIONS_TTL_MS, REFRESH_CEILING_MS, message;
7727
+ var init_state = __esm({
7728
+ "src/hub/state.ts"() {
7729
+ "use strict";
7730
+ init_config();
7731
+ init_agents();
7732
+ init_collector();
7733
+ init_coordinator();
7734
+ init_github();
7735
+ init_bounded();
7736
+ init_pkg();
7737
+ init_sessions();
7738
+ STATE_SCHEMA = 1;
7739
+ STALE_AFTER_MS5 = 3 * 6e4;
7740
+ COLLECTOR_EVERY_MS = 6e4;
7741
+ AGENTS_EVERY_MS = 3e4;
7742
+ COORDINATOR_EVERY_MS = 3e4;
7743
+ VERSIONS_TTL_MS = 6e4;
7744
+ REFRESH_CEILING_MS = {
7745
+ collector: 9e4,
7746
+ agents: 9e4,
7747
+ github: 3e5,
7748
+ coordinator: 9e4
7749
+ };
7750
+ message = (e2) => e2 instanceof Error ? e2.message : String(e2);
7751
+ }
7752
+ });
7753
+
7754
+ // src/commands/hub.ts
7755
+ var hub_exports = {};
7756
+ __export(hub_exports, {
7757
+ SPAWN_OPTIONS: () => SPAWN_OPTIONS,
7758
+ START_WAIT_MS: () => START_WAIT_MS,
7759
+ hubAutostart: () => hubAutostart,
7760
+ hubOpen: () => hubOpen,
7761
+ hubServe: () => hubServe,
7762
+ hubStart: () => hubStart,
7763
+ hubStatus: () => hubStatus,
7764
+ hubStop: () => hubStop,
7765
+ isNodeProcess: () => isNodeProcess,
7766
+ killTree: () => killTree2,
7767
+ processStartMs: () => processStartMs,
7768
+ startHub: () => startHub
7769
+ });
7770
+ import http2 from "http";
7771
+ import path18 from "path";
7772
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync14 } from "fs";
7773
+ import { randomBytes as randomBytes4 } from "crypto";
7774
+ function defaultVersions2() {
7775
+ return { cli: packageInfo().version, caddis: bundleManifest().poolVersion };
7776
+ }
7777
+ function resolvePort(deps) {
7778
+ if (deps.port !== void 0) return deps.port;
7779
+ const cfg = readConfig(deps.home);
7780
+ if (cfg.error) errorLine(`${cfg.error}; using the last good config`);
7781
+ const p2 = cfg.value.port;
7782
+ if (!Number.isInteger(p2) || p2 < 1 || p2 > 65535) {
7783
+ throw new HubError(`config.json port ${p2} is not valid: use a whole number in 1-65535`);
7784
+ }
7785
+ return p2;
7786
+ }
7787
+ function readKeyQuiet(home) {
7788
+ try {
7789
+ const k3 = readFileSync14(keyPath(home), "utf8").trim();
7790
+ return /^[0-9a-f]{64}$/.test(k3) ? k3 : null;
7791
+ } catch {
7792
+ return null;
7793
+ }
7794
+ }
7795
+ function hubRequest(method, port, p2, key, timeoutMs) {
7796
+ return new Promise((resolve) => {
7797
+ const req = http2.request(
7798
+ {
7799
+ host: "127.0.0.1",
7800
+ port,
7801
+ method,
7802
+ path: p2,
7803
+ headers: { host: `127.0.0.1:${port}`, "content-length": 0, ...key ? { [KEY_HEADER]: key } : {} },
7804
+ agent: false,
7805
+ timeout: timeoutMs
7806
+ },
7807
+ (res) => {
7808
+ const chunks = [];
7809
+ res.on("data", (c) => chunks.push(c));
7810
+ res.on("end", () => {
7811
+ let body = {};
7812
+ try {
7813
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
7814
+ } catch {
7815
+ }
7816
+ resolve({ status: res.statusCode ?? 0, body });
7817
+ });
7818
+ res.on("error", () => resolve(null));
7819
+ }
7820
+ );
7821
+ req.on("timeout", () => req.destroy());
7822
+ req.on("error", () => resolve(null));
7823
+ req.end();
7824
+ });
7825
+ }
7826
+ async function defaultSpawn(cmd, args, opts = {}) {
7827
+ const { execa } = await import("execa");
7828
+ const child = execa(cmd, args, { ...SPAWN_OPTIONS, cwd: opts.cwd });
7829
+ child.unref();
7830
+ return {
7831
+ pid: child.pid,
7832
+ exited: child.then(
7833
+ (r2) => r2.exitCode ?? null,
7834
+ () => null
7835
+ )
7836
+ };
7837
+ }
7838
+ async function killTree2(pid) {
7839
+ if (process.platform === "win32") {
7840
+ await run("taskkill", ["/T", "/F", "/PID", String(pid)], { timeout: TOOL_TIMEOUT_MS });
7841
+ return;
7842
+ }
7843
+ try {
7844
+ process.kill(-pid, "SIGTERM");
7845
+ } catch {
7846
+ try {
7847
+ process.kill(pid, "SIGTERM");
7848
+ } catch {
7849
+ }
7850
+ }
7851
+ }
7852
+ async function isNodeProcess(pid) {
7853
+ const r2 = process.platform === "win32" ? await run("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { timeout: TOOL_TIMEOUT_MS }) : await run("ps", ["-p", String(pid), "-o", "comm="], { timeout: TOOL_TIMEOUT_MS });
7854
+ if (!r2.ok) return false;
7855
+ const name = (r2.stdout.split(/\r?\n/)[0] ?? "").replace(/^"([^"]*)".*$/, "$1").trim().toLowerCase();
7856
+ if (!name) return false;
7857
+ const runtime = path18.basename(process.execPath).toLowerCase().replace(/\.exe$/, "");
7858
+ return name.includes("node") || name.includes(runtime);
7859
+ }
7860
+ async function defaultOpener(url) {
7861
+ const r2 = process.platform === "win32" ? await run("cmd", ["/c", "start", "", url], { timeout: TOOL_TIMEOUT_MS }) : process.platform === "darwin" ? await run("open", [url], { timeout: TOOL_TIMEOUT_MS }) : await run("xdg-open", [url], { timeout: TOOL_TIMEOUT_MS });
7862
+ return r2.ok;
7863
+ }
7864
+ async function processStartMs(pid) {
7865
+ if (!Number.isInteger(pid) || pid <= 0) return null;
7866
+ const r2 = process.platform === "win32" ? await run(
7867
+ "powershell",
7868
+ ["-NoProfile", "-NonInteractive", "-Command", `(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`],
7869
+ { timeout: TOOL_TIMEOUT_MS }
7870
+ ) : await run("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: TOOL_TIMEOUT_MS, env: { LC_ALL: "C" } });
7871
+ if (!r2.ok) return null;
7872
+ const text = r2.stdout.trim().replace(/(\.\d{3})\d+/, "$1");
7873
+ const t = Date.parse(text);
7874
+ return Number.isNaN(t) ? null : t;
7875
+ }
7876
+ async function whoami(port) {
7877
+ const r2 = await hubRequest("GET", port, "/api/hub/whoami", null, WHOAMI_TIMEOUT_MS);
7878
+ const id = r2?.status === 200 ? r2.body.instance : void 0;
7879
+ return typeof id === "string" ? id : null;
7880
+ }
7881
+ async function sameProcess(lock, deps) {
7882
+ const home = deps.home ?? caddisHome();
7883
+ if (lock.pid === process.pid) return holderAlive(lock, home, () => false) ? "same" : "other";
7884
+ const started = Date.parse(lock.started_at);
7885
+ if (Number.isNaN(started)) return "other";
7886
+ const t = await (deps.processStart ?? processStartMs)(lock.pid);
7887
+ if (t === null) return "unknown";
7888
+ return t <= started ? "same" : "other";
7889
+ }
7890
+ async function inspect(deps, lock = readLock(deps.home ?? caddisHome())) {
7891
+ const home = deps.home ?? caddisHome();
7892
+ if (!lock) return { kind: "none" };
7893
+ if (!holderAlive(lock, home, deps.alive ?? pidAlive)) return { kind: "stale", lock };
7894
+ if (lock.instance && lock.port > 0 && await whoami(lock.port) === lock.instance) return { kind: "running", lock };
7895
+ if (await sameProcess(lock, deps) === "other") return { kind: "stale", lock };
7896
+ const started = Date.parse(lock.started_at);
7897
+ const young = !Number.isNaN(started) && (deps.now ?? Date.now)() - started < START_WAIT_MS;
7898
+ return young ? { kind: "starting", lock } : { kind: "unresponsive", lock };
7899
+ }
7900
+ async function startHub(deps = {}) {
7901
+ const home = deps.home ?? caddisHome();
7902
+ const now = deps.now ?? Date.now;
7903
+ const port = resolvePort(deps);
7904
+ const info = {
7905
+ pid: process.pid,
7906
+ started_at: new Date(now()).toISOString(),
7907
+ port,
7908
+ instance: randomBytes4(16).toString("hex")
7909
+ };
7910
+ let got = acquireLock(info, home, deps.alive ?? pidAlive);
7911
+ if (!got.ok) {
7912
+ const st = await inspect(deps, got.holder);
7913
+ if (st.kind === "running" || st.kind === "starting" || st.kind === "unresponsive") throw new HubError(refusal(st));
7914
+ removeLockIf(got.holder, home);
7915
+ got = acquireLock(info, home, deps.alive ?? pidAlive);
7916
+ if (!got.ok) throw new HubError(alreadyRunning(got.holder));
7917
+ }
7918
+ let server;
7919
+ const state = deps.state ?? createHub({ home, now });
7920
+ let stopping = null;
7921
+ let resolveDone;
7922
+ const done = new Promise((r2) => resolveDone = r2);
7923
+ const stop = () => {
7924
+ stopping ??= (async () => {
7925
+ try {
7926
+ state.stop();
7927
+ await server.close();
7928
+ } finally {
7929
+ releaseLock(process.pid, home);
7930
+ resolveDone();
7931
+ }
7932
+ })();
7933
+ return stopping;
7934
+ };
7935
+ try {
7936
+ const key = await ensureKey({ home, runCmd: deps.runCmd });
7937
+ server = await startServer({
7938
+ host: "127.0.0.1",
7939
+ port,
7940
+ key,
7941
+ getState: () => state.getState(),
7942
+ versions: deps.versions ?? defaultVersions2(),
7943
+ now,
7944
+ instance: info.instance,
7945
+ onStop: () => void stop()
7946
+ });
7947
+ } catch (e2) {
7948
+ releaseLock(process.pid, home);
7949
+ if (e2.code === "EADDRINUSE") {
7950
+ throw new HubError(`port ${port} is in use by another program: free it or set "port" in the hub config.json`);
7951
+ }
7952
+ throw e2;
7953
+ }
7954
+ writeLock({ ...info, port: server.port }, home);
7955
+ state.start();
7956
+ return { port: server.port, stop, done };
7957
+ }
7958
+ async function killChild(child, deps) {
7959
+ if (child.pid && (deps.alive ?? pidAlive)(child.pid)) await (deps.kill ?? killTree2)(child.pid);
7960
+ }
7961
+ async function hubServe(deps = {}) {
7962
+ const home = deps.home ?? caddisHome();
7963
+ let hub2;
7964
+ try {
7965
+ hub2 = await startHub(deps);
7966
+ } catch (e2) {
7967
+ errorLine(message2(e2));
7968
+ return 1;
7969
+ }
7970
+ let restarting = false;
7971
+ let exitCode = 0;
7972
+ let resolveFinished;
7973
+ const finished = new Promise((r2) => resolveFinished = r2);
7974
+ const watch = (h2) => {
7975
+ void h2.done.then(() => {
7976
+ if (!restarting) resolveFinished();
7977
+ });
7978
+ };
7979
+ watch(hub2);
7980
+ const onSignal = () => void hub2.stop();
7981
+ const onExit = () => releaseLock(process.pid, home);
7982
+ process.once("SIGINT", onSignal);
7983
+ process.once("SIGTERM", onSignal);
7984
+ process.once("exit", onExit);
7985
+ line(`caddis hub serving on ${hubUrl(hub2.port)} (pid ${process.pid}); stop it with: caddis hub stop`);
7986
+ const pkgRoot = packageInfo().root;
7987
+ const newEntry = path18.join(pkgRoot, "dist", "cli.js");
7988
+ const runningVersion = (deps.versions ?? defaultVersions2()).cli ?? packageInfo().version;
7989
+ const restarter = createRestarter({
7990
+ currentVersion: runningVersion,
7991
+ readVersion: () => readInstalledVersion2(pkgRoot),
7992
+ closeServer: async () => {
7993
+ restarting = true;
7994
+ await hub2.stop();
7995
+ },
7996
+ spawnNew: () => (deps.spawn ?? defaultSpawn)(process.execPath, [newEntry, "hub", "serve"], { cwd: hubDir(home) }),
7997
+ probe: async (child) => {
7998
+ const lock = readLock(home);
7999
+ const key = readKeyQuiet(home);
8000
+ if (!lock || !key || lock.pid !== child.pid || lock.port <= 0 || !lock.instance) return null;
8001
+ if (await whoami(lock.port) !== lock.instance) return null;
8002
+ const h2 = await hubRequest("GET", lock.port, "/api/health", key, 1e3);
8003
+ const v2 = h2?.body.versions?.cli;
8004
+ return h2?.status === 200 && typeof v2 === "string" ? v2 : null;
8005
+ },
8006
+ restartOwn: async () => {
8007
+ try {
8008
+ hub2 = await startHub({ ...deps, port: hub2.port });
8009
+ watch(hub2);
8010
+ } finally {
8011
+ restarting = false;
8012
+ }
8013
+ },
8014
+ killChild: (child) => killChild(child, deps),
8015
+ exit: (code) => {
8016
+ exitCode = code;
8017
+ resolveFinished();
8018
+ },
8019
+ log: errorLine,
8020
+ every: (fn, ms) => {
8021
+ const t = setInterval(fn, ms);
8022
+ t.unref();
8023
+ return () => clearInterval(t);
8024
+ },
8025
+ ...deps.restart
8026
+ });
8027
+ restarter.start();
8028
+ await finished;
8029
+ restarter.stop();
8030
+ process.off("SIGINT", onSignal);
8031
+ process.off("SIGTERM", onSignal);
8032
+ process.off("exit", onExit);
8033
+ return exitCode;
8034
+ }
8035
+ async function hubStart(deps = {}) {
8036
+ const home = deps.home ?? caddisHome();
8037
+ const alive = deps.alive ?? pidAlive;
8038
+ try {
8039
+ resolvePort(deps);
8040
+ } catch (e2) {
8041
+ errorLine(message2(e2));
8042
+ return 1;
8043
+ }
8044
+ const st = await inspect(deps);
8045
+ if (st.kind === "running" || st.kind === "starting" || st.kind === "unresponsive") {
8046
+ errorLine(refusal(st));
8047
+ return 1;
8048
+ }
8049
+ if (st.kind === "stale") removeLockIf(st.lock, home);
8050
+ let key;
8051
+ try {
8052
+ key = await ensureKey({ home, runCmd: deps.runCmd });
8053
+ } catch (e2) {
8054
+ errorLine(message2(e2));
8055
+ return 1;
8056
+ }
8057
+ const entry = deps.entry ?? process.argv[1];
8058
+ if (!entry) {
8059
+ errorLine("cannot find the caddis CLI entry script to start the hub");
8060
+ return 1;
8061
+ }
8062
+ const cwd = hubDir(home);
8063
+ mkdirSync7(cwd, { recursive: true });
8064
+ const child = await (deps.spawn ?? defaultSpawn)(process.execPath, [entry, "hub", "serve"], { cwd });
8065
+ let exited = false;
8066
+ let exitCode = null;
8067
+ void child.exited.then((c) => {
8068
+ exited = true;
8069
+ exitCode = c;
8070
+ });
8071
+ const waitMs = deps.startWaitMs ?? START_WAIT_MS;
8072
+ const deadline = Date.now() + waitMs;
8073
+ while (Date.now() < deadline) {
8074
+ if (exited) {
8075
+ errorLine(`caddis hub serve exited (code ${exitCode}) before it answered; run "caddis hub serve" to see the error`);
8076
+ return 1;
8077
+ }
8078
+ const lock = readLock(home);
8079
+ if (lock && lock.pid === child.pid && lock.port > 0 && lock.instance && await whoami(lock.port) === lock.instance) {
8080
+ const h2 = await hubRequest("GET", lock.port, "/api/health", key, 1e3);
8081
+ if (h2?.status === 200) {
8082
+ line(`caddis hub running on ${hubUrl(lock.port)}`);
8083
+ line("open it with: caddis hub open");
8084
+ return 0;
8085
+ }
8086
+ }
8087
+ await sleep(100);
8088
+ }
8089
+ if (child.pid && alive(child.pid)) await (deps.kill ?? killTree2)(child.pid);
8090
+ errorLine(
8091
+ `caddis hub did not answer within ${Math.round(waitMs / 1e3)} s; run "caddis hub serve" to see the error`
8092
+ );
8093
+ return 1;
8094
+ }
8095
+ async function runningHub(deps) {
8096
+ const home = deps.home ?? caddisHome();
8097
+ const st = await inspect(deps);
8098
+ if (st.kind !== "running") return null;
8099
+ const key = readKeyQuiet(home);
8100
+ if (!key) return null;
8101
+ const h2 = await hubRequest("GET", st.lock.port, "/api/health", key, HEALTH_TIMEOUT_MS);
8102
+ return h2?.status === 200 ? { lock: st.lock, key, body: h2.body } : null;
8103
+ }
8104
+ function formatUptime(ms) {
8105
+ let s = Math.max(0, Math.floor(ms / 1e3));
8106
+ const d3 = Math.floor(s / 86400);
8107
+ s -= d3 * 86400;
8108
+ const h2 = Math.floor(s / 3600);
8109
+ s -= h2 * 3600;
8110
+ const m2 = Math.floor(s / 60);
8111
+ s -= m2 * 60;
8112
+ const parts = [];
8113
+ if (d3) parts.push(`${d3}d`);
8114
+ if (d3 || h2) parts.push(`${h2}h`);
8115
+ if (d3 || h2 || m2) parts.push(`${m2}m`);
8116
+ parts.push(`${s}s`);
8117
+ return parts.join(" ");
8118
+ }
8119
+ async function hubStatus(opts = {}) {
8120
+ const now = opts.now ?? Date.now;
8121
+ const hub2 = await runningHub(opts);
8122
+ if (!hub2) {
8123
+ if (opts.json) line(JSON.stringify({ schema: 1, running: false, port: null, pid: null, versions: null }));
8124
+ else line("caddis hub is not running; start it with: caddis hub start");
8125
+ return 1;
8126
+ }
8127
+ const versions = hub2.body.versions ?? {};
8128
+ if (opts.json) {
8129
+ line(JSON.stringify({ schema: 1, running: true, port: hub2.lock.port, pid: hub2.lock.pid, versions }));
8130
+ return 0;
8131
+ }
8132
+ const started = Date.parse(hub2.lock.started_at);
8133
+ line(`caddis hub running on ${hubUrl(hub2.lock.port)}`);
8134
+ line(` pid ${hub2.lock.pid}, uptime ${Number.isNaN(started) ? "unknown" : formatUptime(now() - started)}`);
8135
+ line(` versions: ${Object.entries(versions).map(([k3, v2]) => `${k3} ${v2}`).join(", ")}`);
8136
+ return 0;
8137
+ }
8138
+ async function hubStop(deps = {}) {
8139
+ const home = deps.home ?? caddisHome();
8140
+ const alive = deps.alive ?? pidAlive;
8141
+ const waitMs = deps.stopWaitMs ?? STOP_WAIT_MS;
8142
+ const st = await inspect(deps);
8143
+ if (st.kind === "none") {
8144
+ line("caddis hub is not running");
8145
+ return 0;
8146
+ }
8147
+ const lock = st.lock;
8148
+ if (st.kind === "running") {
8149
+ const key = readKeyQuiet(home);
8150
+ const r2 = key ? await hubRequest("POST", lock.port, "/api/hub/stop", key, waitMs) : null;
8151
+ if (r2?.status === 200) {
8152
+ const deadline2 = Date.now() + waitMs;
8153
+ while (Date.now() < deadline2) {
8154
+ const cur = readLock(home);
8155
+ if (!cur || cur.instance !== lock.instance || !holderAlive(cur, home, alive)) {
8156
+ line("caddis hub stopped");
8157
+ return 0;
8158
+ }
8159
+ await sleep(50);
8160
+ }
8161
+ }
8162
+ }
8163
+ if (!holderAlive(lock, home, alive)) {
8164
+ removeLockIf(lock, home);
8165
+ line("caddis hub is not running (removed a stale lock)");
8166
+ return 0;
8167
+ }
8168
+ const same = await sameProcess(lock, deps);
8169
+ if (same === "unknown") {
8170
+ errorLine(`caddis hub pid ${lock.pid} does not answer and its start time cannot be read; lock kept. Retry, or end that pid by hand`);
8171
+ return 1;
8172
+ }
8173
+ const ours = same === "same" && await (deps.isHubPid ?? isNodeProcess)(lock.pid);
8174
+ if (!ours) {
8175
+ removeLockIf(lock, home);
8176
+ line(`caddis hub is not running (removed a stale lock; pid ${lock.pid} is another program, not killed)`);
8177
+ return 0;
8178
+ }
8179
+ await (deps.kill ?? killTree2)(lock.pid);
8180
+ const deadline = Date.now() + waitMs;
8181
+ while (alive(lock.pid) && Date.now() < deadline) await sleep(50);
8182
+ if (alive(lock.pid)) {
8183
+ errorLine(`could not stop caddis hub (pid ${lock.pid})`);
8184
+ return 1;
8185
+ }
8186
+ removeLockIf(lock, home);
8187
+ line(`caddis hub stopped (killed pid ${lock.pid})`);
8188
+ return 0;
8189
+ }
8190
+ async function hubOpen(deps = {}) {
8191
+ const now = deps.now ?? Date.now;
8192
+ const hub2 = await runningHub(deps);
8193
+ if (!hub2) {
8194
+ errorLine("caddis hub is not running; start it with: caddis hub start");
8195
+ return 1;
8196
+ }
8197
+ const r2 = await hubRequest("POST", hub2.lock.port, "/api/hub/code", hub2.key, HEALTH_TIMEOUT_MS);
8198
+ const code = r2?.status === 200 ? r2.body.code : void 0;
8199
+ if (typeof code !== "string" || !CODE_RE.test(code)) {
8200
+ errorLine(`caddis hub did not give a valid login code (HTTP ${r2?.status ?? "no answer"})`);
8201
+ return 1;
8202
+ }
8203
+ const url = `${hubUrl(hub2.lock.port)}login?code=${code}`;
8204
+ const expires = Date.parse(String(r2?.body.expires_at ?? ""));
8205
+ const secs = Number.isNaN(expires) ? 60 : Math.round((expires - now()) / 1e3);
8206
+ line(url);
8207
+ line(`the code works once, for ${secs} s`);
8208
+ let opened = false;
8209
+ try {
8210
+ opened = await (deps.opener ?? defaultOpener)(url);
8211
+ } catch {
8212
+ opened = false;
8213
+ }
8214
+ if (!opened) line("no browser opened: open this URL in your browser");
8215
+ return 0;
8216
+ }
8217
+ async function hubAutostart(action, deps = {}) {
8218
+ try {
8219
+ const r2 = action === "enable" ? await enableAutostart(deps) : action === "disable" ? await disableAutostart(deps) : action === "status" ? await autostartStatus(deps) : null;
8220
+ if (!r2) {
8221
+ errorLine(`unknown action "${action}": use enable, disable or status`);
8222
+ return 1;
8223
+ }
8224
+ (r2.ok || action === "status" ? line : errorLine)(r2.message);
8225
+ return r2.ok ? 0 : 1;
8226
+ } catch (e2) {
8227
+ errorLine(message2(e2));
8228
+ return 1;
8229
+ }
8230
+ }
8231
+ var SPAWN_OPTIONS, START_WAIT_MS, WHOAMI_TIMEOUT_MS, CODE_RE, STOP_WAIT_MS, HEALTH_TIMEOUT_MS, TOOL_TIMEOUT_MS, HubError, sleep, hubUrl, message2, alreadyRunning, unresponsive, refusal;
8232
+ var init_hub = __esm({
8233
+ "src/commands/hub.ts"() {
8234
+ "use strict";
8235
+ init_autostart();
8236
+ init_config();
8237
+ init_keyfile();
8238
+ init_lock();
8239
+ init_paths();
8240
+ init_restart();
8241
+ init_server();
8242
+ init_state();
8243
+ init_exec();
8244
+ init_log();
8245
+ init_pkg();
8246
+ init_sessions();
8247
+ SPAWN_OPTIONS = {
8248
+ detached: true,
8249
+ stdio: "ignore",
8250
+ windowsHide: true,
8251
+ shell: false,
8252
+ cleanup: false,
8253
+ reject: false
8254
+ };
8255
+ START_WAIT_MS = 2e4;
8256
+ WHOAMI_TIMEOUT_MS = 1500;
8257
+ CODE_RE = /^[A-Za-z0-9_-]+$/;
8258
+ STOP_WAIT_MS = 5e3;
8259
+ HEALTH_TIMEOUT_MS = 3e3;
8260
+ TOOL_TIMEOUT_MS = 15e3;
8261
+ HubError = class extends Error {
8262
+ };
8263
+ sleep = (ms) => new Promise((r2) => setTimeout(r2, ms));
8264
+ hubUrl = (port) => `http://127.0.0.1:${port}/`;
8265
+ message2 = (e2) => e2 instanceof Error ? e2.message : String(e2);
8266
+ alreadyRunning = (l2) => `caddis hub is already running (pid ${l2.pid}, port ${l2.port})`;
8267
+ unresponsive = (l2) => `caddis hub pid ${l2.pid} holds the lock but does not answer: run caddis hub stop`;
8268
+ refusal = (st) => st.kind === "unresponsive" ? unresponsive(st.lock) : alreadyRunning(st.lock);
8269
+ }
8270
+ });
8271
+
5710
8272
  // node_modules/commander/esm.mjs
5711
8273
  var import_index = __toESM(require_commander(), 1);
5712
8274
  var {
@@ -5762,14 +8324,14 @@ function* pluginBlocks(stdout) {
5762
8324
  if (current) yield current;
5763
8325
  }
5764
8326
  async function detect() {
5765
- const path7 = await findBin(BIN);
5766
- if (!path7) {
8327
+ const path19 = await findBin(BIN);
8328
+ if (!path19) {
5767
8329
  return { present: false, note: "no `claude` binary on PATH" };
5768
8330
  }
5769
8331
  const version = await run(BIN, ["--version"], { timeout: 2e4 });
5770
8332
  return {
5771
8333
  present: true,
5772
- path: path7,
8334
+ path: path19,
5773
8335
  agentVersion: version.ok ? version.stdout.trim().split(/\s+/)[0] || void 0 : void 0,
5774
8336
  note: version.ok ? void 0 : "binary found but `claude --version` failed"
5775
8337
  };
@@ -5946,8 +8508,8 @@ function errorText(error) {
5946
8508
  if (!(error instanceof Error)) return String(error);
5947
8509
  const code = error.code;
5948
8510
  const kind = code ?? error.constructor.name;
5949
- const message = code && error.message.startsWith(`${code}: `) ? error.message.slice(code.length + 2) : error.message;
5950
- return `${kind}: ${message}`;
8511
+ const message3 = code && error.message.startsWith(`${code}: `) ? error.message.slice(code.length + 2) : error.message;
8512
+ return `${kind}: ${message3}`;
5951
8513
  }
5952
8514
  function stampMs(stamp) {
5953
8515
  const n = Number(stamp);
@@ -6212,8 +8774,8 @@ async function drive2(_action, options) {
6212
8774
  if (missing.length > 0) {
6213
8775
  let outcome = "there was nothing to restore";
6214
8776
  if (backup) {
6215
- const failure = backup.restore();
6216
- outcome = failure === null ? "the previous plugin was restored" : `the restore FAILED (${failure}); the old plugin is kept at ${backup.location}`;
8777
+ const failure2 = backup.restore();
8778
+ outcome = failure2 === null ? "the previous plugin was restored" : `the restore FAILED (${failure2}); the old plugin is kept at ${backup.location}`;
6217
8779
  }
6218
8780
  steps3.push({ command, ok: false, code: result.code, output: `missing after the install: ${missing.join(", ")}` });
6219
8781
  return {
@@ -6430,8 +8992,8 @@ ${result.stderr}`;
6430
8992
  rmSync2(legacyDir, { recursive: true, force: true });
6431
8993
  results.push({ command: removalCommand, ok: true, code: 0 });
6432
8994
  } catch (error) {
6433
- const message = error instanceof Error ? error.message : String(error);
6434
- results.push({ command: removalCommand, ok: false, code: null, output: message });
8995
+ const message3 = error instanceof Error ? error.message : String(error);
8996
+ results.push({ command: removalCommand, ok: false, code: null, output: message3 });
6435
8997
  }
6436
8998
  }
6437
8999
  const notes = [];
@@ -6476,8 +9038,8 @@ function createStubAdapter(spec) {
6476
9038
  const found = await findBin(bin);
6477
9039
  if (found) return { present: true, path: found, note: NOT_YET_SUPPORTED };
6478
9040
  }
6479
- for (const configPath of spec.configPaths) {
6480
- if (existsSync4(configPath)) return { present: true, path: configPath, note: NOT_YET_SUPPORTED };
9041
+ for (const configPath2 of spec.configPaths) {
9042
+ if (existsSync4(configPath2)) return { present: true, path: configPath2, note: NOT_YET_SUPPORTED };
6481
9043
  }
6482
9044
  return { present: false, note: `no ${spec.bins.map((b3) => `\`${b3}\``).join(" / ")} binary or config found` };
6483
9045
  }
@@ -6594,6 +9156,31 @@ withGlobalFlags(program2.command("status")).description("compact table: cli vers
6594
9156
  const { status: status5 } = await Promise.resolve().then(() => (init_status(), status_exports));
6595
9157
  finish(await status5({ adapters: resolveAdapters(flags), json: options.json }));
6596
9158
  });
9159
+ var hub = program2.command("hub").description("the local caddis hub web server (127.0.0.1 only)");
9160
+ hub.command("start").description("start the hub in the background (hidden)").action(async () => {
9161
+ const { hubStart: hubStart2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
9162
+ finish(await hubStart2());
9163
+ });
9164
+ hub.command("stop").description("stop the running hub").action(async () => {
9165
+ const { hubStop: hubStop2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
9166
+ finish(await hubStop2());
9167
+ });
9168
+ hub.command("status").description("is the hub running: port, pid, versions, uptime (exit 1 when down)").option("--json", "machine-readable output", false).action(async (options) => {
9169
+ const { hubStatus: hubStatus2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
9170
+ finish(await hubStatus2({ json: options.json === true }));
9171
+ });
9172
+ hub.command("open").description("open the hub in your browser with a one-time login code").action(async () => {
9173
+ const { hubOpen: hubOpen2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
9174
+ finish(await hubOpen2());
9175
+ });
9176
+ hub.command("serve").description("run the hub in the foreground (used by start and the logon task)").action(async () => {
9177
+ const { hubServe: hubServe2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
9178
+ finish(await hubServe2());
9179
+ });
9180
+ hub.command("autostart <action>").description("start the hub at logon: enable, disable or status (per user, opt-in)").action(async (action) => {
9181
+ const { hubAutostart: hubAutostart2 } = await Promise.resolve().then(() => (init_hub(), hub_exports));
9182
+ finish(await hubAutostart2(action));
9183
+ });
6597
9184
  program2.addHelpText(
6598
9185
  "after",
6599
9186
  `