@nice-code/commander 0.112.0 → 0.114.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.cjs CHANGED
@@ -307,6 +307,53 @@ async function pingDaemon(record, timeoutMs = 2e3) {
307
307
  }
308
308
  }
309
309
  //#endregion
310
+ //#region src/daemon/packageVersion.ts
311
+ let cached = null;
312
+ /**
313
+ * Resolved relative to the BUILT module, so the candidate list must cover every layout this
314
+ * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that
315
+ * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).
316
+ */
317
+ async function commanderPackageVersion() {
318
+ if (cached != null) return cached;
319
+ for (const candidate of [
320
+ new URL("../package.json", require("url").pathToFileURL(__filename).href),
321
+ new URL("../../package.json", require("url").pathToFileURL(__filename).href),
322
+ new URL("../../../package.json", require("url").pathToFileURL(__filename).href)
323
+ ]) try {
324
+ const parsed = JSON.parse(await (0, node_fs_promises.readFile)(candidate, "utf8"));
325
+ if (typeof parsed.version === "string" && parsed.name === "@nice-code/commander") {
326
+ cached = parsed.version;
327
+ return cached;
328
+ }
329
+ } catch {}
330
+ cached = "0.0.0";
331
+ return cached;
332
+ }
333
+ //#endregion
334
+ //#region src/cli/configSync.ts
335
+ /**
336
+ * Bring the daemon onto `config`'s revision before acting on it. Never fails the command: when
337
+ * the daemon ends up on another revision the start still happens, on the daemon's reading, and
338
+ * the difference is said on stderr.
339
+ */
340
+ async function syncDaemonConfig(config, client, out) {
341
+ if (client.state().configRevisionHash === config.configRevisionHash) return;
342
+ const result = await client.reloadConfig();
343
+ if (result?.configRevisionHash === config.configRevisionHash) return;
344
+ const note = (text) => out.warn(`${out.paint("yellow", "⚠")} ${text}`);
345
+ if (result == null) {
346
+ note("the daemon could not be asked to reload the config — what starts may be on the revision it loaded earlier (`nice-commander shutdown`, then `up`, starts one on this build)");
347
+ return;
348
+ }
349
+ if (!result.applied) {
350
+ note("the daemon kept its last good config — the one on disk did not load there:\n" + result.errors.map((line) => ` - ${line}`).join("\n"));
351
+ return;
352
+ }
353
+ const build = await commanderPackageVersion();
354
+ note(`the daemon reads this config differently from this shell (${client.record.packageVersion === build ? "a value the config computes from the environment, or a plain .mjs/.js helper, stays as the daemon first read it" : `it runs build ${client.record.packageVersion}, this CLI is build ${build}`}) — what starts is the daemon's reading. \`nice-commander shutdown\`, then \`up\`, rebuilds it from here.`);
355
+ }
356
+ //#endregion
310
357
  //#region src/config/flags.ts
