@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.mjs CHANGED
@@ -308,6 +308,53 @@ async function pingDaemon(record, timeoutMs = 2e3) {
308
308
  }
309
309
  }
310
310
  //#endregion
311
+ //#region src/daemon/packageVersion.ts
312
+ let cached = null;
313
+ /**
314
+ * Resolved relative to the BUILT module, so the candidate list must cover every layout this
315
+ * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that
316
+ * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).
317
+ */
318
+ async function commanderPackageVersion() {
319
+ if (cached != null) return cached;
320
+ for (const candidate of [
321
+ new URL("../package.json", import.meta.url),
322
+ new URL("../../package.json", import.meta.url),
323
+ new URL("../../../package.json", import.meta.url)
324
+ ]) try {
325
+ const parsed = JSON.parse(await readFile(candidate, "utf8"));
326
+ if (typeof parsed.version === "string" && parsed.name === "@nice-code/commander") {
327
+ cached = parsed.version;
328
+ return cached;
329
+ }
330
+ } catch {}
331
+ cached = "0.0.0";
332
+ return cached;
333
+ }
334
+ //#endregion
335
+ //#region src/cli/configSync.ts
336
+ /**
337
+ * Bring the daemon onto `config`'s revision before acting on it. Never fails the command: when
338
+ * the daemon ends up on another revision the start still happens, on the daemon's reading, and
339
+ * the difference is said on stderr.
340
+ */
341
+ async function syncDaemonConfig(config, client, out) {
342
+ if (client.state().configRevisionHash === config.configRevisionHash) return;
343
+ const result = await client.reloadConfig();
344
+ if (result?.configRevisionHash === config.configRevisionHash) return;
345
+ const note = (text) => out.warn(`${out.paint("yellow", "⚠")} ${text}`);
346
+ if (result == null) {
347
+ note("the daemon could not be asked to reload the config — what starts may be on the revision it loaded earlier (`nice-commander shutdown`, then `up`, starts one on this build)");
348
+ return;
349
+ }
350
+ if (!result.applied) {
351
+ note("the daemon kept its last good config — the one on disk did not load there:\n" + result.errors.map((line) => ` - ${line}`).join("\n"));
352
+ return;
353
+ }
354
+ const build = await commanderPackageVersion();
355
+ note(`the daemon reads this config differently from this shell (${client.record.packageVersion === build ? "a value the config computes from the environment, or a plain .mjs/.js helper, stays as the daemon first read it" : `it runs build ${client.record.packageVersion}, this CLI is build ${build}`}) — what starts is the daemon's reading. \`nice-commander shutdown\`, then \`up\`, rebuilds it from here.`);
356
+ }
357
+ //#endregion
311
358
  //#region src/config/flags.ts
