@nice-code/commander 0.111.0 → 0.113.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.113.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
@@ -4722,23 +4999,34 @@ var ClientCryptoKeyLink = class {
4722
4999
  localVerifyKeyPair;
4723
5000
  linkedClientKeys = /* @__PURE__ */ new Map();
4724
5001
  storage;
5002
+ storageAdapter;
4725
5003
  identityMode;
4726
5004
  initialized = false;
5005
+ reloadPending = false;
4727
5006
  initializePromise;
4728
5007
  localExchangeKeyPairPromise;
4729
5008
  localVerifyKeyPairPromise;
4730
5009
  constructor({ storageAdapter, identityMode } = {}) {
4731
5010
  if (storageAdapter != null) this.storage = createTypedStorage({ storageAdapter });
5011
+ this.storageAdapter = storageAdapter;
4732
5012
  this.identityMode = identityMode ?? "lazy";
4733
5013
  }
4734
5014
  /**
5015
+ * A namespace of this identity's own store (same backing storage, `prefix` appended), for state
5016
+ * that belongs to this identity and must go wherever its keys go — e.g. a connector's established
5017
+ * sessions. `undefined` when the link has no storage.
5018
+ */
5019
+ scopedStorage(prefix) {
5020
+ return this.storageAdapter?.withKeyPrefix(prefix);
5021
+ }
5022
+ /**
4735
5023
  * Loads the local key pairs and any linked client public keys from storage (when a storage
4736
5024
  * adapter was provided), generating and persisting fresh local key pairs if none exist yet.
4737
5025
  *
4738
5026
  * Must be called (and awaited) before any sign/verify/encrypt/decrypt operation.
4739
5027
  */
4740
5028
  async initialize() {
4741
- if (this.initialized) return;
5029
+ if (this.initialized && !this.reloadPending) return;
4742
5030
  this.initializePromise ??= this.runInitialize();
4743
5031
  try {
4744
5032
  await this.initializePromise;
@@ -4747,11 +5035,23 @@ var ClientCryptoKeyLink = class {
4747
5035
  }
4748
5036
  }
4749
5037
  async runInitialize() {
5038
+ this.initialized = false;
4750
5039
  await this.loadStoredLocalKeys();
4751
5040
  await this.loadLinkedClients();
4752
5041
  this.initialized = true;
4753
5042
  }
4754
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
+ /**
4755
5055
  * Provision the local identity once: load any persisted identity, then mint + persist the exchange
4756
5056
  * and verify key pairs only if absent. Idempotent — a no-op when an identity already exists.
4757
5057
  *
@@ -4776,24 +5076,62 @@ var ClientCryptoKeyLink = class {
4776
5076
  * generates or stores keys it does not need.
4777
5077
  */
4778
5078
  async loadStoredLocalKeys() {
4779
- const storedExchange = await this.storage?.getJson("localExchangeKeyPair");
4780
- if (storedExchange != null) {
4781
- const exchangePrivateKey = await importX25519Key.private.fromFormattedString.extractable(storedExchange.privateKey);
4782
- const exchangePublicKey = await importX25519Key.public.fromFormattedString.extractable(storedExchange.publicKey);
4783
- this.localExchangeKeyPair = {
4784
- privateKey: exchangePrivateKey,
4785
- publicKey: exchangePublicKey
4786
- };
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;
4787
5089
  }
4788
- const storedVerify = await this.storage?.getJson("localVerifyKeyPair");
4789
- if (storedVerify != null) {
4790
- const verifyPrivateKey = await importEd25519Key.private.fromFormattedString.extractable(storedVerify.privateKey);
4791
- const verifyPublicKey = await importEd25519Key.public.fromFormattedString.extractable(storedVerify.publicKey);
4792
- this.localVerifyKeyPair = {
4793
- privateKey: verifyPrivateKey,
4794
- publicKey: verifyPublicKey
4795
- };
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;
4796
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
+ });
4797
5135
  }
4798
5136
  /**
4799
5137
  * Returns the local exchange (X25519) key pair. In `"lazy"` mode it generates + persists it on first
@@ -4808,16 +5146,23 @@ var ClientCryptoKeyLink = class {
4808
5146
  /**
4809
5147
  * Generates + persists the local exchange key pair if absent, returning an already-loaded pair
4810
5148
  * untouched (so provisioning is idempotent). Bypasses the `"required"` guard by design — it is the
4811
- * 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}).
4812
5151
  */
4813
5152
  async mintLocalExchangeKeyPair() {
4814
5153
  if (this.localExchangeKeyPair != null) return this.localExchangeKeyPair;
4815
- this.localExchangeKeyPairPromise ??= (async () => {
4816
- const keyPair = await generateX25519KeyPair();
4817
- this.localExchangeKeyPair = keyPair;
4818
- if (this.storage != null) await this.storage.setJson("localExchangeKeyPair", await this.serializeExchangeKeyPair(keyPair));
4819
- return keyPair;
4820
- })();
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
+ });
4821
5166
  try {
4822
5167
  return await this.localExchangeKeyPairPromise;
4823
5168
  } finally {
@@ -4837,16 +5182,23 @@ var ClientCryptoKeyLink = class {
4837
5182
  /**
4838
5183
  * Generates + persists the local verify key pair if absent, returning an already-loaded pair
4839
5184
  * untouched (so provisioning is idempotent). Bypasses the `"required"` guard by design — it is the
4840
- * 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}).
4841
5187
  */
4842
5188
  async mintLocalVerifyKeyPair() {
4843
5189
  if (this.localVerifyKeyPair != null) return this.localVerifyKeyPair;
4844
- this.localVerifyKeyPairPromise ??= (async () => {
4845
- const keyPair = await generateEd25519KeyPair();
4846
- this.localVerifyKeyPair = keyPair;
4847
- if (this.storage != null) await this.storage.setJson("localVerifyKeyPair", await this.serializeVerifyKeyPair(keyPair));
4848
- return keyPair;
4849
- })();
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
+ });
4850
5202
  try {
4851
5203
  return await this.localVerifyKeyPairPromise;
4852
5204
  } finally {
@@ -6076,12 +6428,13 @@ const isDialUnavailable = (e) => err_wire_connect.isExact(e) && e.hasId("dial_un
6076
6428
  * A dial failure the backoff ladder must PARK on instead of retrying: either no endpoint exists
6077
6429
  * right now ({@link isDialUnavailable}), or the peer rejected the handshake with
6078
6430
  * `identity_pin_mismatch` (the peer has a different key pinned) or
6079
- * `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`).
6080
6433
  * Parking is not terminal: the next explicit `connect()`/dispatch may try again after the app has
6081
6434
  * upgraded or changed endpoints. Other handshake rejections (e.g. a dictionary mismatch) retain
6082
6435
  * the existing retry behavior because a matching deploy can heal them.
6083
6436
  */
6084
- 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"));
6085
6438
  /**
6086
6439
  * The dial-out connection: owns the transport cache, preference-ordered selection, the protocol mux,
6087
6440
  * and the whole **connection lifecycle** — establishment bookkeeping, the keep-alive redial ladder
@@ -9029,6 +9382,8 @@ function handshakeRejectError(stage, rejectFrame) {
9029
9382
  //#region ../nice-wire/src/Connect/duplexLinkSession.ts
9030
9383
  const HANDSHAKE_TIMEOUT_MS$1 = 15e3;
9031
9384
  const LINK_HANDSHAKE_STAGE = "link-handshake";
9385
+ const AWAITING_WELCOME = "a welcome frame";
9386
+ const AWAITING_ACCEPT = "an accept frame";
9032
9387
  /** The duplex twin of the exchange path's `nonProtocolReply` — same typed id, so a consumer's
9033
9388
  * `kind` branch means the same thing whichever carrier served the dial. */
9034
9389
  function wrongHandshakeFrame(channel, expected, receivedKind) {
@@ -9203,9 +9558,34 @@ async function establishSecureDuplexSession(ctx) {
9203
9558
  let active = false;
9204
9559
  const handshakeQueue = [];
9205
9560
  const handshakeWaiters = [];
9561
+ let carrierClosed = false;
9206
9562
  const pendingFrames = [];
9207
9563
  let nonProtocolFrame;
9208
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
+ };
9209
9589
  const mux = ctx.mux;
9210
9590
  channel.attach({
9211
9591
  onMessage: (frame) => {
@@ -9231,7 +9611,7 @@ async function establishSecureDuplexSession(ctx) {
9231
9611
  lane: "handshake"
9232
9612
  });
9233
9613
  const waiter = handshakeWaiters.shift();
9234
- if (waiter != null) waiter(message);
9614
+ if (waiter != null) waiter.resolve(message);
9235
9615
  else handshakeQueue.push(message);
9236
9616
  return;
9237
9617
  }
@@ -9239,23 +9619,31 @@ async function establishSecureDuplexSession(ctx) {
9239
9619
  }
9240
9620
  pendingFrames.push(frame);
9241
9621
  },
9242
- onClose: () => onChannelClosed(disconnectListeners, ctx.lane),
9243
- onError: () => onChannelClosed(disconnectListeners, ctx.lane)
9622
+ onClose: onCarrierClosed,
9623
+ onError: onCarrierClosed
9244
9624
  });
9245
- const nextHandshakeMessage = () => {
9625
+ const nextHandshakeMessage = (awaiting) => {
9246
9626
  const queued = handshakeQueue.shift();
9247
9627
  if (queued != null) return Promise.resolve(queued);
9628
+ if (carrierClosed) return Promise.reject(unansweredError(awaiting, "closed"));
9248
9629
  return new Promise((resolve, reject) => {
9249
- const timeout = setTimeout(() => reject(nonProtocolFrame != null ? err_wire_connect.fromId("endpoint_answered_non_protocol", {
9250
- stage: LINK_HANDSHAKE_STAGE,
9251
- expected: "a handshake frame",
9252
- url: sanitizeEndpoint(channel.label),
9253
- bodyPreview: describeNonProtocolBody(nonProtocolFrame)
9254
- }) : /* @__PURE__ */ new Error(`[${LINK_HANDSHAKE_STAGE}] timed out waiting for peer reply`)), HANDSHAKE_TIMEOUT_MS$1);
9255
- handshakeWaiters.push((message) => {
9256
- clearTimeout(timeout);
9257
- resolve(message);
9258
- });
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);
9259
9647
  });
9260
9648
  };
9261
9649
  try {
@@ -9325,6 +9713,7 @@ function makeSession$1(channel, pipe, disconnectListeners, remoteCaps, muxBindin
9325
9713
  async function runClientHandshake(ctx, nextHandshakeMessage) {
9326
9714
  const secure = ctx.secure;
9327
9715
  const sendHandshake = (encoded) => {
9716
+ if (!ctx.channel.isOpen()) return;
9328
9717
  ctx.channel.send(encoded);
9329
9718
  ctx.tap?.({
9330
9719
  dir: "out",
@@ -9344,13 +9733,13 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
9344
9733
  extraCaps: [...ctx.lane.caps?.() ?? [], ...ctx.mux?.localCaps() ?? []]
9345
9734
  });
9346
9735
  sendHandshake(encodeHandshakeMessage(await handshake.createHello()));
9347
- const welcome = await nextHandshakeMessage();
9736
+ const welcome = await nextHandshakeMessage(AWAITING_WELCOME);
9348
9737
  if (welcome.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, welcome);
9349
- 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);
9350
9739
  sendHandshake(encodeHandshakeMessage(await handshake.onWelcome(welcome)));
9351
- const accept = await nextHandshakeMessage();
9740
+ const accept = await nextHandshakeMessage(AWAITING_ACCEPT);
9352
9741
  if (accept.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, accept);
9353
- 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);
9354
9743
  const result = await handshake.onAccept(accept);
9355
9744
  return {
9356
9745
  crypto: result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
@@ -9386,6 +9775,22 @@ function onChannelClosed(disconnectListeners, lane) {
9386
9775
  lane.onDetach?.();
9387
9776
  }
9388
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
9389
9794
  //#region ../nice-wire/src/Connect/TransportConnection.ts
9390
9795
  let transportOrd = 0;
9391
9796
  /**
@@ -9458,6 +9863,7 @@ var TransportConnection$1 = class {
9458
9863
  return this._processTransportStatus(input);
9459
9864
  }
9460
9865
  _processTransportStatus(input) {
9866
+ if (this.initialized.requiresWebCrypto === true) assertWebCryptoAvailable();
9461
9867
  const statusInfo = addTransportStatusMetadata(this.initialized.getTransport(input));
9462
9868
  if (statusInfo.status === "ready") {
9463
9869
  if (!this._needsAsyncBringUp(statusInfo.readyData)) return {
@@ -9589,6 +9995,22 @@ var WireProtocolMux = class {
9589
9995
  const DEFAULT_HEARTBEAT_IDLE_MS = 15e3;
9590
9996
  const DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS = 5e3;
9591
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
+ }
9592
10014
  /**
9593
10015
  * The ephemeral-identity trap: a coordinate with a persistent id whose
9594
10016
  * crypto identity lives in non-durable storage keys the peer's trust-on-first-use verify-key pin but
@@ -9606,6 +10028,33 @@ function warnOnEphemeralPinnedIdentity(callerName, coordinate, storage) {
9606
10028
  ephemeralIdentityWarned.add(pinKey);
9607
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.`);
9608
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
+ }
9609
10058
  /**
9610
10059
  * Assemble the connection facts a dial-out entry point shares — the one implementation of "how a
9611
10060
  * wire connection's mux, crypto identity, keepalive, and traffic tap are set up" (first-production
@@ -9624,8 +10073,9 @@ function assembleWireConnectionParts(options) {
9624
10073
  if (options.anySecure && link == null) {
9625
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.`);
9626
10075
  if (options.storage != null && options.ephemeralIdentity !== true) warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);
9627
- link = new ClientCryptoKeyLink(options.storage != null ? { storageAdapter: options.storage } : {});
10076
+ link = options.storage != null ? linkOverStorage(options.storage) : new ClientCryptoKeyLink();
9628
10077
  }
10078
+ if (options.reuseExchangeSessions === true) warnOnUnusableSessionReuse(options, link);
9629
10079
  const resolveHeartbeat = () => {
9630
10080
  if (heartbeat === false) return void 0;
9631
10081
  const explicit = heartbeat;
@@ -9645,6 +10095,12 @@ function assembleWireConnectionParts(options) {
9645
10095
  }
9646
10096
  //#endregion
9647
10097
  //#region ../nice-wire/src/Connect/exchangeEnvelope.ts
10098
+ /**
10099
+ * The `err` id an acceptor sends when it refused the session itself (expired, tampered or
10100
+ * wrong-key ticket, or an act at the wrong level) — before any lane ran, so the connector may
10101
+ * drop the session, handshake again and resend the same act.
10102
+ */
10103
+ const WIRE_EXCHANGE_SESSION_REFUSED = "session_refused";
9648
10104
  function encodeExchange(envelope) {
9649
10105
  return JSON.stringify(envelope);
9650
10106
  }
@@ -9673,33 +10129,261 @@ function hasEnvelopeKind(value) {
9673
10129
  return typeof value === "object" && value != null && "k" in value;
9674
10130
  }
9675
10131
  //#endregion
10132
+ //#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
10133
+ const SEALED_ENVELOPE_LENGTH = 2;
10134
+ function createExchangeTicketSealer(link, options = {}) {
10135
+ let keyPromise;
10136
+ const getKey = () => {
10137
+ if (keyPromise == null) keyPromise = link.deriveLocalSealKey({ version: options.version }).catch((err) => {
10138
+ keyPromise = void 0;
10139
+ throw err;
10140
+ });
10141
+ return keyPromise;
10142
+ };
10143
+ return {
10144
+ async seal(value, ttlMs) {
10145
+ const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({
10146
+ dataToEncrypt: pack({
10147
+ v: value,
10148
+ exp: Date.now() + ttlMs
10149
+ }),
10150
+ aesGcmKey: await getKey()
10151
+ });
10152
+ return bytesToBase64(pack([nonce, ciphertext]));
10153
+ },
10154
+ async open(blob) {
10155
+ try {
10156
+ const envelope = unpack(base64ToBytes(blob));
10157
+ if (!Array.isArray(envelope) || envelope.length !== SEALED_ENVELOPE_LENGTH) return void 0;
10158
+ const [nonce, ciphertext] = envelope;
10159
+ if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) return void 0;
10160
+ const payload = unpack(await decryptBytesWithAesGcmKey({
10161
+ dataToDecrypt: {
10162
+ nonce,
10163
+ ciphertext
10164
+ },
10165
+ aesGcmKey: await getKey()
10166
+ }));
10167
+ if (payload == null || typeof payload.exp !== "number" || payload.exp < Date.now()) return;
10168
+ return payload.v;
10169
+ } catch {
10170
+ return;
10171
+ }
10172
+ }
10173
+ };
10174
+ }
10175
+ //#endregion
10176
+ //#region ../nice-wire/src/Connect/exchangeSessionShelf.ts
10177
+ /** Lapse a little before the acceptor would, so a request is never sent on its last second. */
10178
+ function expiryFor(receivedAt, ttlMs) {
10179
+ if (ttlMs == null || !(ttlMs > 0)) return void 0;
10180
+ return receivedAt + ttlMs - Math.min(6e4, ttlMs / 10);
10181
+ }
10182
+ function stateFromRecord(link, record) {
10183
+ const crypto = record.km != null ? createActionFrameCrypto({
10184
+ link,
10185
+ keyMaterial: record.km
10186
+ }) : void 0;
10187
+ return {
10188
+ token: record.t,
10189
+ crypto,
10190
+ expiresAt: record.exp,
10191
+ record
10192
+ };
10193
+ }
10194
+ function isLapsed(state) {
10195
+ return state.expiresAt != null && Date.now() >= state.expiresAt;
10196
+ }
10197
+ /**
10198
+ * One session's lifecycle: at most one handshake in flight, shared by every caller; a refused or
10199
+ * lapsed session is replaced once, however many requests noticed it.
10200
+ */
10201
+ var ExchangeSessionSlot = class {
10202
+ _entry;
10203
+ current(initial, replacement) {
10204
+ const entry = this._entry;
10205
+ if (entry == null) return this._start(initial);
10206
+ if (entry.state != null && isLapsed(entry.state)) return this.renew(entry.state, replacement);
10207
+ return entry.promise;
10208
+ }
10209
+ renew(stale, replacement) {
10210
+ const entry = this._entry;
10211
+ if (entry != null && entry.state !== stale) return entry.promise;
10212
+ return this._start(replacement);
10213
+ }
10214
+ _start(establish) {
10215
+ const entry = { promise: establish() };
10216
+ this._entry = entry;
10217
+ entry.promise.then((state) => {
10218
+ entry.state = state;
10219
+ }, () => {
10220
+ if (this._entry === entry) this._entry = void 0;
10221
+ });
10222
+ return entry.promise;
10223
+ }
10224
+ };
10225
+ /** A session source for one transport alone — today's behaviour, plus renewal on refusal. */
10226
+ function privateSessionSource(handshake) {
10227
+ const slot = new ExchangeSessionSlot();
10228
+ return {
10229
+ current: () => slot.current(handshake, handshake),
10230
+ renew: (stale) => slot.renew(stale, handshake)
10231
+ };
10232
+ }
10233
+ const STORE_KEY = "sessions";
10234
+ const SEAL_VERSION = "connector-exchange-session/v1";
10235
+ /**
10236
+ * Every session one crypto identity holds with its peers, keyed by peer identity: shared in memory
10237
+ * by all of the link's transports, and kept in the link's own storage so a reload restores it.
10238
+ * Stored copies are sealed with a key derived from the link's private key — useless to another
10239
+ * device, and unopenable once the identity is reset.
10240
+ */
10241
+ var ExchangeSessionShelf = class {
10242
+ _link;
10243
+ _slots = /* @__PURE__ */ new Map();
10244
+ _storage;
10245
+ _sealer;
10246
+ constructor(_link) {
10247
+ this._link = _link;
10248
+ this._storage = _link.scopedStorage("wire-exchange/");
10249
+ this._sealer = createExchangeTicketSealer(_link, { version: SEAL_VERSION });
10250
+ }
10251
+ source(key, handshake) {
10252
+ let slot = this._slots.get(key);
10253
+ if (slot == null) {
10254
+ slot = new ExchangeSessionSlot();
10255
+ this._slots.set(key, slot);
10256
+ }
10257
+ const held = slot;
10258
+ const handshakeAndKeep = async () => {
10259
+ const state = await handshake();
10260
+ await this._keep(key, state).catch(() => void 0);
10261
+ return state;
10262
+ };
10263
+ const restoreOrHandshake = async () => {
10264
+ return await this._restore(key).catch(() => void 0) ?? await handshakeAndKeep();
10265
+ };
10266
+ const replace = async () => {
10267
+ await this._forget(key).catch(() => void 0);
10268
+ return await handshakeAndKeep();
10269
+ };
10270
+ return {
10271
+ current: () => held.current(restoreOrHandshake, replace),
10272
+ renew: (stale) => held.renew(stale, replace)
10273
+ };
10274
+ }
10275
+ async _restore(key) {
10276
+ const storage = this._storage;
10277
+ if (storage == null) return void 0;
10278
+ const stored = (await storage.getJson(STORE_KEY))?.[key];
10279
+ if (stored == null || stored.exp <= Date.now()) return void 0;
10280
+ await this._link.initialize();
10281
+ const record = await this._sealer.open(stored.sealed);
10282
+ if (record == null || typeof record.t !== "string") return void 0;
10283
+ return stateFromRecord(this._link, record);
10284
+ }
10285
+ async _keep(key, state) {
10286
+ const storage = this._storage;
10287
+ const record = state.record;
10288
+ if (storage == null || record?.exp == null) return;
10289
+ const ttl = record.exp - Date.now();
10290
+ if (ttl <= 0) return;
10291
+ const sealed = await this._sealer.seal(record, ttl);
10292
+ await this._update(storage, (sessions) => ({
10293
+ ...sessions,
10294
+ [key]: {
10295
+ exp: record.exp ?? 0,
10296
+ sealed
10297
+ }
10298
+ }));
10299
+ }
10300
+ async _forget(key) {
10301
+ const storage = this._storage;
10302
+ if (storage == null) return;
10303
+ await this._update(storage, (sessions) => {
10304
+ const { [key]: _dropped, ...rest } = sessions;
10305
+ return rest;
10306
+ });
10307
+ }
10308
+ async _update(storage, change) {
10309
+ await storage.updateJsonOrDef(STORE_KEY, {}, (current) => {
10310
+ const now = Date.now();
10311
+ const live = {};
10312
+ for (const [key, entry] of Object.entries(change(current))) if (entry.exp > now) live[key] = entry;
10313
+ return live;
10314
+ });
10315
+ }
10316
+ };
10317
+ const shelves = /* @__PURE__ */ new WeakMap();
10318
+ /**
10319
+ * The source a secure exchange draws its session from: shared by peer identity when the config asks
10320
+ * for reuse and names the peer, private to this transport otherwise.
10321
+ */
10322
+ function exchangeSessionSource(secure, lane, handshake) {
10323
+ const peer = secure.expectedPeer;
10324
+ if (secure.reuseExchangeSessions !== true || peer == null) return privateSessionSource(handshake);
10325
+ let shelf = shelves.get(secure.link);
10326
+ if (shelf == null) {
10327
+ shelf = new ExchangeSessionShelf(secure.link);
10328
+ shelves.set(secure.link, shelf);
10329
+ }
10330
+ const key = JSON.stringify([
10331
+ secure.localCoordinate.envId,
10332
+ secure.localCoordinate.perId ?? null,
10333
+ peer.envId,
10334
+ peer.perId ?? null,
10335
+ secure.securityLevel,
10336
+ lane.dictionaryVersion,
10337
+ [...lane.channels ?? []].sort()
10338
+ ]);
10339
+ return shelf.source(key, handshake);
10340
+ }
10341
+ //#endregion
9676
10342
  //#region ../nice-wire/src/Connect/exchangeSession.ts
9677
10343
  const textEncoder$1 = new TextEncoder();
9678
10344
  const textDecoder$1 = new TextDecoder();
10345
+ const PLAIN_STATE = {};
9679
10346
  /** Plain path (no handshake/token): every wire rides a bare `act` envelope, plaintext both ways. */
9680
10347
  function establishPlainExchangeSession(carrier) {
9681
- return makeSession(carrier, {});
10348
+ return makeSession(carrier, {
10349
+ current: async () => PLAIN_STATE,
10350
+ renew: async () => PLAIN_STATE
10351
+ });
9682
10352
  }
9683
10353
  /**
9684
- * Secure path: run the handshake (two exchanges) once at bring-up, then reuse the token + crypto.
9685
- * The lane supplies the handshake payload (`dictionaryVersion`/`channels`, E5 — emitted under the
9686
- * byte-frozen wire names; the version is signed into the challenge).
10354
+ * Secure path: run the handshake (two exchanges) at bring-up — or restore a kept session — then
10355
+ * reuse the token + crypto. The lane supplies the handshake payload (`dictionaryVersion`/`channels`,
10356
+ * E5 — emitted under the byte-frozen wire names; the version is signed into the challenge).
9687
10357
  */
9688
10358
  async function establishSecureExchangeSession(ctx) {
9689
- const state = await runConnectorExchangeHandshake(ctx.carrier, ctx.secure, ctx.lane);
9690
- return makeSession(ctx.carrier, state);
9691
- }
9692
- function makeSession(carrier, state) {
9693
- const runExchange = async (wire, opts) => {
9694
- const request = await buildRequestEnvelope(state, wire);
9695
- return carrier.exchange(encodeExchange(request), { signal: opts?.signal });
10359
+ const source = exchangeSessionSource(ctx.secure, ctx.lane, () => runConnectorExchangeHandshake(ctx.carrier, ctx.secure, ctx.lane));
10360
+ await source.current();
10361
+ return makeSession(ctx.carrier, source, ctx.secure.localCoordinate.insId);
10362
+ }
10363
+ function makeSession(carrier, source, insId) {
10364
+ const post = async (state, wire, signal) => {
10365
+ const request = await buildRequestEnvelope(state, wire, insId);
10366
+ return decodeExchangeReply(asString(await carrier.exchange(encodeExchange(request), { signal })));
10367
+ };
10368
+ const roundTrip = async (wire, signal) => {
10369
+ const state = await source.current();
10370
+ const reply = await post(state, wire, signal);
10371
+ if (reply?.k !== "err" || reply.id !== "session_refused" || state.token == null) return {
10372
+ state,
10373
+ reply
10374
+ };
10375
+ const renewed = await source.renew(state);
10376
+ return {
10377
+ state: renewed,
10378
+ reply: await post(renewed, wire, signal)
10379
+ };
9696
10380
  };
9697
10381
  return {
9698
10382
  send: async (wire, opts) => {
9699
- await runExchange(wire, opts);
10383
+ await roundTrip(wire, opts?.signal);
9700
10384
  },
9701
10385
  exchange: async (wire, opts) => {
9702
- const reply = decodeExchangeReply(asString(await runExchange(wire, opts)));
10386
+ const { state, reply } = await roundTrip(wire, opts?.signal);
9703
10387
  if (reply == null) return {
9704
10388
  ok: false,
9705
10389
  reason: "malformed_reply"
@@ -9721,18 +10405,21 @@ function makeSession(carrier, state) {
9721
10405
  }
9722
10406
  };
9723
10407
  }
9724
- async function buildRequestEnvelope(state, wire) {
10408
+ async function buildRequestEnvelope(state, wire, insId) {
10409
+ const i = state.token != null ? insId : void 0;
9725
10410
  if (state.crypto != null) {
9726
10411
  const ciphertext = await state.crypto.encryptFrame(textEncoder$1.encode(JSON.stringify(wire)));
9727
10412
  return {
9728
10413
  k: "act",
9729
10414
  t: state.token,
10415
+ i,
9730
10416
  c: bytesToBase64(ciphertext)
9731
10417
  };
9732
10418
  }
9733
10419
  return {
9734
10420
  k: "act",
9735
10421
  t: state.token,
10422
+ i,
9736
10423
  w: wire
9737
10424
  };
9738
10425
  }
@@ -9775,14 +10462,13 @@ async function runConnectorExchangeHandshake(carrier, secure, lane) {
9775
10462
  if (accept.t !== "accept") throw nonProtocolReply(carrier, "an accept frame", `hs/${accept.t}`);
9776
10463
  if (acceptReply.t == null) throw new Error(`[${HANDSHAKE_STAGE}] accept missing session token${at(carrier)}`);
9777
10464
  const result = await handshake.onAccept(accept);
9778
- const crypto = result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
9779
- link: secure.link,
9780
- keyMaterial: result.encryptionKeyMaterial
9781
- }) : void 0;
9782
- return {
9783
- token: acceptReply.t,
9784
- crypto
9785
- };
10465
+ const keyMaterial = result.securityLevel === "encrypted" ? result.encryptionKeyMaterial : void 0;
10466
+ return stateFromRecord(secure.link, {
10467
+ t: acceptReply.t,
10468
+ level: result.securityLevel,
10469
+ km: keyMaterial,
10470
+ exp: expiryFor(Date.now(), acceptReply.ttl)
10471
+ });
9786
10472
  }
9787
10473
  const HANDSHAKE_STAGE = "exchange-handshake";
9788
10474
  /**
@@ -10368,50 +11054,6 @@ var WireAcceptor = class {
10368
11054
  }
10369
11055
  };
10370
11056
  //#endregion
10371
- //#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
10372
- const SEALED_ENVELOPE_LENGTH = 2;
10373
- function createExchangeTicketSealer(link, options = {}) {
10374
- let keyPromise;
10375
- const getKey = () => {
10376
- if (keyPromise == null) keyPromise = link.deriveLocalSealKey({ version: options.version }).catch((err) => {
10377
- keyPromise = void 0;
10378
- throw err;
10379
- });
10380
- return keyPromise;
10381
- };
10382
- return {
10383
- async seal(value, ttlMs) {
10384
- const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({
10385
- dataToEncrypt: pack({
10386
- v: value,
10387
- exp: Date.now() + ttlMs
10388
- }),
10389
- aesGcmKey: await getKey()
10390
- });
10391
- return bytesToBase64(pack([nonce, ciphertext]));
10392
- },
10393
- async open(blob) {
10394
- try {
10395
- const envelope = unpack(base64ToBytes(blob));
10396
- if (!Array.isArray(envelope) || envelope.length !== SEALED_ENVELOPE_LENGTH) return void 0;
10397
- const [nonce, ciphertext] = envelope;
10398
- if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) return void 0;
10399
- const payload = unpack(await decryptBytesWithAesGcmKey({
10400
- dataToDecrypt: {
10401
- nonce,
10402
- ciphertext
10403
- },
10404
- aesGcmKey: await getKey()
10405
- }));
10406
- if (payload == null || typeof payload.exp !== "number" || payload.exp < Date.now()) return;
10407
- return payload.v;
10408
- } catch {
10409
- return;
10410
- }
10411
- }
10412
- };
10413
- }
10414
- //#endregion
10415
11057
  //#region ../nice-wire/src/Connect/WireExchangeAcceptor.ts
10416
11058
  /** The default session-ticket lifetime — see {@link IWireExchangeAcceptorOptions.sessionTtlMs}. */
10417
11059
  const DEFAULT_SESSION_TTL_MS = 720 * 60 * 1e3;
@@ -10481,11 +11123,17 @@ var WireExchangeAcceptor = class {
10481
11123
  m: encodeHandshakeMessage(reply)
10482
11124
  };
10483
11125
  const pending = handshake.exportPending();
10484
- if (pending == null) return {
11126
+ const dv = this._dictionaryVersion(message.channels);
11127
+ if (pending == null || dv == null) return {
10485
11128
  k: "err",
10486
11129
  message: "handshake produced no continuation state"
10487
11130
  };
10488
- const hsc = await this._sealer.seal(pending, HANDSHAKE_CONTINUATION_TTL_MS);
11131
+ const continuation = {
11132
+ ...pending,
11133
+ dv,
11134
+ ch: message.channels
11135
+ };
11136
+ const hsc = await this._sealer.seal(continuation, HANDSHAKE_CONTINUATION_TTL_MS);
10489
11137
  return {
10490
11138
  k: "hs",
10491
11139
  m: encodeHandshakeMessage(reply),
@@ -10497,11 +11145,12 @@ var WireExchangeAcceptor = class {
10497
11145
  k: "err",
10498
11146
  message: "prove missing continuation token"
10499
11147
  };
10500
- const pending = await this._sealer.open(request.hsc);
10501
- if (pending == null) return {
11148
+ const continuation = await this._sealer.open(request.hsc);
11149
+ if (continuation == null) return {
10502
11150
  k: "err",
10503
11151
  message: "invalid or expired continuation token"
10504
11152
  };
11153
+ const { dv, ch, ...pending } = continuation;
10505
11154
  const handshake = this._makeHandshake();
10506
11155
  await handshake.restorePending(pending);
10507
11156
  const reply = await handshake.onProve(message);
@@ -10510,13 +11159,16 @@ var WireExchangeAcceptor = class {
10510
11159
  const ticket = {
10511
11160
  client: result.remote,
10512
11161
  securityLevel: result.securityLevel,
10513
- keyMaterial: result.encryptionKeyMaterial
11162
+ keyMaterial: result.encryptionKeyMaterial,
11163
+ dv,
11164
+ ch
10514
11165
  };
10515
11166
  const t = await this._sealer.seal(ticket, this._sessionTtlMs);
10516
11167
  return {
10517
11168
  k: "hs",
10518
11169
  m: encodeHandshakeMessage(reply),
10519
- t
11170
+ t,
11171
+ ttl: this._sessionTtlMs
10520
11172
  };
10521
11173
  }
10522
11174
  return {
@@ -10529,6 +11181,10 @@ var WireExchangeAcceptor = class {
10529
11181
  message: `unexpected handshake message ${message.t}`
10530
11182
  };
10531
11183
  }
11184
+ _dictionaryVersion(channels) {
11185
+ const version = this._lane.dictionaryVersion;
11186
+ return typeof version === "function" ? version({ channels: channels == null ? void 0 : [...channels] }) : version;
11187
+ }
10532
11188
  async _handleAction(request) {
10533
11189
  let client;
10534
11190
  let crypto;
@@ -10536,24 +11192,30 @@ var WireExchangeAcceptor = class {
10536
11192
  let securityLevel = "none";
10537
11193
  if (request.t != null) {
10538
11194
  const ticket = await this._sealer.open(request.t);
10539
- if (ticket == null) return {
10540
- k: "err",
10541
- message: "unknown or expired session token"
10542
- };
10543
- client = new RuntimeCoordinate(ticket.client);
11195
+ if (ticket == null) return refused("unknown or expired session token");
11196
+ if (ticket.dv != null && ticket.dv !== this._dictionaryVersion(ticket.ch)) return refused("session was agreed under another dictionary version");
11197
+ client = new RuntimeCoordinate(typeof request.i === "string" ? {
11198
+ ...ticket.client,
11199
+ insId: request.i
11200
+ } : ticket.client);
10544
11201
  securityLevel = ticket.securityLevel;
10545
- crypto = ticket.securityLevel === "encrypted" && ticket.keyMaterial != null ? createActionFrameCrypto({
10546
- link: this._security.link,
10547
- keyMaterial: ticket.keyMaterial
10548
- }) : void 0;
10549
- if ("c" in request) {
10550
- if (crypto == null) return {
10551
- k: "err",
10552
- message: "session is not encrypted"
10553
- };
10554
- const plain = await crypto.decryptFrame(base64ToBytes(request.c));
10555
- wire = JSON.parse(textDecoder.decode(plain));
10556
- } else wire = request.w;
11202
+ if (ticket.securityLevel === "encrypted") {
11203
+ if (!("c" in request)) return refused("encrypted session refuses a plaintext act");
11204
+ if (ticket.keyMaterial == null) return refused("encrypted session has no key material");
11205
+ crypto = createActionFrameCrypto({
11206
+ link: this._security.link,
11207
+ keyMaterial: ticket.keyMaterial
11208
+ });
11209
+ try {
11210
+ const plain = await crypto.decryptFrame(base64ToBytes(request.c));
11211
+ wire = JSON.parse(textDecoder.decode(plain));
11212
+ } catch {
11213
+ return refused("undecryptable act");
11214
+ }
11215
+ } else {
11216
+ if ("c" in request) return refused("session is not encrypted");
11217
+ wire = request.w;
11218
+ }
10557
11219
  } else {
10558
11220
  if (!this._noneAllowed || "c" in request) return {
10559
11221
  k: "err",
@@ -10571,7 +11233,7 @@ var WireExchangeAcceptor = class {
10571
11233
  k: "err",
10572
11234
  message: laneReply.message
10573
11235
  };
10574
- if (crypto != null && "c" in request) return {
11236
+ if (crypto != null) return {
10575
11237
  k: "act",
10576
11238
  c: bytesToBase64(await crypto.encryptFrame(textEncoder.encode(JSON.stringify(laneReply.wire))))
10577
11239
  };
@@ -10587,6 +11249,13 @@ var WireExchangeAcceptor = class {
10587
11249
  });
10588
11250
  }
10589
11251
  };
11252
+ function refused(message) {
11253
+ return {
11254
+ k: "err",
11255
+ message,
11256
+ id: WIRE_EXCHANGE_SESSION_REFUSED
11257
+ };
11258
+ }
10590
11259
  //#endregion
10591
11260
  //#region ../nice-wire/src/codec/controlFrame.ts
10592
11261
  /** msgpack map (object) first-byte prefixes — fixmap `0x80–0x8f`, map16 `0xde`, map32 `0xdf`. */
@@ -11331,7 +12000,7 @@ var ActionCore = class extends ActionBase {
11331
12000
  * undeclared `NiceError`s) returns `false`.
11332
12001
  */
11333
12002
  isExpectedError(error) {
11334
- return error instanceof NiceError && this.schema.isExpectedError(error);
12003
+ return isNiceError(error) && this.schema.isExpectedError(error);
11335
12004
  }
11336
12005
  toJsonObject() {
11337
12006
  return {
@@ -14950,12 +15619,29 @@ var ActionLocalHandler = class extends ActionHandler {
14950
15619
  if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) return this.actionRouter.domainManager.getActionDomainOrThrow(state.request).hydrateResultPayload(rawResult);
14951
15620
  return state.request.successResult(rawResult);
14952
15621
  });
14953
- 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
+ }
14954
15629
  runningAction._completeWithResult(result);
14955
15630
  } finally {
14956
15631
  popHandlerCuid();
14957
15632
  }
14958
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
+ }
14959
15645
  async handlePayloadWireOrThrow(wire, config) {
14960
15646
  const hydratedAction = this.actionRouter.domainManager.hydrateActionPayload(wire);
14961
15647
  if (!(hydratedAction instanceof ActionPayload_Request)) throw err_nice_action.fromId("wire_action_not_payload", {
@@ -16696,6 +17382,7 @@ var ExchangeTransport = class ExchangeTransport extends Transport {
16696
17382
  return new ExchangeConnection({ initialize: () => ({
16697
17383
  getCacheKey: options.getCacheKey,
16698
17384
  isAvailable: options.available,
17385
+ requiresWebCrypto: options.security != null && options.security.securityLevel !== "none",
16699
17386
  getTransport: (input) => {
16700
17387
  assertProtocolsRideDuplex(options);
16701
17388
  const carrier = options.openCarrier(input);
@@ -16940,6 +17627,7 @@ var LinkTransport = class LinkTransport extends Transport {
16940
17627
  return new LinkConnection({ initialize: () => ({
16941
17628
  getCacheKey: options.getCacheKey,
16942
17629
  isAvailable: options.available,
17630
+ requiresWebCrypto: options.security != null && options.security.securityLevel !== "none",
16943
17631
  getTransport: (input) => ({
16944
17632
  status: "ready",
16945
17633
  readyData: {
@@ -16980,6 +17668,7 @@ function transport(options) {
16980
17668
  link,
16981
17669
  localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),
16982
17670
  expectedPeer: options.expectedPeer?.toJsonObject(),
17671
+ reuseExchangeSessions: options.reuseExchangeSessions,
16983
17672
  dictionaryVersion: channel.dictionaryVersion,
16984
17673
  channelTags: channel.tags,
16985
17674
  mux: options.mux
@@ -17131,6 +17820,8 @@ function connectChannel(runtime, channel, options) {
17131
17820
  storage: options.storage,
17132
17821
  link: options.link,
17133
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"),
17134
17825
  reconnect: options.reconnect,
17135
17826
  heartbeat: options.heartbeat,
17136
17827
  keepLinkAlive: options.keepLinkAlive,
@@ -17147,6 +17838,7 @@ function connectChannel(runtime, channel, options) {
17147
17838
  secure: descriptor.secure ?? true,
17148
17839
  link,
17149
17840
  securityLevel: descriptor.securityLevel ?? securityLevel,
17841
+ reuseExchangeSessions: options.reuseExchangeSessions,
17150
17842
  available: descriptor.available,
17151
17843
  label: descriptor.label,
17152
17844
  mux: wireMux,
@@ -17393,7 +18085,7 @@ function createActionFetchHandler(runtime, options = {}) {
17393
18085
  securityLevel: "none"
17394
18086
  });
17395
18087
  } catch (error) {
17396
- 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")) {
17397
18089
  report?.({
17398
18090
  ok: false,
17399
18091
  returnedVia: transportLabel,
@@ -24551,30 +25243,6 @@ async function ensureStateDir(paths) {
24551
25243
  });
24552
25244
  }
24553
25245
  //#endregion
24554
- //#region src/daemon/packageVersion.ts
24555
- let cached = null;
24556
- /**
24557
- * Resolved relative to the BUILT module, so the candidate list must cover every layout this
24558
- * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that
24559
- * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).
24560
- */
24561
- async function commanderPackageVersion() {
24562
- if (cached != null) return cached;
24563
- for (const candidate of [
24564
- new URL("../package.json", require("url").pathToFileURL(__filename).href),
24565
- new URL("../../package.json", require("url").pathToFileURL(__filename).href),
24566
- new URL("../../../package.json", require("url").pathToFileURL(__filename).href)
24567
- ]) try {
24568
- const parsed = JSON.parse(await (0, node_fs_promises.readFile)(candidate, "utf8"));
24569
- if (typeof parsed.version === "string" && parsed.name === "@nice-code/commander") {
24570
- cached = parsed.version;
24571
- return cached;
24572
- }
24573
- } catch {}
24574
- cached = "0.0.0";
24575
- return cached;
24576
- }
24577
- //#endregion
24578
25246
  //#region src/daemon/runtime.ts
24579
25247
  /** Check before advertising a daemon whose HTTP works but whose wire handshake cannot run. */
24580
25248
  function commanderRuntimeError() {
@@ -25223,6 +25891,11 @@ function checkReloadResult(value) {
25223
25891
  errors
25224
25892
  };
25225
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
+ }
25226
25899
  const OUTCOMES = new Set([
25227
25900
  "ready",
25228
25901
  "spawned",
@@ -25459,6 +26132,11 @@ async function connectDaemon(handle) {
25459
26132
  const request = commanderControlDomain.actionForId("noteRuns").request(input);
25460
26133
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "noteRuns" rejected by the daemon`);
25461
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
+ },
25462
26140
  shutdown: async () => {
25463
26141
  const request = commanderControlDomain.actionForId("shutdown").request({});
25464
26142
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "shutdown" rejected by the daemon`);
@@ -25560,9 +26238,11 @@ function printReport(out, report, state) {
25560
26238
  else {
25561
26239
  for (const result of report.results) {
25562
26240
  if (NARRATED.has(result.outcome)) continue;
26241
+ const node = state.processes[result.id];
25563
26242
  const note = result.reason != null ? ` — ${result.reason}` : "";
25564
- const reach = result.outcome === "already-running" ? reachLine(out, state.processes[result.id]) : "";
26243
+ const reach = result.outcome === "already-running" ? reachLine(out, node) : "";
25565
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`));
25566
26246
  }
25567
26247
  for (const warning of report.warnings) out.warn(`${out.paint("yellow", "⚠")} ${warning}`);
25568
26248
  }
@@ -25597,6 +26277,7 @@ async function cmdUp(ctx) {
25597
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`));
25598
26278
  const client = await connectDaemon(handle);
25599
26279
  try {
26280
+ await syncDaemonConfig(ctx.config, client, ctx.out);
25600
26281
  const wait = !ctx.args.flags.has("--no-wait");
25601
26282
  const staggerMs = staggerFor(ctx.config, ctx.args.positionals);
25602
26283
  const replaceSame = ctx.args.flags.has("--replace-same");
@@ -25619,12 +26300,18 @@ async function controlVerb(ctx, verb) {
25619
26300
  "--with",
25620
26301
  "--all",
25621
26302
  "--any"
25622
- ] : ["--all", "--any"];
26303
+ ] : [
26304
+ "--only",
26305
+ "--all",
26306
+ "--any"
26307
+ ];
25623
26308
  const bad = unknownFlags(ctx.args.flags, known);
25624
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");
25625
26311
  requireSelectionTerms(ctx);
25626
26312
  const client = await connectDaemon(await requireDaemon(ctx.config));
25627
26313
  try {
26314
+ if (verb === "restart") await syncDaemonConfig(ctx.config, client, ctx.out);
25628
26315
  const declared = new Set(ctx.config.processes.map((proc) => proc.id));
25629
26316
  const selection = selectOrExit(ctx, {
25630
26317
  bare: "required",
@@ -25632,8 +26319,11 @@ async function controlVerb(ctx, verb) {
25632
26319
  });
25633
26320
  const replaceSame = ctx.args.flags.has("--replace-same");
25634
26321
  const flags = verb === "restart" ? flagsOrExit(ctx) : null;
25635
- const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", { ids: selection.ordered }) : client.control("restart", {
25636
- 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,
25637
26327
  wait: !ctx.args.flags.has("--no-wait"),
25638
26328
  staggerMs: staggerFor(ctx.config, ctx.args.positionals),
25639
26329
  ...replaceSame ? { replaceSame } : {},
@@ -26190,6 +26880,50 @@ function createPortInspector(options) {
26190
26880
  return { run };
26191
26881
  }
26192
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
26193
26927
  //#region src/cli/commands/ports.ts
26194
26928
  async function portProcessStates(ctx) {
26195
26929
  const handle = await findDaemon(ctx.config);
@@ -26439,8 +27173,10 @@ async function diagnose(ctx, handle) {
26439
27173
  const overrideCount = countOverrides(overrides);
26440
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)`);
26441
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);
26442
27177
  for (const proc of config.processes) {
26443
- 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`);
26444
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`);
26445
27181
  }
26446
27182
  const capability = (0, _nice_code_process.detectCapability)();
@@ -26606,11 +27342,11 @@ function parseNames(values) {
26606
27342
  for (const entry of values) if (entry.includes("=")) return { error: `--unset expects a NAME, got ${JSON.stringify(entry)}` };
26607
27343
  return [...values];
26608
27344
  }
26609
- function describeValue(view) {
27345
+ function describeValue(view, judgedIn) {
26610
27346
  if (view.secret) return view.source === "unset" ? "-" : "••••••";
26611
- return view.value ?? (view.source === "inherited" ? "(the daemon's env)" : "-");
27347
+ return view.value ?? (view.source === "inherited" ? `(${describeJudgedIn(judgedIn)})` : "-");
26612
27348
  }
26613
- function renderProcess(out, definition, views) {
27349
+ function renderProcess(out, definition, views, judgedIn) {
26614
27350
  out.print(out.paint("bold", definition.id));
26615
27351
  if (views.length === 0) {
26616
27352
  out.print(out.paint("gray", " declares no env vars — add `envVars` to the config to tune it"));
@@ -26623,7 +27359,7 @@ function renderProcess(out, definition, views) {
26623
27359
  "NOTES"
26624
27360
  ], views.map((view) => [
26625
27361
  ` ${view.name}`,
26626
- describeValue(view),
27362
+ describeValue(view, judgedIn),
26627
27363
  view.source,
26628
27364
  [
26629
27365
  view.description,
@@ -26649,8 +27385,15 @@ async function cmdEnv(ctx) {
26649
27385
  const { out, config } = ctx;
26650
27386
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
26651
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);
26652
- const handle = mutating ? await findDaemon(config) : null;
26653
- 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
+ }
26654
27397
  try {
26655
27398
  const result = mutating ? await mutate(ctx, paths.envOverridesPath, client, {
26656
27399
  processes: Object.fromEntries(definitions.map((definition) => [definition.id, {
@@ -26662,11 +27405,13 @@ async function cmdEnv(ctx) {
26662
27405
  overrides: await readEnvOverrides(paths.envOverridesPath),
26663
27406
  warnings: []
26664
27407
  };
26665
- 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))]));
26666
27410
  const stale = staleOverrides(config, result.overrides);
26667
27411
  if (out.json) {
26668
27412
  out.printJson({
26669
27413
  overridesPath: paths.envOverridesPath,
27414
+ judgedAgainst: judge.judgedIn,
26670
27415
  processes: definitions.map((definition) => ({
26671
27416
  id: definition.id,
26672
27417
  envVars: views.get(definition.id) ?? []
@@ -26677,9 +27422,10 @@ async function cmdEnv(ctx) {
26677
27422
  return result.warnings.length > 0 ? EXIT.failure : EXIT.ok;
26678
27423
  }
26679
27424
  for (const definition of definitions) {
26680
- renderProcess(out, definition, views.get(definition.id) ?? []);
27425
+ renderProcess(out, definition, views.get(definition.id) ?? [], judge.judgedIn);
26681
27426
  out.print();
26682
27427
  }
27428
+ if ([...views.values()].some((listed) => listed.length > 0)) out.print(out.paint("gray", judge.note));
26683
27429
  const total = countOverrides(result.overrides);
26684
27430
  if (total > 0) out.print(out.paint("gray", `${total} sticky override(s) — they apply to every start until \`nice-commander env <sel> --clear\`.`));
26685
27431
  if (client != null) {
@@ -26805,16 +27551,18 @@ async function cmdExplain(ctx) {
26805
27551
  return EXIT.ok;
26806
27552
  }
26807
27553
  const overrides = await readEnvOverrides(commanderStatePaths(resolveCommanderDataDir(), ctx.config.configKey).envOverridesPath);
27554
+ const judge = await judgeEnv(ctx.config);
26808
27555
  out.print("env:");
26809
27556
  out.print(" note: `run` children inherit THIS shell's environment; daemon-owned starts (`up`) inherit");
26810
27557
  out.print(" the daemon's boot-time snapshot — `doctor` shows that snapshot's age.");
27558
+ out.print(` ${judge.note}`);
26811
27559
  for (const id of selection.ordered) {
26812
27560
  const def = ctx.config.processes.find((proc) => proc.id === id);
26813
27561
  if (def == null) continue;
26814
27562
  const parts = [];
26815
27563
  for (const [key, value] of Object.entries(def.env)) parts.push(value == null ? `${key}=(unset)` : `${key}=${value} (config)`);
26816
- for (const view of envVarViews(def, overrides, process.env)) {
26817
- 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)");
26818
27566
  parts.push(`${view.name}=${shown} (${view.source}${view.source === "override" ? ", sticky" : ""})`);
26819
27567
  }
26820
27568
  if (parts.length > 0) out.print(` ${id}: ${parts.join(" ")}`);
@@ -27315,6 +28063,11 @@ async function cmdRun(ctx) {
27315
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."));
27316
28064
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
27317
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")}`);
27318
28071
  const ledger = (0, _nice_code_process.openProcessLedger)({
27319
28072
  dir: paths.stateDir,
27320
28073
  namespace: paths.ledgerNamespace,
@@ -27324,6 +28077,7 @@ async function cmdRun(ctx) {
27324
28077
  if (handle != null) {
27325
28078
  const client = await connectDaemon(handle);
27326
28079
  try {
28080
+ await syncDaemonConfig(config, client, out);
27327
28081
  const owned = defs.filter((def) => ACTIVE_STATES$1.has(client.state().processes[def.id]?.state ?? ""));
27328
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).`);
27329
28083
  } finally {
@@ -27411,7 +28165,7 @@ async function cmdRun(ctx) {
27411
28165
  });
27412
28166
  let timer = null;
27413
28167
  let timedOut = false;
27414
- let run = null;
28168
+ let run;
27415
28169
  try {
27416
28170
  await proc.start();
27417
28171
  run = noteStart(def);
@@ -27443,7 +28197,7 @@ async function cmdRun(ctx) {
27443
28197
  }
27444
28198
  const code = proc.lastExit?.code ?? (proc.state === "succeeded" ? 0 : 1);
27445
28199
  const failed = code !== 0;
27446
- 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;
27447
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`);
27448
28202
  return {
27449
28203
  id: def.id,
@@ -27963,10 +28717,15 @@ const COMMAND_HELP = [
27963
28717
  command in the same cwd, started outside the daemon
27964
28718
  (a stranger on the port still refuses). --json reports
27965
28719
  every id's outcome, state, pid and endpoints as data.`],
27966
- ["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.`],
27967
28724
  ["restart", ` restart <sel> [--no-wait] [--replace-same] [--with <flag>]
27968
- stop + start, with the flags of the run it replaces
27969
- 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.`],
27970
28729
  ["status", " status [--watch] table from the live status realm"],
27971
28730
  ["logs", " logs <sel> [-f] merged interleaved tail with colored id prefixes"],
27972
28731
  ["list", " list config introspection (processes, suites, warnings)"],
@@ -28070,7 +28829,7 @@ async function withTimeout(ctx, run) {
28070
28829
  async function main() {
28071
28830
  const argv = process.argv.slice(2);
28072
28831
  if (argv[0] === "daemon") {
28073
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-C3BG9bju.cjs"));
28832
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-CcxTP9yh.cjs"));
28074
28833
  return runCommanderDaemon(argv.slice(1));
28075
28834
  }
28076
28835
  const parsed = parseCliArgs(argv);
@@ -28126,6 +28885,7 @@ exports.COMMANDER_SHUTDOWN_PATH = COMMANDER_SHUTDOWN_PATH;
28126
28885
  exports.COMMANDER_TICKET_PATH = COMMANDER_TICKET_PATH;
28127
28886
  exports.COMMANDER_TICKET_PROTOCOL_PREFIX = COMMANDER_TICKET_PROTOCOL_PREFIX;
28128
28887
  exports.COMMANDER_WS_PATH = COMMANDER_WS_PATH;
28888
+ exports.CommanderConfigLoadError = CommanderConfigLoadError;
28129
28889
  exports.RuntimeCoordinate = RuntimeCoordinate;
28130
28890
  exports.ancestors = ancestors;
28131
28891
  exports.applyEnvMutation = applyEnvMutation;
@@ -28151,6 +28911,7 @@ exports.hashCanonical = hashCanonical;
28151
28911
  exports.httpAcceptorCarrier = httpAcceptorCarrier;
28152
28912
  exports.identifyEndpointOwner = identifyEndpointOwner;
28153
28913
  exports.loadCommanderConfigFile = loadCommanderConfigFile;
28914
+ exports.missingRequired = missingRequired;
28154
28915
  exports.mutateSavedFilters = mutateSavedFilters;
28155
28916
  exports.orderByDependency = orderByDependency;
28156
28917
  exports.overrideFingerprint = overrideFingerprint;
@@ -28162,6 +28923,7 @@ exports.readSavedFilters = readSavedFilters;
28162
28923
  exports.readTaskDurations = readTaskDurations;
28163
28924
  exports.recordDaemonAlive = recordDaemonAlive;
28164
28925
  exports.removeInstanceRecord = removeInstanceRecord;
28926
+ exports.requiredRefusal = requiredRefusal;
28165
28927
  exports.resolveCommanderDataDir = resolveCommanderDataDir;
28166
28928
  exports.resolveFlags = resolveFlags;
28167
28929
  exports.runTaskPool = runTaskPool;