311
358
  /**
312
359
  * An argument a shell-string `run` can take appended unquoted in sh, cmd and PowerShell alike.
@@ -605,13 +652,30 @@ function aliasFromNearestTsconfig(configDir) {
605
652
  dir = parent;
606
653
  }
607
654
  }
608
- /** One fresh loader context per load attempt — the reload model depends on it (D2). */
609
- function freshLoader(configPath) {
610
- return (0, jiti.createJiti)((0, node_url.pathToFileURL)(configPath).href, {
655
+ /**
656
+ * One fresh loader context per load attempt — the reload model depends on it (D2).
657
+ *
658
+ * Every file jiti transforms is added to `transformed`. With the caches off that is every module
659
+ * the load reads from source — which is also exactly the set a later load would read afresh, so
660
+ * it is the set worth watching. A module handed to the runtime's own `import()` (a plain `.mjs`
661
+ * helper) is not in it, and would not reload if it were.
662
+ */
663
+ function freshLoader(configPath, transformed) {
664
+ const url = (0, node_url.pathToFileURL)(configPath).href;
665
+ const options = {
611
666
  moduleCache: false,
612
667
  fsCache: false,
613
668
  tryNative: false,
614
669
  alias: aliasFromNearestTsconfig((0, node_path.dirname)(configPath))
670
+ };
671
+ const transform = (0, jiti.createJiti)(url, options).options.transform;
672
+ if (transform == null) return (0, jiti.createJiti)(url, options);
673
+ return (0, jiti.createJiti)(url, {
674
+ ...options,
675
+ transform: (input) => {
676
+ if (input.filename != null) transformed.add((0, node_path.resolve)(input.filename));
677
+ return transform(input);
678
+ }
615
679
  });
616
680
  }
617
681
  /** Extensions jiti hands straight to the runtime's own ESM loader instead of transforming. */
@@ -629,8 +693,8 @@ const NATIVE_ESM = /\.(mjs|js)$/;
629
693
  * `forceTranspile` puts `.mjs` on that same transformed path. Passing `filename` keeps relative
630
694
  * imports and `import.meta` resolving exactly as a native import would.
631
695
  */
632
- async function importFresh(configPath) {
633
- const loader = freshLoader(configPath);
696
+ async function importFresh(configPath, transformed) {
697
+ const loader = freshLoader(configPath, transformed);
634
698
  if (!NATIVE_ESM.test(configPath)) return loader.import(configPath);
635
699
  return loader.evalModule((0, node_fs.readFileSync)(configPath, "utf8"), {
636
700
  filename: configPath,
@@ -639,6 +703,19 @@ async function importFresh(configPath) {
639
703
  async: true
640
704
  });
641
705
  }
706
+ /** A config that could not be loaded. Still says which modules the attempt reached. */
707
+ var CommanderConfigLoadError = class extends Error {
708
+ loadedFiles;
709
+ constructor(message, loadedFiles, cause) {
710
+ super(message, { cause });
711
+ this.name = "CommanderConfigLoadError";
712
+ this.loadedFiles = loadedFiles;
713
+ }
714
+ };
715
+ const IN_NODE_MODULES = /[\\/]node_modules[\\/]/;
716
+ function localModules(transformed, configPath) {
717
+ return [...transformed].filter((file) => file !== configPath && !IN_NODE_MODULES.test(file));
718
+ }
642
719
  /**
643
720
  * Load a config file's default export. Throws an Error naming the file on parse/load failure —
644
721
  * the daemon's reload path catches this and keeps the last-good model.
@@ -647,17 +724,19 @@ async function loadCommanderConfigFile(path) {
647
724
  const explicit = (0, node_path.isAbsolute)(path) ? path : (0, node_path.resolve)(path);
648
725
  if (!(0, node_fs.existsSync)(explicit)) throw new Error(`commander config not found: ${explicit}`);
649
726
  const configPath = (0, node_fs.realpathSync)(explicit);
727
+ const transformed = /* @__PURE__ */ new Set();
650
728
  let mod;
651
729
  try {
652
- mod = await importFresh(configPath);
730
+ mod = await importFresh(configPath, transformed);
653
731
  } catch (error) {
654
- throw new Error(`failed to load ${configPath}: ${error.message}`, { cause: error });
732
+ throw new CommanderConfigLoadError(`failed to load ${configPath}: ${error instanceof Error ? error.message : String(error)}`, localModules(transformed, configPath), error);
655
733
  }
656
734
  if (mod == null || typeof mod !== "object" || !("default" in mod)) throw new Error(`${configPath}: expected a default export`);
657
735
  return {
658
736
  configPath,
659
737
  configDir: (0, node_path.dirname)(configPath),
660
- raw: mod.default
738
+ raw: mod.default,
739
+ loadedFiles: localModules(transformed, configPath)
661
740
  };
662
741
  }
663
742
  //#endregion
@@ -734,6 +813,18 @@ function envVarViews(definition, overrides, baseEnv) {
734
813
  function missingRequired(definition, overrides, baseEnv) {
735
814
  return envVarViews(definition, overrides, baseEnv).filter((view) => view.required && view.source === "unset").map((view) => view.name);
736
815
  }
816
+ const JUDGED_IN = {
817
+ daemon: "the daemon's environment",
818
+ shell: "this shell's environment"
819
+ };
820
+ /** "the daemon's environment" / "this shell's environment". */
821
+ function describeJudgedIn(judgedIn) {
822
+ return JUDGED_IN[judgedIn];
823
+ }
824
+ /** Why a start is refused over `required` variables, with the command that supplies one. */
825
+ function requiredRefusal(id, missing, judgedIn) {
826
+ return `requires ${missing.join(", ")} — no default, no override, and not set in ${JUDGED_IN[judgedIn]}; \`nice-commander env ${id} --set ${missing[0]}=…\` supplies it`;
827
+ }
737
828
  /**
738
829
  * Keep only what the config can justify. Setting a value requires a DECLARED variable on a known
739
830
  * process — that filter is what makes the UI's write path safe. Removing is always allowed, even
@@ -1531,6 +1622,9 @@ function jsErrorOrCastJsError(error, logMessage = true) {
1531
1622
  };
1532
1623
  }
1533
1624
  //#endregion
1625
+ //#region ../nice-error/package.json
1626
+ var version = "0.114.0";
1627
+ //#endregion
1534
1628
  //#region ../nice-error/src/utils/logger.ts
1535
1629
  let activeLogger = {
1536
1630
  warn: (message, meta) => meta !== void 0 ? console.warn(message, meta) : console.warn(message),
@@ -1542,6 +1636,41 @@ function getNiceErrorLogger() {
1542
1636
  return activeLogger;
1543
1637
  }
1544
1638
  //#endregion
1639
+ //#region ../nice-error/src/utils/loadedVersions.ts
1640
+ /** This package's version, read from its manifest when the package is built. */
1641
+ const NICE_ERROR_VERSION = version;
1642
+ const LOADED_VERSIONS_KEY = Symbol.for("@nice-code/error/versions");
1643
+ const LOCKSTEP_RULE = "Every @nice-code/* package must be on the same version (the lockstep rule): an error built by one copy of @nice-code/error fails `instanceof NiceError` in another. `nice-code-lockstep`, shipped in @nice-code/util, lists the versions installed.";
1644
+ /**
1645
+ * Records `version` as loaded in `scope`, and warns when a different version of this package
1646
+ * is already there. Runs when the package loads, so it must never throw.
1647
+ */
1648
+ function registerLoadedVersion(version, scope = globalThis, warn = (message) => console.warn(message)) {
1649
+ try {
1650
+ const loaded = Reflect.get(scope, LOADED_VERSIONS_KEY);
1651
+ if (loaded === void 0) {
1652
+ Reflect.set(scope, LOADED_VERSIONS_KEY, [version]);
1653
+ return;
1654
+ }
1655
+ if (!Array.isArray(loaded) || loaded.includes(version)) return;
1656
+ const others = loaded.filter((other) => typeof other === "string");
1657
+ loaded.push(version);
1658
+ warn(`[@nice-code/error] Version ${version} was loaded beside ${others.join(", ")}. ${LOCKSTEP_RULE}`);
1659
+ } catch {}
1660
+ }
1661
+ let warnedOfUnversionedCopy = false;
1662
+ /**
1663
+ * Warns, once, that an error arrived from a copy of this package that carries no brand: one
1664
+ * released before copies recorded their version, which {@link registerLoadedVersion} cannot see.
1665
+ */
1666
+ function warnOfUnversionedCopy() {
1667
+ if (warnedOfUnversionedCopy) return;
1668
+ warnedOfUnversionedCopy = true;
1669
+ try {
1670
+ getNiceErrorLogger().warn(`[@nice-code/error] Version ${NICE_ERROR_VERSION} received an error built by an older copy of this package, one too old to report its version. ${LOCKSTEP_RULE}`);
1671
+ } catch {}
1672
+ }
1673
+ //#endregion
1545
1674
  //#region ../nice-error/src/NiceError/nice_error.static.ts
1546
1675
  const DUR_OBJ_PACK_PREFIX = "NE_DUROBJ[[";
1547
1676
  const DUR_OBJ_PACK_SUFFIX = "]]NE_DUROBJ";
@@ -1622,6 +1751,7 @@ function serializeErrorCause(value, depth = DEFAULT_CAUSE_DEPTH) {
1622
1751
  }
1623
1752
  //#endregion
1624
1753
  //#region ../nice-error/src/NiceError/NiceError.ts
1754
+ const NICE_ERROR_BRAND = Symbol.for("@nice-code/error");
1625
1755
  var NiceError = class extends Error {
1626
1756
  name = "NiceError";
1627
1757
  def;
@@ -1641,7 +1771,7 @@ var NiceError = class extends Error {
1641
1771
  this.cleanMessage = messagePure;
1642
1772
  this.def = options.def;
1643
1773
  this.ids = options.ids;
1644
- this._errorDataMap = options.errorData;
1774
+ this._errorDataMap = options.errorData ?? {};
1645
1775
  this.httpStatusCode = options.httpStatusCode ?? 500;
1646
1776
  if (options.originError != null) this.originError = options.originError;
1647
1777
  this.timeCreated = options.timeCreated ?? Date.now();
@@ -1901,6 +2031,19 @@ var NiceError = class extends Error {
1901
2031
  return this;
1902
2032
  }
1903
2033
  };
2034
+ Object.defineProperty(NiceError.prototype, NICE_ERROR_BRAND, { value: true });
2035
+ registerLoadedVersion(NICE_ERROR_VERSION);
2036
+ /**
2037
+ * Returns `true` if `value` is a `NiceError` built by any loaded copy of `@nice-code/error`.
2038
+ *
2039
+ * `instanceof NiceError` knows only this copy's class. When an install holds two copies of the
2040
+ * package, an error from the other one fails `instanceof` and passes this — so prefer it
2041
+ * wherever the question is "is this a NiceError?". To use such an error as this copy's own,
2042
+ * pass it through `castNiceError`.
2043
+ */
2044
+ function isNiceError(value) {
2045
+ return typeof value === "object" && value != null && Reflect.get(value, NICE_ERROR_BRAND) === true;
2046
+ }
1904
2047
  //#endregion
1905
2048
  //#region ../nice-error/src/NiceError/NiceErrorHydrated.ts
1906
2049
  var NiceErrorHydrated = class NiceErrorHydrated extends NiceError {
@@ -1978,6 +2121,69 @@ function emitNiceError(error) {
1978
2121
  } catch {}
1979
2122
  }
1980
2123
  //#endregion
2124
+ //#region ../nice-error/src/utils/isNiceErrorObject.ts
2125
+ /**
2126
+ * Returns `true` if `obj` is a JSON-serialised `NiceError` object matching the
2127
+ * current wire format (contextState-based errorData entries).
2128
+ *
2129
+ * Validates:
2130
+ * - Top-level shape (`name`, `message`, `isUnhandled`, `httpStatusCode`, `ids`, `def`)
2131
+ * - Each `errorData` entry has a `contextState` with a valid `kind` discriminant
2132
+ * (`"no_serialization"` or `"unhydrated"`) — rejecting payloads in the old
2133
+ * format (`context` / `serialized` fields) to prevent silent data corruption.
2134
+ */
2135
+ function isNiceErrorObject(obj) {
2136
+ if (typeof obj !== "object" || obj == null) return false;
2137
+ const o = obj;
2138
+ if (o["name"] !== "NiceError" || typeof o["message"] !== "string" || typeof o["isUnhandled"] !== "boolean" || typeof o["httpStatusCode"] !== "number") return false;
2139
+ const ids = o["ids"];
2140
+ if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) return false;
2141
+ const def = o["def"];
2142
+ if (typeof def !== "object" || def == null) return false;
2143
+ const d = def;
2144
+ if (typeof d["domain"] !== "string" || !Array.isArray(d["allDomains"])) return false;
2145
+ const errorData = o["errorData"];
2146
+ if (errorData != null) {
2147
+ if (typeof errorData !== "object") return false;
2148
+ for (const entry of Object.values(errorData)) {
2149
+ if (entry == null) continue;
2150
+ if (typeof entry !== "object") return false;
2151
+ const state = entry["contextState"];
2152
+ if (state == null || typeof state !== "object") return false;
2153
+ const kind = state["kind"];
2154
+ if (kind !== "serde_unset" && kind !== "unhydrated") return false;
2155
+ }
2156
+ }
2157
+ return true;
2158
+ }
2159
+ //#endregion
2160
+ //#region ../nice-error/src/utils/foreignNiceErrorRecord.ts
2161
+ /** A copy released before the brand existed: its class has the same name and the same serializer. */
2162
+ function isUnbrandedNiceError(value) {
2163
+ return value instanceof Error && value.name === "NiceError" && "toJsonObject" in value && typeof value.toJsonObject === "function";
2164
+ }
2165
+ /**
2166
+ * The JSON record of a `NiceError` built by another copy of this package, or `undefined` when
2167
+ * `value` is not one — or is one that cannot serialize itself.
2168
+ *
2169
+ * Call it only after `instanceof NiceError` has failed. The record comes from the other copy's
2170
+ * own `toJsonObject()`, because only that copy knows where its instance keeps its data: read as
2171
+ * if it were this copy's, the instance has no context and a message that is already prefixed.
2172
+ */
2173
+ function foreignNiceErrorRecord(value) {
2174
+ if (typeof value !== "object" || value == null) return void 0;
2175
+ const branded = isNiceError(value);
2176
+ if (!branded && !isUnbrandedNiceError(value)) return void 0;
2177
+ try {
2178
+ const record = value.toJsonObject();
2179
+ if (!isNiceErrorObject(record)) return void 0;
2180
+ if (!branded) warnOfUnversionedCopy();
2181
+ return record;
2182
+ } catch {
2183
+ return;
2184
+ }
2185
+ }
2186
+ //#endregion
1981
2187
  //#region ../nice-error/src/NiceErrorDomain/NiceErrorDomain.ts
1982
2188
  var NiceErrorDomain = class NiceErrorDomain {
1983
2189
  domain;
@@ -2074,7 +2280,7 @@ var NiceErrorDomain = class NiceErrorDomain {
2074
2280
  expected: this.domain,
2075
2281
  received: errDef.domain
2076
2282
  });
2077
- const finalError = error instanceof NiceError ? error : new NiceError(error);
2283
+ const finalError = this._ownInstanceOf(error);
2078
2284
  const reconciledErrorData = {};
2079
2285
  for (const id of finalError.getIds()) {
2080
2286
  const existingData = finalError.getErrorDataForId(id);
@@ -2166,13 +2372,25 @@ var NiceErrorDomain = class NiceErrorDomain {
2166
2372
  * ```
2167
2373
  */
2168
2374
  isExact(error) {
2169
- if (!(error instanceof NiceError)) return false;
2375
+ if (!isNiceError(error)) return false;
2170
2376
  return getErrorDomainProps(error).domain === this.domain;
2171
2377
  }
2378
+ /**
2379
+ * Returns `true` if `error` is a `NiceError` from this domain or from any domain
2380
+ * below it — a child, a grandchild, and so on. Errors from a parent or a sibling
2381
+ * domain return `false`.
2382
+ *
2383
+ * Use it to catch a whole subtree; use `isExact` for this domain alone.
2384
+ *
2385
+ * ```ts
2386
+ * err_auth.isThisOrChild(err_auth_registration.fromId("email_taken")); // true
2387
+ * err_auth_registration.isThisOrChild(err_auth.fromId("account_locked")); // false
2388
+ * ```
2389
+ */
2172
2390
  isThisOrChild(error) {
2173
- if (!(error instanceof NiceError)) return false;
2174
- const errDef = getErrorDomainProps(error);
2175
- return errDef.domain === this.domain || this.allDomains.includes(errDef.domain);
2391
+ if (!isNiceError(error)) return false;
2392
+ const allDomains = getErrorDomainProps(error).allDomains;
2393
+ return Array.isArray(allDomains) && allDomains.includes(this.domain);
2176
2394
  }
2177
2395
  /**
2178
2396
  * Returns `true` if this domain appears anywhere in the target's ancestry
@@ -2182,9 +2400,16 @@ var NiceErrorDomain = class NiceErrorDomain {
2182
2400
  * instance (extracts the domain from its `def`).
2183
2401
  */
2184
2402
  isParentOf(target) {
2185
- const allDomains = target instanceof NiceError ? getErrorDomainProps(target).allDomains : target.allDomains;
2403
+ const allDomains = isNiceError(target) ? getErrorDomainProps(target).allDomains : target.allDomains;
2186
2404
  return Array.isArray(allDomains) && allDomains.includes(this.domain);
2187
2405
  }
2406
+ /** `error` as this copy's `NiceError`: itself, or rebuilt from a record or from another copy's instance. */
2407
+ _ownInstanceOf(error) {
2408
+ if (error instanceof NiceError) return error;
2409
+ const foreignRecord = foreignNiceErrorRecord(error);
2410
+ if (foreignRecord != null) return new NiceError(foreignRecord);
2411
+ return new NiceError(error);
2412
+ }
2188
2413
  _buildDef() {
2189
2414
  return {
2190
2415
  domain: this.domain,
@@ -2321,40 +2546,6 @@ const err_nice_error = err_nice.createChildDomain({
2321
2546
  });
2322
2547
  _setInternalErrorBuilder((kind, ctx) => err_nice_error.fromId(kind, ctx));
2323
2548
  //#endregion
2324
- //#region ../nice-error/src/utils/isNiceErrorObject.ts
2325
- /**
2326
- * Returns `true` if `obj` is a JSON-serialised `NiceError` object matching the
2327
- * current wire format (contextState-based errorData entries).
2328
- *
2329
- * Validates:
2330
- * - Top-level shape (`name`, `message`, `isUnhandled`, `httpStatusCode`, `def`)
2331
- * - Each `errorData` entry has a `contextState` with a valid `kind` discriminant
2332
- * (`"no_serialization"` or `"unhydrated"`) — rejecting payloads in the old
2333
- * format (`context` / `serialized` fields) to prevent silent data corruption.
2334
- */
2335
- function isNiceErrorObject(obj) {
2336
- if (typeof obj !== "object" || obj == null) return false;
2337
- const o = obj;
2338
- if (o["name"] !== "NiceError" || typeof o["message"] !== "string" || typeof o["isUnhandled"] !== "boolean" || typeof o["httpStatusCode"] !== "number") return false;
2339
- const def = o["def"];
2340
- if (typeof def !== "object" || def == null) return false;
2341
- const d = def;
2342
- if (typeof d["domain"] !== "string" || !Array.isArray(d["allDomains"])) return false;
2343
- const errorData = o["errorData"];
2344
- if (errorData != null) {
2345
- if (typeof errorData !== "object") return false;
2346
- for (const entry of Object.values(errorData)) {
2347
- if (entry == null) continue;
2348
- if (typeof entry !== "object") return false;
2349
- const state = entry["contextState"];
2350
- if (state == null || typeof state !== "object") return false;
2351
- const kind = state["kind"];
2352
- if (kind !== "serde_unset" && kind !== "unhydrated") return false;
2353
- }
2354
- }
2355
- return true;
2356
- }
2357
- //#endregion
2358
2549
  //#region ../nice-error/src/utils/isRegularErrorObject.ts
2359
2550
  function isRegularErrorJsonObject(obj) {
2360
2551
  if (typeof obj !== "object" || obj == null) return false;
@@ -2420,6 +2611,11 @@ const inspectPotentialError = (potentialError) => {
2420
2611
  type: "niceError",
2421
2612
  niceError: parsedError
2422
2613
  };
2614
+ const foreignRecord = foreignNiceErrorRecord(parsedError);
2615
+ if (foreignRecord != null) return {
2616
+ type: "niceErrorObject",
2617
+ niceErrorObject: foreignRecord
2618
+ };
2423
2619
  if (isNiceErrorObject(parsedError)) return {
2424
2620
  type: "niceErrorObject",
2425
2621
  niceErrorObject: parsedError
@@ -2550,6 +2746,14 @@ const err_wire_connect = err_nice.createChildDomain({
2550
2746
  */
2551
2747
  endpoint_unreachable: err({ message: ({ url, carrierLabel, reason }) => `Could not reach ${url ?? (carrierLabel != null ? `the "${carrierLabel}" endpoint` : "the endpoint")}: ${reason} — no response was received (a network, DNS or TLS failure; a response the browser blocked or hid, such as a CORS rejection or a refused WebSocket upgrade; or the fetch/socket implementation threw).` }),
2552
2748
  /**
2749
+ * The carrier **opened**, then went away before the handshake finished — so the address
2750
+ * reaches something (unlike `endpoint_unreachable`), and that something hung up without a
2751
+ * protocol answer. Retried like any failed dial.
2752
+ */
2753
+ closed_during_handshake: err({ message: ({ stage, awaiting, url }) => `[${stage}] the connection closed while waiting for ${awaiting} — the endpoint accepted the connection and dropped it before the handshake finished (a server that restarted or failed mid-handshake, a proxy that cut the socket, or a peer that refuses by closing)${url != null ? `. Dialed: ${url}` : ""}.` }),
2754
+ /** The carrier stayed open and the peer never answered the handshake within `timeoutMs`. */
2755
+ handshake_timeout: err({ message: ({ stage, awaiting, timeoutMs, url }) => `[${stage}] timed out after ${timeoutMs} ms waiting for ${awaiting} — the connection is open but the peer did not answer the handshake${url != null ? `. Dialed: ${url}` : ""}.` }),
2756
+ /**
2553
2757
  * The peer **is** a nice-code backend and refused the handshake for a reason that carries no
2554
2758
  * machine-readable id of its own (an older peer, a dictionary/security mismatch, a custom
2555
2759
  * gate). Typed so `classifyConnectFailure` can report `handshake_rejected` — a third
@@ -2569,6 +2773,12 @@ const err_wire_connect = err_nice.createChildDomain({
2569
2773
  * automatic redial park until an explicit retry after the route or expectation changes.
2570
2774
  */
2571
2775
  peer_identity_mismatch: err({ message: ({ expected, actual, endpoint }) => `Secure peer identity mismatch: expected envId=${JSON.stringify(expected.envId)}${expected.perId != null ? `, perId=${JSON.stringify(expected.perId)}` : ""}; received envId=${JSON.stringify(actual.envId)}${actual.perId != null ? `, perId=${JSON.stringify(actual.perId)}` : ""}. ${endpoint != null ? `Dialed ${endpoint}. ` : ""}Carrier fallback and automatic redial are parked until an explicit retry.` }),
2776
+ /**
2777
+ * This runtime has no WebCrypto (`crypto.subtle`), so a secure transport cannot handshake.
2778
+ * Raised before any dial. Not a network condition: transport selection moves on to a plain
2779
+ * carrier when one is configured, and otherwise automatic redial parks on it.
2780
+ */
2781
+ crypto_unavailable: err({ message: ({ reason, pageOrigin }) => reason === "insecure_context" ? `A secure connection needs WebCrypto (crypto.subtle), which a browser provides only to a secure context — and this page${pageOrigin != null ? ` (${pageOrigin})` : ""} is not one. Open it over HTTPS or on localhost. Automatic redial is parked.` : "A secure connection needs WebCrypto (crypto.subtle), which this runtime does not provide. Install a WebCrypto polyfill before connecting (on React Native, react-native-quick-crypto), or set `secure: false` on the carrier for a plain connection. Automatic redial is parked." }),
2572
2782
  /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */
2573
2783
  protocol_unsupported: err({ message: ({ protocolId }) => `Protocol "${protocolId}" cannot speak on this connection — the peer did not advertise "proto:${protocolId}" (or it is not registered here).` }),
2574
2784
  /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; the protocol contract). */
@@ -2591,6 +2801,39 @@ const err_wire_connect = err_nice.createChildDomain({
2591
2801
  }
2592
2802
  });
2593
2803
  //#endregion
2804
+ //#region ../nice-wire/src/Carrier/duplex/inboundFrameQueue.ts
2805
+ /**
2806
+ * Inbound frames in arrival order, for a carrier whose message listener must stay a plain function.
2807
+ * A string, `ArrayBuffer` or `Uint8Array` is delivered in the turn it arrived. Only a `Blob` has to
2808
+ * be read asynchronously, and while one is being read everything behind it waits its turn — a later
2809
+ * frame, and the close.
2810
+ */
2811
+ function createInboundFrameQueue(deliver) {
2812
+ let reading;
2813
+ const later = (step) => {
2814
+ const next = (reading ?? Promise.resolve()).then(step).catch((error) => {
2815
+ console.error("[nice-wire] an inbound frame could not be delivered:", error);
2816
+ }).then(() => {
2817
+ if (reading === next) reading = void 0;
2818
+ });
2819
+ reading = next;
2820
+ };
2821
+ const inOrder = (step) => {
2822
+ if (reading == null) step();
2823
+ else later(step);
2824
+ };
2825
+ return {
2826
+ receive: (data) => {
2827
+ if (typeof data === "string" || data instanceof ArrayBuffer || data instanceof Uint8Array) {
2828
+ inOrder(() => deliver(data));
2829
+ return;
2830
+ }
2831
+ if (typeof Blob !== "undefined" && data instanceof Blob) later(async () => deliver(await data.arrayBuffer()));
2832
+ },
2833
+ afterFrames: inOrder
2834
+ };
2835
+ }
2836
+ //#endregion
2594
2837
  //#region ../nice-wire/src/Connect/sanitizeEndpoint.ts
2595
2838
  /**
2596
2839
  * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can carry
@@ -2658,24 +2901,23 @@ function webSocketByteChannel(ws) {
2658
2901
  let onMessage;
2659
2902
  let onClose;
2660
2903
  const preAttach = [];
2661
- const deliver = (frame) => {
2904
+ const inbound = createInboundFrameQueue((frame) => {
2662
2905
  if (onMessage != null) onMessage(frame);
2663
2906
  else preAttach.push(frame);
2664
- };
2907
+ });
2665
2908
  ws.addEventListener("open", () => {
2666
2909
  opened = true;
2667
2910
  });
2668
- ws.addEventListener("message", async (event) => {
2669
- const frame = await normalizeFrame(event.data);
2670
- if (frame !== void 0) deliver(frame);
2911
+ ws.addEventListener("message", (event) => {
2912
+ inbound.receive(event.data);
2671
2913
  });
2672
2914
  ws.addEventListener("close", (event) => {
2673
2915
  if (opened && !intentional) console.warn("WebSocket closed:", event);
2674
- onClose?.();
2916
+ inbound.afterFrames(() => onClose?.());
2675
2917
  });
2676
2918
  ws.addEventListener("error", () => {
2677
2919
  if (opened) console.warn(`WebSocket error: ${describeSocket(ws)}`);
2678
- onClose?.();
2920
+ inbound.afterFrames(() => onClose?.());
2679
2921
  });
2680
2922
  return {
2681
2923
  ready: new Promise((resolve, reject) => {
@@ -2726,11 +2968,6 @@ function unreachableError(ws, reason) {
2726
2968
  function describeSocket(ws) {
2727
2969
  return (ws.url != null && ws.url !== "" ? sanitizeEndpoint(ws.url) : void 0) ?? "(no url)";
2728
2970
  }
2729
- /** Accept text + binary frames (ArrayBuffer / Uint8Array / Blob); Blobs are converted to a buffer. */
2730
- async function normalizeFrame(data) {
2731
- if (typeof data === "string" || data instanceof ArrayBuffer || data instanceof Uint8Array) return data;
2732
- if (typeof Blob !== "undefined" && data instanceof Blob) return await data.arrayBuffer();
2733
- }
2734
2971
  //#endregion
2735
2972
  //#region ../nice-wire/src/Carrier/duplex/ws/wsCarrier.ts
2736
2973
  /**
@@ -2813,9 +3050,10 @@ function describeNonProtocolBody(raw) {
2813
3050
  function classifyConnectFailure(error) {
2814
3051
  if (!err_wire_connect.isExact(error)) return "unknown";
2815
3052
  if (error.hasId("endpoint_answered_non_protocol")) return "endpoint_answered_non_protocol";
2816
- if (error.hasId("endpoint_unreachable")) return "endpoint_unreachable";
3053
+ if (error.hasId("endpoint_unreachable") || error.hasId("closed_during_handshake") || error.hasId("handshake_timeout")) return "endpoint_unreachable";
2817
3054
  if (error.hasId("protocol_version_mismatch")) return "protocol_version_mismatch";
2818
3055
  if (error.hasId("peer_identity_mismatch")) return "peer_identity_mismatch";
3056
+ if (error.hasId("crypto_unavailable")) return "crypto_unavailable";
2819
3057
  if (error.hasId("identity_pin_mismatch") || error.hasId("handshake_rejected")) return "handshake_rejected";
2820
3058
  return "unknown";
2821
3059
  }
@@ -2824,6 +3062,8 @@ function endpointFromConnectFailure(error) {
2824
3062
  if (!err_wire_connect.isExact(error)) return void 0;
2825
3063
  if (error.hasId("endpoint_answered_non_protocol")) return sanitizeEndpoint(error.getContext("endpoint_answered_non_protocol").url);
2826
3064
  if (error.hasId("endpoint_unreachable")) return sanitizeEndpoint(error.getContext("endpoint_unreachable").url);
3065
+ if (error.hasId("closed_during_handshake")) return sanitizeEndpoint(error.getContext("closed_during_handshake").url);
3066
+ if (error.hasId("handshake_timeout")) return sanitizeEndpoint(error.getContext("handshake_timeout").url);
2827
3067
  if (error.hasId("peer_identity_mismatch")) return sanitizeEndpoint(error.getContext("peer_identity_mismatch").endpoint);
2828
3068
  }
2829
3069
  //#endregion
@@ -2858,6 +3098,7 @@ var ConnectionTransportManager$1 = class {
2858
3098
  async getReadyTransport(input) {
2859
3099
  const candidates = [];
2860
3100
  const unavailableTransports = [];
3101
+ let cryptoUnavailable;
2861
3102
  for (const transport of this._transports) {
2862
3103
  let cacheKey = null;
2863
3104
  try {
@@ -2955,6 +3196,10 @@ var ConnectionTransportManager$1 = class {
2955
3196
  unavailableTransports.push(transport);
2956
3197
  continue;
2957
3198
  }
3199
+ if (isCryptoUnavailable(e)) {
3200
+ cryptoUnavailable ??= e;
3201
+ continue;
3202
+ }
2958
3203
  const failed = Promise.reject(e);
2959
3204
  failed.catch(() => {});
2960
3205
  candidates.push({
@@ -2967,6 +3212,7 @@ var ConnectionTransportManager$1 = class {
2967
3212
  }
2968
3213
  }
2969
3214
  if (candidates.length === 0) {
3215
+ if (cryptoUnavailable != null) throw cryptoUnavailable;
2970
3216
  if (unavailableTransports.length > 0) throw this._errors.unsupported(unavailableTransports.map((t) => t.type));
2971
3217
  throw this._errors.notFound(input);
2972
3218
  }
@@ -3035,6 +3281,7 @@ var ConnectionTransportManager$1 = class {
3035
3281
  }
3036
3282
  };
3037
3283
  const isDialUnavailable$1 = (error) => err_wire_connect.isExact(error) && error.hasId("dial_unavailable");
3284
+ const isCryptoUnavailable = (error) => err_wire_connect.isExact(error) && error.hasId("crypto_unavailable");
3038
3285
  const isTerminalSelectionError = (error) => err_wire_connect.isExact(error) && (error.hasId("peer_identity_mismatch") || error.hasId("protocol_version_mismatch"));
3039
3286
  /** The transport's sanitized route URL for diagnostics; a throwing route resolver yields none. */
3040
3287
  function routeEndpoint(transport, input) {
@@ -4705,6 +4952,36 @@ const serializeX25519Key_Raw = async (key) => {
4705
4952
  };
4706
4953
  };
4707
4954
  //#endregion
4955
+ //#region ../nice-util/src/crypto/client_key_link/withKeyMintLock.ts
4956
+ const queuedInProcess = /* @__PURE__ */ new Map();
4957
+ /**
4958
+ * Run `mint` alone among everything minting under `name`. Web Locks, where the runtime has them,
4959
+ * hold off every tab and worker of the origin; without them (React Native, older runtimes) the turn
4960
+ * is taken within this JS realm only, and a caller narrows the rest by reading the store again
4961
+ * before it writes.
4962
+ */
4963
+ async function withKeyMintLock(name, mint) {
4964
+ const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
4965
+ if (locks != null) {
4966
+ let entered = false;
4967
+ try {
4968
+ return await locks.request(name, () => {
4969
+ entered = true;
4970
+ return mint();
4971
+ });
4972
+ } catch (error) {
4973
+ if (entered) throw error;
4974
+ }
4975
+ }
4976
+ const turn = (queuedInProcess.get(name) ?? Promise.resolve()).then(mint, mint);
4977
+ queuedInProcess.set(name, turn);
4978
+ const release = () => {
4979
+ if (queuedInProcess.get(name) === turn) queuedInProcess.delete(name);
4980
+ };
4981
+ turn.then(release, release);
4982
+ return await turn;
4983
+ }
4984
+ //#endregion
4708
4985
  //#region ../nice-util/src/crypto/client_key_link/ClientCryptoKeyLink.ts
4709
4986
  /**
4710
4987
  * Thrown by the local-key getters when the link is in {@link TIdentityMode} `"required"` and no
@@ -4725,6 +5002,7 @@ var ClientCryptoKeyLink = class {
4725
5002
  storageAdapter;
4726
5003
  identityMode;
4727
5004
  initialized = false;
5005
+ reloadPending = false;
4728
5006
  initializePromise;
4729
5007
  localExchangeKeyPairPromise;
4730
5008
  localVerifyKeyPairPromise;
@@ -4748,7 +5026,7 @@ var ClientCryptoKeyLink = class {
4748
5026
  * Must be called (and awaited) before any sign/verify/encrypt/decrypt operation.
4749
5027
  */
4750
5028
  async initialize() {
4751
- if (this.initialized) return;
5029
+ if (this.initialized && !this.reloadPending) return;
4752
5030
  this.initializePromise ??= this.runInitialize();
4753
5031
  try {
4754
5032
  await this.initializePromise;
@@ -4757,11 +5035,23 @@ var ClientCryptoKeyLink = class {
4757
5035
  }
4758
5036
  }
4759
5037
  async runInitialize() {
5038
+ this.initialized = false;
4760
5039
  await this.loadStoredLocalKeys();
4761
5040
  await this.loadLinkedClients();
4762
5041
  this.initialized = true;
4763
5042
  }
4764
5043
  /**
5044
+ * Have the next {@link initialize} read the store again and take it as the truth: a local identity
5045
+ * the store holds now is adopted, and one it no longer holds is forgotten (the next use mints and
5046
+ * persists a fresh one). For a link that outlives the code that made it — one shared by connections
5047
+ * made at different times: a store cleared in between would otherwise leave an identity that is
5048
+ * presented now and gone after the next reload. A no-op for a link with no storage.
5049
+ */
5050
+ reloadOnNextInitialize() {
5051
+ if (this.storage == null) return;
5052
+ this.reloadPending = true;
5053
+ }
5054
+ /**
4765
5055
  * Provision the local identity once: load any persisted identity, then mint + persist the exchange
4766
5056
  * and verify key pairs only if absent. Idempotent — a no-op when an identity already exists.
4767
5057
  *
@@ -4786,24 +5076,62 @@ var ClientCryptoKeyLink = class {
4786
5076
  * generates or stores keys it does not need.
4787
5077
  */
4788
5078
  async loadStoredLocalKeys() {
4789
- const storedExchange = await this.storage?.getJson("localExchangeKeyPair");
4790
- if (storedExchange != null) {
4791
- const exchangePrivateKey = await importX25519Key.private.fromFormattedString.extractable(storedExchange.privateKey);
4792
- const exchangePublicKey = await importX25519Key.public.fromFormattedString.extractable(storedExchange.publicKey);
4793
- this.localExchangeKeyPair = {
4794
- privateKey: exchangePrivateKey,
4795
- publicKey: exchangePublicKey
4796
- };
5079
+ const forgetUnstored = this.reloadPending;
5080
+ this.reloadPending = false;
5081
+ try {
5082
+ const storedExchange = await this.readStoredExchangeKeyPair();
5083
+ const storedVerify = await this.readStoredVerifyKeyPair();
5084
+ if (storedExchange != null || forgetUnstored) this.localExchangeKeyPair = storedExchange;
5085
+ if (storedVerify != null || forgetUnstored) this.localVerifyKeyPair = storedVerify;
5086
+ } catch (error) {
5087
+ this.reloadPending ||= forgetUnstored;
5088
+ throw error;
4797
5089
  }
4798
- const storedVerify = await this.storage?.getJson("localVerifyKeyPair");
4799
- if (storedVerify != null) {
4800
- const verifyPrivateKey = await importEd25519Key.private.fromFormattedString.extractable(storedVerify.privateKey);
4801
- const verifyPublicKey = await importEd25519Key.public.fromFormattedString.extractable(storedVerify.publicKey);
4802
- this.localVerifyKeyPair = {
4803
- privateKey: verifyPrivateKey,
4804
- publicKey: verifyPublicKey
4805
- };
5090
+ }
5091
+ async readStoredExchangeKeyPair() {
5092
+ const stored = await this.storage?.getJson("localExchangeKeyPair");
5093
+ if (stored == null) return;
5094
+ return {
5095
+ privateKey: await importX25519Key.private.fromFormattedString.extractable(stored.privateKey),
5096
+ publicKey: await importX25519Key.public.fromFormattedString.extractable(stored.publicKey)
5097
+ };
5098
+ }
5099
+ async readStoredVerifyKeyPair() {
5100
+ const stored = await this.storage?.getJson("localVerifyKeyPair");
5101
+ if (stored == null) return;
5102
+ return {
5103
+ privateKey: await importEd25519Key.private.fromFormattedString.extractable(stored.privateKey),
5104
+ publicKey: await importEd25519Key.public.fromFormattedString.extractable(stored.publicKey)
5105
+ };
5106
+ }
5107
+ /**
5108
+ * Mint one local key pair — or adopt the one another link over the same storage minted first.
5109
+ * Two links (or two tabs) that each found the store empty must not each persist a key of their
5110
+ * own: a peer pins the first it sees and refuses the other for good.
5111
+ */
5112
+ async mintOrAdopt(mint) {
5113
+ const storageAdapter = this.storageAdapter;
5114
+ if (storageAdapter == null) {
5115
+ const keyPair = await mint.generate();
5116
+ mint.keep(keyPair);
5117
+ return keyPair;
4806
5118
  }
5119
+ return await withKeyMintLock(`nice-code:key-link:${storageAdapter.keyPrefix}${mint.storageKey}`, async () => {
5120
+ const stored = await mint.readStored();
5121
+ if (stored != null) {
5122
+ mint.keep(stored);
5123
+ return stored;
5124
+ }
5125
+ const generated = await mint.generate();
5126
+ const storedMeanwhile = await mint.readStored();
5127
+ if (storedMeanwhile != null) {
5128
+ mint.keep(storedMeanwhile);
5129
+ return storedMeanwhile;
5130
+ }
5131
+ mint.keep(generated);
5132
+ await mint.store(generated);
5133
+ return generated;
5134
+ });
4807
5135
  }
4808
5136
  /**
4809
5137
  * Returns the local exchange (X25519) key pair. In `"lazy"` mode it generates + persists it on first
@@ -4818,16 +5146,23 @@ var ClientCryptoKeyLink = class {
4818
5146
  /**
4819
5147
  * Generates + persists the local exchange key pair if absent, returning an already-loaded pair
4820
5148
  * untouched (so provisioning is idempotent). Bypasses the `"required"` guard by design — it is the
4821
- * sole minting path. Concurrent callers share a single generation.
5149
+ * sole minting path. Concurrent callers share a single generation, and a pair another link has
5150
+ * stored since this one loaded is adopted instead (see {@link mintOrAdopt}).
4822
5151
  */
4823
5152
  async mintLocalExchangeKeyPair() {
4824
5153
  if (this.localExchangeKeyPair != null) return this.localExchangeKeyPair;
4825
- this.localExchangeKeyPairPromise ??= (async () => {
4826
- const keyPair = await generateX25519KeyPair();
4827
- this.localExchangeKeyPair = keyPair;
4828
- if (this.storage != null) await this.storage.setJson("localExchangeKeyPair", await this.serializeExchangeKeyPair(keyPair));
4829
- return keyPair;
4830
- })();
5154
+ this.localExchangeKeyPairPromise ??= this.mintOrAdopt({
5155
+ storageKey: "localExchangeKeyPair",
5156
+ readStored: () => this.readStoredExchangeKeyPair(),
5157
+ generate: generateX25519KeyPair,
5158
+ keep: (keyPair) => {
5159
+ this.localExchangeKeyPair = keyPair;
5160
+ },
5161
+ store: async (keyPair) => {
5162
+ const serialized = await this.serializeExchangeKeyPair(keyPair);
5163
+ await this.storage?.setJson("localExchangeKeyPair", serialized);
5164
+ }
5165
+ });
4831
5166
  try {
4832
5167
  return await this.localExchangeKeyPairPromise;
4833
5168
  } finally {
@@ -4847,16 +5182,23 @@ var ClientCryptoKeyLink = class {
4847
5182
  /**
4848
5183
  * Generates + persists the local verify key pair if absent, returning an already-loaded pair
4849
5184
  * untouched (so provisioning is idempotent). Bypasses the `"required"` guard by design — it is the
4850
- * sole minting path. Concurrent callers share a single generation.
5185
+ * sole minting path. Concurrent callers share a single generation, and a pair another link has
5186
+ * stored since this one loaded is adopted instead (see {@link mintOrAdopt}).
4851
5187
  */
4852
5188
  async mintLocalVerifyKeyPair() {
4853
5189
  if (this.localVerifyKeyPair != null) return this.localVerifyKeyPair;
4854
- this.localVerifyKeyPairPromise ??= (async () => {
4855
- const keyPair = await generateEd25519KeyPair();
4856
- this.localVerifyKeyPair = keyPair;
4857
- if (this.storage != null) await this.storage.setJson("localVerifyKeyPair", await this.serializeVerifyKeyPair(keyPair));
4858
- return keyPair;
4859
- })();
5190
+ this.localVerifyKeyPairPromise ??= this.mintOrAdopt({
5191
+ storageKey: "localVerifyKeyPair",
5192
+ readStored: () => this.readStoredVerifyKeyPair(),
5193
+ generate: generateEd25519KeyPair,
5194
+ keep: (keyPair) => {
5195
+ this.localVerifyKeyPair = keyPair;
5196
+ },
5197
+ store: async (keyPair) => {
5198
+ const serialized = await this.serializeVerifyKeyPair(keyPair);
5199
+ await this.storage?.setJson("localVerifyKeyPair", serialized);
5200
+ }
5201
+ });
4860
5202
  try {
4861
5203
  return await this.localVerifyKeyPairPromise;
4862
5204
  } finally {
@@ -6086,12 +6428,13 @@ const isDialUnavailable = (e) => err_wire_connect.isExact(e) && e.hasId("dial_un
6086
6428
  * A dial failure the backoff ladder must PARK on instead of retrying: either no endpoint exists
6087
6429
  * right now ({@link isDialUnavailable}), or the peer rejected the handshake with
6088
6430
  * `identity_pin_mismatch` (the peer has a different key pinned) or
6089
- * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation).
6431
+ * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation), or this
6432
+ * runtime has no WebCrypto to handshake with at all (`crypto_unavailable`).
6090
6433
  * Parking is not terminal: the next explicit `connect()`/dispatch may try again after the app has
6091
6434
  * upgraded or changed endpoints. Other handshake rejections (e.g. a dictionary mismatch) retain
6092
6435
  * the existing retry behavior because a matching deploy can heal them.
6093
6436
  */
6094
- const isParkedDialRejection = (e) => isDialUnavailable(e) || err_wire_connect.isExact(e) && (e.hasId("identity_pin_mismatch") || e.hasId("protocol_version_mismatch") || e.hasId("peer_identity_mismatch"));
6437
+ const isParkedDialRejection = (e) => isDialUnavailable(e) || err_wire_connect.isExact(e) && (e.hasId("identity_pin_mismatch") || e.hasId("protocol_version_mismatch") || e.hasId("peer_identity_mismatch") || e.hasId("crypto_unavailable"));
6095
6438
  /**
6096
6439
  * The dial-out connection: owns the transport cache, preference-ordered selection, the protocol mux,
6097
6440
  * and the whole **connection lifecycle** — establishment bookkeeping, the keep-alive redial ladder
@@ -9039,6 +9382,8 @@ function handshakeRejectError(stage, rejectFrame) {
9039
9382
  //#region ../nice-wire/src/Connect/duplexLinkSession.ts
9040
9383
  const HANDSHAKE_TIMEOUT_MS$1 = 15e3;
9041
9384
  const LINK_HANDSHAKE_STAGE = "link-handshake";
9385
+ const AWAITING_WELCOME = "a welcome frame";
9386
+ const AWAITING_ACCEPT = "an accept frame";
9042
9387
  /** The duplex twin of the exchange path's `nonProtocolReply` — same typed id, so a consumer's
9043
9388
  * `kind` branch means the same thing whichever carrier served the dial. */
9044
9389
  function wrongHandshakeFrame(channel, expected, receivedKind) {
@@ -9213,9 +9558,34 @@ async function establishSecureDuplexSession(ctx) {
9213
9558
  let active = false;
9214
9559
  const handshakeQueue = [];
9215
9560
  const handshakeWaiters = [];
9561
+ let carrierClosed = false;
9216
9562
  const pendingFrames = [];
9217
9563
  let nonProtocolFrame;
9218
9564
  let heartbeat;
9565
+ const unansweredError = (awaiting, cause) => {
9566
+ const url = sanitizeEndpoint(channel.label);
9567
+ if (nonProtocolFrame != null) return err_wire_connect.fromId("endpoint_answered_non_protocol", {
9568
+ stage: LINK_HANDSHAKE_STAGE,
9569
+ expected: awaiting,
9570
+ url,
9571
+ bodyPreview: describeNonProtocolBody(nonProtocolFrame)
9572
+ });
9573
+ return cause === "closed" ? err_wire_connect.fromId("closed_during_handshake", {
9574
+ stage: LINK_HANDSHAKE_STAGE,
9575
+ awaiting,
9576
+ url
9577
+ }) : err_wire_connect.fromId("handshake_timeout", {
9578
+ stage: LINK_HANDSHAKE_STAGE,
9579
+ awaiting,
9580
+ timeoutMs: HANDSHAKE_TIMEOUT_MS$1,
9581
+ url
9582
+ });
9583
+ };
9584
+ const onCarrierClosed = () => {
9585
+ carrierClosed = true;
9586
+ for (const waiter of handshakeWaiters.splice(0)) waiter.reject(unansweredError(waiter.awaiting, "closed"));
9587
+ onChannelClosed(disconnectListeners, ctx.lane);
9588
+ };
9219
9589
  const mux = ctx.mux;
9220
9590
  channel.attach({
9221
9591
  onMessage: (frame) => {
@@ -9241,7 +9611,7 @@ async function establishSecureDuplexSession(ctx) {
9241
9611
  lane: "handshake"
9242
9612
  });
9243
9613
  const waiter = handshakeWaiters.shift();
9244
- if (waiter != null) waiter(message);
9614
+ if (waiter != null) waiter.resolve(message);
9245
9615
  else handshakeQueue.push(message);
9246
9616
  return;
9247
9617
  }
@@ -9249,23 +9619,31 @@ async function establishSecureDuplexSession(ctx) {
9249
9619
  }
9250
9620
  pendingFrames.push(frame);
9251
9621
  },
9252
- onClose: () => onChannelClosed(disconnectListeners, ctx.lane),
9253
- onError: () => onChannelClosed(disconnectListeners, ctx.lane)
9622
+ onClose: onCarrierClosed,
9623
+ onError: onCarrierClosed
9254
9624
  });
9255
- const nextHandshakeMessage = () => {
9625
+ const nextHandshakeMessage = (awaiting) => {
9256
9626
  const queued = handshakeQueue.shift();
9257
9627
  if (queued != null) return Promise.resolve(queued);
9628
+ if (carrierClosed) return Promise.reject(unansweredError(awaiting, "closed"));
9258
9629
  return new Promise((resolve, reject) => {
9259
- const timeout = setTimeout(() => reject(nonProtocolFrame != null ? err_wire_connect.fromId("endpoint_answered_non_protocol", {
9260
- stage: LINK_HANDSHAKE_STAGE,
9261
- expected: "a handshake frame",
9262
- url: sanitizeEndpoint(channel.label),
9263
- bodyPreview: describeNonProtocolBody(nonProtocolFrame)
9264
- }) : /* @__PURE__ */ new Error(`[${LINK_HANDSHAKE_STAGE}] timed out waiting for peer reply`)), HANDSHAKE_TIMEOUT_MS$1);
9265
- handshakeWaiters.push((message) => {
9266
- clearTimeout(timeout);
9267
- resolve(message);
9268
- });
9630
+ const timeout = setTimeout(() => {
9631
+ const index = handshakeWaiters.indexOf(waiter);
9632
+ if (index !== -1) handshakeWaiters.splice(index, 1);
9633
+ reject(unansweredError(awaiting, "timeout"));
9634
+ }, HANDSHAKE_TIMEOUT_MS$1);
9635
+ const waiter = {
9636
+ awaiting,
9637
+ resolve: (message) => {
9638
+ clearTimeout(timeout);
9639
+ resolve(message);
9640
+ },
9641
+ reject: (error) => {
9642
+ clearTimeout(timeout);
9643
+ reject(error);
9644
+ }
9645
+ };
9646
+ handshakeWaiters.push(waiter);
9269
9647
  });
9270
9648
  };
9271
9649
  try {
@@ -9335,6 +9713,7 @@ function makeSession$1(channel, pipe, disconnectListeners, remoteCaps, muxBindin
9335
9713
  async function runClientHandshake(ctx, nextHandshakeMessage) {
9336
9714
  const secure = ctx.secure;
9337
9715
  const sendHandshake = (encoded) => {
9716
+ if (!ctx.channel.isOpen()) return;
9338
9717
  ctx.channel.send(encoded);
9339
9718
  ctx.tap?.({
9340
9719
  dir: "out",
@@ -9354,13 +9733,13 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
9354
9733
  extraCaps: [...ctx.lane.caps?.() ?? [], ...ctx.mux?.localCaps() ?? []]
9355
9734
  });
9356
9735
  sendHandshake(encodeHandshakeMessage(await handshake.createHello()));
9357
- const welcome = await nextHandshakeMessage();
9736
+ const welcome = await nextHandshakeMessage(AWAITING_WELCOME);
9358
9737
  if (welcome.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, welcome);
9359
- if (welcome.t !== "welcome") throw wrongHandshakeFrame(ctx.channel, "a welcome frame", welcome.t);
9738
+ if (welcome.t !== "welcome") throw wrongHandshakeFrame(ctx.channel, AWAITING_WELCOME, welcome.t);
9360
9739
  sendHandshake(encodeHandshakeMessage(await handshake.onWelcome(welcome)));
9361
- const accept = await nextHandshakeMessage();
9740
+ const accept = await nextHandshakeMessage(AWAITING_ACCEPT);
9362
9741
  if (accept.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, accept);
9363
- if (accept.t !== "accept") throw wrongHandshakeFrame(ctx.channel, "an accept frame", accept.t);
9742
+ if (accept.t !== "accept") throw wrongHandshakeFrame(ctx.channel, AWAITING_ACCEPT, accept.t);
9364
9743
  const result = await handshake.onAccept(accept);
9365
9744
  return {
9366
9745
  crypto: result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
@@ -9396,6 +9775,22 @@ function onChannelClosed(disconnectListeners, lane) {
9396
9775
  lane.onDetach?.();
9397
9776
  }
9398
9777
  //#endregion
9778
+ //#region ../nice-wire/src/Connect/webCryptoPreflight.ts
9779
+ /**
9780
+ * The one check before a secure transport dials. A browser gives `crypto.subtle` only to a secure
9781
+ * context (HTTPS, or localhost), and some runtimes ship none until a polyfill is installed; either
9782
+ * way the handshake cannot run, and no retry will change that.
9783
+ */
9784
+ function assertWebCryptoAvailable() {
9785
+ const runtime = globalThis;
9786
+ if (runtime.crypto?.subtle != null) return;
9787
+ if (runtime.isSecureContext === false) throw err_wire_connect.fromId("crypto_unavailable", {
9788
+ reason: "insecure_context",
9789
+ pageOrigin: runtime.location?.origin
9790
+ });
9791
+ throw err_wire_connect.fromId("crypto_unavailable", { reason: "no_webcrypto" });
9792
+ }
9793
+ //#endregion
9399
9794
  //#region ../nice-wire/src/Connect/TransportConnection.ts
9400
9795
  let transportOrd = 0;
9401
9796
  /**
@@ -9468,6 +9863,7 @@ var TransportConnection$1 = class {
9468
9863
  return this._processTransportStatus(input);
9469
9864
  }
9470
9865
  _processTransportStatus(input) {
9866
+ if (this.initialized.requiresWebCrypto === true) assertWebCryptoAvailable();
9471
9867
  const statusInfo = addTransportStatusMetadata(this.initialized.getTransport(input));
9472
9868
  if (statusInfo.status === "ready") {
9473
9869
  if (!this._needsAsyncBringUp(statusInfo.readyData)) return {
@@ -9599,6 +9995,22 @@ var WireProtocolMux = class {
9599
9995
  const DEFAULT_HEARTBEAT_IDLE_MS = 15e3;
9600
9996
  const DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS = 5e3;
9601
9997
  const ephemeralIdentityWarned = /* @__PURE__ */ new Set();
9998
+ const linksByStorage = /* @__PURE__ */ new WeakMap();
9999
+ /**
10000
+ * The one identity link over a storage: every connection built from the same adapter presents the
10001
+ * same keys. A link apiece would each find a fresh store empty and mint a key of its own, and the
10002
+ * peer pins only the first it sees.
10003
+ */
10004
+ function linkOverStorage(storage) {
10005
+ const shared = linksByStorage.get(storage);
10006
+ if (shared != null) {
10007
+ shared.reloadOnNextInitialize();
10008
+ return shared;
10009
+ }
10010
+ const link = new ClientCryptoKeyLink({ storageAdapter: storage });
10011
+ linksByStorage.set(storage, link);
10012
+ return link;
10013
+ }
9602
10014
  /**
9603
10015
  * The ephemeral-identity trap: a coordinate with a persistent id whose
9604
10016
  * crypto identity lives in non-durable storage keys the peer's trust-on-first-use verify-key pin but
@@ -9616,6 +10028,33 @@ function warnOnEphemeralPinnedIdentity(callerName, coordinate, storage) {
9616
10028
  ephemeralIdentityWarned.add(pinKey);
9617
10029
  console.warn(`${callerName}: the runtime coordinate [${pinKey}] carries a persistent id, which keys the peer's trust-on-first-use verify-key pin — but the \`storage\` passed here is not known to be durable, so this client's crypto identity may regenerate on reload. The peer will pin the first key it sees and reject every reconnect after the first reload (identity_pin_mismatch). Back the connection with a durable adapter (e.g. createWebLocalStorageAdapter) that persists at least as long as the persistent id, or set \`ephemeralIdentity: true\` if the id is minted fresh per session. Memory adapters are for tests.`);
9618
10030
  }
10031
+ const sessionReuseWarned = /* @__PURE__ */ new Set();
10032
+ /**
10033
+ * `reuseExchangeSessions` where it cannot do what it says. Nothing fails, so nothing else would
10034
+ * tell: the option is ignored on a plain carrier, a link with no storage keeps the session in
10035
+ * memory only, and a per-session identity files it under an id no later load will have. Warned
10036
+ * once per connection identity, peer and cause.
10037
+ */
10038
+ function warnOnUnusableSessionReuse(options, link) {
10039
+ const exchangeCarriers = options.exchangeCarrierSecurity ?? [];
10040
+ if (exchangeCarriers.length === 0) return;
10041
+ const connection = `[${options.identity.envId}::${options.identity.perId ?? "-"} → ${options.peer.envId}::${options.peer.perId ?? "-"}]`;
10042
+ const warn = (cause, detail) => {
10043
+ const key = `${cause}|${connection}`;
10044
+ if (sessionReuseWarned.has(key)) return;
10045
+ sessionReuseWarned.add(key);
10046
+ console.warn(`${options.callerName}: \`reuseExchangeSessions\` ${detail}`);
10047
+ };
10048
+ if (!exchangeCarriers.includes(true)) {
10049
+ warn("plain", `does nothing on the connection ${connection}: every request/reply carrier on it is \`secure: false\`, and a plain carrier has no session to keep. Drop the option, or make the carrier secure.`);
10050
+ return;
10051
+ }
10052
+ if (link?.scopedStorage("") == null) {
10053
+ warn("no-storage", `is on for the connection ${connection}, but its crypto identity has no \`storage\`, so a session is kept in memory only: shared between this page's connections, and gone on reload. Pass \`storage\` (or a \`link\` built over one) to keep sessions across page loads.`);
10054
+ return;
10055
+ }
10056
+ if (options.ephemeralIdentity === true && options.identity.perId != null) warn("per-session-identity", `is on for the connection ${connection} together with \`ephemeralIdentity: true\`. A kept session is filed under the identity's persistent id, and a per-session id is new on every load, so no later load can find it: sessions are reused within this page only. Use an id that survives reloads if a reload should skip the handshake.`);
10057
+ }
9619
10058
  /**
9620
10059
  * Assemble the connection facts a dial-out entry point shares — the one implementation of "how a
9621
10060
  * wire connection's mux, crypto identity, keepalive, and traffic tap are set up" (first-production
@@ -9634,8 +10073,9 @@ function assembleWireConnectionParts(options) {
9634
10073
  if (options.anySecure && link == null) {
9635
10074
  if (options.storage == null && options.ephemeralIdentity !== true) throw new Error(`${options.callerName}: a secure transport requires \`storage\` (or \`link\`) for the crypto identity. Pass it, declare a per-session identity with \`ephemeralIdentity: true\`, or set \`secure: false\` on the carrier for a plain connection.`);
9636
10075
  if (options.storage != null && options.ephemeralIdentity !== true) warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);
9637
- link = new ClientCryptoKeyLink(options.storage != null ? { storageAdapter: options.storage } : {});
10076
+ link = options.storage != null ? linkOverStorage(options.storage) : new ClientCryptoKeyLink();
9638
10077
  }
10078
+ if (options.reuseExchangeSessions === true) warnOnUnusableSessionReuse(options, link);
9639
10079
  const resolveHeartbeat = () => {
9640
10080
  if (heartbeat === false) return void 0;
9641
10081
  const explicit = heartbeat;
@@ -11560,7 +12000,7 @@ var ActionCore = class extends ActionBase {
11560
12000
  * undeclared `NiceError`s) returns `false`.
11561
12001
  */
11562
12002
  isExpectedError(error) {
11563
- return error instanceof NiceError && this.schema.isExpectedError(error);
12003
+ return isNiceError(error) && this.schema.isExpectedError(error);
11564
12004
  }
11565
12005
  toJsonObject() {
11566
12006
  return {
@@ -15179,12 +15619,29 @@ var ActionLocalHandler = class extends ActionHandler {
15179
15619
  if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) return this.actionRouter.domainManager.getActionDomainOrThrow(state.request).hydrateResultPayload(rawResult);
15180
15620
  return state.request.successResult(rawResult);
15181
15621
  });
15182
- const result = ran.ok ? ran.output : state.request.errorResult(ran.error);
15622
+ let result;
15623
+ try {
15624
+ result = ran.ok ? ran.output : this._errorResult(state.request, ran.error);
15625
+ } catch (error) {
15626
+ runningAction._failWithError(error);
15627
+ return;
15628
+ }
15183
15629
  runningAction._completeWithResult(result);
15184
15630
  } finally {
15185
15631
  popHandlerCuid();
15186
15632
  }
15187
15633
  }
15634
+ /**
15635
+ * Building an error result classifies the error, which reads it (`isExact`, `hasId`). An error
15636
+ * that cannot be read still has to answer, so the result becomes the cast of what reading threw.
15637
+ */
15638
+ _errorResult(request, error) {
15639
+ try {
15640
+ return request.errorResult(error);
15641
+ } catch (unreadable) {
15642
+ return request.errorResult(castNiceError(unreadable));
15643
+ }
15644
+ }
15188
15645
  async handlePayloadWireOrThrow(wire, config) {
15189
15646
  const hydratedAction = this.actionRouter.domainManager.hydrateActionPayload(wire);
15190
15647
  if (!(hydratedAction instanceof ActionPayload_Request)) throw err_nice_action.fromId("wire_action_not_payload", {
@@ -16925,6 +17382,7 @@ var ExchangeTransport = class ExchangeTransport extends Transport {
16925
17382
  return new ExchangeConnection({ initialize: () => ({
16926
17383
  getCacheKey: options.getCacheKey,
16927
17384
  isAvailable: options.available,
17385
+ requiresWebCrypto: options.security != null && options.security.securityLevel !== "none",
16928
17386
  getTransport: (input) => {
16929
17387
  assertProtocolsRideDuplex(options);
16930
17388
  const carrier = options.openCarrier(input);
@@ -17169,6 +17627,7 @@ var LinkTransport = class LinkTransport extends Transport {
17169
17627
  return new LinkConnection({ initialize: () => ({
17170
17628
  getCacheKey: options.getCacheKey,
17171
17629
  isAvailable: options.available,
17630
+ requiresWebCrypto: options.security != null && options.security.securityLevel !== "none",
17172
17631
  getTransport: (input) => ({
17173
17632
  status: "ready",
17174
17633
  readyData: {
@@ -17361,6 +17820,8 @@ function connectChannel(runtime, channel, options) {
17361
17820
  storage: options.storage,
17362
17821
  link: options.link,
17363
17822
  ephemeralIdentity: options.ephemeralIdentity,
17823
+ reuseExchangeSessions: options.reuseExchangeSessions,
17824
+ exchangeCarrierSecurity: transports.filter((descriptor) => isExchangeCarrierSource(descriptor.carrier)).map((descriptor) => (descriptor.secure ?? true) && (descriptor.securityLevel ?? securityLevel) !== "none"),
17364
17825
  reconnect: options.reconnect,
17365
17826
  heartbeat: options.heartbeat,
17366
17827
  keepLinkAlive: options.keepLinkAlive,
@@ -17624,7 +18085,7 @@ function createActionFetchHandler(runtime, options = {}) {
17624
18085
  securityLevel: "none"
17625
18086
  });
17626
18087
  } catch (error) {
17627
- if (error instanceof NiceError && error.getIds().some((id) => id === "wire_not_action_data" || id === "wire_action_not_payload")) {
18088
+ if (isNiceError(error) && error.getIds().some((id) => id === "wire_not_action_data" || id === "wire_action_not_payload")) {
17628
18089
  report?.({
17629
18090
  ok: false,
17630
18091
  returnedVia: transportLabel,
@@ -24782,30 +25243,6 @@ async function ensureStateDir(paths) {
24782
25243
  });
24783
25244
  }
24784
25245
  //#endregion
24785
- //#region src/daemon/packageVersion.ts
24786
- let cached = null;
24787
- /**
24788
- * Resolved relative to the BUILT module, so the candidate list must cover every layout this
24789
- * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that
24790
- * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).
24791
- */
24792
- async function commanderPackageVersion() {
24793
- if (cached != null) return cached;
24794
- for (const candidate of [
24795
- new URL("../package.json", require("url").pathToFileURL(__filename).href),
24796
- new URL("../../package.json", require("url").pathToFileURL(__filename).href),
24797
- new URL("../../../package.json", require("url").pathToFileURL(__filename).href)
24798
- ]) try {
24799
- const parsed = JSON.parse(await (0, node_fs_promises.readFile)(candidate, "utf8"));
24800
- if (typeof parsed.version === "string" && parsed.name === "@nice-code/commander") {
24801
- cached = parsed.version;
24802
- return cached;
24803
- }
24804
- } catch {}
24805
- cached = "0.0.0";
24806
- return cached;
24807
- }
24808
- //#endregion
24809
25246
  //#region src/daemon/runtime.ts
24810
25247
  /** Check before advertising a daemon whose HTTP works but whose wire handshake cannot run. */
24811
25248
  function commanderRuntimeError() {
@@ -25454,6 +25891,11 @@ function checkReloadResult(value) {
25454
25891
  errors
25455
25892
  };
25456
25893
  }
25894
+ /** Re-check a reload ack that arrived from a daemon — see `parseActionReport`. */
25895
+ function parseReloadResult(value) {
25896
+ const checked = checkReloadResult(value);
25897
+ return typeof checked === "string" ? null : checked;
25898
+ }
25457
25899
  const OUTCOMES = new Set([
25458
25900
  "ready",
25459
25901
  "spawned",
@@ -25690,6 +26132,11 @@ async function connectDaemon(handle) {
25690
26132
  const request = commanderControlDomain.actionForId("noteRuns").request(input);
25691
26133
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "noteRuns" rejected by the daemon`);
25692
26134
  },
26135
+ reloadConfig: async () => {
26136
+ const request = commanderControlDomain.actionForId("reloadConfig").request({});
26137
+ const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
26138
+ return payload.result.ok ? parseReloadResult(payload.result.output) : null;
26139
+ },
25693
26140
  shutdown: async () => {
25694
26141
  const request = commanderControlDomain.actionForId("shutdown").request({});
25695
26142
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "shutdown" rejected by the daemon`);
@@ -25791,9 +26238,11 @@ function printReport(out, report, state) {
25791
26238
  else {
25792
26239
  for (const result of report.results) {
25793
26240
  if (NARRATED.has(result.outcome)) continue;
26241
+ const node = state.processes[result.id];
25794
26242
  const note = result.reason != null ? ` — ${result.reason}` : "";
25795
- const reach = result.outcome === "already-running" ? reachLine(out, state.processes[result.id]) : "";
26243
+ const reach = result.outcome === "already-running" ? reachLine(out, node) : "";
25796
26244
  out.print(`${stateSymbol(out, result.outcome)} ${out.accent(result.id, result.id)} ${result.outcome}${note}${reach}`);
26245
+ if (result.outcome === "already-running" && (node?.stale === true || node?.envDrift === true)) out.print(out.paint("yellow", ` ${result.id} runs what it was started with — its ${node.stale ? "definition" : "env"} has changed since; \`restart ${result.id}\` applies it`));
25797
26246
  }
25798
26247
  for (const warning of report.warnings) out.warn(`${out.paint("yellow", "⚠")} ${warning}`);
25799
26248
  }
@@ -25828,6 +26277,7 @@ async function cmdUp(ctx) {
25828
26277
  if (handle.replaced != null && !ctx.out.json) ctx.out.print(ctx.out.paint("gray", `· replaced the previous daemon (pid ${handle.replaced.pid}, build ${handle.replaced.packageVersion}) — it predated this CLI and nothing was running`));
25829
26278
  const client = await connectDaemon(handle);
25830
26279
  try {
26280
+ await syncDaemonConfig(ctx.config, client, ctx.out);
25831
26281
  const wait = !ctx.args.flags.has("--no-wait");
25832
26282
  const staggerMs = staggerFor(ctx.config, ctx.args.positionals);
25833
26283
  const replaceSame = ctx.args.flags.has("--replace-same");
@@ -25850,12 +26300,18 @@ async function controlVerb(ctx, verb) {
25850
26300
  "--with",
25851
26301
  "--all",
25852
26302
  "--any"
25853
- ] : ["--all", "--any"];
26303
+ ] : [
26304
+ "--only",
26305
+ "--all",
26306
+ "--any"
26307
+ ];
25854
26308
  const bad = unknownFlags(ctx.args.flags, known);
25855
26309
  if (bad != null) throw new CliExit(EXIT.usage, bad);
26310
+ if (ctx.args.flags.has("--only") && ctx.args.flags.get("--only") !== true) throw new CliExit(EXIT.usage, "--only takes no value");
25856
26311
  requireSelectionTerms(ctx);
25857
26312
  const client = await connectDaemon(await requireDaemon(ctx.config));
25858
26313
  try {
26314
+ if (verb === "restart") await syncDaemonConfig(ctx.config, client, ctx.out);
25859
26315
  const declared = new Set(ctx.config.processes.map((proc) => proc.id));
25860
26316
  const selection = selectOrExit(ctx, {
25861
26317
  bare: "required",
@@ -25863,8 +26319,11 @@ async function controlVerb(ctx, verb) {
25863
26319
  });
25864
26320
  const replaceSame = ctx.args.flags.has("--replace-same");
25865
26321
  const flags = verb === "restart" ? flagsOrExit(ctx) : null;
25866
- const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", { ids: selection.ordered }) : client.control("restart", {
25867
- ids: selection.ordered,
26322
+ const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", ctx.args.flags.has("--only") ? { ids: selection.direct } : {
26323
+ ids: selection.direct,
26324
+ withDependencies: true
26325
+ }) : client.control("restart", {
26326
+ ids: selection.direct,
25868
26327
  wait: !ctx.args.flags.has("--no-wait"),
25869
26328
  staggerMs: staggerFor(ctx.config, ctx.args.positionals),
25870
26329
  ...replaceSame ? { replaceSame } : {},
@@ -26421,6 +26880,50 @@ function createPortInspector(options) {
26421
26880
  return { run };
26422
26881
  }
26423
26882
  //#endregion
26883
+ //#region src/cli/envJudge.ts
26884
+ function shellEnvJudge(unreachable) {
26885
+ return {
26886
+ judgedIn: "shell",
26887
+ note: unreachable == null ? `no daemon is running — whether a variable is set is judged in ${describeJudgedIn("shell")}, which a daemon started from here inherits` : `the daemon could not be asked (${unreachable}) — whether a variable is set is judged in ${describeJudgedIn("shell")} instead`,
26888
+ baseEnv: () => process.env
26889
+ };
26890
+ }
26891
+ /** Reads `state` now, not when asked: the judge outlives the connection it came from. */
26892
+ function daemonEnvJudge(state, daemonPid) {
26893
+ const judged = new Map(Object.entries(state.processes).map(([id, node]) => [id, new Map(node.detail.envVars.map((view) => [view.name, view.source]))]));
26894
+ return {
26895
+ judgedIn: "daemon",
26896
+ note: `whether a variable is set is judged in ${describeJudgedIn("daemon")} (pid ${daemonPid}) — what \`up\` starts inherits that one, not this shell's`,
26897
+ baseEnv: (definition) => {
26898
+ const env = {};
26899
+ for (const declared of definition.envVars) {
26900
+ const source = judged.get(definition.id)?.get(declared.name);
26901
+ if (source === "inherited" || source !== "unset" && process.env[declared.name] != null) env[declared.name] = "";
26902
+ }
26903
+ return env;
26904
+ }
26905
+ };
26906
+ }
26907
+ /**
26908
+ * The judge for a read-only command. A daemon this build cannot talk to must not fail a command
26909
+ * that only wanted its opinion — the shell answers, and the note says why.
26910
+ */
26911
+ async function judgeEnv(config, known) {
26912
+ const handle = known === void 0 ? await findDaemon(config) : known;
26913
+ if (handle == null) return shellEnvJudge();
26914
+ try {
26915
+ const client = await connectDaemon(handle);
26916
+ try {
26917
+ return daemonEnvJudge(client.state(), handle.record.pid);
26918
+ } finally {
26919
+ client.dispose();
26920
+ }
26921
+ } catch (error) {
26922
+ if (!(error instanceof CliExit)) throw error;
26923
+ return shellEnvJudge(error.message);
26924
+ }
26925
+ }
26926
+ //#endregion
26424
26927
  //#region src/cli/commands/ports.ts
26425
26928
  async function portProcessStates(ctx) {
26426
26929
  const handle = await findDaemon(ctx.config);
@@ -26670,8 +27173,10 @@ async function diagnose(ctx, handle) {
26670
27173
  const overrideCount = countOverrides(overrides);
26671
27174
  if (overrideCount > 0) report.info.push(`env overrides: ${overrideCount} set in ${paths.envOverridesPath} — they apply to every start (\`nice-commander env\` lists them, \`--clear\` drops them)`);
26672
27175
  for (const entry of staleOverrides(config, overrides)) report.warnings.push(`env override ${entry.id}.${entry.name} is stored but inert (${entry.reason}) — clear it with \`env ${entry.id} --clear\``);
27176
+ const judge = await judgeEnv(config, handle);
26673
27177
  for (const proc of config.processes) {
26674
- for (const name of missingRequired(proc, overrides, process.env)) report.warnings.push(`"${proc.id}" requires ${name} and nothing supplies it — set it with \`env ${proc.id} --set ${name}=…\``);
27178
+ const missing = missingRequired(proc, overrides, judge.baseEnv(proc));
27179
+ if (missing.length > 0) report.warnings.push(`"${proc.id}" ${requiredRefusal(proc.id, missing, judge.judgedIn)} — a start refuses until then`);
26675
27180
  for (const off of overridesOffEndpoint(proc, overrides)) report.warnings.push(`"${proc.id}" ${off.name}=${off.value} but its endpoint and readiness are still on ${off.port} — it will bind somewhere nothing points at`);
26676
27181
  }
26677
27182
  const capability = (0, _nice_code_process.detectCapability)();
@@ -26837,11 +27342,11 @@ function parseNames(values) {
26837
27342
  for (const entry of values) if (entry.includes("=")) return { error: `--unset expects a NAME, got ${JSON.stringify(entry)}` };
26838
27343
  return [...values];
26839
27344
  }
26840
- function describeValue(view) {
27345
+ function describeValue(view, judgedIn) {
26841
27346
  if (view.secret) return view.source === "unset" ? "-" : "••••••";
26842
- return view.value ?? (view.source === "inherited" ? "(the daemon's env)" : "-");
27347
+ return view.value ?? (view.source === "inherited" ? `(${describeJudgedIn(judgedIn)})` : "-");
26843
27348
  }
26844
- function renderProcess(out, definition, views) {
27349
+ function renderProcess(out, definition, views, judgedIn) {
26845
27350
  out.print(out.paint("bold", definition.id));
26846
27351
  if (views.length === 0) {
26847
27352
  out.print(out.paint("gray", " declares no env vars — add `envVars` to the config to tune it"));
@@ -26854,7 +27359,7 @@ function renderProcess(out, definition, views) {
26854
27359
  "NOTES"
26855
27360
  ], views.map((view) => [
26856
27361
  ` ${view.name}`,
26857
- describeValue(view),
27362
+ describeValue(view, judgedIn),
26858
27363
  view.source,
26859
27364
  [
26860
27365
  view.description,
@@ -26880,8 +27385,15 @@ async function cmdEnv(ctx) {
26880
27385
  const { out, config } = ctx;
26881
27386
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
26882
27387
  const definitions = mutating || ctx.args.positionals.length > 0 || ctx.args.flags.has("--all") ? idsToDefinitions(ctx, selectOrExit(ctx, { bare: "required" }).direct) : config.processes.filter((proc) => proc.envVars.length > 0);
26883
- const handle = mutating ? await findDaemon(config) : null;
26884
- const client = handle == null ? null : await connectDaemon(handle);
27388
+ const handle = await findDaemon(config);
27389
+ let client = null;
27390
+ let unreachable;
27391
+ if (handle != null) try {
27392
+ client = await connectDaemon(handle);
27393
+ } catch (error) {
27394
+ if (mutating || !(error instanceof CliExit)) throw error;
27395
+ unreachable = error.message;
27396
+ }
26885
27397
  try {
26886
27398
  const result = mutating ? await mutate(ctx, paths.envOverridesPath, client, {
26887
27399
  processes: Object.fromEntries(definitions.map((definition) => [definition.id, {
@@ -26893,11 +27405,13 @@ async function cmdEnv(ctx) {
26893
27405
  overrides: await readEnvOverrides(paths.envOverridesPath),
26894
27406
  warnings: []
26895
27407
  };
26896
- const views = new Map(definitions.map((definition) => [definition.id, envVarViews(definition, result.overrides, process.env)]));
27408
+ const judge = client != null ? daemonEnvJudge(client.state(), client.record.pid) : shellEnvJudge(unreachable);
27409
+ const views = new Map(definitions.map((definition) => [definition.id, envVarViews(definition, result.overrides, judge.baseEnv(definition))]));
26897
27410
  const stale = staleOverrides(config, result.overrides);
26898
27411
  if (out.json) {
26899
27412
  out.printJson({
26900
27413
  overridesPath: paths.envOverridesPath,
27414
+ judgedAgainst: judge.judgedIn,
26901
27415
  processes: definitions.map((definition) => ({
26902
27416
  id: definition.id,
26903
27417
  envVars: views.get(definition.id) ?? []
@@ -26908,9 +27422,10 @@ async function cmdEnv(ctx) {
26908
27422
  return result.warnings.length > 0 ? EXIT.failure : EXIT.ok;
26909
27423
  }
26910
27424
  for (const definition of definitions) {
26911
- renderProcess(out, definition, views.get(definition.id) ?? []);
27425
+ renderProcess(out, definition, views.get(definition.id) ?? [], judge.judgedIn);
26912
27426
  out.print();
26913
27427
  }
27428
+ if ([...views.values()].some((listed) => listed.length > 0)) out.print(out.paint("gray", judge.note));
26914
27429
  const total = countOverrides(result.overrides);
26915
27430
  if (total > 0) out.print(out.paint("gray", `${total} sticky override(s) — they apply to every start until \`nice-commander env <sel> --clear\`.`));
26916
27431
  if (client != null) {
@@ -27036,16 +27551,18 @@ async function cmdExplain(ctx) {
27036
27551
  return EXIT.ok;
27037
27552
  }
27038
27553
  const overrides = await readEnvOverrides(commanderStatePaths(resolveCommanderDataDir(), ctx.config.configKey).envOverridesPath);
27554
+ const judge = await judgeEnv(ctx.config);
27039
27555
  out.print("env:");
27040
27556
  out.print(" note: `run` children inherit THIS shell's environment; daemon-owned starts (`up`) inherit");
27041
27557
  out.print(" the daemon's boot-time snapshot — `doctor` shows that snapshot's age.");
27558
+ out.print(` ${judge.note}`);
27042
27559
  for (const id of selection.ordered) {
27043
27560
  const def = ctx.config.processes.find((proc) => proc.id === id);
27044
27561
  if (def == null) continue;
27045
27562
  const parts = [];
27046
27563
  for (const [key, value] of Object.entries(def.env)) parts.push(value == null ? `${key}=(unset)` : `${key}=${value} (config)`);
27047
- for (const view of envVarViews(def, overrides, process.env)) {
27048
- const shown = view.secret ? "•••" : view.value ?? (view.source === "inherited" ? "(from shell)" : "(unset)");
27564
+ for (const view of envVarViews(def, overrides, judge.baseEnv(def))) {
27565
+ const shown = view.secret ? "•••" : view.value ?? (view.source === "inherited" ? `(from ${describeJudgedIn(judge.judgedIn)})` : "(unset)");
27049
27566
  parts.push(`${view.name}=${shown} (${view.source}${view.source === "override" ? ", sticky" : ""})`);
27050
27567
  }
27051
27568
  if (parts.length > 0) out.print(` ${id}: ${parts.join(" ")}`);
@@ -27546,6 +28063,11 @@ async function cmdRun(ctx) {
27546
28063
  if (parallel != null && !defs.some((def) => def.kind === "task")) out.warn(out.paint("yellow", "note: --parallel applies to tasks; this selection has none — ignored."));
27547
28064
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
27548
28065
  const overrides = await readEnvOverrides(paths.envOverridesPath);
28066
+ const unmet = defs.flatMap((def) => {
28067
+ const missing = missingRequired(def, overrides, process.env);
28068
+ return missing.length === 0 ? [] : [`"${def.id}" ${requiredRefusal(def.id, missing, "shell")}`];
28069
+ });
28070
+ if (unmet.length > 0) throw new CliExit(EXIT.failure, `nothing was started — ${unmet.join("\n")}`);
27549
28071
  const ledger = (0, _nice_code_process.openProcessLedger)({
27550
28072
  dir: paths.stateDir,
27551
28073
  namespace: paths.ledgerNamespace,
@@ -27555,6 +28077,7 @@ async function cmdRun(ctx) {
27555
28077
  if (handle != null) {
27556
28078
  const client = await connectDaemon(handle);
27557
28079
  try {
28080
+ await syncDaemonConfig(config, client, out);
27558
28081
  const owned = defs.filter((def) => ACTIVE_STATES$1.has(client.state().processes[def.id]?.state ?? ""));
27559
28082
  if (owned.length > 0) throw new CliExit(EXIT.failure, `"${owned.map((def) => def.id).join("\", \"")}" is owned by the running daemon — \`down\` it there first (silent double-start is never allowed).`);
27560
28083
  } finally {
@@ -27642,7 +28165,7 @@ async function cmdRun(ctx) {
27642
28165
  });
27643
28166
  let timer = null;
27644
28167
  let timedOut = false;
27645
- let run = null;
28168
+ let run;
27646
28169
  try {
27647
28170
  await proc.start();
27648
28171
  run = noteStart(def);
@@ -27674,7 +28197,7 @@ async function cmdRun(ctx) {
27674
28197
  }
27675
28198
  const code = proc.lastExit?.code ?? (proc.state === "succeeded" ? 0 : 1);
27676
28199
  const failed = code !== 0;
27677
- if (!failed && run != null && passthrough.length === 0) run.durationMs = Date.now() - run.startedAt;
28200
+ if (!failed && passthrough.length === 0) run.durationMs = Date.now() - run.startedAt;
27678
28201
  out.print(failed ? `${out.paint("red", "✗")} ${out.accent(def.id, def.id)} exit ${code}` : `${out.paint("green", "✓")} ${out.accent(def.id, def.id)} ok`);
27679
28202
  return {
27680
28203
  id: def.id,
@@ -28194,10 +28717,15 @@ const COMMAND_HELP = [
28194
28717
  command in the same cwd, started outside the daemon
28195
28718
  (a stranger on the port still refuses). --json reports
28196
28719
  every id's outcome, state, pid and endpoints as data.`],
28197
- ["down", " down <sel> stop (reverse-DAG order)"],
28720
+ ["down", ` down <sel> [--only] stop the selection (dependents first) and each of its
28721
+ dependencies that no other live process needs; one
28722
+ that is still needed stays up and is named, with what
28723
+ needs it. --only stops exactly the selection.`],
28198
28724
  ["restart", ` restart <sel> [--no-wait] [--replace-same] [--with <flag>]
28199
- stop + start, with the flags of the run it replaces
28200
- unless --with names others`],
28725
+ stop + start exactly the selection, with the flags of
28726
+ the run it replaces unless --with names others. Its
28727
+ dependencies keep running; one that is down is
28728
+ started first.`],
28201
28729
  ["status", " status [--watch] table from the live status realm"],
28202
28730
  ["logs", " logs <sel> [-f] merged interleaved tail with colored id prefixes"],
28203
28731
  ["list", " list config introspection (processes, suites, warnings)"],
@@ -28301,7 +28829,7 @@ async function withTimeout(ctx, run) {
28301
28829
  async function main() {
28302
28830
  const argv = process.argv.slice(2);
28303
28831
  if (argv[0] === "daemon") {
28304
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-C3BG9bju.cjs"));
28832
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-CcxTP9yh.cjs"));
28305
28833
  return runCommanderDaemon(argv.slice(1));
28306
28834
  }
28307
28835
  const parsed = parseCliArgs(argv);
@@ -28357,6 +28885,7 @@ exports.COMMANDER_SHUTDOWN_PATH = COMMANDER_SHUTDOWN_PATH;
28357
28885
  exports.COMMANDER_TICKET_PATH = COMMANDER_TICKET_PATH;
28358
28886
  exports.COMMANDER_TICKET_PROTOCOL_PREFIX = COMMANDER_TICKET_PROTOCOL_PREFIX;
28359
28887
  exports.COMMANDER_WS_PATH = COMMANDER_WS_PATH;
28888
+ exports.CommanderConfigLoadError = CommanderConfigLoadError;
28360
28889
  exports.RuntimeCoordinate = RuntimeCoordinate;
28361
28890
  exports.ancestors = ancestors;
28362
28891
  exports.applyEnvMutation = applyEnvMutation;
@@ -28382,6 +28911,7 @@ exports.hashCanonical = hashCanonical;
28382
28911
  exports.httpAcceptorCarrier = httpAcceptorCarrier;
28383
28912
  exports.identifyEndpointOwner = identifyEndpointOwner;
28384
28913
  exports.loadCommanderConfigFile = loadCommanderConfigFile;
28914
+ exports.missingRequired = missingRequired;
28385
28915
  exports.mutateSavedFilters = mutateSavedFilters;
28386
28916
  exports.orderByDependency = orderByDependency;
28387
28917
  exports.overrideFingerprint = overrideFingerprint;
@@ -28393,6 +28923,7 @@ exports.readSavedFilters = readSavedFilters;
28393
28923
  exports.readTaskDurations = readTaskDurations;
28394
28924
  exports.recordDaemonAlive = recordDaemonAlive;
28395
28925
  exports.removeInstanceRecord = removeInstanceRecord;
28926
+ exports.requiredRefusal = requiredRefusal;
28396
28927
  exports.resolveCommanderDataDir = resolveCommanderDataDir;
28397
28928
  exports.resolveFlags = resolveFlags;
28398
28929
  exports.runTaskPool = runTaskPool;