@nice-code/commander 0.108.0 → 0.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.cjs CHANGED
@@ -1378,6 +1378,7 @@ function wsAcceptorCarrier(options) {
1378
1378
  carrierLabel: options.carrierLabel ?? "ws",
1379
1379
  secure: options.secure,
1380
1380
  send: options.send,
1381
+ close: options.close,
1381
1382
  upgrade: options.upgrade,
1382
1383
  isUpgrade: options.isUpgrade ?? ((request) => request.headers.get("Upgrade") === "websocket"),
1383
1384
  attachmentStore: options.attachmentStore
@@ -2431,16 +2432,16 @@ const err_wire_connect = err_nice.createChildDomain({
2431
2432
  */
2432
2433
  endpoint_answered_non_protocol: err({ message: ({ stage, expected, url, httpStatus, contentType, receivedKind, bodyPreview }) => {
2433
2434
  const received = httpStatus != null ? `an HTTP ${httpStatus}${contentType != null ? ` ${contentType}` : ""} response` : receivedKind != null ? `a "${receivedKind}" frame` : "a response it could not decode";
2434
- return `[${stage}] expected ${expected ?? "a nice-wire frame"} but received ${received} — the endpoint answered but is not speaking the nice-wire protocol (wrong URL, an intercepting proxy/WAF, or a different server)${url != null ? `. Dialed: ${url}` : ""}${bodyPreview != null ? `. Body: ${JSON.stringify(bodyPreview)}` : ""}.`;
2435
+ const diagnosis = httpStatus != null && httpStatus >= 500 ? "the server answered with an error instead of a nice-wire frame (check the server's logs: a crashed handler or an unavailable upstream answers this way)" : "the endpoint answered but is not speaking the nice-wire protocol (wrong URL, an intercepting proxy/WAF, or a different server)";
2436
+ return `[${stage}] expected ${expected ?? "a nice-wire frame"} but received ${received} — ` + diagnosis + `${url != null ? `. Dialed: ${url}` : ""}${bodyPreview != null ? `. Body: ${JSON.stringify(bodyPreview)}` : ""}.`;
2435
2437
  } }),
2436
2438
  /**
2437
- * Consumer feedback (meteor-connect-bridge W3) — **nothing answered**: DNS/refused/TLS/offline,
2438
- * or a socket that errored before it opened. The sibling of
2439
- * `endpoint_answered_non_protocol`, and the reason the two are separate ids: they need
2440
- * opposite developer responses (start the server / open the firewall, vs fix the URL or the
2441
- * proxy in front of it).
2439
+ * **No response was received**: DNS/refused/TLS/offline, a socket that errored before it
2440
+ * opened, or a response the platform hid from the caller (a CORS-blocked answer, a refused
2441
+ * WebSocket upgrade, an injected fetch/socket that threw). The sibling of
2442
+ * `endpoint_answered_non_protocol`, which carries the response it did see.
2442
2443
  */
2443
- endpoint_unreachable: err({ message: ({ url, carrierLabel, reason }) => `Could not reach ${url ?? (carrierLabel != null ? `the "${carrierLabel}" endpoint` : "the endpoint")}: ${reason} — nothing answered there (wrong host/port, the server is not running, or a firewall/offline network).` }),
2444
+ 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).` }),
2444
2445
  /**
2445
2446
  * The peer **is** a nice-code backend and refused the handshake for a reason that carries no
2446
2447
  * machine-readable id of its own (an older peer, a dictionary/security mismatch, a custom
@@ -2483,6 +2484,29 @@ const err_wire_connect = err_nice.createChildDomain({
2483
2484
  }
2484
2485
  });
2485
2486
  //#endregion
2487
+ //#region ../nice-wire/src/Connect/sanitizeEndpoint.ts
2488
+ /**
2489
+ * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can carry
2490
+ * secrets (capability tokens, signed leases), so only the scheme, host, port, and path survive.
2491
+ */
2492
+ function sanitizeEndpoint(raw) {
2493
+ if (raw == null) return void 0;
2494
+ try {
2495
+ const url = new URL(raw);
2496
+ if (url.host !== "") {
2497
+ url.username = "";
2498
+ url.password = "";
2499
+ url.search = "";
2500
+ url.hash = "";
2501
+ return url.toString();
2502
+ }
2503
+ } catch {}
2504
+ const head = raw.split(/[?#]/, 1)[0] ?? "";
2505
+ const authority = /^([a-z][a-z\d+.-]*:)?\/\//i.exec(head);
2506
+ if (authority != null) return authority[0] + head.slice(authority[0].length).replace(/^[^/@]*@/, "");
2507
+ return head.replace(/^[^/]*@/, "");
2508
+ }
2509
+ //#endregion
2486
2510
  //#region ../nice-wire/src/Carrier/duplex/ws/ws_util.ts
2487
2511
  /**
2488
2512
  * Send a text or binary frame over a socket. A binary formatter may hand back a `Uint8Array` whose
@@ -2577,8 +2601,9 @@ function webSocketByteChannel(ws) {
2577
2601
  }
2578
2602
  /**
2579
2603
  * A failed dial, as a structured error the error pipeline (and a consumer's logs) can actually
2580
- * read. A socket that errors or closes *before* it opened means nothing answered, so it carries
2581
- * the same typed `endpoint_unreachable` id as the HTTP carrier's `fetch` rejection — that is what
2604
+ * read. A socket that errors or closes *before* it opened yields no readable response (the browser
2605
+ * also hides a refused upgrade's status), so it carries the same typed `endpoint_unreachable` id as
2606
+ * the HTTP carrier's `fetch` rejection — that is what
2582
2607
  * makes `EWireConnectFailureKind` trustworthy on both carriers rather than HTTP-only (feedback W3).
2583
2608
  */
2584
2609
  function dialFailedError(ws) {
@@ -2586,13 +2611,13 @@ function dialFailedError(ws) {
2586
2611
  }
2587
2612
  function unreachableError(ws, reason) {
2588
2613
  return err_wire_connect.fromId("endpoint_unreachable", {
2589
- url: ws.url != null && ws.url !== "" ? ws.url : void 0,
2614
+ url: ws.url != null && ws.url !== "" ? sanitizeEndpoint(ws.url) : void 0,
2590
2615
  carrierLabel: "ws",
2591
2616
  reason
2592
2617
  });
2593
2618
  }
2594
2619
  function describeSocket(ws) {
2595
- return ws.url != null && ws.url !== "" ? ws.url : "(no url)";
2620
+ return (ws.url != null && ws.url !== "" ? sanitizeEndpoint(ws.url) : void 0) ?? "(no url)";
2596
2621
  }
2597
2622
  /** Accept text + binary frames (ArrayBuffer / Uint8Array / Blob); Blobs are converted to a buffer. */
2598
2623
  async function normalizeFrame(data) {
@@ -2675,23 +2700,6 @@ function describeNonProtocolBody(raw) {
2675
2700
  return flattened.length > BODY_PREVIEW_LIMIT ? `${flattened.slice(0, BODY_PREVIEW_LIMIT)}…` : flattened;
2676
2701
  }
2677
2702
  /**
2678
- * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can
2679
- * contain secrets, so connection errors retain only the scheme, host, port, and path.
2680
- */
2681
- function sanitizeEndpoint(raw) {
2682
- if (raw == null) return void 0;
2683
- try {
2684
- const url = new URL(raw);
2685
- url.username = "";
2686
- url.password = "";
2687
- url.search = "";
2688
- url.hash = "";
2689
- return url.toString();
2690
- } catch {
2691
- return raw.split(/[?#]/, 1)[0];
2692
- }
2693
- }
2694
- /**
2695
2703
  * Classify a dial failure. Reads typed ids only — the ids are raised at the layer that still holds
2696
2704
  * the evidence precisely so this never has to sniff message text.
2697
2705
  */
@@ -2704,12 +2712,12 @@ function classifyConnectFailure(error) {
2704
2712
  if (error.hasId("identity_pin_mismatch") || error.hasId("handshake_rejected")) return "handshake_rejected";
2705
2713
  return "unknown";
2706
2714
  }
2707
- /** The endpoint a failure names, when it carries one — the URL actually dialed. */
2715
+ /** The endpoint a failure names, when it carries one — the URL actually dialed, sanitized. */
2708
2716
  function endpointFromConnectFailure(error) {
2709
2717
  if (!err_wire_connect.isExact(error)) return void 0;
2710
- if (error.hasId("endpoint_answered_non_protocol")) return error.getContext("endpoint_answered_non_protocol").url;
2711
- if (error.hasId("endpoint_unreachable")) return error.getContext("endpoint_unreachable").url;
2712
- if (error.hasId("peer_identity_mismatch")) return error.getContext("peer_identity_mismatch").endpoint;
2718
+ if (error.hasId("endpoint_answered_non_protocol")) return sanitizeEndpoint(error.getContext("endpoint_answered_non_protocol").url);
2719
+ if (error.hasId("endpoint_unreachable")) return sanitizeEndpoint(error.getContext("endpoint_unreachable").url);
2720
+ if (error.hasId("peer_identity_mismatch")) return sanitizeEndpoint(error.getContext("peer_identity_mismatch").endpoint);
2713
2721
  }
2714
2722
  //#endregion
2715
2723
  //#region ../nice-wire/src/Connect/ConnectionTransportManager.ts
@@ -2744,81 +2752,110 @@ var ConnectionTransportManager$1 = class {
2744
2752
  const candidates = [];
2745
2753
  const unavailableTransports = [];
2746
2754
  for (const transport of this._transports) {
2747
- if (!transport.isAvailable(input)) {
2748
- unavailableTransports.push(transport);
2749
- continue;
2750
- }
2751
- const cacheKey = transport.getCacheKey(input);
2752
- if (cacheKey != null) {
2753
- const cached = this._cache.get(cacheKey);
2754
- if (cached != null) {
2755
- if (cached instanceof Promise) {
2755
+ let cacheKey = null;
2756
+ try {
2757
+ if (!transport.isAvailable(input)) {
2758
+ unavailableTransports.push(transport);
2759
+ continue;
2760
+ }
2761
+ cacheKey = transport.getCacheKey(input);
2762
+ if (cacheKey != null) {
2763
+ const cached = this._cache.get(cacheKey);
2764
+ if (cached != null) {
2765
+ if (cached instanceof Promise) {
2766
+ candidates.push({
2767
+ transport,
2768
+ promise: cached,
2769
+ cacheKey,
2770
+ fresh: false
2771
+ });
2772
+ continue;
2773
+ }
2756
2774
  candidates.push({
2757
2775
  transport,
2758
- promise: cached
2776
+ promise: Promise.resolve({
2777
+ ...cached,
2778
+ transport
2779
+ }),
2780
+ cacheKey,
2781
+ fresh: false
2782
+ });
2783
+ break;
2784
+ }
2785
+ }
2786
+ const statusInfo = transport.getTransport(input);
2787
+ if (statusInfo.status === "ready") {
2788
+ const readyData = statusInfo.readyData;
2789
+ if (cacheKey != null) {
2790
+ const key = cacheKey;
2791
+ const entry = {
2792
+ methods: readyData,
2793
+ transport
2794
+ };
2795
+ this._cache.set(key, entry);
2796
+ readyData.addOnDisconnectListener?.(() => {
2797
+ if (this._cache.get(key) === entry) this._cache.delete(key);
2759
2798
  });
2760
- continue;
2761
2799
  }
2762
2800
  candidates.push({
2763
2801
  transport,
2764
2802
  promise: Promise.resolve({
2765
- ...cached,
2803
+ methods: readyData,
2766
2804
  transport
2767
- })
2805
+ }),
2806
+ cacheKey,
2807
+ fresh: true
2768
2808
  });
2769
2809
  break;
2770
2810
  }
2771
- }
2772
- const statusInfo = transport.getTransport(input);
2773
- if (statusInfo.status === "ready") {
2774
- const readyData = statusInfo.readyData;
2775
- if (cacheKey != null) {
2776
- const entry = {
2777
- methods: readyData,
2778
- transport
2779
- };
2780
- this._cache.set(cacheKey, entry);
2781
- readyData.addOnDisconnectListener?.(() => {
2782
- if (this._cache.get(cacheKey) === entry) this._cache.delete(cacheKey);
2811
+ if (statusInfo.status === "unsupported") {
2812
+ unavailableTransports.push(transport);
2813
+ continue;
2814
+ }
2815
+ if (statusInfo.status === "initializing") {
2816
+ const key = cacheKey;
2817
+ const promise = statusInfo.initializationPromise.then((info) => {
2818
+ if (info.status === "failed") throw info.error;
2819
+ if (info.status === "unsupported") throw this._errors.unsupported([transport.type]);
2820
+ const readyData = info.readyData;
2821
+ const entry = {
2822
+ methods: readyData,
2823
+ transport
2824
+ };
2825
+ if (key != null) if (this._cache.get(key) === promise) {
2826
+ this._cache.set(key, entry);
2827
+ readyData.addOnDisconnectListener?.(() => {
2828
+ if (this._cache.get(key) === entry) this._cache.delete(key);
2829
+ });
2830
+ } else readyData.disconnect?.();
2831
+ return entry;
2832
+ }).catch((e) => {
2833
+ if (key != null && this._cache.get(key) === promise) this._cache.delete(key);
2834
+ throw e;
2835
+ });
2836
+ promise.catch(() => {});
2837
+ if (key != null) this._cache.set(key, promise);
2838
+ candidates.push({
2839
+ transport,
2840
+ promise,
2841
+ cacheKey: key,
2842
+ fresh: true
2783
2843
  });
2784
2844
  }
2845
+ } catch (e) {
2846
+ if (isDialUnavailable$1(e)) {
2847
+ if (candidates.length === 0) throw e;
2848
+ unavailableTransports.push(transport);
2849
+ continue;
2850
+ }
2851
+ const failed = Promise.reject(e);
2852
+ failed.catch(() => {});
2785
2853
  candidates.push({
2786
2854
  transport,
2787
- promise: Promise.resolve({
2788
- methods: readyData,
2789
- transport
2790
- })
2791
- });
2792
- break;
2793
- }
2794
- if (statusInfo.status === "unsupported") {
2795
- unavailableTransports.push(transport);
2796
- continue;
2797
- }
2798
- if (statusInfo.status === "initializing") {
2799
- const promise = statusInfo.initializationPromise.then((info) => {
2800
- if (info.status === "failed") throw info.error;
2801
- if (info.status === "unsupported") throw this._errors.unsupported([transport.type]);
2802
- const readyData = info.readyData;
2803
- const entry = {
2804
- methods: readyData,
2805
- transport
2806
- };
2807
- if (cacheKey != null) if (this._cache.get(cacheKey) === promise) {
2808
- this._cache.set(cacheKey, entry);
2809
- readyData.addOnDisconnectListener?.(() => {
2810
- if (this._cache.get(cacheKey) === entry) this._cache.delete(cacheKey);
2811
- });
2812
- } else readyData.disconnect?.();
2813
- return entry;
2814
- }).catch((e) => {
2815
- if (cacheKey != null && this._cache.get(cacheKey) === promise) this._cache.delete(cacheKey);
2816
- throw e;
2817
- });
2818
- if (cacheKey != null) this._cache.set(cacheKey, promise);
2819
- candidates.push({
2820
- transport,
2821
- promise
2855
+ promise: failed,
2856
+ cacheKey,
2857
+ fresh: true,
2858
+ callerThrew: true
2822
2859
  });
2823
2860
  }
2824
2861
  }
@@ -2828,31 +2865,79 @@ var ConnectionTransportManager$1 = class {
2828
2865
  }
2829
2866
  let lastError;
2830
2867
  let lastTransport;
2831
- for (const candidate of candidates) try {
2832
- return await candidate.promise;
2833
- } catch (e) {
2834
- if (err_wire_connect.isExact(e) && e.hasId("peer_identity_mismatch")) {
2835
- const context = e.getContext("peer_identity_mismatch");
2836
- const endpoint = sanitizeEndpoint(candidate.transport.getRouteInfo(input)?.url);
2837
- if (endpoint != null && context.endpoint == null) throw err_wire_connect.fromId("peer_identity_mismatch", {
2838
- ...context,
2839
- endpoint
2840
- }).withOriginError(e);
2841
- throw e;
2868
+ let lastCallerThrew = false;
2869
+ for (const candidate of candidates) {
2870
+ let ready;
2871
+ try {
2872
+ ready = await candidate.promise;
2873
+ } catch (e) {
2874
+ if (isTerminalSelectionError(e)) {
2875
+ this._abandonWarmUps(candidates, candidate);
2876
+ throw this._withDialedEndpoint(e, candidate.transport, input);
2877
+ }
2878
+ lastError = e;
2879
+ lastTransport = candidate.transport;
2880
+ lastCallerThrew = candidate.callerThrew === true;
2881
+ continue;
2842
2882
  }
2843
- if (err_wire_connect.isExact(e) && e.hasId("protocol_version_mismatch")) throw e;
2844
- lastError = e;
2845
- lastTransport = candidate.transport;
2883
+ ready.methods.onSelected?.();
2884
+ return ready;
2846
2885
  }
2847
2886
  if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch") || lastError.hasId("protocol_version_mismatch") || lastError.hasId("peer_identity_mismatch"))) throw lastError;
2887
+ if (lastCallerThrew && !err_wire_connect.isExact(lastError)) throw lastError;
2848
2888
  throw this._errors.initializationFailed(input, {
2849
2889
  cause: describeTransportFailure(lastError),
2850
- endpoint: endpointFromConnectFailure(lastError) ?? lastTransport?.getRouteInfo(input)?.url,
2890
+ endpoint: endpointFromConnectFailure(lastError) ?? routeEndpoint(lastTransport, input),
2851
2891
  kind: classifyConnectFailure(lastError),
2852
2892
  origin: lastError
2853
2893
  });
2854
2894
  }
2895
+ /**
2896
+ * Close the parallel warm-ups this selection started besides `failed`. Each one's cache slot is
2897
+ * released so a later dispatch re-dials; a warm-up still connecting closes itself when it lands.
2898
+ */
2899
+ _abandonWarmUps(candidates, failed) {
2900
+ for (const candidate of candidates) {
2901
+ if (candidate === failed || !candidate.fresh) continue;
2902
+ const key = candidate.cacheKey;
2903
+ if (key != null && this._cache.get(key) === candidate.promise) this._cache.delete(key);
2904
+ candidate.promise.then((entry) => {
2905
+ if (key == null) {
2906
+ entry.methods.disconnect?.();
2907
+ return;
2908
+ }
2909
+ const cached = this._cache.get(key);
2910
+ if (cached != null && !(cached instanceof Promise) && cached.methods === entry.methods) {
2911
+ this._cache.delete(key);
2912
+ entry.methods.disconnect?.();
2913
+ }
2914
+ }, () => {});
2915
+ }
2916
+ }
2917
+ /** Attach the sanitized dialed endpoint to a peer-identity mismatch that lacks one. */
2918
+ _withDialedEndpoint(error, transport, input) {
2919
+ if (!err_wire_connect.isExact(error) || !error.hasId("peer_identity_mismatch")) return error;
2920
+ const context = error.getContext("peer_identity_mismatch");
2921
+ if (context.endpoint != null) return error;
2922
+ const endpoint = routeEndpoint(transport, input);
2923
+ if (endpoint == null) return error;
2924
+ return err_wire_connect.fromId("peer_identity_mismatch", {
2925
+ ...context,
2926
+ endpoint
2927
+ }).withOriginError(error);
2928
+ }
2855
2929
  };
2930
+ const isDialUnavailable$1 = (error) => err_wire_connect.isExact(error) && error.hasId("dial_unavailable");
2931
+ const isTerminalSelectionError = (error) => err_wire_connect.isExact(error) && (error.hasId("peer_identity_mismatch") || error.hasId("protocol_version_mismatch"));
2932
+ /** The transport's sanitized route URL for diagnostics; a throwing route resolver yields none. */
2933
+ function routeEndpoint(transport, input) {
2934
+ if (transport == null) return void 0;
2935
+ try {
2936
+ return sanitizeEndpoint(transport.getRouteInfo(input)?.url);
2937
+ } catch {
2938
+ return;
2939
+ }
2940
+ }
2856
2941
  /**
2857
2942
  * A short, human-readable reason for a transport failing to connect — surfaced in the
2858
2943
  * consumer's initialization-failed message so the caller sees *why* (e.g. a rejected handshake) rather
@@ -8843,7 +8928,7 @@ function wrongHandshakeFrame(channel, expected, receivedKind) {
8843
8928
  return err_wire_connect.fromId("endpoint_answered_non_protocol", {
8844
8929
  stage: LINK_HANDSHAKE_STAGE,
8845
8930
  expected,
8846
- url: channel.label,
8931
+ url: sanitizeEndpoint(channel.label),
8847
8932
  receivedKind: `hs/${receivedKind}`
8848
8933
  });
8849
8934
  }
@@ -8893,6 +8978,32 @@ function startHeartbeat(channel, config, tap) {
8893
8978
  }
8894
8979
  };
8895
8980
  }
8981
+ function bindMux(mux, remoteIds, pipe, disconnectListeners, tap) {
8982
+ let attached = false;
8983
+ let closed = false;
8984
+ const held = [];
8985
+ disconnectListeners.push(() => {
8986
+ closed = true;
8987
+ held.length = 0;
8988
+ if (attached) mux.detach();
8989
+ });
8990
+ return {
8991
+ mux,
8992
+ dispatch: (frame) => {
8993
+ if (attached) return mux.dispatchIncoming(frame);
8994
+ if (peekProtocolPrefix(frame) == null) return false;
8995
+ if (!closed) held.push(frame);
8996
+ return true;
8997
+ },
8998
+ attach: () => {
8999
+ if (attached || closed) return;
9000
+ attached = true;
9001
+ mux.setRemoteProtocolIds(remoteIds());
9002
+ mux.attach(tap != null ? (bytes) => pipe.send(bytes, mux.protocolIdFor(bytes) ?? "protocol") : (bytes) => pipe.send(bytes));
9003
+ for (const frame of held.splice(0)) mux.dispatchIncoming(frame);
9004
+ }
9005
+ };
9006
+ }
8896
9007
  /**
8897
9008
  * Wrap a carrier so a **deliberate local** `close()` notifies the session immediately and exactly
8898
9009
  * once, rather than waiting for the platform's close event. On a real WebSocket that event lags a
@@ -8949,6 +9060,7 @@ function establishPlainDuplexSession(ctx) {
8949
9060
  const mux = ctx.mux;
8950
9061
  const heartbeat = ctx.heartbeat != null ? startHeartbeat(channel, ctx.heartbeat, tap) : void 0;
8951
9062
  if (heartbeat != null) disconnectListeners.push(heartbeat.stop);
9063
+ const muxBinding = mux == null ? void 0 : bindMux(mux, () => protocolsFromCaps(mux.localCaps()), pipe, disconnectListeners, tap);
8952
9064
  channel.attach({
8953
9065
  onMessage: (frame) => {
8954
9066
  heartbeat?.noteInbound();
@@ -8960,17 +9072,13 @@ function establishPlainDuplexSession(ctx) {
8960
9072
  });
8961
9073
  return;
8962
9074
  }
8963
- handleIncomingFrame(pipe, frame, mux, ctx.lane, port, tap);
9075
+ handleIncomingFrame(pipe, frame, muxBinding, ctx.lane, port, tap);
8964
9076
  },
8965
9077
  onClose: () => onChannelClosed(disconnectListeners, ctx.lane),
8966
9078
  onError: () => onChannelClosed(disconnectListeners, ctx.lane)
8967
9079
  });
8968
- if (mux != null) {
8969
- mux.setRemoteProtocolIds(protocolsFromCaps(mux.localCaps()));
8970
- mux.attach(tap != null ? (bytes) => pipe.send(bytes, mux.protocolIdFor(bytes) ?? "protocol") : (bytes) => pipe.send(bytes));
8971
- disconnectListeners.push(() => mux.detach());
8972
- }
8973
- return makeSession$1(channel, pipe, disconnectListeners, void 0);
9080
+ if (ctx.deferMuxAttach !== true) muxBinding?.attach();
9081
+ return makeSession$1(channel, pipe, disconnectListeners, void 0, muxBinding);
8974
9082
  }
8975
9083
  /**
8976
9084
  * Secure path: a single message handler feeds the handshake until it completes, then routes lane
@@ -9004,7 +9112,7 @@ async function establishSecureDuplexSession(ctx) {
9004
9112
  return;
9005
9113
  }
9006
9114
  if (active && session.pipe != null && session.port != null) {
9007
- handleIncomingFrame(session.pipe, frame, mux, ctx.lane, session.port, tap);
9115
+ handleIncomingFrame(session.pipe, frame, session.muxBinding, ctx.lane, session.port, tap);
9008
9116
  return;
9009
9117
  }
9010
9118
  if (typeof frame === "string") {
@@ -9034,7 +9142,7 @@ async function establishSecureDuplexSession(ctx) {
9034
9142
  const timeout = setTimeout(() => reject(nonProtocolFrame != null ? err_wire_connect.fromId("endpoint_answered_non_protocol", {
9035
9143
  stage: LINK_HANDSHAKE_STAGE,
9036
9144
  expected: "a handshake frame",
9037
- url: channel.label,
9145
+ url: sanitizeEndpoint(channel.label),
9038
9146
  bodyPreview: describeNonProtocolBody(nonProtocolFrame)
9039
9147
  }) : /* @__PURE__ */ new Error(`[${LINK_HANDSHAKE_STAGE}] timed out waiting for peer reply`)), HANDSHAKE_TIMEOUT_MS$1);
9040
9148
  handshakeWaiters.push((message) => {
@@ -9043,28 +9151,31 @@ async function establishSecureDuplexSession(ctx) {
9043
9151
  });
9044
9152
  });
9045
9153
  };
9046
- const { crypto, remoteCaps } = await runClientHandshake({
9047
- ...ctx,
9048
- channel
9049
- }, nextHandshakeMessage);
9050
- const pipe = makePipe(channel, crypto, tap);
9051
- const port = makeLanePort(channel, pipe);
9052
- session.pipe = pipe;
9053
- session.port = port;
9054
- if (mux != null) {
9055
- mux.setRemoteProtocolIds(protocolsFromCaps(remoteCaps));
9056
- mux.attach(tap != null ? (bytes) => pipe.send(bytes, mux.protocolIdFor(bytes) ?? "protocol") : (bytes) => pipe.send(bytes));
9057
- disconnectListeners.push(() => mux.detach());
9058
- }
9059
- ctx.lane.onAttach?.(port, { remoteCaps: remoteCaps ?? [] });
9060
- active = true;
9061
- for (const frame of pendingFrames) await handleIncomingFrame(pipe, frame, mux, ctx.lane, port, tap);
9062
- pendingFrames.length = 0;
9063
- if (ctx.heartbeat != null) {
9064
- heartbeat = startHeartbeat(channel, ctx.heartbeat, tap);
9065
- disconnectListeners.push(heartbeat.stop);
9066
- }
9067
- return makeSession$1(channel, pipe, disconnectListeners, remoteCaps);
9154
+ try {
9155
+ const { crypto, remoteCaps } = await runClientHandshake({
9156
+ ...ctx,
9157
+ channel
9158
+ }, nextHandshakeMessage);
9159
+ const pipe = makePipe(channel, crypto, tap);
9160
+ const port = makeLanePort(channel, pipe);
9161
+ session.pipe = pipe;
9162
+ session.port = port;
9163
+ const muxBinding = mux == null ? void 0 : bindMux(mux, () => protocolsFromCaps(remoteCaps), pipe, disconnectListeners, tap);
9164
+ session.muxBinding = muxBinding;
9165
+ if (ctx.deferMuxAttach !== true) muxBinding?.attach();
9166
+ ctx.lane.onAttach?.(port, { remoteCaps: remoteCaps ?? [] });
9167
+ active = true;
9168
+ for (const frame of pendingFrames) await handleIncomingFrame(pipe, frame, muxBinding, ctx.lane, port, tap);
9169
+ pendingFrames.length = 0;
9170
+ if (ctx.heartbeat != null) {
9171
+ heartbeat = startHeartbeat(channel, ctx.heartbeat, tap);
9172
+ disconnectListeners.push(heartbeat.stop);
9173
+ }
9174
+ return makeSession$1(channel, pipe, disconnectListeners, remoteCaps, muxBinding);
9175
+ } catch (error) {
9176
+ closeQuietly(channel);
9177
+ throw error;
9178
+ }
9068
9179
  }
9069
9180
  function makePipe(channel, crypto, tap) {
9070
9181
  return createFrameCryptoPipe({
@@ -9087,19 +9198,21 @@ function makeLanePort(channel, pipe) {
9087
9198
  isOpen: () => channel.isOpen()
9088
9199
  };
9089
9200
  }
9090
- function makeSession$1(channel, pipe, disconnectListeners, remoteCaps) {
9201
+ function closeQuietly(channel) {
9202
+ try {
9203
+ channel.close();
9204
+ } catch {}
9205
+ }
9206
+ function makeSession$1(channel, pipe, disconnectListeners, remoteCaps, muxBinding) {
9091
9207
  return {
9092
9208
  send: (frame) => pipe.send(frame),
9093
9209
  isOpen: () => channel.isOpen(),
9094
- close: () => {
9095
- try {
9096
- channel.close();
9097
- } catch {}
9098
- },
9210
+ close: () => closeQuietly(channel),
9099
9211
  addOnDisconnectListener: (listener) => {
9100
9212
  disconnectListeners.push(listener);
9101
9213
  },
9102
- remoteCaps
9214
+ remoteCaps,
9215
+ attachMux: muxBinding == null ? void 0 : () => muxBinding.attach()
9103
9216
  };
9104
9217
  }
9105
9218
  async function runClientHandshake(ctx, nextHandshakeMessage) {
@@ -9141,15 +9254,15 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
9141
9254
  };
9142
9255
  }
9143
9256
  /** Decrypt → mux dispatch → the lane. Awaited by the pre-ready flush so frame order holds. */
9144
- async function handleIncomingFrame(pipe, frame, mux, lane, port, tap) {
9257
+ async function handleIncomingFrame(pipe, frame, muxBinding, lane, port, tap) {
9145
9258
  const wireBytes = tap != null ? wireFrameByteSize(frame) : 0;
9146
9259
  const decoded = await pipe.decryptIncoming(frame);
9147
9260
  if (decoded === void 0) return;
9148
- if (mux?.dispatchIncoming(decoded)) {
9261
+ if (muxBinding?.dispatch(decoded)) {
9149
9262
  tap?.({
9150
9263
  dir: "in",
9151
9264
  bytes: wireBytes,
9152
- lane: mux.protocolIdFor(decoded) ?? "protocol"
9265
+ lane: muxBinding.mux.protocolIdFor(decoded) ?? "protocol"
9153
9266
  });
9154
9267
  return;
9155
9268
  }
@@ -9578,7 +9691,7 @@ async function exchangeHandshakeFrame(carrier, request, expected) {
9578
9691
  if (reply == null) throw err_wire_connect.fromId("endpoint_answered_non_protocol", {
9579
9692
  stage: HANDSHAKE_STAGE,
9580
9693
  expected,
9581
- url: carrier.label,
9694
+ url: sanitizeEndpoint(carrier.label),
9582
9695
  bodyPreview: describeNonProtocolBody(raw)
9583
9696
  });
9584
9697
  if (reply.k === "err") throw err_wire_connect.fromId("handshake_rejected", {
@@ -9592,13 +9705,14 @@ function nonProtocolReply(carrier, expected, receivedKind) {
9592
9705
  return err_wire_connect.fromId("endpoint_answered_non_protocol", {
9593
9706
  stage: HANDSHAKE_STAGE,
9594
9707
  expected,
9595
- url: carrier.label,
9708
+ url: sanitizeEndpoint(carrier.label),
9596
9709
  receivedKind
9597
9710
  });
9598
9711
  }
9599
9712
  /** Make a peer-bug message self-locating without inventing a typed id for it. */
9600
9713
  function at(carrier) {
9601
- return carrier.label != null ? ` (endpoint: ${carrier.label})` : "";
9714
+ const endpoint = sanitizeEndpoint(carrier.label);
9715
+ return endpoint != null ? ` (endpoint: ${endpoint})` : "";
9602
9716
  }
9603
9717
  function asString(frame) {
9604
9718
  if (typeof frame === "string") return frame;
@@ -9651,6 +9765,7 @@ var AcceptorSecureSession = class {
9651
9765
  t: "reject",
9652
9766
  reason: "server handshake failed; check server logs"
9653
9767
  }));
9768
+ this.config.close?.();
9654
9769
  } catch {}
9655
9770
  });
9656
9771
  }
@@ -9685,12 +9800,15 @@ var AcceptorSecureSession = class {
9685
9800
  });
9686
9801
  if (message.t === "hello") {
9687
9802
  this._helloChannels = message.channels;
9688
- this.config.send(encodeHandshakeMessage(await this._handshake.onHello(message)));
9803
+ const reply = await this._handshake.onHello(message);
9804
+ this.config.send(encodeHandshakeMessage(reply));
9805
+ if (reply.t === "reject") this._refuse();
9689
9806
  } else if (message.t === "prove") {
9690
9807
  const reply = await this._handshake.onProve(message);
9691
9808
  this.config.send(encodeHandshakeMessage(reply));
9692
9809
  const result = this._handshake.getResult();
9693
9810
  if (reply.t === "accept" && result != null) this._complete(result);
9811
+ else if (reply.t === "reject") this._refuse();
9694
9812
  }
9695
9813
  return;
9696
9814
  }
@@ -9698,6 +9816,11 @@ var AcceptorSecureSession = class {
9698
9816
  if (bytes === void 0) return;
9699
9817
  this.config.routeAction(bytes, wireBytes);
9700
9818
  }
9819
+ /** A refused handshake ends this connection: later frames are ignored and the socket closes. */
9820
+ _refuse() {
9821
+ this._handshakeFailed = true;
9822
+ this.config.close?.();
9823
+ }
9701
9824
  _complete(result) {
9702
9825
  this._authed = true;
9703
9826
  this._handshake = void 0;
@@ -9778,6 +9901,7 @@ const KEEPALIVE_PONG = "pong";
9778
9901
  */
9779
9902
  var WireAcceptor = class {
9780
9903
  _send;
9904
+ _close;
9781
9905
  _tap;
9782
9906
  _security;
9783
9907
  _lane;
@@ -9801,6 +9925,7 @@ var WireAcceptor = class {
9801
9925
  _gateWarned = /* @__PURE__ */ new Set();
9802
9926
  constructor(options) {
9803
9927
  this._send = options.send;
9928
+ this._close = options.close;
9804
9929
  this._tap = options.tap;
9805
9930
  this._security = options.security;
9806
9931
  this._lane = options.lane;
@@ -9965,6 +10090,7 @@ var WireAcceptor = class {
9965
10090
  extraCaps: this._protocolCaps(),
9966
10091
  noneAllowed: this._noneAllowed,
9967
10092
  send: (frame, tapLane) => this._writeTapped(connection, frame, tapLane ?? "handshake"),
10093
+ close: this._close == null ? void 0 : () => this._close?.(connection),
9968
10094
  tap: this._tap,
9969
10095
  onAuthenticated: (auth) => this._onAuthenticated(connection, auth),
9970
10096
  routePlain: (frame, wireBytes) => this._receivePlain(connection, frame, wireBytes),
@@ -9977,7 +10103,7 @@ var WireAcceptor = class {
9977
10103
  /** Bind + persist a connection's authenticated identity once its handshake completes. */
9978
10104
  _onAuthenticated(connection, auth) {
9979
10105
  if (this._disposed) return;
9980
- this._bind(connection, auth.client);
10106
+ this._bind(connection, auth.client, auth.securityLevel);
9981
10107
  this._levelByConn.set(connection, auth.securityLevel);
9982
10108
  this._lane.onAuthenticated?.(connection, auth);
9983
10109
  const advertisedIds = protocolsFromCaps(auth.remoteCaps);
@@ -10001,12 +10127,14 @@ var WireAcceptor = class {
10001
10127
  /**
10002
10128
  * Plain-path identity binding: bind the connection to a self-asserted client coordinate (the
10003
10129
  * lane decoded it off an inbound frame) and persist a fresh binding when the identity is new.
10004
- * Secure mode never calls this — the handshake binds the authenticated coordinate instead.
10130
+ * Secure mode never calls this — the handshake binds the authenticated coordinate instead. While
10131
+ * another live connection holds that coordinate through a handshake, pushes and
10132
+ * `connectionForClient` keep resolving to it; the plain claim takes over only once it drops.
10005
10133
  */
10006
10134
  bindPlainConnection(connection, client) {
10007
10135
  if (this._disposed) return;
10008
10136
  const isNewBinding = this._clientByConn.get(connection)?.stringId !== client.stringId;
10009
- this._bind(connection, client);
10137
+ this._bind(connection, client, "none");
10010
10138
  if (isNewBinding) this._persist(connection, {
10011
10139
  v: 1,
10012
10140
  client: client.toJsonObject(),
@@ -10026,11 +10154,12 @@ var WireAcceptor = class {
10026
10154
  console.warn(`[wire-acceptor] ignored a persisted connection binding of unknown schema version ${JSON.stringify(binding.v)} (expected 1) — treating the connection as fresh (err_nice_wire_connect.binding_version_mismatch).`);
10027
10155
  return;
10028
10156
  }
10029
- this._bind(connection, new RuntimeCoordinate(binding.client));
10030
- this._bindingByConn.set(connection, binding);
10031
- this._lane.restoreBindingState?.(connection, binding.lane);
10032
10157
  const secure = binding.secure;
10033
10158
  const security = this._security;
10159
+ const level = secure != null && security != null ? secure.securityLevel : "none";
10160
+ this._bind(connection, new RuntimeCoordinate(binding.client), level);
10161
+ this._bindingByConn.set(connection, binding);
10162
+ this._lane.restoreBindingState?.(connection, binding.lane);
10034
10163
  if (secure != null && security != null) {
10035
10164
  this._levelByConn.set(connection, secure.securityLevel);
10036
10165
  this._sessionFor(connection, security).rehydrate(secure);
@@ -10042,11 +10171,13 @@ var WireAcceptor = class {
10042
10171
  this._bindingByConn.set(connection, binding);
10043
10172
  this._onConnectionBound?.(connection, binding);
10044
10173
  }
10045
- _bind(connection, client) {
10174
+ _bind(connection, client, level) {
10046
10175
  const previous = this._clientByConn.get(connection);
10047
10176
  if (previous != null && previous.stringId !== client.stringId && this._connByClient.get(previous.stringId) === connection) this._connByClient.delete(previous.stringId);
10048
- this._connByClient.set(client.stringId, connection);
10049
10177
  this._clientByConn.set(connection, client);
10178
+ const holder = this._connByClient.get(client.stringId);
10179
+ if (level === "none" && holder != null && holder !== connection && this.levelFor(holder) !== "none") return;
10180
+ this._connByClient.set(client.stringId, connection);
10050
10181
  }
10051
10182
  /** Forget a connection (call on socket close) so stale entries don't misroute later traffic. */
10052
10183
  drop(connection) {
@@ -13769,10 +13900,14 @@ var ChannelConnector = class extends PeerLink {
13769
13900
  defaultLocalCoordinate: () => ActionRuntime.getDefault().coordinate
13770
13901
  });
13771
13902
  for (const transport of transports) {
13903
+ const securityLevel = transport._inboundSecurityLevel();
13772
13904
  const connection = transport._createConnection({ resolvers: {
13773
13905
  onIncomingActionDataJson: (json, reliability) => {
13774
13906
  if (reliability?.ack != null) this._applyAck(reliableStreamId(this.peer, json.domain, json.id, reliability.streamKey), reliability.ack);
13775
- this._emitIncoming(json);
13907
+ this._emitIncoming(json, {
13908
+ receiver: this,
13909
+ securityLevel
13910
+ });
13776
13911
  },
13777
13912
  onControlMessage: (message) => {
13778
13913
  const streamId = reliableStreamId(this.peer, message.domain, message.id, message.k);
@@ -14395,35 +14530,60 @@ var ActionRuntime = class {
14395
14530
  _addHandlers(handlers, options) {
14396
14531
  this._assertActive();
14397
14532
  this._assertNoDuplicateLocalExecutors(handlers);
14398
- for (const handler of handlers) {
14399
- let ownership = this._handlerOwnership.get(handler);
14400
- if (ownership == null) {
14401
- const handlerRouter = handler.getActionRouter();
14402
- ownership = {
14403
- persistent: false,
14404
- leases: /* @__PURE__ */ new Set()
14405
- };
14406
- try {
14407
- this.actionRouter.addDomainsFromOther(handlerRouter);
14408
- if (handler.handlerType === "peer") {
14409
- ownership.unbind = handler._setIncomingActionDataListener(this, (json, metadata) => this.resolveIncomingActionPayload(json, metadata));
14410
- this._registeredPeerHandlers.push(handler);
14411
- }
14412
- for (const key of handlerRouter.getRegisteredKeys()) this.actionRouter.addForKey(key, handler);
14413
- } catch (error) {
14414
- ownership.unbind?.();
14415
- this.actionRouter.removeRouteData(handler);
14416
- const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14417
- if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14418
- throw error;
14533
+ const installed = [];
14534
+ const promoted = [];
14535
+ try {
14536
+ for (const handler of handlers) {
14537
+ let ownership = this._handlerOwnership.get(handler);
14538
+ if (ownership == null) {
14539
+ ownership = this._installHandler(handler);
14540
+ installed.push(handler);
14541
+ }
14542
+ if (options.persistent && !ownership.persistent) {
14543
+ ownership.persistent = true;
14544
+ promoted.push(ownership);
14419
14545
  }
14420
- this._handlerOwnership.set(handler, ownership);
14546
+ if (options.lease != null) ownership.leases.add(options.lease);
14547
+ }
14548
+ } catch (error) {
14549
+ for (const ownership of promoted) ownership.persistent = false;
14550
+ for (const handler of installed) {
14551
+ const ownership = this._handlerOwnership.get(handler);
14552
+ if (ownership != null) this._uninstallHandler(handler, ownership);
14421
14553
  }
14422
- if (options.persistent) ownership.persistent = true;
14423
- if (options.lease != null) ownership.leases.add(options.lease);
14554
+ throw error;
14424
14555
  }
14425
14556
  if (options.register) this._registerWithRoutedRoots();
14426
14557
  }
14558
+ _installHandler(handler) {
14559
+ const handlerRouter = handler.getActionRouter();
14560
+ const ownership = {
14561
+ persistent: false,
14562
+ leases: /* @__PURE__ */ new Set()
14563
+ };
14564
+ try {
14565
+ this.actionRouter.addDomainsFromOther(handlerRouter);
14566
+ if (handler.handlerType === "peer") {
14567
+ ownership.unbind = handler._setIncomingActionDataListener(this, (json, metadata) => this.resolveIncomingActionPayload(json, metadata));
14568
+ this._registeredPeerHandlers.push(handler);
14569
+ }
14570
+ for (const key of handlerRouter.getRegisteredKeys()) this.actionRouter.addForKey(key, handler);
14571
+ } catch (error) {
14572
+ this._uninstallHandler(handler, ownership);
14573
+ throw error;
14574
+ }
14575
+ this._handlerOwnership.set(handler, ownership);
14576
+ return ownership;
14577
+ }
14578
+ _uninstallHandler(handler, ownership) {
14579
+ ownership.unbind?.();
14580
+ this.actionRouter.removeRouteData(handler);
14581
+ if (handler.handlerType === "peer") {
14582
+ const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14583
+ if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14584
+ }
14585
+ this._handlerOwnership.delete(handler);
14586
+ }
14427
14587
  _assertNoDuplicateLocalExecutors(handlers) {
14428
14588
  for (const handler of handlers) for (const domain of handler.getActionRouter().getDomains()) this.actionRouter.domainManager.assertCanAddDomain(domain);
14429
14589
  const staged = /* @__PURE__ */ new Map();
@@ -14440,11 +14600,7 @@ var ActionRuntime = class {
14440
14600
  for (const [handler, ownership] of this._handlerOwnership) {
14441
14601
  ownership.leases.delete(lease);
14442
14602
  if (ownership.persistent || ownership.leases.size > 0) continue;
14443
- ownership.unbind?.();
14444
- this.actionRouter.removeRouteData(handler);
14445
- const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14446
- if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14447
- this._handlerOwnership.delete(handler);
14603
+ this._uninstallHandler(handler, ownership);
14448
14604
  }
14449
14605
  }
14450
14606
  /**
@@ -14567,29 +14723,21 @@ var ActionRuntime = class {
14567
14723
  const originClient = runningAction.context.originClient;
14568
14724
  if (originClient.envId === "_unset_" || originClient.isSameFor(this._coordinate).id) return;
14569
14725
  const arrival = runningAction.context._getReceiverMetadata();
14726
+ if (arrival != null && !(arrival.receiver instanceof PeerLink)) return;
14727
+ const arrivalLink = arrival?.receiver instanceof PeerLink ? arrival.receiver : void 0;
14570
14728
  runningAction.addUpdateListeners([(update) => {
14571
14729
  if (update.type === "finished" && update.finishType === "success") {
14572
14730
  if (this._disposed) return;
14573
- const returnHandler = arrival?.receiver instanceof PeerLink ? this._registeredPeerHandlers.includes(arrival.receiver) && arrival.receiver.canPush ? arrival.receiver : void 0 : this.getReturnHandlerForOrigin(originClient);
14574
- if (returnHandler == null || !canReturnToOrigin(arrival, returnHandler)) return;
14575
- returnHandler.sendReturnPayload(update.response, { targetLocalRuntime: this }).catch(() => {});
14731
+ const returnHandler = arrivalLink != null ? this._registeredPeerHandlers.includes(arrivalLink) && arrivalLink.canPush ? arrivalLink : void 0 : this.getReturnHandlerForOrigin(originClient);
14732
+ if (returnHandler == null) return;
14733
+ returnHandler.sendReturnPayload(update.response, {
14734
+ targetLocalRuntime: this,
14735
+ arrival
14736
+ }).catch(() => {});
14576
14737
  }
14577
14738
  }]);
14578
14739
  }
14579
14740
  };
14580
- /**
14581
- * May a result be routed back to the action's *claimed* origin over `returnHandler`?
14582
- *
14583
- * - No arrival facts (a locally dispatched action, or an advanced caller supplying its own wire):
14584
- * unchanged behaviour.
14585
- * - The frame arrived on this very handler: always — that is answering on the link it came from.
14586
- * - Otherwise the origin coordinate is only trustworthy when the arrival was authenticated; an
14587
- * unauthenticated claim must never select a different connection.
14588
- */
14589
- function canReturnToOrigin(arrival, returnHandler) {
14590
- if (arrival == null || arrival.receiver === returnHandler) return true;
14591
- return arrival.securityLevel != null && arrival.securityLevel !== "none";
14592
- }
14593
14741
  const runtimeState = {
14594
14742
  defaultLocalRuntime: void 0,
14595
14743
  assumedRuntimeInfo: void 0
@@ -14681,12 +14829,12 @@ var ActionLocalHandler = class extends ActionHandler {
14681
14829
  pushHandlerCuid(runningAction.cuid);
14682
14830
  try {
14683
14831
  const ran = await niceTryAsync(async () => {
14684
- const securityLevel = state.request.context._getReceiverMetadata()?.securityLevel;
14832
+ const metadata = state.request.context._getReceiverMetadata();
14685
14833
  const context = {
14686
14834
  runtime,
14687
14835
  origin: state.request.context.originClient,
14688
- authenticatedOrigin: securityLevel != null && securityLevel !== "none" ? state.request.context.originClient : void 0,
14689
- securityLevel,
14836
+ authenticatedOrigin: metadata?.originAuthenticated === true ? state.request.context.originClient : void 0,
14837
+ securityLevel: metadata?.securityLevel,
14690
14838
  reliability: state.request.context.reliability,
14691
14839
  run: (request, options) => runtime.run(request, options)
14692
14840
  };
@@ -15245,6 +15393,7 @@ var ChannelAcceptor = class extends PeerLink {
15245
15393
  const security = options.security;
15246
15394
  this.wireAcceptor = new WireAcceptor({
15247
15395
  send: options.send,
15396
+ close: options.close,
15248
15397
  tap: options.wireTap,
15249
15398
  security: security == null ? void 0 : {
15250
15399
  securityLevel: security.securityLevel,
@@ -15535,11 +15684,13 @@ var ChannelAcceptor = class extends PeerLink {
15535
15684
  _emitIncomingFromReceiver(wire, reliability, arrivalOverride) {
15536
15685
  const arrival = arrivalOverride ?? this._receiverMetadataByWire.get(wire);
15537
15686
  this._receiverMetadataByWire.delete(wire);
15687
+ const securityLevel = arrival?.securityLevel;
15538
15688
  this._emitIncoming(wire, {
15539
15689
  receiver: this,
15540
15690
  connection: arrival?.connection,
15541
15691
  bindingGeneration: arrival?.bindingGeneration,
15542
- securityLevel: arrival?.securityLevel,
15692
+ securityLevel,
15693
+ originAuthenticated: securityLevel != null && securityLevel !== "none",
15543
15694
  reliability
15544
15695
  });
15545
15696
  }
@@ -15808,10 +15959,10 @@ var ChannelAcceptor = class extends PeerLink {
15808
15959
  }
15809
15960
  }
15810
15961
  async sendReturnPayload(payload, config) {
15811
- const arrival = payload.context._getReceiverMetadata();
15812
- const connection = arrival?.receiver === this ? this._liveArrivalConnection(arrival) : this.wireAcceptor.connectionForClient(payload.context.originClient.stringId);
15962
+ const arrival = config.arrival ?? payload.context._getReceiverMetadata();
15963
+ const connection = arrival == null ? this.wireAcceptor.connectionForClient(payload.context.originClient.stringId) : arrival.receiver === this ? this._liveArrivalConnection(arrival) : void 0;
15813
15964
  if (connection == null) return false;
15814
- const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate);
15965
+ const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate, arrival?.reliability);
15815
15966
  this._reportServed(payload, bytes);
15816
15967
  return true;
15817
15968
  }
@@ -15868,11 +16019,11 @@ var ChannelAcceptor = class extends PeerLink {
15868
16019
  }).withOriginError(cause);
15869
16020
  }
15870
16021
  /** Encode + send one payload; returns the encoded frame's size so a logger can report it. */
15871
- _sendPayload(connection, payload, localClient, reliability) {
16022
+ _sendPayload(connection, payload, localClient, answered) {
15872
16023
  const encoding = this._connEncoding.get(connection) ?? "binary";
15873
- let rel = reliability;
15874
- if (rel == null && payload.type === "result") {
15875
- const streamKey = payload.context.reliability?.streamKey;
16024
+ let rel;
16025
+ if (payload.type === "result") {
16026
+ const streamKey = (answered ?? payload.context.reliability)?.streamKey;
15876
16027
  const streamId = reliableStreamId(payload.context.originClient, payload.domain, payload.id, streamKey);
15877
16028
  const receiver = this._persistedReceiver?.hasStream(streamId) ? this._persistedReceiver : this._inbox.hasStream(streamId) ? this._inbox : void 0;
15878
16029
  if (receiver != null) {
@@ -15947,6 +16098,7 @@ function createSecureChannelAcceptor(options) {
15947
16098
  };
15948
16099
  const baseOptions = {
15949
16100
  send: options.send,
16101
+ close: options.close,
15950
16102
  runtime: options.runtime,
15951
16103
  defaultTimeout: options.defaultTimeout,
15952
16104
  logger: options.logger,
@@ -15974,11 +16126,14 @@ function createSecureChannelAcceptor(options) {
15974
16126
  }
15975
16127
  //#endregion
15976
16128
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/Carrier.types.ts
15977
- /** Convert action routing data into wire's generic carrier dial shape. */
16129
+ /**
16130
+ * Convert action routing data into wire's generic carrier dial shape. The routing fields also stay at
16131
+ * the top level, so a carrier source written for the older `open(input: TTransportRouteParams)` shape
16132
+ * still reads `input.action`.
16133
+ */
15978
16134
  function toActionDialParams(input) {
15979
16135
  return {
15980
- localClient: input.localClient,
15981
- externalClient: input.externalClient,
16136
+ ...input,
15982
16137
  dialContext: input
15983
16138
  };
15984
16139
  }
@@ -16290,7 +16445,12 @@ function isSessionEnvelope(envelope) {
16290
16445
  * definition can be shared across multiple handlers — each handler builds its own live
16291
16446
  * {@link TransportConnection} via {@link TransportConnection._createConnection}.
16292
16447
  */
16293
- var Transport = class {};
16448
+ var Transport = class {
16449
+ /** @internal The security level frames received over this transport were protected at. */
16450
+ _inboundSecurityLevel() {
16451
+ return "none";
16452
+ }
16453
+ };
16294
16454
  //#endregion
16295
16455
  //#region ../nice-action/src/ActionRuntime/Transport/SecureSession/establishExchangeSession.ts
16296
16456
  /** Plain path (no handshake/token): every action rides a bare `act` envelope, plaintext both ways. */
@@ -16411,11 +16571,15 @@ var ExchangeConnection = class extends TransportConnection {
16411
16571
  * can't deliver an unsolicited frame (the runtime never picks it for the return path).
16412
16572
  */
16413
16573
  var ExchangeTransport = class ExchangeTransport extends Transport {
16414
- options;
16415
16574
  type = "exchange";
16575
+ options;
16416
16576
  constructor(options) {
16417
16577
  super();
16418
- this.options = options;
16578
+ if (options.getCacheKey != null && options.getTransportCacheKey != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "ExchangeTransport: pass only `getCacheKey`; `getTransportCacheKey` is deprecated" });
16579
+ this.options = {
16580
+ ...options,
16581
+ getCacheKey: options.getCacheKey ?? options.getTransportCacheKey
16582
+ };
16419
16583
  }
16420
16584
  static create(options) {
16421
16585
  return new ExchangeTransport(options);
@@ -16649,11 +16813,17 @@ var LinkConnection = class extends TransportConnection {
16649
16813
  * or an in-memory pipe. Reported with an overridable carrier label in the devtools (defaults to "link").
16650
16814
  */
16651
16815
  var LinkTransport = class LinkTransport extends Transport {
16652
- options;
16653
16816
  type = "duplex";
16817
+ options;
16654
16818
  constructor(options) {
16655
16819
  super();
16656
- this.options = options;
16820
+ if (options.getCacheKey != null && options.getTransportCacheKey != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "LinkTransport: pass only `getCacheKey`; `getTransportCacheKey` is deprecated" });
16821
+ if (options.heartbeat != null && options.linkKeepalive != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "LinkTransport: pass only `heartbeat`; `linkKeepalive` is deprecated" });
16822
+ this.options = {
16823
+ ...options,
16824
+ getCacheKey: options.getCacheKey ?? options.getTransportCacheKey,
16825
+ heartbeat: options.heartbeat ?? options.linkKeepalive
16826
+ };
16657
16827
  }
16658
16828
  static create(options) {
16659
16829
  return new LinkTransport(options);
@@ -16676,6 +16846,9 @@ var LinkTransport = class LinkTransport extends Transport {
16676
16846
  })
16677
16847
  }) }, ctx.resolvers);
16678
16848
  }
16849
+ _inboundSecurityLevel() {
16850
+ return this.options.security?.securityLevel ?? "none";
16851
+ }
16679
16852
  getRouteInfo(input) {
16680
16853
  if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);
16681
16854
  return {
@@ -16828,6 +17001,8 @@ function warnOnSharedConnectionIdentity(runtime, peer, identity) {
16828
17001
  */
16829
17002
  function connectChannel(runtime, channel, options) {
16830
17003
  if (options.carriers == null === (options.transports == null)) throw err_nice_action.fromId("conflicting_connect_options", { detail: "connectChannel requires exactly one of `carriers` or deprecated `transports`" });
17004
+ if (options.reconnect != null && options.keepLinkAlive != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "connectChannel: pass only `reconnect`; `keepLinkAlive` is deprecated" });
17005
+ if (options.heartbeat != null && options.linkKeepalive != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "connectChannel: pass only `heartbeat`; `linkKeepalive` is deprecated" });
16831
17006
  const transports = options.carriers?.map((carrier) => ({
16832
17007
  carrier,
16833
17008
  secure: carrier.secure,
@@ -16994,7 +17169,8 @@ var ExchangeAcceptor = class {
16994
17169
  const startedAt = Date.now();
16995
17170
  const result = await (await this._runtime._handleActionPayloadWireFromReceiver(wire, {
16996
17171
  receiver: this,
16997
- securityLevel: request.securityLevel
17172
+ securityLevel: request.securityLevel,
17173
+ originAuthenticated: client != null && request.securityLevel !== "none"
16998
17174
  })).waitForResultPayload();
16999
17175
  const resultWire = result.toJsonObject();
17000
17176
  if (report != null) {
@@ -17380,6 +17556,7 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
17380
17556
  verifyKeyResolver: secure.verifyKeyResolver,
17381
17557
  securityLevel,
17382
17558
  send: carrier.send,
17559
+ close: carrier.close,
17383
17560
  defaultTimeout: options.defaultTimeout,
17384
17561
  resolveChannel,
17385
17562
  logger: options.logger,
@@ -17390,6 +17567,7 @@ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
17390
17567
  }) : createChannelAcceptor({
17391
17568
  createFormatMessage: channel.createCodec,
17392
17569
  send: carrier.send,
17570
+ close: carrier.close,
17393
17571
  runtime,
17394
17572
  defaultTimeout: options.defaultTimeout,
17395
17573
  logger: options.logger,
@@ -20499,6 +20677,21 @@ function createWriteHandle() {
20499
20677
  //#endregion
20500
20678
  //#region ../nice-realm/src/RealmClient/RealmClient.ts
20501
20679
  enablePatches();
20680
+ function createStepGuard() {
20681
+ let failure;
20682
+ return {
20683
+ run(step) {
20684
+ try {
20685
+ step();
20686
+ } catch (error) {
20687
+ failure ??= { error };
20688
+ }
20689
+ },
20690
+ rethrow() {
20691
+ if (failure != null) throw failure.error;
20692
+ }
20693
+ };
20694
+ }
20502
20695
  /** The durable-write backlog cap (§4): past this many unconfirmed reassert frames, new reassert
20503
20696
  * writes reject loudly instead of growing memory for the length of the outage. */
20504
20697
  const MAX_REASSERT_PENDING_FRAMES = 256;
@@ -20583,12 +20776,16 @@ function connectRealm(realm, options) {
20583
20776
  if (status === next) return;
20584
20777
  status = next;
20585
20778
  if (next === "live") hasBeenLive = true;
20586
- for (const listener of [...statusListeners]) listener(next, { hasBeenLive });
20587
- devtools?.onStatus?.(next, { hasBeenLive });
20588
- if (next === "detached") rejectHydrateQueue();
20779
+ const guard = createStepGuard();
20780
+ if (next === "detached") guard.run(rejectHydrateQueue);
20781
+ for (const listener of [...statusListeners]) guard.run(() => listener(next, { hasBeenLive }));
20782
+ guard.run(() => devtools?.onStatus?.(next, { hasBeenLive }));
20783
+ guard.rethrow();
20589
20784
  };
20590
20785
  let pending = [];
20591
20786
  const hydrateQueue = [];
20787
+ /** Set from the hydrate's `confirmedVersion` until its queue drains: new writes queue behind. */
20788
+ let hydrating = false;
20592
20789
  let nextSeq = 0;
20593
20790
  let flushScheduled = false;
20594
20791
  let projecting = false;
@@ -21074,7 +21271,7 @@ function connectRealm(realm, options) {
21074
21271
  if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
21075
21272
  rejectUnsent(queued.controller, queued.kind, error, queued.intentName);
21076
21273
  };
21077
- const mustQueueUntilHydrate = () => confirmedVersion === -1 || hydrateQueue.length > 0;
21274
+ const mustQueueUntilHydrate = () => confirmedVersion === -1 || hydrating;
21078
21275
  const queueUntilHydrate = (queuedWrite, durability) => {
21079
21276
  const controller = createWriteHandle();
21080
21277
  if (status === "detached") return rejectUnsent(controller, queuedWrite.kind, neverHydratedError(), queuedWrite.intentName);
@@ -21088,8 +21285,10 @@ function connectRealm(realm, options) {
21088
21285
  const index = hydrateQueue.indexOf(queued);
21089
21286
  if (index < 0) return;
21090
21287
  hydrateQueue.splice(index, 1);
21091
- rejectQueued(queued, neverHydratedError());
21092
- notifyPending();
21288
+ const guard = createStepGuard();
21289
+ guard.run(() => rejectQueued(queued, neverHydratedError()));
21290
+ guard.run(notifyPending);
21291
+ guard.rethrow();
21093
21292
  }, expiryMs);
21094
21293
  unrefTimer(queued.expiryTimer);
21095
21294
  }
@@ -21097,26 +21296,36 @@ function connectRealm(realm, options) {
21097
21296
  notifyPending();
21098
21297
  return controller.handle;
21099
21298
  };
21100
- const drainHydrateQueue = () => {
21299
+ const runQueued = (queued) => {
21300
+ if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
21301
+ const { controller } = queued;
21302
+ let sent;
21303
+ try {
21304
+ sent = queued.run();
21305
+ } catch (cause) {
21306
+ console.error(`${warnTag()} a write queued before the first hydrate threw`, cause);
21307
+ rejectQueued(queued, castNiceError(cause));
21308
+ return;
21309
+ }
21310
+ const settled = sent;
21311
+ settled.then(controller.confirm, () => {
21312
+ if (settled.error != null) controller.reject(settled.error);
21313
+ });
21314
+ };
21315
+ /** Runs every queued write; a throwing app callback is held by `guard` and strands nothing. */
21316
+ const drainHydrateQueue = (guard) => {
21101
21317
  for (let queued = hydrateQueue.shift(); queued != null; queued = hydrateQueue.shift()) {
21102
- if (queued.expiryTimer != null) clearTimeout(queued.expiryTimer);
21103
- const { controller } = queued;
21104
- let sent;
21105
- try {
21106
- sent = queued.run();
21107
- } catch (cause) {
21108
- console.error(`${warnTag()} a write queued before the first hydrate threw`, cause);
21109
- rejectQueued(queued, castNiceError(cause));
21110
- continue;
21111
- }
21112
- const settled = sent;
21113
- settled.then(controller.confirm, () => {
21114
- if (settled.error != null) controller.reject(settled.error);
21115
- });
21318
+ const next = queued;
21319
+ guard.run(() => runQueued(next));
21116
21320
  }
21321
+ guard.run(notifyPending);
21117
21322
  };
21118
21323
  const rejectHydrateQueue = () => {
21119
- for (const queued of hydrateQueue.splice(0)) rejectQueued(queued, neverHydratedError());
21324
+ if (hydrateQueue.length === 0) return;
21325
+ const guard = createStepGuard();
21326
+ for (const queued of hydrateQueue.splice(0)) guard.run(() => rejectQueued(queued, neverHydratedError()));
21327
+ guard.run(notifyPending);
21328
+ guard.rethrow();
21120
21329
  };
21121
21330
  const enqueueWrite = (patches, writeOptions) => {
21122
21331
  const durability = writeOptions?.durability;
@@ -21377,15 +21586,23 @@ function connectRealm(realm, options) {
21377
21586
  };
21378
21587
  localMaxPatchesCeiling = void 0;
21379
21588
  warnOnIdentityMismatch(frame.avatar);
21380
- setStatus("live");
21381
- if (helloInFlight) recordRttSample(Date.now() - helloSentAt);
21382
- helloInFlight = false;
21383
- if (!isFirstHydrate && realm.transient.length > 0 && options.assertOnAttach != null && !hasPendingSystemAssert()) enqueueSystemAssert(confirmed);
21384
- revalidateAndResendPending();
21385
- project({ fullReplace: true });
21386
- if (options.assertOnAttach != null && !hasPendingSystemAssert()) applyUpdate(options.assertOnAttach);
21387
- drainHydrateQueue();
21589
+ hydrating = true;
21590
+ const guard = createStepGuard();
21591
+ try {
21592
+ guard.run(() => setStatus("live"));
21593
+ if (helloInFlight) recordRttSample(Date.now() - helloSentAt);
21594
+ helloInFlight = false;
21595
+ if (!isFirstHydrate && realm.transient.length > 0 && options.assertOnAttach != null && !hasPendingSystemAssert()) guard.run(() => enqueueSystemAssert(confirmed));
21596
+ guard.run(revalidateAndResendPending);
21597
+ guard.run(() => project({ fullReplace: true }));
21598
+ const assertOnAttach = options.assertOnAttach;
21599
+ if (assertOnAttach != null && !hasPendingSystemAssert()) guard.run(() => applyUpdate(assertOnAttach));
21600
+ } finally {
21601
+ drainHydrateQueue(guard);
21602
+ hydrating = false;
21603
+ }
21388
21604
  checkReownWatch();
21605
+ guard.rethrow();
21389
21606
  return;
21390
21607
  }
21391
21608
  case REALM_FRAME_KIND.keyDict:
@@ -21783,10 +22000,12 @@ function connectRealm(realm, options) {
21783
22000
  port.send(bye);
21784
22001
  } catch {}
21785
22002
  helloInFlight = false;
21786
- setStatus("detached");
22003
+ const guard = createStepGuard();
22004
+ guard.run(() => setStatus("detached"));
21787
22005
  options.connection.release();
21788
- for (const frame of pending.splice(0)) settleReject(frame, err_realm.fromId("frame_too_stale", { basisVersion: frame.basisVersion }));
21789
- project();
22006
+ for (const frame of pending.splice(0)) guard.run(() => settleReject(frame, err_realm.fromId("frame_too_stale", { basisVersion: frame.basisVersion })));
22007
+ guard.run(() => project());
22008
+ guard.rethrow();
21790
22009
  }
21791
22010
  };
21792
22011
  devtools?.handleReady?.({
@@ -22738,7 +22957,8 @@ function unwrapOptional(node) {
22738
22957
  }
22739
22958
  const OMIT = {
22740
22959
  value: void 0,
22741
- anyVisible: false
22960
+ anyVisible: false,
22961
+ structural: false
22742
22962
  };
22743
22963
  /** Does `path` pass through a record entry? Its containers are then data, not structure. */
22744
22964
  function underRecordEntry(schemaRoot, path) {
@@ -22751,19 +22971,21 @@ function underRecordEntry(schemaRoot, path) {
22751
22971
  function pruneNode(ctx, node, value, path, inEntry = underRecordEntry(ctx.schemaRoot, path)) {
22752
22972
  if (value === void 0) return OMIT;
22753
22973
  const inner = unwrapOptional(node);
22974
+ const required = node.kind !== "optional";
22754
22975
  if (inner.kind === "object") {
22755
22976
  const out = {};
22756
22977
  let anyVisible = false;
22978
+ let structural = false;
22757
22979
  for (const [key, child] of Object.entries(inner.entries)) {
22758
22980
  const pruned = pruneNode(ctx, child, value[key], [...path, key], inEntry);
22759
- if (pruned.anyVisible) {
22760
- out[key] = pruned.value;
22761
- anyVisible = true;
22762
- }
22981
+ if (pruned.anyVisible || pruned.structural) out[key] = pruned.value;
22982
+ if (pruned.anyVisible) anyVisible = true;
22983
+ if (pruned.structural) structural = true;
22763
22984
  }
22764
22985
  return {
22765
22986
  value: out,
22766
- anyVisible
22987
+ anyVisible,
22988
+ structural: required && structural
22767
22989
  };
22768
22990
  }
22769
22991
  if (inner.kind === "record") {
@@ -22776,17 +22998,37 @@ function pruneNode(ctx, node, value, path, inEntry = underRecordEntry(ctx.schema
22776
22998
  anyVisible = true;
22777
22999
  }
22778
23000
  }
22779
- const structural = !inEntry && ctx.trie.reachesBeneath(path);
23001
+ const structural = required && !inEntry && ctx.trie.reachesBeneath(path);
22780
23002
  return {
22781
23003
  value: out,
22782
- anyVisible: anyVisible || structural || leafVisible(ctx, path)
23004
+ anyVisible: anyVisible || leafVisible(ctx, path),
23005
+ structural
22783
23006
  };
22784
23007
  }
22785
23008
  return leafVisible(ctx, path) ? {
22786
23009
  value,
22787
- anyVisible: true
23010
+ anyVisible: true,
23011
+ structural: false
22788
23012
  } : OMIT;
22789
23013
  }
23014
+ /**
23015
+ * Whether the avatar holds `path`'s parent, so a structure-only patch there reveals nothing: true
23016
+ * unless an optional sits between the top level and `path` that neither state shows the avatar.
23017
+ */
23018
+ function holdsParent(ctx, path, states) {
23019
+ for (let depth = path.length - 1; depth >= 2; depth--) {
23020
+ const ancestorPath = path.slice(0, depth);
23021
+ const ancestor = schemaNodeAtPath(ctx.schemaRoot, ancestorPath);
23022
+ if (ancestor?.kind !== "optional") continue;
23023
+ return states.some((state) => state != null && pruneNode(ctx, ancestor, getAtPath$1(state, ancestorPath), ancestorPath).anyVisible);
23024
+ }
23025
+ return true;
23026
+ }
23027
+ /** A sliced patch target ships for its visible content, or as structure inside a held parent. */
23028
+ function patchTargetShips(ctx, pruned, path, states) {
23029
+ if (pruned.anyVisible) return true;
23030
+ return pruned.structural && holdsParent(ctx, path, states);
23031
+ }
22790
23032
  /** The avatar's sliced view of the whole state — the hydrate payload. */
22791
23033
  function sliceStateForAvatar(ctx, state) {
22792
23034
  const out = {};
@@ -22798,9 +23040,10 @@ function sliceStateForAvatar(ctx, state) {
22798
23040
  * possibly with a pruned value (a subtree patch spanning mixed-visibility leaves sends each
22799
23041
  * audience only its slice). `statePrev` (pre-commit) drives `remove` expansion; a replay path may
22800
23042
  * pass `undefined` — a `remove` that can't be proven invisible is then included (removing a key
22801
- * the avatar never had must be a client-side no-op).
23043
+ * the avatar never had must be a client-side no-op). `stateAfter` (post-commit), with `statePrev`,
23044
+ * decides whether the avatar holds an optional ancestor of a structure-only container patch.
22802
23045
  */
22803
- function slicePatchForAvatar(ctx, patch, statePrev) {
23046
+ function slicePatchForAvatar(ctx, patch, statePrev, stateAfter) {
22804
23047
  const path = patch.path;
22805
23048
  const node = schemaNodeAtPath(ctx.schemaRoot, path);
22806
23049
  if (node == null) return void 0;
@@ -22809,10 +23052,10 @@ function slicePatchForAvatar(ctx, patch, statePrev) {
22809
23052
  if (patch.op === "remove") {
22810
23053
  const prev = statePrev == null ? void 0 : getAtPath$1(statePrev, path);
22811
23054
  if (prev === void 0) return patch;
22812
- return pruneNode(ctx, node, prev, [...path]).anyVisible ? patch : void 0;
23055
+ return patchTargetShips(ctx, pruneNode(ctx, node, prev, [...path]), path, [statePrev, stateAfter]) ? patch : void 0;
22813
23056
  }
22814
23057
  const pruned = pruneNode(ctx, node, patch.value, [...path]);
22815
- if (!pruned.anyVisible) return void 0;
23058
+ if (!patchTargetShips(ctx, pruned, path, [statePrev, stateAfter])) return void 0;
22816
23059
  return {
22817
23060
  op: patch.op,
22818
23061
  path,
@@ -23080,7 +23323,7 @@ var RealmServerEngine = class {
23080
23323
  sliced.push(sliceTransientRefreshForAvatar(this._sliceCtx(avatar), patch));
23081
23324
  continue;
23082
23325
  }
23083
- const slicedPatch = slicePatchForAvatar(this._sliceCtx(avatar), patch, void 0);
23326
+ const slicedPatch = slicePatchForAvatar(this._sliceCtx(avatar), patch, void 0, this._state);
23084
23327
  if (slicedPatch != null) sliced.push(slicedPatch);
23085
23328
  }
23086
23329
  this._sendPatchesFrame(conn, sliced, options.lastKnownVersion, this._version);
@@ -23684,6 +23927,7 @@ var RealmServerEngine = class {
23684
23927
  }
23685
23928
  _broadcast(namePatches, statePrev, fromVersion, toVersion) {
23686
23929
  if (this._connections.size === 0) return;
23930
+ const stateAfter = this._state;
23687
23931
  const cache = /* @__PURE__ */ new Map();
23688
23932
  for (const conn of this._connections.values()) {
23689
23933
  const groupKey = `${viewSignatureKey(conn.avatar)}/${conn.slot}`;
@@ -23691,7 +23935,7 @@ var RealmServerEngine = class {
23691
23935
  if (chunks === void 0) {
23692
23936
  const sliced = [];
23693
23937
  for (const patch of namePatches) {
23694
- const slicedPatch = slicePatchForAvatar(this._sliceCtx(conn.avatar), patch, statePrev);
23938
+ const slicedPatch = slicePatchForAvatar(this._sliceCtx(conn.avatar), patch, statePrev, stateAfter);
23695
23939
  if (slicedPatch != null) sliced.push(slicedPatch);
23696
23940
  }
23697
23941
  chunks = sliced.length === 0 ? null : this._encodePatchesChunked(sliced, conn.slot, fromVersion, toVersion);
@@ -24184,7 +24428,8 @@ function commanderStatePaths(dataDir, configKey) {
24184
24428
  bootLogPath: (0, node_path.join)(stateDir, "daemon-boot.log"),
24185
24429
  ingestSeqPath: (0, node_path.join)(stateDir, "ingest-seq"),
24186
24430
  envOverridesPath: (0, node_path.join)(stateDir, "env-overrides.json"),
24187
- savedFiltersPath: (0, node_path.join)(stateDir, "saved-filters.json")
24431
+ savedFiltersPath: (0, node_path.join)(stateDir, "saved-filters.json"),
24432
+ lastStartsPath: (0, node_path.join)(stateDir, "last-starts.json")
24188
24433
  };
24189
24434
  }
24190
24435
  async function ensureStateDir(paths) {
@@ -24248,6 +24493,7 @@ const commanderStatusRealm = defineRealm({
24248
24493
  state: t.string(),
24249
24494
  pid: t.optional(t.number()),
24250
24495
  startedAt: t.optional(t.number()),
24496
+ lastStartedAt: t.optional(t.number()),
24251
24497
  sawOutputAt: t.optional(t.number()),
24252
24498
  lastTask: t.optional(t.object({
24253
24499
  outcome: t.string(),
@@ -27505,7 +27751,7 @@ async function withTimeout(ctx, run) {
27505
27751
  async function main() {
27506
27752
  const argv = process.argv.slice(2);
27507
27753
  if (argv[0] === "daemon") {
27508
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-BHPsC_5Q.cjs"));
27754
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-CVu9gjbx.cjs"));
27509
27755
  return runCommanderDaemon(argv.slice(1));
27510
27756
  }
27511
27757
  const parsed = parseCliArgs(argv);