312
359
  /**
313
360
  * An argument a shell-string `run` can take appended unquoted in sh, cmd and PowerShell alike.
@@ -606,13 +653,30 @@ function aliasFromNearestTsconfig(configDir) {
606
653
  dir = parent;
607
654
  }
608
655
  }
609
- /** One fresh loader context per load attempt — the reload model depends on it (D2). */
610
- function freshLoader(configPath) {
611
- return createJiti(pathToFileURL(configPath).href, {
656
+ /**
657
+ * One fresh loader context per load attempt — the reload model depends on it (D2).
658
+ *
659
+ * Every file jiti transforms is added to `transformed`. With the caches off that is every module
660
+ * the load reads from source — which is also exactly the set a later load would read afresh, so
661
+ * it is the set worth watching. A module handed to the runtime's own `import()` (a plain `.mjs`
662
+ * helper) is not in it, and would not reload if it were.
663
+ */
664
+ function freshLoader(configPath, transformed) {
665
+ const url = pathToFileURL(configPath).href;
666
+ const options = {
612
667
  moduleCache: false,
613
668
  fsCache: false,
614
669
  tryNative: false,
615
670
  alias: aliasFromNearestTsconfig(dirname(configPath))
671
+ };
672
+ const transform = createJiti(url, options).options.transform;
673
+ if (transform == null) return createJiti(url, options);
674
+ return createJiti(url, {
675
+ ...options,
676
+ transform: (input) => {
677
+ if (input.filename != null) transformed.add(resolve(input.filename));
678
+ return transform(input);
679
+ }
616
680
  });
617
681
  }
618
682
  /** Extensions jiti hands straight to the runtime's own ESM loader instead of transforming. */
@@ -630,8 +694,8 @@ const NATIVE_ESM = /\.(mjs|js)$/;
630
694
  * `forceTranspile` puts `.mjs` on that same transformed path. Passing `filename` keeps relative
631
695
  * imports and `import.meta` resolving exactly as a native import would.
632
696
  */
633
- async function importFresh(configPath) {
634
- const loader = freshLoader(configPath);
697
+ async function importFresh(configPath, transformed) {
698
+ const loader = freshLoader(configPath, transformed);
635
699
  if (!NATIVE_ESM.test(configPath)) return loader.import(configPath);
636
700
  return loader.evalModule(readFileSync(configPath, "utf8"), {
637
701
  filename: configPath,
@@ -640,6 +704,19 @@ async function importFresh(configPath) {
640
704
  async: true
641
705
  });
642
706
  }
707
+ /** A config that could not be loaded. Still says which modules the attempt reached. */
708
+ var CommanderConfigLoadError = class extends Error {
709
+ loadedFiles;
710
+ constructor(message, loadedFiles, cause) {
711
+ super(message, { cause });
712
+ this.name = "CommanderConfigLoadError";
713
+ this.loadedFiles = loadedFiles;
714
+ }
715
+ };
716
+ const IN_NODE_MODULES = /[\\/]node_modules[\\/]/;
717
+ function localModules(transformed, configPath) {
718
+ return [...transformed].filter((file) => file !== configPath && !IN_NODE_MODULES.test(file));
719
+ }
643
720
  /**
644
721
  * Load a config file's default export. Throws an Error naming the file on parse/load failure —
645
722
  * the daemon's reload path catches this and keeps the last-good model.
@@ -648,17 +725,19 @@ async function loadCommanderConfigFile(path) {
648
725
  const explicit = isAbsolute(path) ? path : resolve(path);
649
726
  if (!existsSync(explicit)) throw new Error(`commander config not found: ${explicit}`);
650
727
  const configPath = realpathSync(explicit);
728
+ const transformed = /* @__PURE__ */ new Set();
651
729
  let mod;
652
730
  try {
653
- mod = await importFresh(configPath);
731
+ mod = await importFresh(configPath, transformed);
654
732
  } catch (error) {
655
- throw new Error(`failed to load ${configPath}: ${error.message}`, { cause: error });
733
+ throw new CommanderConfigLoadError(`failed to load ${configPath}: ${error instanceof Error ? error.message : String(error)}`, localModules(transformed, configPath), error);
656
734
  }
657
735
  if (mod == null || typeof mod !== "object" || !("default" in mod)) throw new Error(`${configPath}: expected a default export`);
658
736
  return {
659
737
  configPath,
660
738
  configDir: dirname(configPath),
661
- raw: mod.default
739
+ raw: mod.default,
740
+ loadedFiles: localModules(transformed, configPath)
662
741
  };
663
742
  }
664
743
  //#endregion
@@ -735,6 +814,18 @@ function envVarViews(definition, overrides, baseEnv) {
735
814
  function missingRequired(definition, overrides, baseEnv) {
736
815
  return envVarViews(definition, overrides, baseEnv).filter((view) => view.required && view.source === "unset").map((view) => view.name);
737
816
  }
817
+ const JUDGED_IN = {
818
+ daemon: "the daemon's environment",
819
+ shell: "this shell's environment"
820
+ };
821
+ /** "the daemon's environment" / "this shell's environment". */
822
+ function describeJudgedIn(judgedIn) {
823
+ return JUDGED_IN[judgedIn];
824
+ }
825
+ /** Why a start is refused over `required` variables, with the command that supplies one. */
826
+ function requiredRefusal(id, missing, judgedIn) {
827
+ return `requires ${missing.join(", ")} — no default, no override, and not set in ${JUDGED_IN[judgedIn]}; \`nice-commander env ${id} --set ${missing[0]}=…\` supplies it`;
828
+ }
738
829
  /**
739
830
  * Keep only what the config can justify. Setting a value requires a DECLARED variable on a known
740
831
  * process — that filter is what makes the UI's write path safe. Removing is always allowed, even
@@ -1532,6 +1623,9 @@ function jsErrorOrCastJsError(error, logMessage = true) {
1532
1623
  };
1533
1624
  }
1534
1625
  //#endregion
1626
+ //#region ../nice-error/package.json
1627
+ var version = "0.113.0";
1628
+ //#endregion
1535
1629
  //#region ../nice-error/src/utils/logger.ts
1536
1630
  let activeLogger = {
1537
1631
  warn: (message, meta) => meta !== void 0 ? console.warn(message, meta) : console.warn(message),
@@ -1543,6 +1637,41 @@ function getNiceErrorLogger() {
1543
1637
  return activeLogger;
1544
1638
  }
1545
1639
  //#endregion
1640
+ //#region ../nice-error/src/utils/loadedVersions.ts
1641
+ /** This package's version, read from its manifest when the package is built. */
1642
+ const NICE_ERROR_VERSION = version;
1643
+ const LOADED_VERSIONS_KEY = Symbol.for("@nice-code/error/versions");
1644
+ const LOCKSTEP_RULE = "Every @nice-code/* package must be on the same version (the lockstep rule): an error built by one copy of @nice-code/error fails `instanceof NiceError` in another. `nice-code-lockstep`, shipped in @nice-code/util, lists the versions installed.";
1645
+ /**
1646
+ * Records `version` as loaded in `scope`, and warns when a different version of this package
1647
+ * is already there. Runs when the package loads, so it must never throw.
1648
+ */
1649
+ function registerLoadedVersion(version, scope = globalThis, warn = (message) => console.warn(message)) {
1650
+ try {
1651
+ const loaded = Reflect.get(scope, LOADED_VERSIONS_KEY);
1652
+ if (loaded === void 0) {
1653
+ Reflect.set(scope, LOADED_VERSIONS_KEY, [version]);
1654
+ return;
1655
+ }
1656
+ if (!Array.isArray(loaded) || loaded.includes(version)) return;
1657
+ const others = loaded.filter((other) => typeof other === "string");
1658
+ loaded.push(version);
1659
+ warn(`[@nice-code/error] Version ${version} was loaded beside ${others.join(", ")}. ${LOCKSTEP_RULE}`);
1660
+ } catch {}
1661
+ }
1662
+ let warnedOfUnversionedCopy = false;
1663
+ /**
1664
+ * Warns, once, that an error arrived from a copy of this package that carries no brand: one
1665
+ * released before copies recorded their version, which {@link registerLoadedVersion} cannot see.
1666
+ */
1667
+ function warnOfUnversionedCopy() {
1668
+ if (warnedOfUnversionedCopy) return;
1669
+ warnedOfUnversionedCopy = true;
1670
+ try {
1671
+ getNiceErrorLogger().warn(`[@nice-code/error] Version ${NICE_ERROR_VERSION} received an error built by an older copy of this package, one too old to report its version. ${LOCKSTEP_RULE}`);
1672
+ } catch {}
1673
+ }
1674
+ //#endregion
1546
1675
  //#region ../nice-error/src/NiceError/nice_error.static.ts
1547
1676
  const DUR_OBJ_PACK_PREFIX = "NE_DUROBJ[[";
1548
1677
  const DUR_OBJ_PACK_SUFFIX = "]]NE_DUROBJ";
@@ -1623,6 +1752,7 @@ function serializeErrorCause(value, depth = DEFAULT_CAUSE_DEPTH) {
1623
1752
  }
1624
1753
  //#endregion
1625
1754
  //#region ../nice-error/src/NiceError/NiceError.ts
1755
+ const NICE_ERROR_BRAND = Symbol.for("@nice-code/error");
1626
1756
  var NiceError = class extends Error {
1627
1757
  name = "NiceError";
1628
1758
  def;
@@ -1642,7 +1772,7 @@ var NiceError = class extends Error {
1642
1772
  this.cleanMessage = messagePure;
1643
1773
  this.def = options.def;
1644
1774
  this.ids = options.ids;
1645
- this._errorDataMap = options.errorData;
1775
+ this._errorDataMap = options.errorData ?? {};
1646
1776
  this.httpStatusCode = options.httpStatusCode ?? 500;
1647
1777
  if (options.originError != null) this.originError = options.originError;
1648
1778
  this.timeCreated = options.timeCreated ?? Date.now();
@@ -1902,6 +2032,19 @@ var NiceError = class extends Error {
1902
2032
  return this;
1903
2033
  }
1904
2034
  };
2035
+ Object.defineProperty(NiceError.prototype, NICE_ERROR_BRAND, { value: true });
2036
+ registerLoadedVersion(NICE_ERROR_VERSION);
2037
+ /**
2038
+ * Returns `true` if `value` is a `NiceError` built by any loaded copy of `@nice-code/error`.
2039
+ *
2040
+ * `instanceof NiceError` knows only this copy's class. When an install holds two copies of the
2041
+ * package, an error from the other one fails `instanceof` and passes this — so prefer it
2042
+ * wherever the question is "is this a NiceError?". To use such an error as this copy's own,
2043
+ * pass it through `castNiceError`.
2044
+ */
2045
+ function isNiceError(value) {
2046
+ return typeof value === "object" && value != null && Reflect.get(value, NICE_ERROR_BRAND) === true;
2047
+ }
1905
2048
  //#endregion
1906
2049
  //#region ../nice-error/src/NiceError/NiceErrorHydrated.ts
1907
2050
  var NiceErrorHydrated = class NiceErrorHydrated extends NiceError {
@@ -1979,6 +2122,69 @@ function emitNiceError(error) {
1979
2122
  } catch {}
1980
2123
  }
1981
2124
  //#endregion
2125
+ //#region ../nice-error/src/utils/isNiceErrorObject.ts
2126
+ /**
2127
+ * Returns `true` if `obj` is a JSON-serialised `NiceError` object matching the
2128
+ * current wire format (contextState-based errorData entries).
2129
+ *
2130
+ * Validates:
2131
+ * - Top-level shape (`name`, `message`, `isUnhandled`, `httpStatusCode`, `ids`, `def`)
2132
+ * - Each `errorData` entry has a `contextState` with a valid `kind` discriminant
2133
+ * (`"no_serialization"` or `"unhydrated"`) — rejecting payloads in the old
2134
+ * format (`context` / `serialized` fields) to prevent silent data corruption.
2135
+ */
2136
+ function isNiceErrorObject(obj) {
2137
+ if (typeof obj !== "object" || obj == null) return false;
2138
+ const o = obj;
2139
+ if (o["name"] !== "NiceError" || typeof o["message"] !== "string" || typeof o["isUnhandled"] !== "boolean" || typeof o["httpStatusCode"] !== "number") return false;
2140
+ const ids = o["ids"];
2141
+ if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) return false;
2142
+ const def = o["def"];
2143
+ if (typeof def !== "object" || def == null) return false;
2144
+ const d = def;
2145
+ if (typeof d["domain"] !== "string" || !Array.isArray(d["allDomains"])) return false;
2146
+ const errorData = o["errorData"];
2147
+ if (errorData != null) {
2148
+ if (typeof errorData !== "object") return false;
2149
+ for (const entry of Object.values(errorData)) {
2150
+ if (entry == null) continue;
2151
+ if (typeof entry !== "object") return false;
2152
+ const state = entry["contextState"];
2153
+ if (state == null || typeof state !== "object") return false;
2154
+ const kind = state["kind"];
2155
+ if (kind !== "serde_unset" && kind !== "unhydrated") return false;
2156
+ }
2157
+ }
2158
+ return true;
2159
+ }
2160
+ //#endregion
2161
+ //#region ../nice-error/src/utils/foreignNiceErrorRecord.ts
2162
+ /** A copy released before the brand existed: its class has the same name and the same serializer. */
2163
+ function isUnbrandedNiceError(value) {
2164
+ return value instanceof Error && value.name === "NiceError" && "toJsonObject" in value && typeof value.toJsonObject === "function";
2165
+ }
2166
+ /**
2167
+ * The JSON record of a `NiceError` built by another copy of this package, or `undefined` when
2168
+ * `value` is not one — or is one that cannot serialize itself.
2169
+ *
2170
+ * Call it only after `instanceof NiceError` has failed. The record comes from the other copy's
2171
+ * own `toJsonObject()`, because only that copy knows where its instance keeps its data: read as
2172
+ * if it were this copy's, the instance has no context and a message that is already prefixed.
2173
+ */
2174
+ function foreignNiceErrorRecord(value) {
2175
+ if (typeof value !== "object" || value == null) return void 0;
2176
+ const branded = isNiceError(value);
2177
+ if (!branded && !isUnbrandedNiceError(value)) return void 0;
2178
+ try {
2179
+ const record = value.toJsonObject();
2180
+ if (!isNiceErrorObject(record)) return void 0;
2181
+ if (!branded) warnOfUnversionedCopy();
2182
+ return record;
2183
+ } catch {
2184
+ return;
2185
+ }
2186
+ }
2187
+ //#endregion
1982
2188
  //#region ../nice-error/src/NiceErrorDomain/NiceErrorDomain.ts
1983
2189
  var NiceErrorDomain = class NiceErrorDomain {
1984
2190
  domain;
@@ -2075,7 +2281,7 @@ var NiceErrorDomain = class NiceErrorDomain {
2075
2281
  expected: this.domain,
2076
2282
  received: errDef.domain
2077
2283
  });
2078
- const finalError = error instanceof NiceError ? error : new NiceError(error);
2284
+ const finalError = this._ownInstanceOf(error);
2079
2285
  const reconciledErrorData = {};
2080
2286
  for (const id of finalError.getIds()) {
2081
2287
  const existingData = finalError.getErrorDataForId(id);
@@ -2167,13 +2373,25 @@ var NiceErrorDomain = class NiceErrorDomain {
2167
2373
  * ```
2168
2374
  */
2169
2375
  isExact(error) {
2170
- if (!(error instanceof NiceError)) return false;
2376
+ if (!isNiceError(error)) return false;
2171
2377
  return getErrorDomainProps(error).domain === this.domain;
2172
2378
  }
2379
+ /**
2380
+ * Returns `true` if `error` is a `NiceError` from this domain or from any domain
2381
+ * below it — a child, a grandchild, and so on. Errors from a parent or a sibling
2382
+ * domain return `false`.
2383
+ *
2384
+ * Use it to catch a whole subtree; use `isExact` for this domain alone.
2385
+ *
2386
+ * ```ts
2387
+ * err_auth.isThisOrChild(err_auth_registration.fromId("email_taken")); // true
2388
+ * err_auth_registration.isThisOrChild(err_auth.fromId("account_locked")); // false
2389
+ * ```
2390
+ */
2173
2391
  isThisOrChild(error) {
2174
- if (!(error instanceof NiceError)) return false;
2175
- const errDef = getErrorDomainProps(error);
2176
- return errDef.domain === this.domain || this.allDomains.includes(errDef.domain);
2392
+ if (!isNiceError(error)) return false;
2393
+ const allDomains = getErrorDomainProps(error).allDomains;
2394
+ return Array.isArray(allDomains) && allDomains.includes(this.domain);
2177
2395
  }
2178
2396
  /**
2179
2397
  * Returns `true` if this domain appears anywhere in the target's ancestry
@@ -2183,9 +2401,16 @@ var NiceErrorDomain = class NiceErrorDomain {
2183
2401
  * instance (extracts the domain from its `def`).
2184
2402
  */
2185
2403
  isParentOf(target) {
2186
- const allDomains = target instanceof NiceError ? getErrorDomainProps(target).allDomains : target.allDomains;
2404
+ const allDomains = isNiceError(target) ? getErrorDomainProps(target).allDomains : target.allDomains;
2187
2405
  return Array.isArray(allDomains) && allDomains.includes(this.domain);
2188
2406
  }
2407
+ /** `error` as this copy's `NiceError`: itself, or rebuilt from a record or from another copy's instance. */
2408
+ _ownInstanceOf(error) {
2409
+ if (error instanceof NiceError) return error;
2410
+ const foreignRecord = foreignNiceErrorRecord(error);
2411
+ if (foreignRecord != null) return new NiceError(foreignRecord);
2412
+ return new NiceError(error);
2413
+ }
2189
2414
  _buildDef() {
2190
2415
  return {
2191
2416
  domain: this.domain,
@@ -2322,40 +2547,6 @@ const err_nice_error = err_nice.createChildDomain({
2322
2547
  });
2323
2548
  _setInternalErrorBuilder((kind, ctx) => err_nice_error.fromId(kind, ctx));
2324
2549
  //#endregion
2325
- //#region ../nice-error/src/utils/isNiceErrorObject.ts
2326
- /**
2327
- * Returns `true` if `obj` is a JSON-serialised `NiceError` object matching the
2328
- * current wire format (contextState-based errorData entries).
2329
- *
2330
- * Validates:
2331
- * - Top-level shape (`name`, `message`, `isUnhandled`, `httpStatusCode`, `def`)
2332
- * - Each `errorData` entry has a `contextState` with a valid `kind` discriminant
2333
- * (`"no_serialization"` or `"unhydrated"`) — rejecting payloads in the old
2334
- * format (`context` / `serialized` fields) to prevent silent data corruption.
2335
- */
2336
- function isNiceErrorObject(obj) {
2337
- if (typeof obj !== "object" || obj == null) return false;
2338
- const o = obj;
2339
- if (o["name"] !== "NiceError" || typeof o["message"] !== "string" || typeof o["isUnhandled"] !== "boolean" || typeof o["httpStatusCode"] !== "number") return false;
2340
- const def = o["def"];
2341
- if (typeof def !== "object" || def == null) return false;
2342
- const d = def;
2343
- if (typeof d["domain"] !== "string" || !Array.isArray(d["allDomains"])) return false;
2344
- const errorData = o["errorData"];
2345
- if (errorData != null) {
2346
- if (typeof errorData !== "object") return false;
2347
- for (const entry of Object.values(errorData)) {
2348
- if (entry == null) continue;
2349
- if (typeof entry !== "object") return false;
2350
- const state = entry["contextState"];
2351
- if (state == null || typeof state !== "object") return false;
2352
- const kind = state["kind"];
2353
- if (kind !== "serde_unset" && kind !== "unhydrated") return false;
2354
- }
2355
- }
2356
- return true;
2357
- }
2358
- //#endregion
2359
2550
  //#region ../nice-error/src/utils/isRegularErrorObject.ts
2360
2551
  function isRegularErrorJsonObject(obj) {
2361
2552
  if (typeof obj !== "object" || obj == null) return false;
@@ -2421,6 +2612,11 @@ const inspectPotentialError = (potentialError) => {
2421
2612
  type: "niceError",
2422
2613
  niceError: parsedError
2423
2614
  };
2615
+ const foreignRecord = foreignNiceErrorRecord(parsedError);
2616
+ if (foreignRecord != null) return {
2617
+ type: "niceErrorObject",
2618
+ niceErrorObject: foreignRecord
2619
+ };
2424
2620
  if (isNiceErrorObject(parsedError)) return {
2425
2621
  type: "niceErrorObject",
2426
2622
  niceErrorObject: parsedError
@@ -2551,6 +2747,14 @@ const err_wire_connect = err_nice.createChildDomain({
2551
2747
  */
2552
2748
  endpoint_unreachable: err({ message: ({ url, carrierLabel, reason }) => `Could not reach ${url ?? (carrierLabel != null ? `the "${carrierLabel}" endpoint` : "the endpoint")}: ${reason} — no response was received (a network, DNS or TLS failure; a response the browser blocked or hid, such as a CORS rejection or a refused WebSocket upgrade; or the fetch/socket implementation threw).` }),
2553
2749
  /**
2750
+ * The carrier **opened**, then went away before the handshake finished — so the address
2751
+ * reaches something (unlike `endpoint_unreachable`), and that something hung up without a
2752
+ * protocol answer. Retried like any failed dial.
2753
+ */
2754
+ closed_during_handshake: err({ message: ({ stage, awaiting, url }) => `[${stage}] the connection closed while waiting for ${awaiting} — the endpoint accepted the connection and dropped it before the handshake finished (a server that restarted or failed mid-handshake, a proxy that cut the socket, or a peer that refuses by closing)${url != null ? `. Dialed: ${url}` : ""}.` }),
2755
+ /** The carrier stayed open and the peer never answered the handshake within `timeoutMs`. */
2756
+ handshake_timeout: err({ message: ({ stage, awaiting, timeoutMs, url }) => `[${stage}] timed out after ${timeoutMs} ms waiting for ${awaiting} — the connection is open but the peer did not answer the handshake${url != null ? `. Dialed: ${url}` : ""}.` }),
2757
+ /**
2554
2758
  * The peer **is** a nice-code backend and refused the handshake for a reason that carries no
2555
2759
  * machine-readable id of its own (an older peer, a dictionary/security mismatch, a custom
2556
2760
  * gate). Typed so `classifyConnectFailure` can report `handshake_rejected` — a third
@@ -2570,6 +2774,12 @@ const err_wire_connect = err_nice.createChildDomain({
2570
2774
  * automatic redial park until an explicit retry after the route or expectation changes.
2571
2775
  */
2572
2776
  peer_identity_mismatch: err({ message: ({ expected, actual, endpoint }) => `Secure peer identity mismatch: expected envId=${JSON.stringify(expected.envId)}${expected.perId != null ? `, perId=${JSON.stringify(expected.perId)}` : ""}; received envId=${JSON.stringify(actual.envId)}${actual.perId != null ? `, perId=${JSON.stringify(actual.perId)}` : ""}. ${endpoint != null ? `Dialed ${endpoint}. ` : ""}Carrier fallback and automatic redial are parked until an explicit retry.` }),
2777
+ /**
2778
+ * This runtime has no WebCrypto (`crypto.subtle`), so a secure transport cannot handshake.
2779
+ * Raised before any dial. Not a network condition: transport selection moves on to a plain
2780
+ * carrier when one is configured, and otherwise automatic redial parks on it.
2781
+ */
2782
+ crypto_unavailable: err({ message: ({ reason, pageOrigin }) => reason === "insecure_context" ? `A secure connection needs WebCrypto (crypto.subtle), which a browser provides only to a secure context — and this page${pageOrigin != null ? ` (${pageOrigin})` : ""} is not one. Open it over HTTPS or on localhost. Automatic redial is parked.` : "A secure connection needs WebCrypto (crypto.subtle), which this runtime does not provide. Install a WebCrypto polyfill before connecting (on React Native, react-native-quick-crypto), or set `secure: false` on the carrier for a plain connection. Automatic redial is parked." }),
2573
2783
  /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */
2574
2784
  protocol_unsupported: err({ message: ({ protocolId }) => `Protocol "${protocolId}" cannot speak on this connection — the peer did not advertise "proto:${protocolId}" (or it is not registered here).` }),
2575
2785
  /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; the protocol contract). */
@@ -2592,6 +2802,39 @@ const err_wire_connect = err_nice.createChildDomain({
2592
2802
  }
2593
2803
  });
2594
2804
  //#endregion
2805
+ //#region ../nice-wire/src/Carrier/duplex/inboundFrameQueue.ts
2806
+ /**
2807
+ * Inbound frames in arrival order, for a carrier whose message listener must stay a plain function.
2808
+ * A string, `ArrayBuffer` or `Uint8Array` is delivered in the turn it arrived. Only a `Blob` has to
2809
+ * be read asynchronously, and while one is being read everything behind it waits its turn — a later
2810
+ * frame, and the close.
2811
+ */
2812
+ function createInboundFrameQueue(deliver) {
2813
+ let reading;
2814
+ const later = (step) => {
2815
+ const next = (reading ?? Promise.resolve()).then(step).catch((error) => {
2816
+ console.error("[nice-wire] an inbound frame could not be delivered:", error);
2817
+ }).then(() => {
2818
+ if (reading === next) reading = void 0;
2819
+ });
2820
+ reading = next;
2821
+ };
2822
+ const inOrder = (step) => {
2823
+ if (reading == null) step();
2824
+ else later(step);
2825
+ };
2826
+ return {
2827
+ receive: (data) => {
2828
+ if (typeof data === "string" || data instanceof ArrayBuffer || data instanceof Uint8Array) {
2829
+ inOrder(() => deliver(data));
2830
+ return;
2831
+ }
2832
+ if (typeof Blob !== "undefined" && data instanceof Blob) later(async () => deliver(await data.arrayBuffer()));
2833
+ },
2834
+ afterFrames: inOrder
2835
+ };
2836
+ }
2837
+ //#endregion
2595
2838
  //#region ../nice-wire/src/Connect/sanitizeEndpoint.ts
2596
2839
  /**
2597
2840
  * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can carry
@@ -2659,24 +2902,23 @@ function webSocketByteChannel(ws) {
2659
2902
  let onMessage;
2660
2903
  let onClose;
2661
2904
  const preAttach = [];
2662
- const deliver = (frame) => {
2905
+ const inbound = createInboundFrameQueue((frame) => {
2663
2906
  if (onMessage != null) onMessage(frame);
2664
2907
  else preAttach.push(frame);
2665
- };
2908
+ });
2666
2909
  ws.addEventListener("open", () => {
2667
2910
  opened = true;
2668
2911
  });
2669
- ws.addEventListener("message", async (event) => {
2670
- const frame = await normalizeFrame(event.data);
2671
- if (frame !== void 0) deliver(frame);
2912
+ ws.addEventListener("message", (event) => {
2913
+ inbound.receive(event.data);
2672
2914
  });
2673
2915
  ws.addEventListener("close", (event) => {
2674
2916
  if (opened && !intentional) console.warn("WebSocket closed:", event);
2675
- onClose?.();
2917
+ inbound.afterFrames(() => onClose?.());
2676
2918
  });
2677
2919
  ws.addEventListener("error", () => {
2678
2920
  if (opened) console.warn(`WebSocket error: ${describeSocket(ws)}`);
2679
- onClose?.();
2921
+ inbound.afterFrames(() => onClose?.());
2680
2922
  });
2681
2923
  return {
2682
2924
  ready: new Promise((resolve, reject) => {
@@ -2727,11 +2969,6 @@ function unreachableError(ws, reason) {
2727
2969
  function describeSocket(ws) {
2728
2970
  return (ws.url != null && ws.url !== "" ? sanitizeEndpoint(ws.url) : void 0) ?? "(no url)";
2729
2971
  }
2730
- /** Accept text + binary frames (ArrayBuffer / Uint8Array / Blob); Blobs are converted to a buffer. */
2731
- async function normalizeFrame(data) {
2732
- if (typeof data === "string" || data instanceof ArrayBuffer || data instanceof Uint8Array) return data;
2733
- if (typeof Blob !== "undefined" && data instanceof Blob) return await data.arrayBuffer();
2734
- }
2735
2972
  //#endregion
2736
2973
  //#region ../nice-wire/src/Carrier/duplex/ws/wsCarrier.ts
2737
2974
  /**
@@ -2814,9 +3051,10 @@ function describeNonProtocolBody(raw) {
2814
3051
  function classifyConnectFailure(error) {
2815
3052
  if (!err_wire_connect.isExact(error)) return "unknown";
2816
3053
  if (error.hasId("endpoint_answered_non_protocol")) return "endpoint_answered_non_protocol";
2817
- if (error.hasId("endpoint_unreachable")) return "endpoint_unreachable";
3054
+ if (error.hasId("endpoint_unreachable") || error.hasId("closed_during_handshake") || error.hasId("handshake_timeout")) return "endpoint_unreachable";
2818
3055
  if (error.hasId("protocol_version_mismatch")) return "protocol_version_mismatch";
2819
3056
  if (error.hasId("peer_identity_mismatch")) return "peer_identity_mismatch";
3057
+ if (error.hasId("crypto_unavailable")) return "crypto_unavailable";
2820
3058
  if (error.hasId("identity_pin_mismatch") || error.hasId("handshake_rejected")) return "handshake_rejected";
2821
3059
  return "unknown";
2822
3060
  }
@@ -2825,6 +3063,8 @@ function endpointFromConnectFailure(error) {
2825
3063
  if (!err_wire_connect.isExact(error)) return void 0;
2826
3064
  if (error.hasId("endpoint_answered_non_protocol")) return sanitizeEndpoint(error.getContext("endpoint_answered_non_protocol").url);
2827
3065
  if (error.hasId("endpoint_unreachable")) return sanitizeEndpoint(error.getContext("endpoint_unreachable").url);
3066
+ if (error.hasId("closed_during_handshake")) return sanitizeEndpoint(error.getContext("closed_during_handshake").url);
3067
+ if (error.hasId("handshake_timeout")) return sanitizeEndpoint(error.getContext("handshake_timeout").url);
2828
3068
  if (error.hasId("peer_identity_mismatch")) return sanitizeEndpoint(error.getContext("peer_identity_mismatch").endpoint);
2829
3069
  }
2830
3070
  //#endregion
@@ -2859,6 +3099,7 @@ var ConnectionTransportManager$1 = class {
2859
3099
  async getReadyTransport(input) {
2860
3100
  const candidates = [];
2861
3101
  const unavailableTransports = [];
3102
+ let cryptoUnavailable;
2862
3103
  for (const transport of this._transports) {
2863
3104
  let cacheKey = null;
2864
3105
  try {
@@ -2956,6 +3197,10 @@ var ConnectionTransportManager$1 = class {
2956
3197
  unavailableTransports.push(transport);
2957
3198
  continue;
2958
3199
  }
3200
+ if (isCryptoUnavailable(e)) {
3201
+ cryptoUnavailable ??= e;
3202
+ continue;
3203
+ }
2959
3204
  const failed = Promise.reject(e);
2960
3205
  failed.catch(() => {});
2961
3206
  candidates.push({
@@ -2968,6 +3213,7 @@ var ConnectionTransportManager$1 = class {
2968
3213
  }
2969
3214
  }
2970
3215
  if (candidates.length === 0) {
3216
+ if (cryptoUnavailable != null) throw cryptoUnavailable;
2971
3217
  if (unavailableTransports.length > 0) throw this._errors.unsupported(unavailableTransports.map((t) => t.type));
2972
3218
  throw this._errors.notFound(input);
2973
3219
  }
@@ -3036,6 +3282,7 @@ var ConnectionTransportManager$1 = class {
3036
3282
  }
3037
3283
  };
3038
3284
  const isDialUnavailable$1 = (error) => err_wire_connect.isExact(error) && error.hasId("dial_unavailable");
3285
+ const isCryptoUnavailable = (error) => err_wire_connect.isExact(error) && error.hasId("crypto_unavailable");
3039
3286
  const isTerminalSelectionError = (error) => err_wire_connect.isExact(error) && (error.hasId("peer_identity_mismatch") || error.hasId("protocol_version_mismatch"));
3040
3287
  /** The transport's sanitized route URL for diagnostics; a throwing route resolver yields none. */
3041
3288
  function routeEndpoint(transport, input) {
@@ -4706,6 +4953,36 @@ const serializeX25519Key_Raw = async (key) => {
4706
4953
  };
4707
4954
  };
4708
4955
  //#endregion
4956
+ //#region ../nice-util/src/crypto/client_key_link/withKeyMintLock.ts
4957
+ const queuedInProcess = /* @__PURE__ */ new Map();
4958
+ /**
4959
+ * Run `mint` alone among everything minting under `name`. Web Locks, where the runtime has them,
4960
+ * hold off every tab and worker of the origin; without them (React Native, older runtimes) the turn
4961
+ * is taken within this JS realm only, and a caller narrows the rest by reading the store again
4962
+ * before it writes.
4963
+ */
4964
+ async function withKeyMintLock(name, mint) {
4965
+ const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
4966
+ if (locks != null) {
4967
+ let entered = false;
4968
+ try {
4969
+ return await locks.request(name, () => {
4970
+ entered = true;
4971
+ return mint();
4972
+ });
4973
+ } catch (error) {
4974
+ if (entered) throw error;
4975
+ }
4976
+ }
4977
+ const turn = (queuedInProcess.get(name) ?? Promise.resolve()).then(mint, mint);
4978
+ queuedInProcess.set(name, turn);
4979
+ const release = () => {
4980
+ if (queuedInProcess.get(name) === turn) queuedInProcess.delete(name);
4981
+ };
4982
+ turn.then(release, release);
4983
+ return await turn;
4984
+ }
4985
+ //#endregion
4709
4986
  //#region ../nice-util/src/crypto/client_key_link/ClientCryptoKeyLink.ts
4710
4987
  /**
4711
4988
  * Thrown by the local-key getters when the link is in {@link TIdentityMode} `"required"` and no
@@ -4723,23 +5000,34 @@ var ClientCryptoKeyLink = class {
4723
5000
  localVerifyKeyPair;
4724
5001
  linkedClientKeys = /* @__PURE__ */ new Map();
4725
5002
  storage;
5003
+ storageAdapter;
4726
5004
  identityMode;
4727
5005
  initialized = false;
5006
+ reloadPending = false;
4728
5007
  initializePromise;
4729
5008
  localExchangeKeyPairPromise;
4730
5009
  localVerifyKeyPairPromise;
4731
5010
  constructor({ storageAdapter, identityMode } = {}) {
4732
5011
  if (storageAdapter != null) this.storage = createTypedStorage({ storageAdapter });
5012
+ this.storageAdapter = storageAdapter;
4733
5013
  this.identityMode = identityMode ?? "lazy";
4734
5014
  }
4735
5015
  /**
5016
+ * A namespace of this identity's own store (same backing storage, `prefix` appended), for state
5017
+ * that belongs to this identity and must go wherever its keys go — e.g. a connector's established
5018
+ * sessions. `undefined` when the link has no storage.
5019
+ */
5020
+ scopedStorage(prefix) {
5021
+ return this.storageAdapter?.withKeyPrefix(prefix);
5022
+ }
5023
+ /**
4736
5024
  * Loads the local key pairs and any linked client public keys from storage (when a storage
4737
5025
  * adapter was provided), generating and persisting fresh local key pairs if none exist yet.
4738
5026
  *
4739
5027
  * Must be called (and awaited) before any sign/verify/encrypt/decrypt operation.
4740
5028
  */
4741
5029
  async initialize() {
4742
- if (this.initialized) return;
5030
+ if (this.initialized && !this.reloadPending) return;
4743
5031
  this.initializePromise ??= this.runInitialize();
4744
5032
  try {
4745
5033
  await this.initializePromise;
@@ -4748,11 +5036,23 @@ var ClientCryptoKeyLink = class {
4748
5036
  }
4749
5037
  }
4750
5038
  async runInitialize() {
5039
+ this.initialized = false;
4751
5040
  await this.loadStoredLocalKeys();
4752
5041
  await this.loadLinkedClients();
4753
5042
  this.initialized = true;
4754
5043
  }
4755
5044
  /**
5045
+ * Have the next {@link initialize} read the store again and take it as the truth: a local identity
5046
+ * the store holds now is adopted, and one it no longer holds is forgotten (the next use mints and
5047
+ * persists a fresh one). For a link that outlives the code that made it — one shared by connections
5048
+ * made at different times: a store cleared in between would otherwise leave an identity that is
5049
+ * presented now and gone after the next reload. A no-op for a link with no storage.
5050
+ */
5051
+ reloadOnNextInitialize() {
5052
+ if (this.storage == null) return;
5053
+ this.reloadPending = true;
5054
+ }
5055
+ /**
4756
5056
  * Provision the local identity once: load any persisted identity, then mint + persist the exchange
4757
5057
  * and verify key pairs only if absent. Idempotent — a no-op when an identity already exists.
4758
5058
  *
@@ -4777,24 +5077,62 @@ var ClientCryptoKeyLink = class {
4777
5077
  * generates or stores keys it does not need.
4778
5078
  */
4779
5079
  async loadStoredLocalKeys() {
4780
- const storedExchange = await this.storage?.getJson("localExchangeKeyPair");
4781
- if (storedExchange != null) {
4782
- const exchangePrivateKey = await importX25519Key.private.fromFormattedString.extractable(storedExchange.privateKey);
4783
- const exchangePublicKey = await importX25519Key.public.fromFormattedString.extractable(storedExchange.publicKey);
4784
- this.localExchangeKeyPair = {
4785
- privateKey: exchangePrivateKey,
4786
- publicKey: exchangePublicKey
4787
- };
5080
+ const forgetUnstored = this.reloadPending;
5081
+ this.reloadPending = false;
5082
+ try {
5083
+ const storedExchange = await this.readStoredExchangeKeyPair();
5084
+ const storedVerify = await this.readStoredVerifyKeyPair();
5085
+ if (storedExchange != null || forgetUnstored) this.localExchangeKeyPair = storedExchange;
5086
+ if (storedVerify != null || forgetUnstored) this.localVerifyKeyPair = storedVerify;
5087
+ } catch (error) {
5088
+ this.reloadPending ||= forgetUnstored;
5089
+ throw error;
4788
5090
  }
4789
- const storedVerify = await this.storage?.getJson("localVerifyKeyPair");
4790
- if (storedVerify != null) {
4791
- const verifyPrivateKey = await importEd25519Key.private.fromFormattedString.extractable(storedVerify.privateKey);
4792
- const verifyPublicKey = await importEd25519Key.public.fromFormattedString.extractable(storedVerify.publicKey);
4793
- this.localVerifyKeyPair = {
4794
- privateKey: verifyPrivateKey,
4795
- publicKey: verifyPublicKey
4796
- };
5091
+ }
5092
+ async readStoredExchangeKeyPair() {
5093
+ const stored = await this.storage?.getJson("localExchangeKeyPair");
5094
+ if (stored == null) return;
5095
+ return {
5096
+ privateKey: await importX25519Key.private.fromFormattedString.extractable(stored.privateKey),
5097
+ publicKey: await importX25519Key.public.fromFormattedString.extractable(stored.publicKey)
5098
+ };
5099
+ }
5100
+ async readStoredVerifyKeyPair() {
5101
+ const stored = await this.storage?.getJson("localVerifyKeyPair");
5102
+ if (stored == null) return;
5103
+ return {
5104
+ privateKey: await importEd25519Key.private.fromFormattedString.extractable(stored.privateKey),
5105
+ publicKey: await importEd25519Key.public.fromFormattedString.extractable(stored.publicKey)
5106
+ };
5107
+ }
5108
+ /**
5109
+ * Mint one local key pair — or adopt the one another link over the same storage minted first.
5110
+ * Two links (or two tabs) that each found the store empty must not each persist a key of their
5111
+ * own: a peer pins the first it sees and refuses the other for good.
5112
+ */
5113
+ async mintOrAdopt(mint) {
5114
+ const storageAdapter = this.storageAdapter;
5115
+ if (storageAdapter == null) {
5116
+ const keyPair = await mint.generate();
5117
+ mint.keep(keyPair);
5118
+ return keyPair;
4797
5119
  }
5120
+ return await withKeyMintLock(`nice-code:key-link:${storageAdapter.keyPrefix}${mint.storageKey}`, async () => {
5121
+ const stored = await mint.readStored();
5122
+ if (stored != null) {
5123
+ mint.keep(stored);
5124
+ return stored;
5125
+ }
5126
+ const generated = await mint.generate();
5127
+ const storedMeanwhile = await mint.readStored();
5128
+ if (storedMeanwhile != null) {
5129
+ mint.keep(storedMeanwhile);
5130
+ return storedMeanwhile;
5131
+ }
5132
+ mint.keep(generated);
5133
+ await mint.store(generated);
5134
+ return generated;
5135
+ });
4798
5136
  }
4799
5137
  /**
4800
5138
  * Returns the local exchange (X25519) key pair. In `"lazy"` mode it generates + persists it on first
@@ -4809,16 +5147,23 @@ var ClientCryptoKeyLink = class {
4809
5147
  /**
4810
5148
  * Generates + persists the local exchange key pair if absent, returning an already-loaded pair
4811
5149
  * untouched (so provisioning is idempotent). Bypasses the `"required"` guard by design — it is the
4812
- * sole minting path. Concurrent callers share a single generation.
5150
+ * sole minting path. Concurrent callers share a single generation, and a pair another link has
5151
+ * stored since this one loaded is adopted instead (see {@link mintOrAdopt}).
4813
5152
  */
4814
5153
  async mintLocalExchangeKeyPair() {
4815
5154
  if (this.localExchangeKeyPair != null) return this.localExchangeKeyPair;
4816
- this.localExchangeKeyPairPromise ??= (async () => {
4817
- const keyPair = await generateX25519KeyPair();
4818
- this.localExchangeKeyPair = keyPair;
4819
- if (this.storage != null) await this.storage.setJson("localExchangeKeyPair", await this.serializeExchangeKeyPair(keyPair));
4820
- return keyPair;
4821
- })();
5155
+ this.localExchangeKeyPairPromise ??= this.mintOrAdopt({
5156
+ storageKey: "localExchangeKeyPair",
5157
+ readStored: () => this.readStoredExchangeKeyPair(),
5158
+ generate: generateX25519KeyPair,
5159
+ keep: (keyPair) => {
5160
+ this.localExchangeKeyPair = keyPair;
5161
+ },
5162
+ store: async (keyPair) => {
5163
+ const serialized = await this.serializeExchangeKeyPair(keyPair);
5164
+ await this.storage?.setJson("localExchangeKeyPair", serialized);
5165
+ }
5166
+ });
4822
5167
  try {
4823
5168
  return await this.localExchangeKeyPairPromise;
4824
5169
  } finally {
@@ -4838,16 +5183,23 @@ var ClientCryptoKeyLink = class {
4838
5183
  /**
4839
5184
  * Generates + persists the local verify key pair if absent, returning an already-loaded pair
4840
5185
  * untouched (so provisioning is idempotent). Bypasses the `"required"` guard by design — it is the
4841
- * sole minting path. Concurrent callers share a single generation.
5186
+ * sole minting path. Concurrent callers share a single generation, and a pair another link has
5187
+ * stored since this one loaded is adopted instead (see {@link mintOrAdopt}).
4842
5188
  */
4843
5189
  async mintLocalVerifyKeyPair() {
4844
5190
  if (this.localVerifyKeyPair != null) return this.localVerifyKeyPair;
4845
- this.localVerifyKeyPairPromise ??= (async () => {
4846
- const keyPair = await generateEd25519KeyPair();
4847
- this.localVerifyKeyPair = keyPair;
4848
- if (this.storage != null) await this.storage.setJson("localVerifyKeyPair", await this.serializeVerifyKeyPair(keyPair));
4849
- return keyPair;
4850
- })();
5191
+ this.localVerifyKeyPairPromise ??= this.mintOrAdopt({
5192
+ storageKey: "localVerifyKeyPair",
5193
+ readStored: () => this.readStoredVerifyKeyPair(),
5194
+ generate: generateEd25519KeyPair,
5195
+ keep: (keyPair) => {
5196
+ this.localVerifyKeyPair = keyPair;
5197
+ },
5198
+ store: async (keyPair) => {
5199
+ const serialized = await this.serializeVerifyKeyPair(keyPair);
5200
+ await this.storage?.setJson("localVerifyKeyPair", serialized);
5201
+ }
5202
+ });
4851
5203
  try {
4852
5204
  return await this.localVerifyKeyPairPromise;
4853
5205
  } finally {
@@ -6077,12 +6429,13 @@ const isDialUnavailable = (e) => err_wire_connect.isExact(e) && e.hasId("dial_un
6077
6429
  * A dial failure the backoff ladder must PARK on instead of retrying: either no endpoint exists
6078
6430
  * right now ({@link isDialUnavailable}), or the peer rejected the handshake with
6079
6431
  * `identity_pin_mismatch` (the peer has a different key pinned) or
6080
- * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation).
6432
+ * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation), or this
6433
+ * runtime has no WebCrypto to handshake with at all (`crypto_unavailable`).
6081
6434
  * Parking is not terminal: the next explicit `connect()`/dispatch may try again after the app has
6082
6435
  * upgraded or changed endpoints. Other handshake rejections (e.g. a dictionary mismatch) retain
6083
6436
  * the existing retry behavior because a matching deploy can heal them.
6084
6437
  */
6085
- const isParkedDialRejection = (e) => isDialUnavailable(e) || err_wire_connect.isExact(e) && (e.hasId("identity_pin_mismatch") || e.hasId("protocol_version_mismatch") || e.hasId("peer_identity_mismatch"));
6438
+ const isParkedDialRejection = (e) => isDialUnavailable(e) || err_wire_connect.isExact(e) && (e.hasId("identity_pin_mismatch") || e.hasId("protocol_version_mismatch") || e.hasId("peer_identity_mismatch") || e.hasId("crypto_unavailable"));
6086
6439
  /**
6087
6440
  * The dial-out connection: owns the transport cache, preference-ordered selection, the protocol mux,
6088
6441
  * and the whole **connection lifecycle** — establishment bookkeeping, the keep-alive redial ladder
@@ -9030,6 +9383,8 @@ function handshakeRejectError(stage, rejectFrame) {
9030
9383
  //#region ../nice-wire/src/Connect/duplexLinkSession.ts
9031
9384
  const HANDSHAKE_TIMEOUT_MS$1 = 15e3;
9032
9385
  const LINK_HANDSHAKE_STAGE = "link-handshake";
9386
+ const AWAITING_WELCOME = "a welcome frame";
9387
+ const AWAITING_ACCEPT = "an accept frame";
9033
9388
  /** The duplex twin of the exchange path's `nonProtocolReply` — same typed id, so a consumer's
9034
9389
  * `kind` branch means the same thing whichever carrier served the dial. */
9035
9390
  function wrongHandshakeFrame(channel, expected, receivedKind) {
@@ -9204,9 +9559,34 @@ async function establishSecureDuplexSession(ctx) {
9204
9559
  let active = false;
9205
9560
  const handshakeQueue = [];
9206
9561
  const handshakeWaiters = [];
9562
+ let carrierClosed = false;
9207
9563
  const pendingFrames = [];
9208
9564
  let nonProtocolFrame;
9209
9565
  let heartbeat;
9566
+ const unansweredError = (awaiting, cause) => {
9567
+ const url = sanitizeEndpoint(channel.label);
9568
+ if (nonProtocolFrame != null) return err_wire_connect.fromId("endpoint_answered_non_protocol", {
9569
+ stage: LINK_HANDSHAKE_STAGE,
9570
+ expected: awaiting,
9571
+ url,
9572
+ bodyPreview: describeNonProtocolBody(nonProtocolFrame)
9573
+ });
9574
+ return cause === "closed" ? err_wire_connect.fromId("closed_during_handshake", {
9575
+ stage: LINK_HANDSHAKE_STAGE,
9576
+ awaiting,
9577
+ url
9578
+ }) : err_wire_connect.fromId("handshake_timeout", {
9579
+ stage: LINK_HANDSHAKE_STAGE,
9580
+ awaiting,
9581
+ timeoutMs: HANDSHAKE_TIMEOUT_MS$1,
9582
+ url
9583
+ });
9584
+ };
9585
+ const onCarrierClosed = () => {
9586
+ carrierClosed = true;
9587
+ for (const waiter of handshakeWaiters.splice(0)) waiter.reject(unansweredError(waiter.awaiting, "closed"));
9588
+ onChannelClosed(disconnectListeners, ctx.lane);
9589
+ };
9210
9590
  const mux = ctx.mux;
9211
9591
  channel.attach({
9212
9592
  onMessage: (frame) => {
@@ -9232,7 +9612,7 @@ async function establishSecureDuplexSession(ctx) {
9232
9612
  lane: "handshake"
9233
9613
  });
9234
9614
  const waiter = handshakeWaiters.shift();
9235
- if (waiter != null) waiter(message);
9615
+ if (waiter != null) waiter.resolve(message);
9236
9616
  else handshakeQueue.push(message);
9237
9617
  return;
9238
9618
  }
@@ -9240,23 +9620,31 @@ async function establishSecureDuplexSession(ctx) {
9240
9620
  }
9241
9621
  pendingFrames.push(frame);
9242
9622
  },
9243
- onClose: () => onChannelClosed(disconnectListeners, ctx.lane),
9244
- onError: () => onChannelClosed(disconnectListeners, ctx.lane)
9623
+ onClose: onCarrierClosed,
9624
+ onError: onCarrierClosed
9245
9625
  });
9246
- const nextHandshakeMessage = () => {
9626
+ const nextHandshakeMessage = (awaiting) => {
9247
9627
  const queued = handshakeQueue.shift();
9248
9628
  if (queued != null) return Promise.resolve(queued);
9629
+ if (carrierClosed) return Promise.reject(unansweredError(awaiting, "closed"));
9249
9630
  return new Promise((resolve, reject) => {
9250
- const timeout = setTimeout(() => reject(nonProtocolFrame != null ? err_wire_connect.fromId("endpoint_answered_non_protocol", {
9251
- stage: LINK_HANDSHAKE_STAGE,
9252
- expected: "a handshake frame",
9253
- url: sanitizeEndpoint(channel.label),
9254
- bodyPreview: describeNonProtocolBody(nonProtocolFrame)
9255
- }) : /* @__PURE__ */ new Error(`[${LINK_HANDSHAKE_STAGE}] timed out waiting for peer reply`)), HANDSHAKE_TIMEOUT_MS$1);
9256
- handshakeWaiters.push((message) => {
9257
- clearTimeout(timeout);
9258
- resolve(message);
9259
- });
9631
+ const timeout = setTimeout(() => {
9632
+ const index = handshakeWaiters.indexOf(waiter);
9633
+ if (index !== -1) handshakeWaiters.splice(index, 1);
9634
+ reject(unansweredError(awaiting, "timeout"));
9635
+ }, HANDSHAKE_TIMEOUT_MS$1);
9636
+ const waiter = {
9637
+ awaiting,
9638
+ resolve: (message) => {
9639
+ clearTimeout(timeout);
9640
+ resolve(message);
9641
+ },
9642
+ reject: (error) => {
9643
+ clearTimeout(timeout);
9644
+ reject(error);
9645
+ }
9646
+ };
9647
+ handshakeWaiters.push(waiter);
9260
9648
  });
9261
9649
  };
9262
9650
  try {
@@ -9326,6 +9714,7 @@ function makeSession$1(channel, pipe, disconnectListeners, remoteCaps, muxBindin
9326
9714
  async function runClientHandshake(ctx, nextHandshakeMessage) {
9327
9715
  const secure = ctx.secure;
9328
9716
  const sendHandshake = (encoded) => {
9717
+ if (!ctx.channel.isOpen()) return;
9329
9718
  ctx.channel.send(encoded);
9330
9719
  ctx.tap?.({
9331
9720
  dir: "out",
@@ -9345,13 +9734,13 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
9345
9734
  extraCaps: [...ctx.lane.caps?.() ?? [], ...ctx.mux?.localCaps() ?? []]
9346
9735
  });
9347
9736
  sendHandshake(encodeHandshakeMessage(await handshake.createHello()));
9348
- const welcome = await nextHandshakeMessage();
9737
+ const welcome = await nextHandshakeMessage(AWAITING_WELCOME);
9349
9738
  if (welcome.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, welcome);
9350
- if (welcome.t !== "welcome") throw wrongHandshakeFrame(ctx.channel, "a welcome frame", welcome.t);
9739
+ if (welcome.t !== "welcome") throw wrongHandshakeFrame(ctx.channel, AWAITING_WELCOME, welcome.t);
9351
9740
  sendHandshake(encodeHandshakeMessage(await handshake.onWelcome(welcome)));
9352
- const accept = await nextHandshakeMessage();
9741
+ const accept = await nextHandshakeMessage(AWAITING_ACCEPT);
9353
9742
  if (accept.t === "reject") throw handshakeRejectError(LINK_HANDSHAKE_STAGE, accept);
9354
- if (accept.t !== "accept") throw wrongHandshakeFrame(ctx.channel, "an accept frame", accept.t);
9743
+ if (accept.t !== "accept") throw wrongHandshakeFrame(ctx.channel, AWAITING_ACCEPT, accept.t);
9355
9744
  const result = await handshake.onAccept(accept);
9356
9745
  return {
9357
9746
  crypto: result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
@@ -9387,6 +9776,22 @@ function onChannelClosed(disconnectListeners, lane) {
9387
9776
  lane.onDetach?.();
9388
9777
  }
9389
9778
  //#endregion
9779
+ //#region ../nice-wire/src/Connect/webCryptoPreflight.ts
9780
+ /**
9781
+ * The one check before a secure transport dials. A browser gives `crypto.subtle` only to a secure
9782
+ * context (HTTPS, or localhost), and some runtimes ship none until a polyfill is installed; either
9783
+ * way the handshake cannot run, and no retry will change that.
9784
+ */
9785
+ function assertWebCryptoAvailable() {
9786
+ const runtime = globalThis;
9787
+ if (runtime.crypto?.subtle != null) return;
9788
+ if (runtime.isSecureContext === false) throw err_wire_connect.fromId("crypto_unavailable", {
9789
+ reason: "insecure_context",
9790
+ pageOrigin: runtime.location?.origin
9791
+ });
9792
+ throw err_wire_connect.fromId("crypto_unavailable", { reason: "no_webcrypto" });
9793
+ }
9794
+ //#endregion
9390
9795
  //#region ../nice-wire/src/Connect/TransportConnection.ts
9391
9796
  let transportOrd = 0;
9392
9797
  /**
@@ -9459,6 +9864,7 @@ var TransportConnection$1 = class {
9459
9864
  return this._processTransportStatus(input);
9460
9865
  }
9461
9866
  _processTransportStatus(input) {
9867
+ if (this.initialized.requiresWebCrypto === true) assertWebCryptoAvailable();
9462
9868
  const statusInfo = addTransportStatusMetadata(this.initialized.getTransport(input));
9463
9869
  if (statusInfo.status === "ready") {
9464
9870
  if (!this._needsAsyncBringUp(statusInfo.readyData)) return {
@@ -9590,6 +9996,22 @@ var WireProtocolMux = class {
9590
9996
  const DEFAULT_HEARTBEAT_IDLE_MS = 15e3;
9591
9997
  const DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS = 5e3;
9592
9998
  const ephemeralIdentityWarned = /* @__PURE__ */ new Set();
9999
+ const linksByStorage = /* @__PURE__ */ new WeakMap();
10000
+ /**
10001
+ * The one identity link over a storage: every connection built from the same adapter presents the
10002
+ * same keys. A link apiece would each find a fresh store empty and mint a key of its own, and the
10003
+ * peer pins only the first it sees.
10004
+ */
10005
+ function linkOverStorage(storage) {
10006
+ const shared = linksByStorage.get(storage);
10007
+ if (shared != null) {
10008
+ shared.reloadOnNextInitialize();
10009
+ return shared;
10010
+ }
10011
+ const link = new ClientCryptoKeyLink({ storageAdapter: storage });
10012
+ linksByStorage.set(storage, link);
10013
+ return link;
10014
+ }
9593
10015
  /**
9594
10016
  * The ephemeral-identity trap: a coordinate with a persistent id whose
9595
10017
  * crypto identity lives in non-durable storage keys the peer's trust-on-first-use verify-key pin but
@@ -9607,6 +10029,33 @@ function warnOnEphemeralPinnedIdentity(callerName, coordinate, storage) {
9607
10029
  ephemeralIdentityWarned.add(pinKey);
9608
10030
  console.warn(`${callerName}: the runtime coordinate [${pinKey}] carries a persistent id, which keys the peer's trust-on-first-use verify-key pin — but the \`storage\` passed here is not known to be durable, so this client's crypto identity may regenerate on reload. The peer will pin the first key it sees and reject every reconnect after the first reload (identity_pin_mismatch). Back the connection with a durable adapter (e.g. createWebLocalStorageAdapter) that persists at least as long as the persistent id, or set \`ephemeralIdentity: true\` if the id is minted fresh per session. Memory adapters are for tests.`);
9609
10031
  }
10032
+ const sessionReuseWarned = /* @__PURE__ */ new Set();
10033
+ /**
10034
+ * `reuseExchangeSessions` where it cannot do what it says. Nothing fails, so nothing else would
10035
+ * tell: the option is ignored on a plain carrier, a link with no storage keeps the session in
10036
+ * memory only, and a per-session identity files it under an id no later load will have. Warned
10037
+ * once per connection identity, peer and cause.
10038
+ */
10039
+ function warnOnUnusableSessionReuse(options, link) {
10040
+ const exchangeCarriers = options.exchangeCarrierSecurity ?? [];
10041
+ if (exchangeCarriers.length === 0) return;
10042
+ const connection = `[${options.identity.envId}::${options.identity.perId ?? "-"} → ${options.peer.envId}::${options.peer.perId ?? "-"}]`;
10043
+ const warn = (cause, detail) => {
10044
+ const key = `${cause}|${connection}`;
10045
+ if (sessionReuseWarned.has(key)) return;
10046
+ sessionReuseWarned.add(key);
10047
+ console.warn(`${options.callerName}: \`reuseExchangeSessions\` ${detail}`);
10048
+ };
10049
+ if (!exchangeCarriers.includes(true)) {
10050
+ warn("plain", `does nothing on the connection ${connection}: every request/reply carrier on it is \`secure: false\`, and a plain carrier has no session to keep. Drop the option, or make the carrier secure.`);
10051
+ return;
10052
+ }
10053
+ if (link?.scopedStorage("") == null) {
10054
+ warn("no-storage", `is on for the connection ${connection}, but its crypto identity has no \`storage\`, so a session is kept in memory only: shared between this page's connections, and gone on reload. Pass \`storage\` (or a \`link\` built over one) to keep sessions across page loads.`);
10055
+ return;
10056
+ }
10057
+ if (options.ephemeralIdentity === true && options.identity.perId != null) warn("per-session-identity", `is on for the connection ${connection} together with \`ephemeralIdentity: true\`. A kept session is filed under the identity's persistent id, and a per-session id is new on every load, so no later load can find it: sessions are reused within this page only. Use an id that survives reloads if a reload should skip the handshake.`);
10058
+ }
9610
10059
  /**
9611
10060
  * Assemble the connection facts a dial-out entry point shares — the one implementation of "how a
9612
10061
  * wire connection's mux, crypto identity, keepalive, and traffic tap are set up" (first-production
@@ -9625,8 +10074,9 @@ function assembleWireConnectionParts(options) {
9625
10074
  if (options.anySecure && link == null) {
9626
10075
  if (options.storage == null && options.ephemeralIdentity !== true) throw new Error(`${options.callerName}: a secure transport requires \`storage\` (or \`link\`) for the crypto identity. Pass it, declare a per-session identity with \`ephemeralIdentity: true\`, or set \`secure: false\` on the carrier for a plain connection.`);
9627
10076
  if (options.storage != null && options.ephemeralIdentity !== true) warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);
9628
- link = new ClientCryptoKeyLink(options.storage != null ? { storageAdapter: options.storage } : {});
10077
+ link = options.storage != null ? linkOverStorage(options.storage) : new ClientCryptoKeyLink();
9629
10078
  }
10079
+ if (options.reuseExchangeSessions === true) warnOnUnusableSessionReuse(options, link);
9630
10080
  const resolveHeartbeat = () => {
9631
10081
  if (heartbeat === false) return void 0;
9632
10082
  const explicit = heartbeat;
@@ -9646,6 +10096,12 @@ function assembleWireConnectionParts(options) {
9646
10096
  }
9647
10097
  //#endregion
9648
10098
  //#region ../nice-wire/src/Connect/exchangeEnvelope.ts
10099
+ /**
10100
+ * The `err` id an acceptor sends when it refused the session itself (expired, tampered or
10101
+ * wrong-key ticket, or an act at the wrong level) — before any lane ran, so the connector may
10102
+ * drop the session, handshake again and resend the same act.
10103
+ */
10104
+ const WIRE_EXCHANGE_SESSION_REFUSED = "session_refused";
9649
10105
  function encodeExchange(envelope) {
9650
10106
  return JSON.stringify(envelope);
9651
10107
  }
@@ -9674,33 +10130,261 @@ function hasEnvelopeKind(value) {
9674
10130
  return typeof value === "object" && value != null && "k" in value;
9675
10131
  }
9676
10132
  //#endregion
10133
+ //#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
10134
+ const SEALED_ENVELOPE_LENGTH = 2;
10135
+ function createExchangeTicketSealer(link, options = {}) {
10136
+ let keyPromise;
10137
+ const getKey = () => {
10138
+ if (keyPromise == null) keyPromise = link.deriveLocalSealKey({ version: options.version }).catch((err) => {
10139
+ keyPromise = void 0;
10140
+ throw err;
10141
+ });
10142
+ return keyPromise;
10143
+ };
10144
+ return {
10145
+ async seal(value, ttlMs) {
10146
+ const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({
10147
+ dataToEncrypt: pack({
10148
+ v: value,
10149
+ exp: Date.now() + ttlMs
10150
+ }),
10151
+ aesGcmKey: await getKey()
10152
+ });
10153
+ return bytesToBase64(pack([nonce, ciphertext]));
10154
+ },
10155
+ async open(blob) {
10156
+ try {
10157
+ const envelope = unpack(base64ToBytes(blob));
10158
+ if (!Array.isArray(envelope) || envelope.length !== SEALED_ENVELOPE_LENGTH) return void 0;
10159
+ const [nonce, ciphertext] = envelope;
10160
+ if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) return void 0;
10161
+ const payload = unpack(await decryptBytesWithAesGcmKey({
10162
+ dataToDecrypt: {
10163
+ nonce,
10164
+ ciphertext
10165
+ },
10166
+ aesGcmKey: await getKey()
10167
+ }));
10168
+ if (payload == null || typeof payload.exp !== "number" || payload.exp < Date.now()) return;
10169
+ return payload.v;
10170
+ } catch {
10171
+ return;
10172
+ }
10173
+ }
10174
+ };
10175
+ }
10176
+ //#endregion
10177
+ //#region ../nice-wire/src/Connect/exchangeSessionShelf.ts
10178
+ /** Lapse a little before the acceptor would, so a request is never sent on its last second. */
10179
+ function expiryFor(receivedAt, ttlMs) {
10180
+ if (ttlMs == null || !(ttlMs > 0)) return void 0;
10181
+ return receivedAt + ttlMs - Math.min(6e4, ttlMs / 10);
10182
+ }
10183
+ function stateFromRecord(link, record) {
10184
+ const crypto = record.km != null ? createActionFrameCrypto({
10185
+ link,
10186
+ keyMaterial: record.km
10187
+ }) : void 0;
10188
+ return {
10189
+ token: record.t,
10190
+ crypto,
10191
+ expiresAt: record.exp,
10192
+ record
10193
+ };
10194
+ }
10195
+ function isLapsed(state) {
10196
+ return state.expiresAt != null && Date.now() >= state.expiresAt;
10197
+ }
10198
+ /**
10199
+ * One session's lifecycle: at most one handshake in flight, shared by every caller; a refused or
10200
+ * lapsed session is replaced once, however many requests noticed it.
10201
+ */
10202
+ var ExchangeSessionSlot = class {
10203
+ _entry;
10204
+ current(initial, replacement) {
10205
+ const entry = this._entry;
10206
+ if (entry == null) return this._start(initial);
10207
+ if (entry.state != null && isLapsed(entry.state)) return this.renew(entry.state, replacement);
10208
+ return entry.promise;
10209
+ }
10210
+ renew(stale, replacement) {
10211
+ const entry = this._entry;
10212
+ if (entry != null && entry.state !== stale) return entry.promise;
10213
+ return this._start(replacement);
10214
+ }
10215
+ _start(establish) {
10216
+ const entry = { promise: establish() };
10217
+ this._entry = entry;
10218
+ entry.promise.then((state) => {
10219
+ entry.state = state;
10220
+ }, () => {
10221
+ if (this._entry === entry) this._entry = void 0;
10222
+ });
10223
+ return entry.promise;
10224
+ }
10225
+ };
10226
+ /** A session source for one transport alone — today's behaviour, plus renewal on refusal. */
10227
+ function privateSessionSource(handshake) {
10228
+ const slot = new ExchangeSessionSlot();
10229
+ return {
10230
+ current: () => slot.current(handshake, handshake),
10231
+ renew: (stale) => slot.renew(stale, handshake)
10232
+ };
10233
+ }
10234
+ const STORE_KEY = "sessions";
10235
+ const SEAL_VERSION = "connector-exchange-session/v1";
10236
+ /**
10237
+ * Every session one crypto identity holds with its peers, keyed by peer identity: shared in memory
10238
+ * by all of the link's transports, and kept in the link's own storage so a reload restores it.
10239
+ * Stored copies are sealed with a key derived from the link's private key — useless to another
10240
+ * device, and unopenable once the identity is reset.
10241
+ */
10242
+ var ExchangeSessionShelf = class {
10243
+ _link;
10244
+ _slots = /* @__PURE__ */ new Map();
10245
+ _storage;
10246
+ _sealer;
10247
+ constructor(_link) {
10248
+ this._link = _link;
10249
+ this._storage = _link.scopedStorage("wire-exchange/");
10250
+ this._sealer = createExchangeTicketSealer(_link, { version: SEAL_VERSION });
10251
+ }
10252
+ source(key, handshake) {
10253
+ let slot = this._slots.get(key);
10254
+ if (slot == null) {
10255
+ slot = new ExchangeSessionSlot();
10256
+ this._slots.set(key, slot);
10257
+ }
10258
+ const held = slot;
10259
+ const handshakeAndKeep = async () => {
10260
+ const state = await handshake();
10261
+ await this._keep(key, state).catch(() => void 0);
10262
+ return state;
10263
+ };
10264
+ const restoreOrHandshake = async () => {
10265
+ return await this._restore(key).catch(() => void 0) ?? await handshakeAndKeep();
10266
+ };
10267
+ const replace = async () => {
10268
+ await this._forget(key).catch(() => void 0);
10269
+ return await handshakeAndKeep();
10270
+ };
10271
+ return {
10272
+ current: () => held.current(restoreOrHandshake, replace),
10273
+ renew: (stale) => held.renew(stale, replace)
10274
+ };
10275
+ }
10276
+ async _restore(key) {
10277
+ const storage = this._storage;
10278
+ if (storage == null) return void 0;
10279
+ const stored = (await storage.getJson(STORE_KEY))?.[key];
10280
+ if (stored == null || stored.exp <= Date.now()) return void 0;
10281
+ await this._link.initialize();
10282
+ const record = await this._sealer.open(stored.sealed);
10283
+ if (record == null || typeof record.t !== "string") return void 0;
10284
+ return stateFromRecord(this._link, record);
10285
+ }
10286
+ async _keep(key, state) {
10287
+ const storage = this._storage;
10288
+ const record = state.record;
10289
+ if (storage == null || record?.exp == null) return;
10290
+ const ttl = record.exp - Date.now();
10291
+ if (ttl <= 0) return;
10292
+ const sealed = await this._sealer.seal(record, ttl);
10293
+ await this._update(storage, (sessions) => ({
10294
+ ...sessions,
10295
+ [key]: {
10296
+ exp: record.exp ?? 0,
10297
+ sealed
10298
+ }
10299
+ }));
10300
+ }
10301
+ async _forget(key) {
10302
+ const storage = this._storage;
10303
+ if (storage == null) return;
10304
+ await this._update(storage, (sessions) => {
10305
+ const { [key]: _dropped, ...rest } = sessions;
10306
+ return rest;
10307
+ });
10308
+ }
10309
+ async _update(storage, change) {
10310
+ await storage.updateJsonOrDef(STORE_KEY, {}, (current) => {
10311
+ const now = Date.now();
10312
+ const live = {};
10313
+ for (const [key, entry] of Object.entries(change(current))) if (entry.exp > now) live[key] = entry;
10314
+ return live;
10315
+ });
10316
+ }
10317
+ };
10318
+ const shelves = /* @__PURE__ */ new WeakMap();
10319
+ /**
10320
+ * The source a secure exchange draws its session from: shared by peer identity when the config asks
10321
+ * for reuse and names the peer, private to this transport otherwise.
10322
+ */
10323
+ function exchangeSessionSource(secure, lane, handshake) {
10324
+ const peer = secure.expectedPeer;
10325
+ if (secure.reuseExchangeSessions !== true || peer == null) return privateSessionSource(handshake);
10326
+ let shelf = shelves.get(secure.link);
10327
+ if (shelf == null) {
10328
+ shelf = new ExchangeSessionShelf(secure.link);
10329
+ shelves.set(secure.link, shelf);
10330
+ }
10331
+ const key = JSON.stringify([
10332
+ secure.localCoordinate.envId,
10333
+ secure.localCoordinate.perId ?? null,
10334
+ peer.envId,
10335
+ peer.perId ?? null,
10336
+ secure.securityLevel,
10337
+ lane.dictionaryVersion,
10338
+ [...lane.channels ?? []].sort()
10339
+ ]);
10340
+ return shelf.source(key, handshake);
10341
+ }
10342
+ //#endregion
9677
10343
  //#region ../nice-wire/src/Connect/exchangeSession.ts
9678
10344
  const textEncoder$1 = new TextEncoder();
9679
10345
  const textDecoder$1 = new TextDecoder();
10346
+ const PLAIN_STATE = {};
9680
10347
  /** Plain path (no handshake/token): every wire rides a bare `act` envelope, plaintext both ways. */
9681
10348
  function establishPlainExchangeSession(carrier) {
9682
- return makeSession(carrier, {});
10349
+ return makeSession(carrier, {
10350
+ current: async () => PLAIN_STATE,
10351
+ renew: async () => PLAIN_STATE
10352
+ });
9683
10353
  }
9684
10354
  /**
9685
- * Secure path: run the handshake (two exchanges) once at bring-up, then reuse the token + crypto.
9686
- * The lane supplies the handshake payload (`dictionaryVersion`/`channels`, E5 — emitted under the
9687
- * byte-frozen wire names; the version is signed into the challenge).
10355
+ * Secure path: run the handshake (two exchanges) at bring-up — or restore a kept session — then
10356
+ * reuse the token + crypto. The lane supplies the handshake payload (`dictionaryVersion`/`channels`,
10357
+ * E5 — emitted under the byte-frozen wire names; the version is signed into the challenge).
9688
10358
  */
9689
10359
  async function establishSecureExchangeSession(ctx) {
9690
- const state = await runConnectorExchangeHandshake(ctx.carrier, ctx.secure, ctx.lane);
9691
- return makeSession(ctx.carrier, state);
9692
- }
9693
- function makeSession(carrier, state) {
9694
- const runExchange = async (wire, opts) => {
9695
- const request = await buildRequestEnvelope(state, wire);
9696
- return carrier.exchange(encodeExchange(request), { signal: opts?.signal });
10360
+ const source = exchangeSessionSource(ctx.secure, ctx.lane, () => runConnectorExchangeHandshake(ctx.carrier, ctx.secure, ctx.lane));
10361
+ await source.current();
10362
+ return makeSession(ctx.carrier, source, ctx.secure.localCoordinate.insId);
10363
+ }
10364
+ function makeSession(carrier, source, insId) {
10365
+ const post = async (state, wire, signal) => {
10366
+ const request = await buildRequestEnvelope(state, wire, insId);
10367
+ return decodeExchangeReply(asString(await carrier.exchange(encodeExchange(request), { signal })));
10368
+ };
10369
+ const roundTrip = async (wire, signal) => {
10370
+ const state = await source.current();
10371
+ const reply = await post(state, wire, signal);
10372
+ if (reply?.k !== "err" || reply.id !== "session_refused" || state.token == null) return {
10373
+ state,
10374
+ reply
10375
+ };
10376
+ const renewed = await source.renew(state);
10377
+ return {
10378
+ state: renewed,
10379
+ reply: await post(renewed, wire, signal)
10380
+ };
9697
10381
  };
9698
10382
  return {
9699
10383
  send: async (wire, opts) => {
9700
- await runExchange(wire, opts);
10384
+ await roundTrip(wire, opts?.signal);
9701
10385
  },
9702
10386
  exchange: async (wire, opts) => {
9703
- const reply = decodeExchangeReply(asString(await runExchange(wire, opts)));
10387
+ const { state, reply } = await roundTrip(wire, opts?.signal);
9704
10388
  if (reply == null) return {
9705
10389
  ok: false,
9706
10390
  reason: "malformed_reply"
@@ -9722,18 +10406,21 @@ function makeSession(carrier, state) {
9722
10406
  }
9723
10407
  };
9724
10408
  }
9725
- async function buildRequestEnvelope(state, wire) {
10409
+ async function buildRequestEnvelope(state, wire, insId) {
10410
+ const i = state.token != null ? insId : void 0;
9726
10411
  if (state.crypto != null) {
9727
10412
  const ciphertext = await state.crypto.encryptFrame(textEncoder$1.encode(JSON.stringify(wire)));
9728
10413
  return {
9729
10414
  k: "act",
9730
10415
  t: state.token,
10416
+ i,
9731
10417
  c: bytesToBase64(ciphertext)
9732
10418
  };
9733
10419
  }
9734
10420
  return {
9735
10421
  k: "act",
9736
10422
  t: state.token,
10423
+ i,
9737
10424
  w: wire
9738
10425
  };
9739
10426
  }
@@ -9776,14 +10463,13 @@ async function runConnectorExchangeHandshake(carrier, secure, lane) {
9776
10463
  if (accept.t !== "accept") throw nonProtocolReply(carrier, "an accept frame", `hs/${accept.t}`);
9777
10464
  if (acceptReply.t == null) throw new Error(`[${HANDSHAKE_STAGE}] accept missing session token${at(carrier)}`);
9778
10465
  const result = await handshake.onAccept(accept);
9779
- const crypto = result.securityLevel === "encrypted" && result.encryptionKeyMaterial != null ? createActionFrameCrypto({
9780
- link: secure.link,
9781
- keyMaterial: result.encryptionKeyMaterial
9782
- }) : void 0;
9783
- return {
9784
- token: acceptReply.t,
9785
- crypto
9786
- };
10466
+ const keyMaterial = result.securityLevel === "encrypted" ? result.encryptionKeyMaterial : void 0;
10467
+ return stateFromRecord(secure.link, {
10468
+ t: acceptReply.t,
10469
+ level: result.securityLevel,
10470
+ km: keyMaterial,
10471
+ exp: expiryFor(Date.now(), acceptReply.ttl)
10472
+ });
9787
10473
  }
9788
10474
  const HANDSHAKE_STAGE = "exchange-handshake";
9789
10475
  /**
@@ -10369,50 +11055,6 @@ var WireAcceptor = class {
10369
11055
  }
10370
11056
  };
10371
11057
  //#endregion
10372
- //#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
10373
- const SEALED_ENVELOPE_LENGTH = 2;
10374
- function createExchangeTicketSealer(link, options = {}) {
10375
- let keyPromise;
10376
- const getKey = () => {
10377
- if (keyPromise == null) keyPromise = link.deriveLocalSealKey({ version: options.version }).catch((err) => {
10378
- keyPromise = void 0;
10379
- throw err;
10380
- });
10381
- return keyPromise;
10382
- };
10383
- return {
10384
- async seal(value, ttlMs) {
10385
- const { nonce, ciphertext } = await encryptBytesWithAesGcmKey({
10386
- dataToEncrypt: pack({
10387
- v: value,
10388
- exp: Date.now() + ttlMs
10389
- }),
10390
- aesGcmKey: await getKey()
10391
- });
10392
- return bytesToBase64(pack([nonce, ciphertext]));
10393
- },
10394
- async open(blob) {
10395
- try {
10396
- const envelope = unpack(base64ToBytes(blob));
10397
- if (!Array.isArray(envelope) || envelope.length !== SEALED_ENVELOPE_LENGTH) return void 0;
10398
- const [nonce, ciphertext] = envelope;
10399
- if (!(nonce instanceof Uint8Array) || !(ciphertext instanceof Uint8Array)) return void 0;
10400
- const payload = unpack(await decryptBytesWithAesGcmKey({
10401
- dataToDecrypt: {
10402
- nonce,
10403
- ciphertext
10404
- },
10405
- aesGcmKey: await getKey()
10406
- }));
10407
- if (payload == null || typeof payload.exp !== "number" || payload.exp < Date.now()) return;
10408
- return payload.v;
10409
- } catch {
10410
- return;
10411
- }
10412
- }
10413
- };
10414
- }
10415
- //#endregion
10416
11058
  //#region ../nice-wire/src/Connect/WireExchangeAcceptor.ts
10417
11059
  /** The default session-ticket lifetime — see {@link IWireExchangeAcceptorOptions.sessionTtlMs}. */
10418
11060
  const DEFAULT_SESSION_TTL_MS = 720 * 60 * 1e3;
@@ -10482,11 +11124,17 @@ var WireExchangeAcceptor = class {
10482
11124
  m: encodeHandshakeMessage(reply)
10483
11125
  };
10484
11126
  const pending = handshake.exportPending();
10485
- if (pending == null) return {
11127
+ const dv = this._dictionaryVersion(message.channels);
11128
+ if (pending == null || dv == null) return {
10486
11129
  k: "err",
10487
11130
  message: "handshake produced no continuation state"
10488
11131
  };
10489
- const hsc = await this._sealer.seal(pending, HANDSHAKE_CONTINUATION_TTL_MS);
11132
+ const continuation = {
11133
+ ...pending,
11134
+ dv,
11135
+ ch: message.channels
11136
+ };
11137
+ const hsc = await this._sealer.seal(continuation, HANDSHAKE_CONTINUATION_TTL_MS);
10490
11138
  return {
10491
11139
  k: "hs",
10492
11140
  m: encodeHandshakeMessage(reply),
@@ -10498,11 +11146,12 @@ var WireExchangeAcceptor = class {
10498
11146
  k: "err",
10499
11147
  message: "prove missing continuation token"
10500
11148
  };
10501
- const pending = await this._sealer.open(request.hsc);
10502
- if (pending == null) return {
11149
+ const continuation = await this._sealer.open(request.hsc);
11150
+ if (continuation == null) return {
10503
11151
  k: "err",
10504
11152
  message: "invalid or expired continuation token"
10505
11153
  };
11154
+ const { dv, ch, ...pending } = continuation;
10506
11155
  const handshake = this._makeHandshake();
10507
11156
  await handshake.restorePending(pending);
10508
11157
  const reply = await handshake.onProve(message);
@@ -10511,13 +11160,16 @@ var WireExchangeAcceptor = class {
10511
11160
  const ticket = {
10512
11161
  client: result.remote,
10513
11162
  securityLevel: result.securityLevel,
10514
- keyMaterial: result.encryptionKeyMaterial
11163
+ keyMaterial: result.encryptionKeyMaterial,
11164
+ dv,
11165
+ ch
10515
11166
  };
10516
11167
  const t = await this._sealer.seal(ticket, this._sessionTtlMs);
10517
11168
  return {
10518
11169
  k: "hs",
10519
11170
  m: encodeHandshakeMessage(reply),
10520
- t
11171
+ t,
11172
+ ttl: this._sessionTtlMs
10521
11173
  };
10522
11174
  }
10523
11175
  return {
@@ -10530,6 +11182,10 @@ var WireExchangeAcceptor = class {
10530
11182
  message: `unexpected handshake message ${message.t}`
10531
11183
  };
10532
11184
  }
11185
+ _dictionaryVersion(channels) {
11186
+ const version = this._lane.dictionaryVersion;
11187
+ return typeof version === "function" ? version({ channels: channels == null ? void 0 : [...channels] }) : version;
11188
+ }
10533
11189
  async _handleAction(request) {
10534
11190
  let client;
10535
11191
  let crypto;
@@ -10537,24 +11193,30 @@ var WireExchangeAcceptor = class {
10537
11193
  let securityLevel = "none";
10538
11194
  if (request.t != null) {
10539
11195
  const ticket = await this._sealer.open(request.t);
10540
- if (ticket == null) return {
10541
- k: "err",
10542
- message: "unknown or expired session token"
10543
- };
10544
- client = new RuntimeCoordinate(ticket.client);
11196
+ if (ticket == null) return refused("unknown or expired session token");
11197
+ if (ticket.dv != null && ticket.dv !== this._dictionaryVersion(ticket.ch)) return refused("session was agreed under another dictionary version");
11198
+ client = new RuntimeCoordinate(typeof request.i === "string" ? {
11199
+ ...ticket.client,
11200
+ insId: request.i
11201
+ } : ticket.client);
10545
11202
  securityLevel = ticket.securityLevel;
10546
- crypto = ticket.securityLevel === "encrypted" && ticket.keyMaterial != null ? createActionFrameCrypto({
10547
- link: this._security.link,
10548
- keyMaterial: ticket.keyMaterial
10549
- }) : void 0;
10550
- if ("c" in request) {
10551
- if (crypto == null) return {
10552
- k: "err",
10553
- message: "session is not encrypted"
10554
- };
10555
- const plain = await crypto.decryptFrame(base64ToBytes(request.c));
10556
- wire = JSON.parse(textDecoder.decode(plain));
10557
- } else wire = request.w;
11203
+ if (ticket.securityLevel === "encrypted") {
11204
+ if (!("c" in request)) return refused("encrypted session refuses a plaintext act");
11205
+ if (ticket.keyMaterial == null) return refused("encrypted session has no key material");
11206
+ crypto = createActionFrameCrypto({
11207
+ link: this._security.link,
11208
+ keyMaterial: ticket.keyMaterial
11209
+ });
11210
+ try {
11211
+ const plain = await crypto.decryptFrame(base64ToBytes(request.c));
11212
+ wire = JSON.parse(textDecoder.decode(plain));
11213
+ } catch {
11214
+ return refused("undecryptable act");
11215
+ }
11216
+ } else {
11217
+ if ("c" in request) return refused("session is not encrypted");
11218
+ wire = request.w;
11219
+ }
10558
11220
  } else {
10559
11221
  if (!this._noneAllowed || "c" in request) return {
10560
11222
  k: "err",
@@ -10572,7 +11234,7 @@ var WireExchangeAcceptor = class {
10572
11234
  k: "err",
10573
11235
  message: laneReply.message
10574
11236
  };
10575
- if (crypto != null && "c" in request) return {
11237
+ if (crypto != null) return {
10576
11238
  k: "act",
10577
11239
  c: bytesToBase64(await crypto.encryptFrame(textEncoder.encode(JSON.stringify(laneReply.wire))))
10578
11240
  };
@@ -10588,6 +11250,13 @@ var WireExchangeAcceptor = class {
10588
11250
  });
10589
11251
  }
10590
11252
  };
11253
+ function refused(message) {
11254
+ return {
11255
+ k: "err",
11256
+ message,
11257
+ id: WIRE_EXCHANGE_SESSION_REFUSED
11258
+ };
11259
+ }
10591
11260
  //#endregion
10592
11261
  //#region ../nice-wire/src/codec/controlFrame.ts
10593
11262
  /** msgpack map (object) first-byte prefixes — fixmap `0x80–0x8f`, map16 `0xde`, map32 `0xdf`. */
@@ -11332,7 +12001,7 @@ var ActionCore = class extends ActionBase {
11332
12001
  * undeclared `NiceError`s) returns `false`.
11333
12002
  */
11334
12003
  isExpectedError(error) {
11335
- return error instanceof NiceError && this.schema.isExpectedError(error);
12004
+ return isNiceError(error) && this.schema.isExpectedError(error);
11336
12005
  }
11337
12006
  toJsonObject() {
11338
12007
  return {
@@ -14951,12 +15620,29 @@ var ActionLocalHandler = class extends ActionHandler {
14951
15620
  if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) return this.actionRouter.domainManager.getActionDomainOrThrow(state.request).hydrateResultPayload(rawResult);
14952
15621
  return state.request.successResult(rawResult);
14953
15622
  });
14954
- const result = ran.ok ? ran.output : state.request.errorResult(ran.error);
15623
+ let result;
15624
+ try {
15625
+ result = ran.ok ? ran.output : this._errorResult(state.request, ran.error);
15626
+ } catch (error) {
15627
+ runningAction._failWithError(error);
15628
+ return;
15629
+ }
14955
15630
  runningAction._completeWithResult(result);
14956
15631
  } finally {
14957
15632
  popHandlerCuid();
14958
15633
  }
14959
15634
  }
15635
+ /**
15636
+ * Building an error result classifies the error, which reads it (`isExact`, `hasId`). An error
15637
+ * that cannot be read still has to answer, so the result becomes the cast of what reading threw.
15638
+ */
15639
+ _errorResult(request, error) {
15640
+ try {
15641
+ return request.errorResult(error);
15642
+ } catch (unreadable) {
15643
+ return request.errorResult(castNiceError(unreadable));
15644
+ }
15645
+ }
14960
15646
  async handlePayloadWireOrThrow(wire, config) {
14961
15647
  const hydratedAction = this.actionRouter.domainManager.hydrateActionPayload(wire);
14962
15648
  if (!(hydratedAction instanceof ActionPayload_Request)) throw err_nice_action.fromId("wire_action_not_payload", {
@@ -16697,6 +17383,7 @@ var ExchangeTransport = class ExchangeTransport extends Transport {
16697
17383
  return new ExchangeConnection({ initialize: () => ({
16698
17384
  getCacheKey: options.getCacheKey,
16699
17385
  isAvailable: options.available,
17386
+ requiresWebCrypto: options.security != null && options.security.securityLevel !== "none",
16700
17387
  getTransport: (input) => {
16701
17388
  assertProtocolsRideDuplex(options);
16702
17389
  const carrier = options.openCarrier(input);
@@ -16941,6 +17628,7 @@ var LinkTransport = class LinkTransport extends Transport {
16941
17628
  return new LinkConnection({ initialize: () => ({
16942
17629
  getCacheKey: options.getCacheKey,
16943
17630
  isAvailable: options.available,
17631
+ requiresWebCrypto: options.security != null && options.security.securityLevel !== "none",
16944
17632
  getTransport: (input) => ({
16945
17633
  status: "ready",
16946
17634
  readyData: {
@@ -16981,6 +17669,7 @@ function transport(options) {
16981
17669
  link,
16982
17670
  localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),
16983
17671
  expectedPeer: options.expectedPeer?.toJsonObject(),
17672
+ reuseExchangeSessions: options.reuseExchangeSessions,
16984
17673
  dictionaryVersion: channel.dictionaryVersion,
16985
17674
  channelTags: channel.tags,
16986
17675
  mux: options.mux
@@ -17132,6 +17821,8 @@ function connectChannel(runtime, channel, options) {
17132
17821
  storage: options.storage,
17133
17822
  link: options.link,
17134
17823
  ephemeralIdentity: options.ephemeralIdentity,
17824
+ reuseExchangeSessions: options.reuseExchangeSessions,
17825
+ exchangeCarrierSecurity: transports.filter((descriptor) => isExchangeCarrierSource(descriptor.carrier)).map((descriptor) => (descriptor.secure ?? true) && (descriptor.securityLevel ?? securityLevel) !== "none"),
17135
17826
  reconnect: options.reconnect,
17136
17827
  heartbeat: options.heartbeat,
17137
17828
  keepLinkAlive: options.keepLinkAlive,
@@ -17148,6 +17839,7 @@ function connectChannel(runtime, channel, options) {
17148
17839
  secure: descriptor.secure ?? true,
17149
17840
  link,
17150
17841
  securityLevel: descriptor.securityLevel ?? securityLevel,
17842
+ reuseExchangeSessions: options.reuseExchangeSessions,
17151
17843
  available: descriptor.available,
17152
17844
  label: descriptor.label,
17153
17845
  mux: wireMux,
@@ -17394,7 +18086,7 @@ function createActionFetchHandler(runtime, options = {}) {
17394
18086
  securityLevel: "none"
17395
18087
  });
17396
18088
  } catch (error) {
17397
- if (error instanceof NiceError && error.getIds().some((id) => id === "wire_not_action_data" || id === "wire_action_not_payload")) {
18089
+ if (isNiceError(error) && error.getIds().some((id) => id === "wire_not_action_data" || id === "wire_action_not_payload")) {
17398
18090
  report?.({
17399
18091
  ok: false,
17400
18092
  returnedVia: transportLabel,
@@ -24552,30 +25244,6 @@ async function ensureStateDir(paths) {
24552
25244
  });
24553
25245
  }
24554
25246
  //#endregion
24555
- //#region src/daemon/packageVersion.ts
24556
- let cached = null;
24557
- /**
24558
- * Resolved relative to the BUILT module, so the candidate list must cover every layout this
24559
- * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that
24560
- * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).
24561
- */
24562
- async function commanderPackageVersion() {
24563
- if (cached != null) return cached;
24564
- for (const candidate of [
24565
- new URL("../package.json", import.meta.url),
24566
- new URL("../../package.json", import.meta.url),
24567
- new URL("../../../package.json", import.meta.url)
24568
- ]) try {
24569
- const parsed = JSON.parse(await readFile(candidate, "utf8"));
24570
- if (typeof parsed.version === "string" && parsed.name === "@nice-code/commander") {
24571
- cached = parsed.version;
24572
- return cached;
24573
- }
24574
- } catch {}
24575
- cached = "0.0.0";
24576
- return cached;
24577
- }
24578
- //#endregion
24579
25247
  //#region src/daemon/runtime.ts
24580
25248
  /** Check before advertising a daemon whose HTTP works but whose wire handshake cannot run. */
24581
25249
  function commanderRuntimeError() {
@@ -25224,6 +25892,11 @@ function checkReloadResult(value) {
25224
25892
  errors
25225
25893
  };
25226
25894
  }
25895
+ /** Re-check a reload ack that arrived from a daemon — see `parseActionReport`. */
25896
+ function parseReloadResult(value) {
25897
+ const checked = checkReloadResult(value);
25898
+ return typeof checked === "string" ? null : checked;
25899
+ }
25227
25900
  const OUTCOMES = new Set([
25228
25901
  "ready",
25229
25902
  "spawned",
@@ -25460,6 +26133,11 @@ async function connectDaemon(handle) {
25460
26133
  const request = commanderControlDomain.actionForId("noteRuns").request(input);
25461
26134
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "noteRuns" rejected by the daemon`);
25462
26135
  },
26136
+ reloadConfig: async () => {
26137
+ const request = commanderControlDomain.actionForId("reloadConfig").request({});
26138
+ const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
26139
+ return payload.result.ok ? parseReloadResult(payload.result.output) : null;
26140
+ },
25463
26141
  shutdown: async () => {
25464
26142
  const request = commanderControlDomain.actionForId("shutdown").request({});
25465
26143
  if (!(await (await runtime.handleActionPayload(request)).waitForResultPayload()).result.ok) throw new CliExit(EXIT.failure, `action "shutdown" rejected by the daemon`);
@@ -25561,9 +26239,11 @@ function printReport(out, report, state) {
25561
26239
  else {
25562
26240
  for (const result of report.results) {
25563
26241
  if (NARRATED.has(result.outcome)) continue;
26242
+ const node = state.processes[result.id];
25564
26243
  const note = result.reason != null ? ` — ${result.reason}` : "";
25565
- const reach = result.outcome === "already-running" ? reachLine(out, state.processes[result.id]) : "";
26244
+ const reach = result.outcome === "already-running" ? reachLine(out, node) : "";
25566
26245
  out.print(`${stateSymbol(out, result.outcome)} ${out.accent(result.id, result.id)} ${result.outcome}${note}${reach}`);
26246
+ if (result.outcome === "already-running" && (node?.stale === true || node?.envDrift === true)) out.print(out.paint("yellow", ` ${result.id} runs what it was started with — its ${node.stale ? "definition" : "env"} has changed since; \`restart ${result.id}\` applies it`));
25567
26247
  }
25568
26248
  for (const warning of report.warnings) out.warn(`${out.paint("yellow", "⚠")} ${warning}`);
25569
26249
  }
@@ -25598,6 +26278,7 @@ async function cmdUp(ctx) {
25598
26278
  if (handle.replaced != null && !ctx.out.json) ctx.out.print(ctx.out.paint("gray", `· replaced the previous daemon (pid ${handle.replaced.pid}, build ${handle.replaced.packageVersion}) — it predated this CLI and nothing was running`));
25599
26279
  const client = await connectDaemon(handle);
25600
26280
  try {
26281
+ await syncDaemonConfig(ctx.config, client, ctx.out);
25601
26282
  const wait = !ctx.args.flags.has("--no-wait");
25602
26283
  const staggerMs = staggerFor(ctx.config, ctx.args.positionals);
25603
26284
  const replaceSame = ctx.args.flags.has("--replace-same");
@@ -25620,12 +26301,18 @@ async function controlVerb(ctx, verb) {
25620
26301
  "--with",
25621
26302
  "--all",
25622
26303
  "--any"
25623
- ] : ["--all", "--any"];
26304
+ ] : [
26305
+ "--only",
26306
+ "--all",
26307
+ "--any"
26308
+ ];
25624
26309
  const bad = unknownFlags(ctx.args.flags, known);
25625
26310
  if (bad != null) throw new CliExit(EXIT.usage, bad);
26311
+ if (ctx.args.flags.has("--only") && ctx.args.flags.get("--only") !== true) throw new CliExit(EXIT.usage, "--only takes no value");
25626
26312
  requireSelectionTerms(ctx);
25627
26313
  const client = await connectDaemon(await requireDaemon(ctx.config));
25628
26314
  try {
26315
+ if (verb === "restart") await syncDaemonConfig(ctx.config, client, ctx.out);
25629
26316
  const declared = new Set(ctx.config.processes.map((proc) => proc.id));
25630
26317
  const selection = selectOrExit(ctx, {
25631
26318
  bare: "required",
@@ -25633,8 +26320,11 @@ async function controlVerb(ctx, verb) {
25633
26320
  });
25634
26321
  const replaceSame = ctx.args.flags.has("--replace-same");
25635
26322
  const flags = verb === "restart" ? flagsOrExit(ctx) : null;
25636
- const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", { ids: selection.ordered }) : client.control("restart", {
25637
- ids: selection.ordered,
26323
+ const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", ctx.args.flags.has("--only") ? { ids: selection.direct } : {
26324
+ ids: selection.direct,
26325
+ withDependencies: true
26326
+ }) : client.control("restart", {
26327
+ ids: selection.direct,
25638
26328
  wait: !ctx.args.flags.has("--no-wait"),
25639
26329
  staggerMs: staggerFor(ctx.config, ctx.args.positionals),
25640
26330
  ...replaceSame ? { replaceSame } : {},
@@ -26191,6 +26881,50 @@ function createPortInspector(options) {
26191
26881
  return { run };
26192
26882
  }
26193
26883
  //#endregion
26884
+ //#region src/cli/envJudge.ts
26885
+ function shellEnvJudge(unreachable) {
26886
+ return {
26887
+ judgedIn: "shell",
26888
+ note: unreachable == null ? `no daemon is running — whether a variable is set is judged in ${describeJudgedIn("shell")}, which a daemon started from here inherits` : `the daemon could not be asked (${unreachable}) — whether a variable is set is judged in ${describeJudgedIn("shell")} instead`,
26889
+ baseEnv: () => process.env
26890
+ };
26891
+ }
26892
+ /** Reads `state` now, not when asked: the judge outlives the connection it came from. */
26893
+ function daemonEnvJudge(state, daemonPid) {
26894
+ const judged = new Map(Object.entries(state.processes).map(([id, node]) => [id, new Map(node.detail.envVars.map((view) => [view.name, view.source]))]));
26895
+ return {
26896
+ judgedIn: "daemon",
26897
+ note: `whether a variable is set is judged in ${describeJudgedIn("daemon")} (pid ${daemonPid}) — what \`up\` starts inherits that one, not this shell's`,
26898
+ baseEnv: (definition) => {
26899
+ const env = {};
26900
+ for (const declared of definition.envVars) {
26901
+ const source = judged.get(definition.id)?.get(declared.name);
26902
+ if (source === "inherited" || source !== "unset" && process.env[declared.name] != null) env[declared.name] = "";
26903
+ }
26904
+ return env;
26905
+ }
26906
+ };
26907
+ }
26908
+ /**
26909
+ * The judge for a read-only command. A daemon this build cannot talk to must not fail a command
26910
+ * that only wanted its opinion — the shell answers, and the note says why.
26911
+ */
26912
+ async function judgeEnv(config, known) {
26913
+ const handle = known === void 0 ? await findDaemon(config) : known;
26914
+ if (handle == null) return shellEnvJudge();
26915
+ try {
26916
+ const client = await connectDaemon(handle);
26917
+ try {
26918
+ return daemonEnvJudge(client.state(), handle.record.pid);
26919
+ } finally {
26920
+ client.dispose();
26921
+ }
26922
+ } catch (error) {
26923
+ if (!(error instanceof CliExit)) throw error;
26924
+ return shellEnvJudge(error.message);
26925
+ }
26926
+ }
26927
+ //#endregion
26194
26928
  //#region src/cli/commands/ports.ts
26195
26929
  async function portProcessStates(ctx) {
26196
26930
  const handle = await findDaemon(ctx.config);
@@ -26440,8 +27174,10 @@ async function diagnose(ctx, handle) {
26440
27174
  const overrideCount = countOverrides(overrides);
26441
27175
  if (overrideCount > 0) report.info.push(`env overrides: ${overrideCount} set in ${paths.envOverridesPath} — they apply to every start (\`nice-commander env\` lists them, \`--clear\` drops them)`);
26442
27176
  for (const entry of staleOverrides(config, overrides)) report.warnings.push(`env override ${entry.id}.${entry.name} is stored but inert (${entry.reason}) — clear it with \`env ${entry.id} --clear\``);
27177
+ const judge = await judgeEnv(config, handle);
26443
27178
  for (const proc of config.processes) {
26444
- for (const name of missingRequired(proc, overrides, process.env)) report.warnings.push(`"${proc.id}" requires ${name} and nothing supplies it — set it with \`env ${proc.id} --set ${name}=…\``);
27179
+ const missing = missingRequired(proc, overrides, judge.baseEnv(proc));
27180
+ if (missing.length > 0) report.warnings.push(`"${proc.id}" ${requiredRefusal(proc.id, missing, judge.judgedIn)} — a start refuses until then`);
26445
27181
  for (const off of overridesOffEndpoint(proc, overrides)) report.warnings.push(`"${proc.id}" ${off.name}=${off.value} but its endpoint and readiness are still on ${off.port} — it will bind somewhere nothing points at`);
26446
27182
  }
26447
27183
  const capability = detectCapability();
@@ -26607,11 +27343,11 @@ function parseNames(values) {
26607
27343
  for (const entry of values) if (entry.includes("=")) return { error: `--unset expects a NAME, got ${JSON.stringify(entry)}` };
26608
27344
  return [...values];
26609
27345
  }
26610
- function describeValue(view) {
27346
+ function describeValue(view, judgedIn) {
26611
27347
  if (view.secret) return view.source === "unset" ? "-" : "••••••";
26612
- return view.value ?? (view.source === "inherited" ? "(the daemon's env)" : "-");
27348
+ return view.value ?? (view.source === "inherited" ? `(${describeJudgedIn(judgedIn)})` : "-");
26613
27349
  }
26614
- function renderProcess(out, definition, views) {
27350
+ function renderProcess(out, definition, views, judgedIn) {
26615
27351
  out.print(out.paint("bold", definition.id));
26616
27352
  if (views.length === 0) {
26617
27353
  out.print(out.paint("gray", " declares no env vars — add `envVars` to the config to tune it"));
@@ -26624,7 +27360,7 @@ function renderProcess(out, definition, views) {
26624
27360
  "NOTES"
26625
27361
  ], views.map((view) => [
26626
27362
  ` ${view.name}`,
26627
- describeValue(view),
27363
+ describeValue(view, judgedIn),
26628
27364
  view.source,
26629
27365
  [
26630
27366
  view.description,
@@ -26650,8 +27386,15 @@ async function cmdEnv(ctx) {
26650
27386
  const { out, config } = ctx;
26651
27387
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
26652
27388
  const definitions = mutating || ctx.args.positionals.length > 0 || ctx.args.flags.has("--all") ? idsToDefinitions(ctx, selectOrExit(ctx, { bare: "required" }).direct) : config.processes.filter((proc) => proc.envVars.length > 0);
26653
- const handle = mutating ? await findDaemon(config) : null;
26654
- const client = handle == null ? null : await connectDaemon(handle);
27389
+ const handle = await findDaemon(config);
27390
+ let client = null;
27391
+ let unreachable;
27392
+ if (handle != null) try {
27393
+ client = await connectDaemon(handle);
27394
+ } catch (error) {
27395
+ if (mutating || !(error instanceof CliExit)) throw error;
27396
+ unreachable = error.message;
27397
+ }
26655
27398
  try {
26656
27399
  const result = mutating ? await mutate(ctx, paths.envOverridesPath, client, {
26657
27400
  processes: Object.fromEntries(definitions.map((definition) => [definition.id, {
@@ -26663,11 +27406,13 @@ async function cmdEnv(ctx) {
26663
27406
  overrides: await readEnvOverrides(paths.envOverridesPath),
26664
27407
  warnings: []
26665
27408
  };
26666
- const views = new Map(definitions.map((definition) => [definition.id, envVarViews(definition, result.overrides, process.env)]));
27409
+ const judge = client != null ? daemonEnvJudge(client.state(), client.record.pid) : shellEnvJudge(unreachable);
27410
+ const views = new Map(definitions.map((definition) => [definition.id, envVarViews(definition, result.overrides, judge.baseEnv(definition))]));
26667
27411
  const stale = staleOverrides(config, result.overrides);
26668
27412
  if (out.json) {
26669
27413
  out.printJson({
26670
27414
  overridesPath: paths.envOverridesPath,
27415
+ judgedAgainst: judge.judgedIn,
26671
27416
  processes: definitions.map((definition) => ({
26672
27417
  id: definition.id,
26673
27418
  envVars: views.get(definition.id) ?? []
@@ -26678,9 +27423,10 @@ async function cmdEnv(ctx) {
26678
27423
  return result.warnings.length > 0 ? EXIT.failure : EXIT.ok;
26679
27424
  }
26680
27425
  for (const definition of definitions) {
26681
- renderProcess(out, definition, views.get(definition.id) ?? []);
27426
+ renderProcess(out, definition, views.get(definition.id) ?? [], judge.judgedIn);
26682
27427
  out.print();
26683
27428
  }
27429
+ if ([...views.values()].some((listed) => listed.length > 0)) out.print(out.paint("gray", judge.note));
26684
27430
  const total = countOverrides(result.overrides);
26685
27431
  if (total > 0) out.print(out.paint("gray", `${total} sticky override(s) — they apply to every start until \`nice-commander env <sel> --clear\`.`));
26686
27432
  if (client != null) {
@@ -26806,16 +27552,18 @@ async function cmdExplain(ctx) {
26806
27552
  return EXIT.ok;
26807
27553
  }
26808
27554
  const overrides = await readEnvOverrides(commanderStatePaths(resolveCommanderDataDir(), ctx.config.configKey).envOverridesPath);
27555
+ const judge = await judgeEnv(ctx.config);
26809
27556
  out.print("env:");
26810
27557
  out.print(" note: `run` children inherit THIS shell's environment; daemon-owned starts (`up`) inherit");
26811
27558
  out.print(" the daemon's boot-time snapshot — `doctor` shows that snapshot's age.");
27559
+ out.print(` ${judge.note}`);
26812
27560
  for (const id of selection.ordered) {
26813
27561
  const def = ctx.config.processes.find((proc) => proc.id === id);
26814
27562
  if (def == null) continue;
26815
27563
  const parts = [];
26816
27564
  for (const [key, value] of Object.entries(def.env)) parts.push(value == null ? `${key}=(unset)` : `${key}=${value} (config)`);
26817
- for (const view of envVarViews(def, overrides, process.env)) {
26818
- const shown = view.secret ? "•••" : view.value ?? (view.source === "inherited" ? "(from shell)" : "(unset)");
27565
+ for (const view of envVarViews(def, overrides, judge.baseEnv(def))) {
27566
+ const shown = view.secret ? "•••" : view.value ?? (view.source === "inherited" ? `(from ${describeJudgedIn(judge.judgedIn)})` : "(unset)");
26819
27567
  parts.push(`${view.name}=${shown} (${view.source}${view.source === "override" ? ", sticky" : ""})`);
26820
27568
  }
26821
27569
  if (parts.length > 0) out.print(` ${id}: ${parts.join(" ")}`);
@@ -27316,6 +28064,11 @@ async function cmdRun(ctx) {
27316
28064
  if (parallel != null && !defs.some((def) => def.kind === "task")) out.warn(out.paint("yellow", "note: --parallel applies to tasks; this selection has none — ignored."));
27317
28065
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
27318
28066
  const overrides = await readEnvOverrides(paths.envOverridesPath);
28067
+ const unmet = defs.flatMap((def) => {
28068
+ const missing = missingRequired(def, overrides, process.env);
28069
+ return missing.length === 0 ? [] : [`"${def.id}" ${requiredRefusal(def.id, missing, "shell")}`];
28070
+ });
28071
+ if (unmet.length > 0) throw new CliExit(EXIT.failure, `nothing was started — ${unmet.join("\n")}`);
27319
28072
  const ledger = openProcessLedger({
27320
28073
  dir: paths.stateDir,
27321
28074
  namespace: paths.ledgerNamespace,
@@ -27325,6 +28078,7 @@ async function cmdRun(ctx) {
27325
28078
  if (handle != null) {
27326
28079
  const client = await connectDaemon(handle);
27327
28080
  try {
28081
+ await syncDaemonConfig(config, client, out);
27328
28082
  const owned = defs.filter((def) => ACTIVE_STATES$1.has(client.state().processes[def.id]?.state ?? ""));
27329
28083
  if (owned.length > 0) throw new CliExit(EXIT.failure, `"${owned.map((def) => def.id).join("\", \"")}" is owned by the running daemon — \`down\` it there first (silent double-start is never allowed).`);
27330
28084
  } finally {
@@ -27412,7 +28166,7 @@ async function cmdRun(ctx) {
27412
28166
  });
27413
28167
  let timer = null;
27414
28168
  let timedOut = false;
27415
- let run = null;
28169
+ let run;
27416
28170
  try {
27417
28171
  await proc.start();
27418
28172
  run = noteStart(def);
@@ -27444,7 +28198,7 @@ async function cmdRun(ctx) {
27444
28198
  }
27445
28199
  const code = proc.lastExit?.code ?? (proc.state === "succeeded" ? 0 : 1);
27446
28200
  const failed = code !== 0;
27447
- if (!failed && run != null && passthrough.length === 0) run.durationMs = Date.now() - run.startedAt;
28201
+ if (!failed && passthrough.length === 0) run.durationMs = Date.now() - run.startedAt;
27448
28202
  out.print(failed ? `${out.paint("red", "✗")} ${out.accent(def.id, def.id)} exit ${code}` : `${out.paint("green", "✓")} ${out.accent(def.id, def.id)} ok`);
27449
28203
  return {
27450
28204
  id: def.id,
@@ -27964,10 +28718,15 @@ const COMMAND_HELP = [
27964
28718
  command in the same cwd, started outside the daemon
27965
28719
  (a stranger on the port still refuses). --json reports
27966
28720
  every id's outcome, state, pid and endpoints as data.`],
27967
- ["down", " down <sel> stop (reverse-DAG order)"],
28721
+ ["down", ` down <sel> [--only] stop the selection (dependents first) and each of its
28722
+ dependencies that no other live process needs; one
28723
+ that is still needed stays up and is named, with what
28724
+ needs it. --only stops exactly the selection.`],
27968
28725
  ["restart", ` restart <sel> [--no-wait] [--replace-same] [--with <flag>]
27969
- stop + start, with the flags of the run it replaces
27970
- unless --with names others`],
28726
+ stop + start exactly the selection, with the flags of
28727
+ the run it replaces unless --with names others. Its
28728
+ dependencies keep running; one that is down is
28729
+ started first.`],
27971
28730
  ["status", " status [--watch] table from the live status realm"],
27972
28731
  ["logs", " logs <sel> [-f] merged interleaved tail with colored id prefixes"],
27973
28732
  ["list", " list config introspection (processes, suites, warnings)"],
@@ -28071,7 +28830,7 @@ async function withTimeout(ctx, run) {
28071
28830
  async function main() {
28072
28831
  const argv = process.argv.slice(2);
28073
28832
  if (argv[0] === "daemon") {
28074
- const { runCommanderDaemon } = await import("./main-DSPhWTfM.mjs");
28833
+ const { runCommanderDaemon } = await import("./main-Bxa0Lop9.mjs");
28075
28834
  return runCommanderDaemon(argv.slice(1));
28076
28835
  }
28077
28836
  const parsed = parseCliArgs(argv);
@@ -28120,6 +28879,6 @@ main().then((code) => {
28120
28879
  process.exitCode = EXIT.failure;
28121
28880
  });
28122
28881
  //#endregion
28123
- export { savedFilterId as $, commanderRuntimeError as A, createDefaultServeLogger as B, COMMANDER_HEALTH_PATH as C, COMMANDER_TICKET_PROTOCOL_PREFIX as D, COMMANDER_TICKET_PATH as E, findDaemonProcesses as F, effectiveEnv as G, createMemoryStorageAdapter_json as H, createRealmAcceptor as I, hashCanonical as J, envVarViews as K, createRealmServerEngine as L, commanderStatePaths as M, ensureStateDir as N, COMMANDER_WS_PATH as O, resolveCommanderDataDir as P, withDependencies as Q, httpAcceptorCarrier as R, COMMANDER_BOOTSTRAP_PATH as S, COMMANDER_SHUTDOWN_PATH as T, wsAcceptorCarrier as U, RuntimeCoordinate as V, validateCommanderConfig as W, orderByDependency as X, loadCommanderConfigFile as Y, stopSetWithDependencies as Z, applyEnvMutation as _, durationKey as a, writeInstanceRecord as at, commanderChannel as b, withDuration as c, writeLastStarts as d, resolveFlags as et, parseLogsClientMessage as f, signalStray as g, identifyEndpointOwner as h, runTaskPool as i, removeInstanceRecord as it, commanderPackageVersion as j, commanderStatusRealm as k, writeTaskDurations as l, createPortInspector as m, readSavedFilters as n, readInstanceRecord as nt, estimateMs as o, ancestors as p, overrideFingerprint as q, writeSavedFilters as r, recordDaemonAlive as rt, readTaskDurations as s, mutateSavedFilters as t, runWithArgs as tt, readLastStarts as u, countOverrides as v, COMMANDER_LOGS_PATH as w, commanderControlDomain as x, readEnvOverrides as y, serveChannel as z };
28882
+ export { stopSetWithDependencies as $, commanderRuntimeError as A, RuntimeCoordinate as B, COMMANDER_HEALTH_PATH as C, COMMANDER_TICKET_PROTOCOL_PREFIX as D, COMMANDER_TICKET_PATH as E, createRealmAcceptor as F, envVarViews as G, wsAcceptorCarrier as H, createRealmServerEngine as I, requiredRefusal as J, missingRequired as K, httpAcceptorCarrier as L, ensureStateDir as M, resolveCommanderDataDir as N, COMMANDER_WS_PATH as O, findDaemonProcesses as P, orderByDependency as Q, serveChannel as R, COMMANDER_BOOTSTRAP_PATH as S, COMMANDER_SHUTDOWN_PATH as T, validateCommanderConfig as U, createMemoryStorageAdapter_json as V, effectiveEnv as W, CommanderConfigLoadError as X, hashCanonical as Y, loadCommanderConfigFile as Z, applyEnvMutation as _, durationKey as a, readInstanceRecord as at, commanderChannel as b, withDuration as c, writeInstanceRecord as ct, writeLastStarts as d, withDependencies as et, parseLogsClientMessage as f, signalStray as g, identifyEndpointOwner as h, runTaskPool as i, commanderPackageVersion as it, commanderStatePaths as j, commanderStatusRealm as k, writeTaskDurations as l, createPortInspector as m, readSavedFilters as n, resolveFlags as nt, estimateMs as o, recordDaemonAlive as ot, ancestors as p, overrideFingerprint as q, writeSavedFilters as r, runWithArgs as rt, readTaskDurations as s, removeInstanceRecord as st, mutateSavedFilters as t, savedFilterId as tt, readLastStarts as u, countOverrides as v, COMMANDER_LOGS_PATH as w, commanderControlDomain as x, readEnvOverrides as y, createDefaultServeLogger as z };
28124
28883
 
28125
28884
  //# sourceMappingURL=cli.mjs.map