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