@kelceyp/caw 1.0.32 → 1.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/caw.js +608 -113
  2. package/package.json +1 -1
package/dist/caw.js CHANGED
@@ -7747,8 +7747,8 @@ var require_constants = __commonJS((exports, module) => {
7747
7747
 
7748
7748
  // node_modules/semver/internal/debug.js
7749
7749
  var require_debug = __commonJS((exports, module) => {
7750
- var debug2 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {};
7751
- module.exports = debug2;
7750
+ var debug3 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {};
7751
+ module.exports = debug3;
7752
7752
  });
7753
7753
 
7754
7754
  // node_modules/semver/internal/re.js
@@ -7758,7 +7758,7 @@ var require_re = __commonJS((exports, module) => {
7758
7758
  MAX_SAFE_BUILD_LENGTH,
7759
7759
  MAX_LENGTH
7760
7760
  } = require_constants();
7761
- var debug2 = require_debug();
7761
+ var debug3 = require_debug();
7762
7762
  exports = module.exports = {};
7763
7763
  var re = exports.re = [];
7764
7764
  var safeRe = exports.safeRe = [];
@@ -7781,7 +7781,7 @@ var require_re = __commonJS((exports, module) => {
7781
7781
  var createToken = (name, value, isGlobal) => {
7782
7782
  const safe = makeSafeRegex(value);
7783
7783
  const index = R++;
7784
- debug2(name, index, value);
7784
+ debug3(name, index, value);
7785
7785
  t[name] = index;
7786
7786
  src[index] = value;
7787
7787
  safeSrc[index] = safe;
@@ -7876,7 +7876,7 @@ var require_identifiers = __commonJS((exports, module) => {
7876
7876
 
7877
7877
  // node_modules/semver/classes/semver.js
7878
7878
  var require_semver = __commonJS((exports, module) => {
7879
- var debug2 = require_debug();
7879
+ var debug3 = require_debug();
7880
7880
  var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
7881
7881
  var { safeRe: re, t } = require_re();
7882
7882
  var parseOptions = require_parse_options();
@@ -7909,7 +7909,7 @@ var require_semver = __commonJS((exports, module) => {
7909
7909
  if (version.length > MAX_LENGTH) {
7910
7910
  throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
7911
7911
  }
7912
- debug2("SemVer", version, options);
7912
+ debug3("SemVer", version, options);
7913
7913
  this.options = options;
7914
7914
  this.loose = !!options.loose;
7915
7915
  this.includePrerelease = !!options.includePrerelease;
@@ -7957,7 +7957,7 @@ var require_semver = __commonJS((exports, module) => {
7957
7957
  return this.version;
7958
7958
  }
7959
7959
  compare(other) {
7960
- debug2("SemVer.compare", this.version, this.options, other);
7960
+ debug3("SemVer.compare", this.version, this.options, other);
7961
7961
  if (!(other instanceof SemVer)) {
7962
7962
  if (typeof other === "string" && other === this.version) {
7963
7963
  return 0;
@@ -8008,7 +8008,7 @@ var require_semver = __commonJS((exports, module) => {
8008
8008
  do {
8009
8009
  const a = this.prerelease[i];
8010
8010
  const b = other.prerelease[i];
8011
- debug2("prerelease compare", i, a, b);
8011
+ debug3("prerelease compare", i, a, b);
8012
8012
  if (a === undefined && b === undefined) {
8013
8013
  return 0;
8014
8014
  } else if (b === undefined) {
@@ -8030,7 +8030,7 @@ var require_semver = __commonJS((exports, module) => {
8030
8030
  do {
8031
8031
  const a = this.build[i];
8032
8032
  const b = other.build[i];
8033
- debug2("build compare", i, a, b);
8033
+ debug3("build compare", i, a, b);
8034
8034
  if (a === undefined && b === undefined) {
8035
8035
  return 0;
8036
8036
  } else if (b === undefined) {
@@ -8615,21 +8615,21 @@ var require_range = __commonJS((exports, module) => {
8615
8615
  const loose = this.options.loose;
8616
8616
  const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
8617
8617
  range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
8618
- debug2("hyphen replace", range);
8618
+ debug3("hyphen replace", range);
8619
8619
  range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
8620
- debug2("comparator trim", range);
8620
+ debug3("comparator trim", range);
8621
8621
  range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
8622
- debug2("tilde trim", range);
8622
+ debug3("tilde trim", range);
8623
8623
  range = range.replace(re[t.CARETTRIM], caretTrimReplace);
8624
- debug2("caret trim", range);
8624
+ debug3("caret trim", range);
8625
8625
  let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
8626
8626
  if (loose) {
8627
8627
  rangeList = rangeList.filter((comp) => {
8628
- debug2("loose invalid filter", comp, this.options);
8628
+ debug3("loose invalid filter", comp, this.options);
8629
8629
  return !!comp.match(re[t.COMPARATORLOOSE]);
8630
8630
  });
8631
8631
  }
8632
- debug2("range list", rangeList);
8632
+ debug3("range list", rangeList);
8633
8633
  const rangeMap = new Map;
8634
8634
  const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
8635
8635
  for (const comp of comparators) {
@@ -8683,7 +8683,7 @@ var require_range = __commonJS((exports, module) => {
8683
8683
  var cache = new LRU;
8684
8684
  var parseOptions = require_parse_options();
8685
8685
  var Comparator = require_comparator();
8686
- var debug2 = require_debug();
8686
+ var debug3 = require_debug();
8687
8687
  var SemVer = require_semver();
8688
8688
  var {
8689
8689
  safeRe: re,
@@ -8711,15 +8711,15 @@ var require_range = __commonJS((exports, module) => {
8711
8711
  };
8712
8712
  var parseComparator = (comp, options) => {
8713
8713
  comp = comp.replace(re[t.BUILD], "");
8714
- debug2("comp", comp, options);
8714
+ debug3("comp", comp, options);
8715
8715
  comp = replaceCarets(comp, options);
8716
- debug2("caret", comp);
8716
+ debug3("caret", comp);
8717
8717
  comp = replaceTildes(comp, options);
8718
- debug2("tildes", comp);
8718
+ debug3("tildes", comp);
8719
8719
  comp = replaceXRanges(comp, options);
8720
- debug2("xrange", comp);
8720
+ debug3("xrange", comp);
8721
8721
  comp = replaceStars(comp, options);
8722
- debug2("stars", comp);
8722
+ debug3("stars", comp);
8723
8723
  return comp;
8724
8724
  };
8725
8725
  var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
@@ -8730,7 +8730,7 @@ var require_range = __commonJS((exports, module) => {
8730
8730
  var replaceTilde = (comp, options) => {
8731
8731
  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
8732
8732
  return comp.replace(r, (_, M, m, p, pr) => {
8733
- debug2("tilde", comp, _, M, m, p, pr);
8733
+ debug3("tilde", comp, _, M, m, p, pr);
8734
8734
  let ret;
8735
8735
  if (isX(M)) {
8736
8736
  ret = "";
@@ -8739,12 +8739,12 @@ var require_range = __commonJS((exports, module) => {
8739
8739
  } else if (isX(p)) {
8740
8740
  ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
8741
8741
  } else if (pr) {
8742
- debug2("replaceTilde pr", pr);
8742
+ debug3("replaceTilde pr", pr);
8743
8743
  ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
8744
8744
  } else {
8745
8745
  ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
8746
8746
  }
8747
- debug2("tilde return", ret);
8747
+ debug3("tilde return", ret);
8748
8748
  return ret;
8749
8749
  });
8750
8750
  };
@@ -8752,11 +8752,11 @@ var require_range = __commonJS((exports, module) => {
8752
8752
  return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
8753
8753
  };
8754
8754
  var replaceCaret = (comp, options) => {
8755
- debug2("caret", comp, options);
8755
+ debug3("caret", comp, options);
8756
8756
  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
8757
8757
  const z = options.includePrerelease ? "-0" : "";
8758
8758
  return comp.replace(r, (_, M, m, p, pr) => {
8759
- debug2("caret", comp, _, M, m, p, pr);
8759
+ debug3("caret", comp, _, M, m, p, pr);
8760
8760
  let ret;
8761
8761
  if (isX(M)) {
8762
8762
  ret = "";
@@ -8769,7 +8769,7 @@ var require_range = __commonJS((exports, module) => {
8769
8769
  ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
8770
8770
  }
8771
8771
  } else if (pr) {
8772
- debug2("replaceCaret pr", pr);
8772
+ debug3("replaceCaret pr", pr);
8773
8773
  if (M === "0") {
8774
8774
  if (m === "0") {
8775
8775
  ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
@@ -8780,7 +8780,7 @@ var require_range = __commonJS((exports, module) => {
8780
8780
  ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
8781
8781
  }
8782
8782
  } else {
8783
- debug2("no pr");
8783
+ debug3("no pr");
8784
8784
  if (M === "0") {
8785
8785
  if (m === "0") {
8786
8786
  ret = `>=${M}.${m}.${p} <${M}.${m}.${+p + 1}-0`;
@@ -8791,19 +8791,19 @@ var require_range = __commonJS((exports, module) => {
8791
8791
  ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
8792
8792
  }
8793
8793
  }
8794
- debug2("caret return", ret);
8794
+ debug3("caret return", ret);
8795
8795
  return ret;
8796
8796
  });
8797
8797
  };
8798
8798
  var replaceXRanges = (comp, options) => {
8799
- debug2("replaceXRanges", comp, options);
8799
+ debug3("replaceXRanges", comp, options);
8800
8800
  return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
8801
8801
  };
8802
8802
  var replaceXRange = (comp, options) => {
8803
8803
  comp = comp.trim();
8804
8804
  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
8805
8805
  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
8806
- debug2("xRange", comp, ret, gtlt, M, m, p, pr);
8806
+ debug3("xRange", comp, ret, gtlt, M, m, p, pr);
8807
8807
  if (invalidXRangeOrder(M, m, p)) {
8808
8808
  return comp;
8809
8809
  }
@@ -8853,16 +8853,16 @@ var require_range = __commonJS((exports, module) => {
8853
8853
  } else if (xp) {
8854
8854
  ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
8855
8855
  }
8856
- debug2("xRange return", ret);
8856
+ debug3("xRange return", ret);
8857
8857
  return ret;
8858
8858
  });
8859
8859
  };
8860
8860
  var replaceStars = (comp, options) => {
8861
- debug2("replaceStars", comp, options);
8861
+ debug3("replaceStars", comp, options);
8862
8862
  return comp.trim().replace(re[t.STAR], "");
8863
8863
  };
8864
8864
  var replaceGTE0 = (comp, options) => {
8865
- debug2("replaceGTE0", comp, options);
8865
+ debug3("replaceGTE0", comp, options);
8866
8866
  return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
8867
8867
  };
8868
8868
  var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
@@ -8900,7 +8900,7 @@ var require_range = __commonJS((exports, module) => {
8900
8900
  }
8901
8901
  if (version.prerelease.length && !options.includePrerelease) {
8902
8902
  for (let i = 0;i < set.length; i++) {
8903
- debug2(set[i].semver);
8903
+ debug3(set[i].semver);
8904
8904
  if (set[i].semver === Comparator.ANY) {
8905
8905
  continue;
8906
8906
  }
@@ -8935,7 +8935,7 @@ var require_comparator = __commonJS((exports, module) => {
8935
8935
  }
8936
8936
  }
8937
8937
  comp = comp.trim().split(/\s+/).join(" ");
8938
- debug2("comparator", comp, options);
8938
+ debug3("comparator", comp, options);
8939
8939
  this.options = options;
8940
8940
  this.loose = !!options.loose;
8941
8941
  this.parse(comp);
@@ -8944,7 +8944,7 @@ var require_comparator = __commonJS((exports, module) => {
8944
8944
  } else {
8945
8945
  this.value = this.operator + this.semver.version;
8946
8946
  }
8947
- debug2("comp", this);
8947
+ debug3("comp", this);
8948
8948
  }
8949
8949
  parse(comp) {
8950
8950
  const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
@@ -8966,7 +8966,7 @@ var require_comparator = __commonJS((exports, module) => {
8966
8966
  return this.value;
8967
8967
  }
8968
8968
  test(version) {
8969
- debug2("Comparator.test", version, this.options.loose);
8969
+ debug3("Comparator.test", version, this.options.loose);
8970
8970
  if (this.semver === ANY || version === ANY) {
8971
8971
  return true;
8972
8972
  }
@@ -9023,7 +9023,7 @@ var require_comparator = __commonJS((exports, module) => {
9023
9023
  var parseOptions = require_parse_options();
9024
9024
  var { safeRe: re, t } = require_re();
9025
9025
  var cmp = require_cmp();
9026
- var debug2 = require_debug();
9026
+ var debug3 = require_debug();
9027
9027
  var SemVer = require_semver();
9028
9028
  var Range = require_range();
9029
9029
  });
@@ -10778,10 +10778,10 @@ function resolve(overrideBinPath) {
10778
10778
  }
10779
10779
 
10780
10780
  // src/commands/start.js
10781
- import fs6 from "node:fs";
10782
- import path6 from "node:path";
10781
+ import fs8 from "node:fs";
10782
+ import path8 from "node:path";
10783
10783
  import os2 from "node:os";
10784
- import crypto from "node:crypto";
10784
+ import crypto2 from "node:crypto";
10785
10785
  import { execSync as execSync4 } from "node:child_process";
10786
10786
 
10787
10787
  // src/config.js
@@ -10845,6 +10845,48 @@ function readPendingConfig(envDir) {
10845
10845
  function deletePendingConfig(envDir) {
10846
10846
  fs4.unlinkSync(pendingPath(envDir));
10847
10847
  }
10848
+ var TERMINAL_OUTCOMES = Object.freeze([
10849
+ "success",
10850
+ "checksum_mismatch",
10851
+ "collision",
10852
+ "import_error",
10853
+ "catalogue_invalid",
10854
+ "unknown_error"
10855
+ ]);
10856
+ var TRANSIENT_OUTCOMES = Object.freeze([
10857
+ "catalogue_unreachable",
10858
+ "not_found"
10859
+ ]);
10860
+ var TRANSIENT_SET = new Set(TRANSIENT_OUTCOMES);
10861
+ function isTerminalOutcome(outcome) {
10862
+ return !TRANSIENT_SET.has(outcome);
10863
+ }
10864
+ function readInstalledBundles(envDir) {
10865
+ let config;
10866
+ try {
10867
+ config = readConfig(envDir);
10868
+ } catch (e) {
10869
+ if (e.code === "ENOENT")
10870
+ return [];
10871
+ throw e;
10872
+ }
10873
+ const installed = config?.bundles?.installed;
10874
+ return Array.isArray(installed) ? installed : [];
10875
+ }
10876
+ function appendInstalledBundle(envDir, entry) {
10877
+ if (entry === null || typeof entry !== "object") {
10878
+ throw new TypeError("appendInstalledBundle: entry must be an object");
10879
+ }
10880
+ if (!isTerminalOutcome(entry.outcome)) {
10881
+ return { persisted: false, reason: "transient" };
10882
+ }
10883
+ const config = readConfig(envDir);
10884
+ const nextBundles = { ...config.bundles ?? {} };
10885
+ const current = Array.isArray(nextBundles.installed) ? nextBundles.installed : [];
10886
+ nextBundles.installed = [...current, entry];
10887
+ writeConfig(envDir, { ...config, bundles: nextBundles });
10888
+ return { persisted: true };
10889
+ }
10848
10890
 
10849
10891
  // src/process-manager.js
10850
10892
  import fs5 from "node:fs";
@@ -11125,26 +11167,476 @@ async function emitCawCmdStop({ config }) {
11125
11167
  return emitCawCmd({ op: "stop", config });
11126
11168
  }
11127
11169
 
11170
+ // src/first-run-install.js
11171
+ import fs7 from "node:fs";
11172
+ import path7 from "node:path";
11173
+ import crypto from "node:crypto";
11174
+
11175
+ // src/bundle-install-lock.js
11176
+ import fs6 from "node:fs";
11177
+ import path6 from "node:path";
11178
+ var LOCK_FILENAME = "config.bundle-install.lock";
11179
+ var STALE_LOCK_MS = 1e4;
11180
+ function lockPathFor(envDir) {
11181
+ return path6.join(envDir, LOCK_FILENAME);
11182
+ }
11183
+ function makeReleaser(lockPath) {
11184
+ let released = false;
11185
+ return () => {
11186
+ if (released)
11187
+ return;
11188
+ released = true;
11189
+ try {
11190
+ fs6.unlinkSync(lockPath);
11191
+ } catch {}
11192
+ };
11193
+ }
11194
+ var NOOP_RELEASE = () => {};
11195
+ function acquire({ envDir }) {
11196
+ fs6.mkdirSync(envDir, { recursive: true });
11197
+ const lockPath = lockPathFor(envDir);
11198
+ try {
11199
+ const fd = fs6.openSync(lockPath, "wx");
11200
+ fs6.closeSync(fd);
11201
+ return { acquired: true, release: makeReleaser(lockPath) };
11202
+ } catch (e) {
11203
+ if (e.code !== "EEXIST")
11204
+ throw e;
11205
+ }
11206
+ try {
11207
+ const st = fs6.statSync(lockPath);
11208
+ if (Date.now() - st.mtimeMs > STALE_LOCK_MS) {
11209
+ try {
11210
+ fs6.unlinkSync(lockPath);
11211
+ } catch {}
11212
+ try {
11213
+ const fd = fs6.openSync(lockPath, "wx");
11214
+ fs6.closeSync(fd);
11215
+ return { acquired: true, release: makeReleaser(lockPath) };
11216
+ } catch {}
11217
+ }
11218
+ } catch {}
11219
+ return { acquired: false, release: NOOP_RELEASE };
11220
+ }
11221
+ var __test__ = Object.freeze({ LOCK_FILENAME, STALE_LOCK_MS });
11222
+
11223
+ // src/catalogue.js
11224
+ var DEFAULT_CATALOGUE_URL = "https://athenadesign.com.au/caw/bundles.json";
11225
+ var CATALOGUE_URL_ENV_VAR = "CAW_BUNDLES_CATALOGUE_URL";
11226
+
11227
+ class CatalogueInvalidError extends Error {
11228
+ constructor(message, { cause } = {}) {
11229
+ super(message);
11230
+ this.name = "CatalogueInvalidError";
11231
+ if (cause)
11232
+ this.cause = cause;
11233
+ }
11234
+ }
11235
+
11236
+ class CatalogueUnreachableError extends Error {
11237
+ constructor(message, { cause, status } = {}) {
11238
+ super(message);
11239
+ this.name = "CatalogueUnreachableError";
11240
+ if (cause)
11241
+ this.cause = cause;
11242
+ if (typeof status === "number")
11243
+ this.status = status;
11244
+ }
11245
+ }
11246
+ function resolveUrl(envOverrides) {
11247
+ const override = envOverrides?.[CATALOGUE_URL_ENV_VAR];
11248
+ if (typeof override === "string" && override.length > 0)
11249
+ return override;
11250
+ return DEFAULT_CATALOGUE_URL;
11251
+ }
11252
+ function validateEntries(payload) {
11253
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
11254
+ throw new CatalogueInvalidError("Catalogue payload must be a JSON object with a `bundles` array");
11255
+ }
11256
+ const bundles = payload.bundles;
11257
+ if (!Array.isArray(bundles)) {
11258
+ throw new CatalogueInvalidError("Catalogue payload must contain a top-level `bundles` array");
11259
+ }
11260
+ const entries = [];
11261
+ for (let i = 0;i < bundles.length; i++) {
11262
+ const raw = bundles[i];
11263
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
11264
+ throw new CatalogueInvalidError(`Catalogue entry at index ${i} is not an object`);
11265
+ }
11266
+ if (typeof raw.name !== "string" || raw.name.length === 0) {
11267
+ throw new CatalogueInvalidError(`Catalogue entry at index ${i} is missing a string \`name\``);
11268
+ }
11269
+ if (typeof raw.url !== "string" || raw.url.length === 0) {
11270
+ throw new CatalogueInvalidError(`Catalogue entry \`${raw.name}\` is missing a string \`url\``);
11271
+ }
11272
+ const entry = { ...raw };
11273
+ if ("sha256" in entry && typeof entry.sha256 !== "string") {
11274
+ console.warn(`[catalogue] Dropped malformed sha256 on entry \`${entry.name}\` (expected string, got ${typeof entry.sha256})`);
11275
+ delete entry.sha256;
11276
+ }
11277
+ if ("version" in entry && typeof entry.version !== "string") {
11278
+ console.warn(`[catalogue] Dropped malformed version on entry \`${entry.name}\` (expected string, got ${typeof entry.version})`);
11279
+ delete entry.version;
11280
+ }
11281
+ entries.push(entry);
11282
+ }
11283
+ return entries;
11284
+ }
11285
+ async function resolveCatalogue({ envDir: _envDir, fetch: fetch2, envOverrides }) {
11286
+ if (typeof fetch2 !== "function") {
11287
+ throw new TypeError("resolveCatalogue requires an injected `fetch` function");
11288
+ }
11289
+ const url = resolveUrl(envOverrides);
11290
+ let response;
11291
+ try {
11292
+ response = await fetch2(url);
11293
+ } catch (e) {
11294
+ throw new CatalogueUnreachableError(`Catalogue fetch failed for ${url}: ${e.message}`, { cause: e });
11295
+ }
11296
+ if (!response || typeof response.status !== "number") {
11297
+ throw new CatalogueUnreachableError(`Catalogue fetch returned no response for ${url}`);
11298
+ }
11299
+ if (response.status < 200 || response.status >= 300) {
11300
+ throw new CatalogueUnreachableError(`Catalogue fetch returned HTTP ${response.status} for ${url}`, { status: response.status });
11301
+ }
11302
+ let bodyText;
11303
+ try {
11304
+ bodyText = await response.text();
11305
+ } catch (e) {
11306
+ throw new CatalogueUnreachableError(`Catalogue response body read failed for ${url}: ${e.message}`, { cause: e });
11307
+ }
11308
+ let payload;
11309
+ try {
11310
+ payload = JSON.parse(bodyText);
11311
+ } catch (e) {
11312
+ throw new CatalogueInvalidError(`Catalogue payload is not valid JSON: ${e.message}`, { cause: e });
11313
+ }
11314
+ const entries = validateEntries(payload);
11315
+ return { entries };
11316
+ }
11317
+
11318
+ // src/first-run-install.js
11319
+ var AUTO_INSTALL_ON_FIRST_RUN = Object.freeze(["user-manual"]);
11320
+ var INFO_TIMEOUT_MS = 2000;
11321
+ var SHARED_EXPORTS_DIR = "shared-exports";
11322
+ var OUTCOME = Object.freeze({
11323
+ SUCCESS: "success",
11324
+ CATALOGUE_UNREACHABLE: "catalogue_unreachable",
11325
+ CATALOGUE_INVALID: "catalogue_invalid",
11326
+ NOT_FOUND: "not_found",
11327
+ CHECKSUM_MISMATCH: "checksum_mismatch",
11328
+ COLLISION: "collision",
11329
+ IMPORT_ERROR: "import_error",
11330
+ UNKNOWN_ERROR: "unknown_error"
11331
+ });
11332
+ function debug2(out, msg) {
11333
+ if (out && typeof out.debug === "function") {
11334
+ try {
11335
+ out.debug(msg);
11336
+ } catch {}
11337
+ }
11338
+ }
11339
+ function writeStdout(out, line) {
11340
+ if (out && typeof out.stdout === "function") {
11341
+ try {
11342
+ out.stdout(line);
11343
+ } catch {}
11344
+ } else {
11345
+ console.log(line);
11346
+ }
11347
+ }
11348
+ function resolveFetch(out) {
11349
+ return out && typeof out.fetch === "function" ? out.fetch : fetch;
11350
+ }
11351
+ function stagedZipPath(envDir, name) {
11352
+ return path7.join(envDir, SHARED_EXPORTS_DIR, `${name}.zip`);
11353
+ }
11354
+ function sha256File(filePath) {
11355
+ return crypto.createHash("sha256").update(fs7.readFileSync(filePath)).digest("hex");
11356
+ }
11357
+ async function fetchInfo(port, fetchFn) {
11358
+ const controller = new AbortController;
11359
+ const timer = setTimeout(() => controller.abort(), INFO_TIMEOUT_MS);
11360
+ try {
11361
+ const res = await fetchFn(`http://localhost:${port}/api/info`, { signal: controller.signal });
11362
+ if (!res || typeof res.status !== "number")
11363
+ return null;
11364
+ if (res.status < 200 || res.status >= 300)
11365
+ return null;
11366
+ return await res.json();
11367
+ } catch {
11368
+ return null;
11369
+ } finally {
11370
+ clearTimeout(timer);
11371
+ }
11372
+ }
11373
+ async function downloadTo(url, targetPath, fetchFn) {
11374
+ const res = await fetchFn(url);
11375
+ if (!res || typeof res.status !== "number") {
11376
+ throw new Error(`download: no response for ${url}`);
11377
+ }
11378
+ if (res.status < 200 || res.status >= 300) {
11379
+ throw new Error(`download: HTTP ${res.status} for ${url}`);
11380
+ }
11381
+ const buf = Buffer.from(await res.arrayBuffer());
11382
+ fs7.mkdirSync(path7.dirname(targetPath), { recursive: true });
11383
+ fs7.writeFileSync(targetPath, buf);
11384
+ }
11385
+ async function postImport(port, filename, fetchFn) {
11386
+ const url = `http://localhost:${port}/api/shared/bundle/import`;
11387
+ let res;
11388
+ try {
11389
+ res = await fetchFn(url, {
11390
+ method: "POST",
11391
+ headers: { "content-type": "application/json" },
11392
+ body: JSON.stringify({ filename, placement: "rootChildren" })
11393
+ });
11394
+ } catch (e) {
11395
+ return { ok: false, outcome: OUTCOME.IMPORT_ERROR, message: e?.message ?? "import fetch failed" };
11396
+ }
11397
+ if (!res || typeof res.status !== "number") {
11398
+ return { ok: false, outcome: OUTCOME.IMPORT_ERROR, message: "no import response" };
11399
+ }
11400
+ let body = null;
11401
+ try {
11402
+ body = await res.json();
11403
+ } catch {
11404
+ body = null;
11405
+ }
11406
+ if (res.status >= 200 && res.status < 300)
11407
+ return { ok: true, body };
11408
+ if (res.status === 409 && body?.code === "ROOT_CHILDREN_COLLISION") {
11409
+ return { ok: false, outcome: OUTCOME.COLLISION, message: body?.error ?? "ROOT_CHILDREN_COLLISION" };
11410
+ }
11411
+ const reason = body?.code ?? body?.error ?? `HTTP ${res.status}`;
11412
+ return { ok: false, outcome: OUTCOME.IMPORT_ERROR, message: reason };
11413
+ }
11414
+ function filenameFromCatalogueEntry(entry, name) {
11415
+ try {
11416
+ const u = new URL(entry.url);
11417
+ const base = path7.basename(u.pathname);
11418
+ return base && base.length > 0 ? base : `${name}.zip`;
11419
+ } catch {
11420
+ return `${name}.zip`;
11421
+ }
11422
+ }
11423
+ async function ensureLocalBundleFile({ envDir, name, entry, fetchFn }) {
11424
+ const sharedDir = path7.join(envDir, SHARED_EXPORTS_DIR);
11425
+ fs7.mkdirSync(sharedDir, { recursive: true });
11426
+ if (entry) {
11427
+ const filename = filenameFromCatalogueEntry(entry, name);
11428
+ const filePath = path7.join(sharedDir, filename);
11429
+ let needDownload = !fs7.existsSync(filePath);
11430
+ if (!needDownload && entry.sha256) {
11431
+ try {
11432
+ if (sha256File(filePath) !== entry.sha256)
11433
+ needDownload = true;
11434
+ } catch {
11435
+ needDownload = true;
11436
+ }
11437
+ }
11438
+ if (needDownload) {
11439
+ await downloadTo(entry.url, filePath, fetchFn);
11440
+ }
11441
+ if (entry.sha256) {
11442
+ const actual = sha256File(filePath);
11443
+ if (actual !== entry.sha256) {
11444
+ const err = new Error(`sha256 mismatch: expected ${entry.sha256}, got ${actual}`);
11445
+ err.__outcome = OUTCOME.CHECKSUM_MISMATCH;
11446
+ throw err;
11447
+ }
11448
+ }
11449
+ return { filename, sourceSha256: entry.sha256 };
11450
+ }
11451
+ const stagedPath = stagedZipPath(envDir, name);
11452
+ if (!fs7.existsSync(stagedPath)) {
11453
+ const err = new Error(`no staged zip at ${stagedPath}`);
11454
+ err.__outcome = OUTCOME.NOT_FOUND;
11455
+ throw err;
11456
+ }
11457
+ let sourceSha256;
11458
+ try {
11459
+ sourceSha256 = sha256File(stagedPath);
11460
+ } catch {
11461
+ sourceSha256 = undefined;
11462
+ }
11463
+ return { filename: `${name}.zip`, sourceSha256 };
11464
+ }
11465
+ function buildAttemptEntry({ name, outcome, filename, sha256, landingPaths, counts }) {
11466
+ const entry = {
11467
+ name,
11468
+ attemptedAt: new Date().toISOString(),
11469
+ outcome,
11470
+ filename
11471
+ };
11472
+ if (sha256)
11473
+ entry.sha256 = sha256;
11474
+ if (landingPaths)
11475
+ entry.landingPaths = landingPaths;
11476
+ if (counts)
11477
+ entry.counts = counts;
11478
+ return entry;
11479
+ }
11480
+ function persistAttempt(envDir, entry, out) {
11481
+ try {
11482
+ return appendInstalledBundle(envDir, entry);
11483
+ } catch (e) {
11484
+ debug2(out, `first-run-install: appendInstalledBundle failed: ${e?.message ?? e}`);
11485
+ return { persisted: false, reason: "append-error" };
11486
+ }
11487
+ }
11488
+ async function processBundle({ name, envDir, port, catalogueResult, out, fetchFn }) {
11489
+ const catalogueEntry = catalogueResult?.entries?.find?.((e) => e.name === name) ?? null;
11490
+ let localFile;
11491
+ try {
11492
+ localFile = await ensureLocalBundleFile({ envDir, name, entry: catalogueEntry, fetchFn });
11493
+ } catch (e) {
11494
+ if (e && e.__outcome) {
11495
+ if (e.__outcome === OUTCOME.NOT_FOUND && catalogueResult?.unreachable) {
11496
+ return { outcome: OUTCOME.CATALOGUE_UNREACHABLE, message: "catalogue unreachable and no staged zip" };
11497
+ }
11498
+ return { outcome: e.__outcome, message: e.message };
11499
+ }
11500
+ return { outcome: OUTCOME.UNKNOWN_ERROR, message: e?.message ?? String(e) };
11501
+ }
11502
+ const imp = await postImport(port, localFile.filename, fetchFn);
11503
+ if (!imp.ok) {
11504
+ return { outcome: imp.outcome, message: imp.message, filename: localFile.filename };
11505
+ }
11506
+ return {
11507
+ outcome: OUTCOME.SUCCESS,
11508
+ filename: localFile.filename,
11509
+ sha256: localFile.sourceSha256,
11510
+ landingPaths: imp.body?.landingPaths,
11511
+ counts: imp.body?.counts
11512
+ };
11513
+ }
11514
+ async function tryResolveCatalogue({ envDir, fetchFn, out }) {
11515
+ try {
11516
+ const envOverrides = { [CATALOGUE_URL_ENV_VAR]: process.env[CATALOGUE_URL_ENV_VAR] };
11517
+ const { entries } = await resolveCatalogue({ envDir, fetch: fetchFn, envOverrides });
11518
+ return { unreachable: false, entries };
11519
+ } catch (e) {
11520
+ if (e instanceof CatalogueUnreachableError) {
11521
+ debug2(out, `first-run-install: catalogue unreachable: ${e.message}`);
11522
+ return { unreachable: true, entries: [] };
11523
+ }
11524
+ throw e;
11525
+ }
11526
+ }
11527
+ function emitStdoutForOutcome(out, outcome) {
11528
+ if (outcome === OUTCOME.SUCCESS) {
11529
+ writeStdout(out, `Installed shipped bundle: user-manual`);
11530
+ return true;
11531
+ }
11532
+ if (isTerminalOutcome(outcome)) {
11533
+ writeStdout(out, `Warning: could not install user manual (${outcome})`);
11534
+ return true;
11535
+ }
11536
+ return false;
11537
+ }
11538
+ async function runFirstRunInstall({ envDir, config, port, out } = {}) {
11539
+ const fetchFn = resolveFetch(out);
11540
+ let lock;
11541
+ try {
11542
+ lock = acquire({ envDir });
11543
+ } catch (e) {
11544
+ debug2(out, `first-run-install: lock.acquire threw: ${e?.message ?? e}`);
11545
+ return;
11546
+ }
11547
+ if (!lock.acquired) {
11548
+ debug2(out, "first-run-install: lock contended → silent no-op");
11549
+ return;
11550
+ }
11551
+ let stdoutEmitted = false;
11552
+ try {
11553
+ const info = await fetchInfo(port, fetchFn);
11554
+ if (!info || info.databaseInitializedThisBoot !== true) {
11555
+ debug2(out, "first-run-install: gate closed (databaseInitializedThisBoot != true)");
11556
+ return;
11557
+ }
11558
+ let cache = [];
11559
+ try {
11560
+ cache = readInstalledBundles(envDir);
11561
+ } catch (e) {
11562
+ debug2(out, `first-run-install: readInstalledBundles failed: ${e?.message ?? e}`);
11563
+ cache = [];
11564
+ }
11565
+ const terminalCachedNames = new Set(cache.filter((e) => e && typeof e.name === "string" && isTerminalOutcome(e.outcome)).map((e) => e.name));
11566
+ const pending = AUTO_INSTALL_ON_FIRST_RUN.filter((n) => !terminalCachedNames.has(n));
11567
+ if (pending.length === 0) {
11568
+ debug2(out, "first-run-install: all bundles already terminal-cached");
11569
+ return;
11570
+ }
11571
+ let catalogueResult;
11572
+ try {
11573
+ catalogueResult = await tryResolveCatalogue({ envDir, fetchFn, out });
11574
+ } catch (e) {
11575
+ const outcome = e instanceof CatalogueInvalidError ? OUTCOME.CATALOGUE_INVALID : OUTCOME.UNKNOWN_ERROR;
11576
+ for (const name of pending) {
11577
+ persistAttempt(envDir, buildAttemptEntry({ name, outcome, filename: `${name}.zip` }), out);
11578
+ }
11579
+ if (!stdoutEmitted)
11580
+ stdoutEmitted = emitStdoutForOutcome(out, outcome);
11581
+ return;
11582
+ }
11583
+ for (const name of pending) {
11584
+ let result;
11585
+ try {
11586
+ result = await processBundle({ name, envDir, port, catalogueResult, out, fetchFn });
11587
+ } catch (e) {
11588
+ debug2(out, `first-run-install: processBundle threw for ${name}: ${e?.message ?? e}`);
11589
+ result = { outcome: OUTCOME.UNKNOWN_ERROR, message: e?.message ?? String(e), filename: `${name}.zip` };
11590
+ }
11591
+ const entry = buildAttemptEntry({
11592
+ name,
11593
+ outcome: result.outcome,
11594
+ filename: result.filename ?? `${name}.zip`,
11595
+ sha256: result.sha256,
11596
+ landingPaths: result.landingPaths,
11597
+ counts: result.counts
11598
+ });
11599
+ persistAttempt(envDir, entry, out);
11600
+ debug2(out, `first-run-install: ${name} → ${result.outcome}${result.message ? ` (${result.message})` : ""}`);
11601
+ if (!stdoutEmitted)
11602
+ stdoutEmitted = emitStdoutForOutcome(out, result.outcome);
11603
+ }
11604
+ } catch (e) {
11605
+ debug2(out, `first-run-install: contain-degrade wrapper caught: ${e?.message ?? e}`);
11606
+ const outcome = e instanceof CatalogueInvalidError ? OUTCOME.CATALOGUE_INVALID : e instanceof CatalogueUnreachableError ? OUTCOME.CATALOGUE_UNREACHABLE : OUTCOME.UNKNOWN_ERROR;
11607
+ if (!stdoutEmitted && isTerminalOutcome(outcome)) {
11608
+ emitStdoutForOutcome(out, outcome);
11609
+ }
11610
+ } finally {
11611
+ try {
11612
+ lock.release();
11613
+ } catch (e) {
11614
+ debug2(out, `first-run-install: lock.release threw: ${e?.message ?? e}`);
11615
+ }
11616
+ }
11617
+ }
11618
+ var __test__2 = Object.freeze({ OUTCOME, INFO_TIMEOUT_MS, SHARED_EXPORTS_DIR });
11619
+
11128
11620
  // src/commands/start.js
11129
11621
  function resolveEnvDir(rawEnvDir) {
11130
11622
  if (rawEnvDir.startsWith("~")) {
11131
- rawEnvDir = path6.join(os2.homedir(), rawEnvDir.slice(1));
11623
+ rawEnvDir = path8.join(os2.homedir(), rawEnvDir.slice(1));
11132
11624
  }
11133
- return path6.resolve(rawEnvDir);
11625
+ return path8.resolve(rawEnvDir);
11134
11626
  }
11135
11627
  function configExists(envDir) {
11136
- return fs6.existsSync(path6.join(envDir, "config.json"));
11628
+ return fs8.existsSync(path8.join(envDir, "config.json"));
11137
11629
  }
11138
11630
  function validateEnvFile(envDir) {
11139
- const envFilePath = path6.join(envDir, ".env");
11140
- if (!fs6.existsSync(envFilePath)) {
11631
+ const envFilePath = path8.join(envDir, ".env");
11632
+ if (!fs8.existsSync(envFilePath)) {
11141
11633
  return {
11142
11634
  ok: false,
11143
11635
  message: `Error: Environment file not found: ${envFilePath}
11144
11636
  Create it with your configuration variables (e.g., OPENAI_API_KEY, CLAUDE_CODE_OAUTH_TOKEN).`
11145
11637
  };
11146
11638
  }
11147
- const content = fs6.readFileSync(envFilePath, "utf8");
11639
+ const content = fs8.readFileSync(envFilePath, "utf8");
11148
11640
  const lines = content.split(`
11149
11641
  `);
11150
11642
  for (let i = 0;i < lines.length; i++) {
@@ -11166,10 +11658,10 @@ var MAX_LOG_SIZE = 10 * 1024 * 1024;
11166
11658
  var LOG_RETAIN = 5;
11167
11659
  function rotateLogIfNeeded(envDir) {
11168
11660
  try {
11169
- const logPath = path6.join(envDir, "server.log");
11170
- if (!fs6.existsSync(logPath))
11661
+ const logPath = path8.join(envDir, "server.log");
11662
+ if (!fs8.existsSync(logPath))
11171
11663
  return;
11172
- const stats = fs6.statSync(logPath);
11664
+ const stats = fs8.statSync(logPath);
11173
11665
  if (stats.size <= MAX_LOG_SIZE)
11174
11666
  return;
11175
11667
  const now = new Date;
@@ -11183,18 +11675,18 @@ function rotateLogIfNeeded(envDir) {
11183
11675
  pad2(now.getMinutes()),
11184
11676
  pad2(now.getSeconds())
11185
11677
  ].join("-");
11186
- fs6.renameSync(logPath, `${logPath}.${timestamp}`);
11678
+ fs8.renameSync(logPath, `${logPath}.${timestamp}`);
11187
11679
  console.log(`Rotated server.log (was ${(stats.size / 1024 / 1024).toFixed(1)} MB)`);
11188
- const rotated = fs6.readdirSync(envDir).filter((f) => f.startsWith("server.log.")).map((f) => ({ name: f, mtime: fs6.statSync(path6.join(envDir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime);
11680
+ const rotated = fs8.readdirSync(envDir).filter((f) => f.startsWith("server.log.")).map((f) => ({ name: f, mtime: fs8.statSync(path8.join(envDir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime);
11189
11681
  for (const file of rotated.slice(LOG_RETAIN)) {
11190
- fs6.unlinkSync(path6.join(envDir, file.name));
11682
+ fs8.unlinkSync(path8.join(envDir, file.name));
11191
11683
  }
11192
11684
  } catch (err) {
11193
11685
  console.warn(`Warning: log rotation failed: ${err.message}`);
11194
11686
  }
11195
11687
  }
11196
11688
  function buildEnvNodeArgs(envDir) {
11197
- const envFilePath = path6.join(envDir, ".env");
11689
+ const envFilePath = path8.join(envDir, ".env");
11198
11690
  return [`--env-file=${envFilePath}`];
11199
11691
  }
11200
11692
  function sleepSync(ms) {
@@ -11209,22 +11701,22 @@ function ensureInstallIdentity(envDir) {
11209
11701
  if (hasFullIdentity(existing))
11210
11702
  return existing;
11211
11703
  }
11212
- fs6.mkdirSync(envDir, { recursive: true });
11213
- const lockPath = path6.join(envDir, "config.identity.lock");
11704
+ fs8.mkdirSync(envDir, { recursive: true });
11705
+ const lockPath = path8.join(envDir, "config.identity.lock");
11214
11706
  let acquired = false;
11215
11707
  for (let attempt = 0;attempt < 100; attempt++) {
11216
11708
  try {
11217
- const fd = fs6.openSync(lockPath, "wx");
11218
- fs6.closeSync(fd);
11709
+ const fd = fs8.openSync(lockPath, "wx");
11710
+ fs8.closeSync(fd);
11219
11711
  acquired = true;
11220
11712
  break;
11221
11713
  } catch (e) {
11222
11714
  if (e.code !== "EEXIST")
11223
11715
  throw e;
11224
11716
  try {
11225
- const st = fs6.statSync(lockPath);
11717
+ const st = fs8.statSync(lockPath);
11226
11718
  if (Date.now() - st.mtimeMs > 1e4) {
11227
- fs6.unlinkSync(lockPath);
11719
+ fs8.unlinkSync(lockPath);
11228
11720
  continue;
11229
11721
  }
11230
11722
  } catch {}
@@ -11236,11 +11728,11 @@ function ensureInstallIdentity(envDir) {
11236
11728
  const merged = { ...existing };
11237
11729
  let mutated = false;
11238
11730
  if (typeof merged.installId !== "string" || merged.installId.length === 0) {
11239
- merged.installId = crypto.randomUUID();
11731
+ merged.installId = crypto2.randomUUID();
11240
11732
  mutated = true;
11241
11733
  }
11242
11734
  if (typeof merged.installSalt !== "string" || merged.installSalt.length === 0) {
11243
- merged.installSalt = crypto.randomBytes(32).toString("base64url");
11735
+ merged.installSalt = crypto2.randomBytes(32).toString("base64url");
11244
11736
  mutated = true;
11245
11737
  }
11246
11738
  if (typeof merged.analyticsEnabled !== "boolean") {
@@ -11254,18 +11746,18 @@ function ensureInstallIdentity(envDir) {
11254
11746
  } finally {
11255
11747
  if (acquired) {
11256
11748
  try {
11257
- fs6.unlinkSync(lockPath);
11749
+ fs8.unlinkSync(lockPath);
11258
11750
  } catch {}
11259
11751
  }
11260
11752
  }
11261
11753
  }
11262
11754
  function bootstrap(envDir) {
11263
- fs6.mkdirSync(envDir, { recursive: true });
11264
- fs6.mkdirSync(path6.join(envDir, "assets"), { recursive: true });
11755
+ fs8.mkdirSync(envDir, { recursive: true });
11756
+ fs8.mkdirSync(path8.join(envDir, "assets"), { recursive: true });
11265
11757
  ensureInstallIdentity(envDir);
11266
- const envFilePath = path6.join(envDir, ".env");
11267
- if (!fs6.existsSync(envFilePath)) {
11268
- fs6.writeFileSync(envFilePath, [
11758
+ const envFilePath = path8.join(envDir, ".env");
11759
+ if (!fs8.existsSync(envFilePath)) {
11760
+ fs8.writeFileSync(envFilePath, [
11269
11761
  "# CAW environment configuration",
11270
11762
  "# Uncomment and set values as needed",
11271
11763
  "",
@@ -11378,9 +11870,11 @@ How would you like to proceed?`,
11378
11870
  if (hasPendingConfig(envDir)) {
11379
11871
  console.log(`Server is already running on port ${config.port}.`);
11380
11872
  console.log("There are pending configuration changes. Stop the server first to apply them.");
11873
+ await runFirstRunInstall({ envDir, config, port: config.port, out: undefined });
11381
11874
  process.exit(0);
11382
11875
  }
11383
11876
  console.log(`Server is already running on port ${config.port}.`);
11877
+ await runFirstRunInstall({ envDir, config, port: config.port, out: undefined });
11384
11878
  process.exit(0);
11385
11879
  }
11386
11880
  await emitCawCmdStart({ config: readConfig(envDir) });
@@ -11438,26 +11932,27 @@ How would you like to proceed?`,
11438
11932
  const started = await pollHealth(activeConfig.port);
11439
11933
  if (!started) {
11440
11934
  console.error(`Server did not become healthy within 10 seconds.`);
11441
- console.error(`Check logs with: caw logs${envDir !== path6.join(os2.homedir(), ".caw") ? ` --env-dir ${envDir}` : ""}`);
11935
+ console.error(`Check logs with: caw logs${envDir !== path8.join(os2.homedir(), ".caw") ? ` --env-dir ${envDir}` : ""}`);
11442
11936
  process.exit(1);
11443
11937
  }
11444
11938
  console.log(`Server started successfully on http://localhost:${activeConfig.port}`);
11939
+ await runFirstRunInstall({ envDir, config: activeConfig, port: activeConfig.port, out: undefined });
11445
11940
  }).onError({ exitCode: 1 }).build();
11446
11941
  };
11447
11942
  var start_default = Object.freeze({ create: create2 });
11448
11943
 
11449
11944
  // src/commands/stop.js
11450
- import fs7 from "node:fs";
11451
- import path7 from "node:path";
11945
+ import fs9 from "node:fs";
11946
+ import path9 from "node:path";
11452
11947
  import os3 from "node:os";
11453
11948
  function resolveEnvDir2(rawEnvDir) {
11454
11949
  if (rawEnvDir.startsWith("~")) {
11455
- rawEnvDir = path7.join(os3.homedir(), rawEnvDir.slice(1));
11950
+ rawEnvDir = path9.join(os3.homedir(), rawEnvDir.slice(1));
11456
11951
  }
11457
- return path7.resolve(rawEnvDir);
11952
+ return path9.resolve(rawEnvDir);
11458
11953
  }
11459
11954
  function configExists2(envDir) {
11460
- return fs7.existsSync(path7.join(envDir, "config.json"));
11955
+ return fs9.existsSync(path9.join(envDir, "config.json"));
11461
11956
  }
11462
11957
  async function checkHealth2(port) {
11463
11958
  try {
@@ -11527,7 +12022,7 @@ var create3 = () => {
11527
12022
  return createCommand("stop").summary("Stop the caw server").param((p) => p.name("env-dir").type("string").flag("env-dir").default("~/.caw/")).param((p) => p.name("force").type("boolean").flag("force").default(false)).run(async (ctx) => {
11528
12023
  const envDir = resolveEnvDir2(ctx.params["env-dir"]);
11529
12024
  const force = ctx.params.force;
11530
- if (!fs7.existsSync(envDir) || !configExists2(envDir)) {
12025
+ if (!fs9.existsSync(envDir) || !configExists2(envDir)) {
11531
12026
  console.log("Server is not running (no environment directory or config found).");
11532
12027
  process.exit(0);
11533
12028
  }
@@ -11548,13 +12043,13 @@ var stop_default = Object.freeze({ create: create3 });
11548
12043
 
11549
12044
  // src/commands/status.js
11550
12045
  var import_semver = __toESM(require_semver2(), 1);
11551
- import fs9 from "node:fs";
11552
- import path9 from "node:path";
12046
+ import fs11 from "node:fs";
12047
+ import path11 from "node:path";
11553
12048
  import os4 from "node:os";
11554
12049
 
11555
12050
  // src/registry.js
11556
- import fs8 from "node:fs";
11557
- import path8 from "node:path";
12051
+ import fs10 from "node:fs";
12052
+ import path10 from "node:path";
11558
12053
  var CACHE_FILENAME = "caw-cache.json";
11559
12054
  var DEFAULT_TIMEOUT_MS = 1e4;
11560
12055
  var DEFAULT_TTL_MS = 60 * 60 * 1000;
@@ -11570,18 +12065,18 @@ async function fetchLatestVersion(packageName, { timeoutMs = DEFAULT_TIMEOUT_MS
11570
12065
  return data["dist-tags"].latest;
11571
12066
  }
11572
12067
  function readCache(envDir) {
11573
- const cachePath = path8.join(envDir, CACHE_FILENAME);
12068
+ const cachePath = path10.join(envDir, CACHE_FILENAME);
11574
12069
  try {
11575
- return JSON.parse(fs8.readFileSync(cachePath, "utf8"));
12070
+ return JSON.parse(fs10.readFileSync(cachePath, "utf8"));
11576
12071
  } catch {
11577
12072
  return null;
11578
12073
  }
11579
12074
  }
11580
12075
  function writeCache(envDir, cache) {
11581
- const cachePath = path8.join(envDir, CACHE_FILENAME);
12076
+ const cachePath = path10.join(envDir, CACHE_FILENAME);
11582
12077
  const tmp = cachePath + ".tmp";
11583
- fs8.writeFileSync(tmp, JSON.stringify(cache, null, 2));
11584
- fs8.renameSync(tmp, cachePath);
12078
+ fs10.writeFileSync(tmp, JSON.stringify(cache, null, 2));
12079
+ fs10.renameSync(tmp, cachePath);
11585
12080
  }
11586
12081
  function isCacheStale(cache, ttlMs = DEFAULT_TTL_MS) {
11587
12082
  if (!cache)
@@ -11598,12 +12093,12 @@ function isCacheStale(cache, ttlMs = DEFAULT_TTL_MS) {
11598
12093
  // src/commands/status.js
11599
12094
  function resolveEnvDir3(rawEnvDir) {
11600
12095
  if (rawEnvDir.startsWith("~")) {
11601
- rawEnvDir = path9.join(os4.homedir(), rawEnvDir.slice(1));
12096
+ rawEnvDir = path11.join(os4.homedir(), rawEnvDir.slice(1));
11602
12097
  }
11603
- return path9.resolve(rawEnvDir);
12098
+ return path11.resolve(rawEnvDir);
11604
12099
  }
11605
12100
  function configExists3(envDir) {
11606
- return fs9.existsSync(path9.join(envDir, "config.json"));
12101
+ return fs11.existsSync(path11.join(envDir, "config.json"));
11607
12102
  }
11608
12103
  async function fetchHealth(port) {
11609
12104
  try {
@@ -11616,7 +12111,7 @@ async function fetchHealth(port) {
11616
12111
  return null;
11617
12112
  }
11618
12113
  }
11619
- async function fetchInfo(port) {
12114
+ async function fetchInfo2(port) {
11620
12115
  try {
11621
12116
  const response = await fetch(`http://localhost:${port}/api/info`);
11622
12117
  if (response.ok) {
@@ -11646,7 +12141,7 @@ function formatUptime(ms) {
11646
12141
  function getUptimeFromPidFile(envDir) {
11647
12142
  const filePath = pidFilePath(envDir);
11648
12143
  try {
11649
- const stat = fs9.statSync(filePath);
12144
+ const stat = fs11.statSync(filePath);
11650
12145
  return Date.now() - stat.mtimeMs;
11651
12146
  } catch {
11652
12147
  return null;
@@ -11661,7 +12156,7 @@ function getUptimeFromPm2(runState) {
11661
12156
  var create4 = () => {
11662
12157
  return createCommand("status").summary("Show caw server status").param((p) => p.name("env-dir").type("string").flag("env-dir").default("~/.caw/")).run(async (ctx) => {
11663
12158
  const envDir = resolveEnvDir3(ctx.params["env-dir"]);
11664
- if (!fs9.existsSync(envDir) || !configExists3(envDir)) {
12159
+ if (!fs11.existsSync(envDir) || !configExists3(envDir)) {
11665
12160
  console.log("Server: not configured");
11666
12161
  console.log(` No environment found at ${envDir}`);
11667
12162
  process.exit(0);
@@ -11690,7 +12185,7 @@ var create4 = () => {
11690
12185
  }
11691
12186
  const processLabel = pm.mode === "pm2" ? `running (pm2: ${runState.pm2Name})` : `running (PID ${runState.pid})`;
11692
12187
  const health = await fetchHealth(config.port);
11693
- const info = await fetchInfo(config.port);
12188
+ const info = await fetchInfo2(config.port);
11694
12189
  const healthStatus = health ? health.status === "ok" ? "ok" : health.status : "unreachable";
11695
12190
  const uptimeMs = pm.mode === "pm2" ? getUptimeFromPm2(runState) : getUptimeFromPidFile(envDir);
11696
12191
  const uptimeLabel = uptimeMs !== null ? formatUptime(uptimeMs) : "unknown";
@@ -11726,21 +12221,21 @@ var create4 = () => {
11726
12221
  var status_default = Object.freeze({ create: create4 });
11727
12222
 
11728
12223
  // src/commands/logs.js
11729
- import fs10 from "node:fs";
11730
- import path10 from "node:path";
12224
+ import fs12 from "node:fs";
12225
+ import path12 from "node:path";
11731
12226
  import os5 from "node:os";
11732
12227
  import { spawn as spawn2 } from "node:child_process";
11733
12228
  function resolveEnvDir4(rawEnvDir) {
11734
12229
  if (rawEnvDir.startsWith("~")) {
11735
- rawEnvDir = path10.join(os5.homedir(), rawEnvDir.slice(1));
12230
+ rawEnvDir = path12.join(os5.homedir(), rawEnvDir.slice(1));
11736
12231
  }
11737
- return path10.resolve(rawEnvDir);
12232
+ return path12.resolve(rawEnvDir);
11738
12233
  }
11739
12234
  var create5 = () => {
11740
12235
  return createCommand("logs").summary("Tail the caw server logs").param((p) => p.name("env-dir").type("string").flag("env-dir").default("~/.caw/")).run(async (ctx) => {
11741
12236
  const envDir = resolveEnvDir4(ctx.params["env-dir"]);
11742
- const logPath = path10.join(envDir, "server.log");
11743
- if (!fs10.existsSync(logPath)) {
12237
+ const logPath = path12.join(envDir, "server.log");
12238
+ if (!fs12.existsSync(logPath)) {
11744
12239
  console.log(`No log file found at ${logPath}`);
11745
12240
  process.exit(0);
11746
12241
  }
@@ -11762,19 +12257,19 @@ var logs_default = Object.freeze({ create: create5 });
11762
12257
 
11763
12258
  // src/commands/upgrade.js
11764
12259
  var import_semver2 = __toESM(require_semver2(), 1);
11765
- import fs11 from "node:fs";
11766
- import path11 from "node:path";
12260
+ import fs13 from "node:fs";
12261
+ import path13 from "node:path";
11767
12262
  import os6 from "node:os";
11768
12263
  import { execSync as execSync5 } from "node:child_process";
11769
12264
  var COMPATIBLE_SERVER_RANGE = "^1";
11770
12265
  function resolveEnvDir5(rawEnvDir) {
11771
12266
  if (rawEnvDir.startsWith("~")) {
11772
- rawEnvDir = path11.join(os6.homedir(), rawEnvDir.slice(1));
12267
+ rawEnvDir = path13.join(os6.homedir(), rawEnvDir.slice(1));
11773
12268
  }
11774
- return path11.resolve(rawEnvDir);
12269
+ return path13.resolve(rawEnvDir);
11775
12270
  }
11776
12271
  function configExists4(envDir) {
11777
- return fs11.existsSync(path11.join(envDir, "config.json"));
12272
+ return fs13.existsSync(path13.join(envDir, "config.json"));
11778
12273
  }
11779
12274
  async function checkHealth3(port) {
11780
12275
  try {
@@ -11856,7 +12351,7 @@ var create6 = () => {
11856
12351
  let skipInstall = false;
11857
12352
  if (import_semver2.default.gte(installedVersion, latestServerVersion)) {
11858
12353
  let needsRestart = false;
11859
- if (fs11.existsSync(envDir) && configExists4(envDir)) {
12354
+ if (fs13.existsSync(envDir) && configExists4(envDir)) {
11860
12355
  const config = readConfigWithDefaults(envDir);
11861
12356
  const pm = createProcessManager(config, envDir);
11862
12357
  if (pm.isRunning().running) {
@@ -11904,7 +12399,7 @@ var create6 = () => {
11904
12399
  process.exit(0);
11905
12400
  }
11906
12401
  let serverWasStopped = false;
11907
- if (fs11.existsSync(envDir) && configExists4(envDir)) {
12402
+ if (fs13.existsSync(envDir) && configExists4(envDir)) {
11908
12403
  const config = readConfigWithDefaults(envDir);
11909
12404
  const pm = createProcessManager(config, envDir);
11910
12405
  const runState = pm.isRunning();
@@ -11955,7 +12450,7 @@ var create6 = () => {
11955
12450
  process.exit(1);
11956
12451
  }
11957
12452
  }
11958
- if (serverWasStopped || fs11.existsSync(envDir) && configExists4(envDir)) {
12453
+ if (serverWasStopped || fs13.existsSync(envDir) && configExists4(envDir)) {
11959
12454
  const config = readConfigWithDefaults(envDir);
11960
12455
  const pm = createProcessManager(config, envDir);
11961
12456
  const newServerInfo = resolve();
@@ -11985,18 +12480,18 @@ var create6 = () => {
11985
12480
  var upgrade_default = Object.freeze({ create: create6 });
11986
12481
 
11987
12482
  // src/commands/restart.js
11988
- import fs12 from "node:fs";
11989
- import path12 from "node:path";
12483
+ import fs14 from "node:fs";
12484
+ import path14 from "node:path";
11990
12485
  import os7 from "node:os";
11991
12486
  import { execSync as execSync6 } from "node:child_process";
11992
12487
  function resolveEnvDir6(rawEnvDir) {
11993
12488
  if (rawEnvDir.startsWith("~")) {
11994
- rawEnvDir = path12.join(os7.homedir(), rawEnvDir.slice(1));
12489
+ rawEnvDir = path14.join(os7.homedir(), rawEnvDir.slice(1));
11995
12490
  }
11996
- return path12.resolve(rawEnvDir);
12491
+ return path14.resolve(rawEnvDir);
11997
12492
  }
11998
12493
  function configExists5(envDir) {
11999
- return fs12.existsSync(path12.join(envDir, "config.json"));
12494
+ return fs14.existsSync(path14.join(envDir, "config.json"));
12000
12495
  }
12001
12496
  function buildChangeSummary2(active, pending) {
12002
12497
  const changes = [];
@@ -12035,7 +12530,7 @@ var create7 = () => {
12035
12530
  }
12036
12531
  const envDir = resolveEnvDir6(ctx.params["env-dir"]);
12037
12532
  const force = ctx.params.force;
12038
- if (fs12.existsSync(envDir) && configExists5(envDir)) {
12533
+ if (fs14.existsSync(envDir) && configExists5(envDir)) {
12039
12534
  const config2 = readConfigWithDefaults(envDir);
12040
12535
  const pm3 = createProcessManager(config2, envDir);
12041
12536
  const result = await executeStop(pm3, config2, force, ctx.prompt, envDir);
@@ -12138,7 +12633,7 @@ How would you like to proceed?`,
12138
12633
  const started = await pollHealth(activeConfig.port);
12139
12634
  if (!started) {
12140
12635
  console.error(`Server did not become healthy within 10 seconds.`);
12141
- console.error(`Check logs with: caw logs${envDir !== path12.join(os7.homedir(), ".caw") ? ` --env-dir ${envDir}` : ""}`);
12636
+ console.error(`Check logs with: caw logs${envDir !== path14.join(os7.homedir(), ".caw") ? ` --env-dir ${envDir}` : ""}`);
12142
12637
  process.exit(1);
12143
12638
  }
12144
12639
  console.log(`Server started successfully on http://localhost:${activeConfig.port}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kelceyp/caw",
3
- "version": "1.0.32",
3
+ "version": "1.0.34",
4
4
  "type": "module",
5
5
  "description": "Unified Web/MCP server with React web app. Provides MD document management, handlebars based templating (documents, prompts and saved searches), user stories including task management and search (rag, fts & metadata with query language). CAW works with any agent that supports MCP but has specific integrations for Claude Code, Codex and Cursor CLI that enable agent orchestration. For humans, think of this as a browser-based reskinning of these tools enabling all prompts and outputs to be captured. For agents, this means that any of these three agents can be used by any other as a \"sub-agent\". And this works recursively to a user configurable depth.",
6
6
  "keywords": [