@nice-code/commander 0.97.0 → 0.102.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
@@ -1313,6 +1313,74 @@ function staggerFor(config, terms) {
1313
1313
  return stagger;
1314
1314
  }
1315
1315
  //#endregion
1316
+ //#region ../nice-wire/src/Carrier/AcceptorCarrier.ts
1317
+ /** Build the inert lifecycle slot shared by duplex acceptor carrier factories. */
1318
+ function createDuplexCarrierLifecycle(limits) {
1319
+ let router;
1320
+ let disposed = false;
1321
+ const windows = /* @__PURE__ */ new Map();
1322
+ const maxFrameBytes = limits?.maxFrameBytes;
1323
+ const rate = limits?.rate;
1324
+ if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
1325
+ if (rate != null && (!Number.isSafeInteger(rate.maxMessages) || rate.maxMessages <= 0 || !Number.isSafeInteger(rate.windowMs) || rate.windowMs <= 0)) throw new Error("inbound rate limits must be positive safe integers");
1326
+ const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
1327
+ return {
1328
+ receive(connection, frame) {
1329
+ if (disposed) return;
1330
+ if (router == null) throw new Error("acceptor carrier not served yet — activate it before feeding frames");
1331
+ if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
1332
+ limits?.onExceeded(connection, "frame_bytes");
1333
+ return;
1334
+ }
1335
+ if (rate != null) {
1336
+ const now = Date.now();
1337
+ let window = windows.get(connection);
1338
+ if (window == null || now - window.startedAt >= rate.windowMs) {
1339
+ window = {
1340
+ count: 0,
1341
+ startedAt: now
1342
+ };
1343
+ windows.set(connection, window);
1344
+ }
1345
+ window.count += 1;
1346
+ if (window.count > rate.maxMessages) {
1347
+ limits?.onExceeded(connection, "message_rate");
1348
+ return;
1349
+ }
1350
+ }
1351
+ router.receive(connection, frame);
1352
+ },
1353
+ drop(connection) {
1354
+ if (disposed) return;
1355
+ windows.delete(connection);
1356
+ router?.drop(connection);
1357
+ },
1358
+ _activate(liveRouter) {
1359
+ if (disposed) throw new Error("acceptor carrier already disposed");
1360
+ router = liveRouter;
1361
+ },
1362
+ _dispose() {
1363
+ if (disposed) return;
1364
+ disposed = true;
1365
+ router = void 0;
1366
+ windows.clear();
1367
+ }
1368
+ };
1369
+ }
1370
+ /** Build a WebSocket acceptor carrier for `serveWire` or `serveChannel`. */
1371
+ function wsAcceptorCarrier(options) {
1372
+ return {
1373
+ ...createDuplexCarrierLifecycle(options.inboundLimits),
1374
+ shape: "duplex",
1375
+ carrierLabel: options.carrierLabel ?? "ws",
1376
+ secure: options.secure,
1377
+ send: options.send,
1378
+ upgrade: options.upgrade,
1379
+ isUpgrade: options.isUpgrade ?? ((request) => request.headers.get("Upgrade") === "websocket"),
1380
+ attachmentStore: options.attachmentStore
1381
+ };
1382
+ }
1383
+ //#endregion
1316
1384
  //#region ../nice-error/src/internal/internal_errors.ts
1317
1385
  let _build;
1318
1386
  /** Wired once by `nice_core_errors` at module init to avoid an import cycle. */
@@ -2324,7 +2392,7 @@ async function niceTryAsync(fn) {
2324
2392
  //#endregion
2325
2393
  //#region ../nice-wire/src/Connect/err_wire_connect.ts
2326
2394
  /**
2327
- * The Connect layer's error domain (shared-base-connect plan, Phase 1). Declared with the types
2395
+ * The Connect layer's error domain. Declared with the types
2328
2396
  * so Phases 2–6 throw against a fixed vocabulary instead of inventing ad-hoc `Error`s per phase;
2329
2397
  * each id notes the phase that starts raising it. (`protocol_unsupported` is the link-level
2330
2398
  * error `nice-realm`'s `err_realm` doc already points at as living here.)
@@ -2343,12 +2411,13 @@ const err_wire_connect = err_nice.createChildDomain({
2343
2411
  */
2344
2412
  dial_failed: err({ message: ({ peerId, carrierLabel, reason, endpoint }) => `Dialing peer [${peerId}] over "${carrierLabel}"${endpoint != null ? ` against ${endpoint}` : ""} failed: ${reason}` }),
2345
2413
  /**
2346
- * Resilience-surface §6 — the carrier has **no valid endpoint right now** (`createRequest`
2414
+ * the resilience contract — the carrier has **no valid endpoint right now** (`createRequest`
2347
2415
  * returned `null`, e.g. a torn-down session's mutable dial context). Not a failure: a policy
2348
2416
  * signal. The transport selection rethrows it unwrapped, and a keep-alive redial loop PARKS on
2349
2417
  * it — no dialing garbage, no backoff churn — until the next explicit `connect()`/dispatch.
2350
2418
  */
2351
2419
  dial_unavailable: err({ message: ({ carrierLabel }) => `Dial over "${carrierLabel}" unavailable — createRequest returned null (no valid endpoint right now). A keep-alive redial parks on this until the next explicit connect()/dispatch.` }),
2420
+ conflicting_connect_options: err({ message: ({ detail }) => `Conflicting connection options: ${detail}` }),
2352
2421
  /**
2353
2422
  * Consumer feedback (meteor-connect-bridge W1/W3) — **something answered, and it is not
2354
2423
  * nice-wire**. The dominant real-world causes are a wrong URL/port, an intercepting proxy or
@@ -2377,11 +2446,23 @@ const err_wire_connect = err_nice.createChildDomain({
2377
2446
  * `identity_pin_mismatch` stays its own id: it is permanent and the redial loop parks on it.
2378
2447
  */
2379
2448
  handshake_rejected: err({ message: ({ stage, reason }) => `[${stage}] rejected by peer: ${reason}` }),
2449
+ /**
2450
+ * The peer explicitly reported that the secure handshake has no compatible first-party wire
2451
+ * generation. This is terminal for the current builds: transport fallback and automatic
2452
+ * redial park until the application explicitly retries after an upgrade or rollback.
2453
+ */
2454
+ protocol_version_mismatch: err({ message: ({ reason, observedProtocolVersion, localSupportedProtocolVersions, remoteSupportedProtocolVersions }) => `Handshake protocol version mismatch: ${reason}. Local support: [${localSupportedProtocolVersions.join(", ")}]${remoteSupportedProtocolVersions != null ? `; remote support: [${remoteSupportedProtocolVersions.join(", ")}]` : ""}${observedProtocolVersion != null ? `; observed version: ${observedProtocolVersion}` : ""}. Carrier fallback and automatic redial are parked until an explicit retry.` }),
2455
+ /**
2456
+ * A secure endpoint answered as nice-wire but advertised a different runtime identity from the
2457
+ * one the caller selected. This is terminal for the current endpoint selection, so fallback and
2458
+ * automatic redial park until an explicit retry after the route or expectation changes.
2459
+ */
2460
+ 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.` }),
2380
2461
  /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */
2381
2462
  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).` }),
2382
- /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; plan D-11). */
2463
+ /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; the protocol contract). */
2383
2464
  protocol_on_exchange_only: err({ message: ({ protocolId }) => `Protocol "${protocolId}" needs a duplex transport — this connection is exchange-only (request/reply), which carries only the lane.` }),
2384
- /** Phase 4 — the acceptor security gate (review A.6): protocol frame on a non-authenticated connection without `allowPlain`. */
2465
+ /** Phase 4 — the acceptor security gate: protocol frame on a non-authenticated connection without `allowPlain`. */
2385
2466
  protocol_security_blocked: err({ message: ({ protocolId, securityLevel }) => `Protocol "${protocolId}" frame blocked: connection is at security level "${securityLevel}" and the protocol did not opt into allowPlain.` }),
2386
2467
  /** Phase 4 — rehydrate saw a binding with an unknown schema version: treat the socket as fresh. */
2387
2468
  binding_version_mismatch: err({ message: ({ found, expected }) => `Persisted connection binding has schema version ${JSON.stringify(found)} (this build reads v${expected}) — the binding is invalidated; the connection must re-handshake.` }),
@@ -2519,7 +2600,7 @@ async function normalizeFrame(data) {
2519
2600
  //#region ../nice-wire/src/Carrier/duplex/ws/wsCarrier.ts
2520
2601
  /**
2521
2602
  * A WebSocket {@link IWireDuplexCarrierSource}: opens an `arraybuffer` socket (cached per endpoint)
2522
- * and adapts it to a carrier — generalized over an opaque dial context (shared-base-connect plan,
2603
+ * and adapts it to a carrier — generalized over an opaque dial context (shared connection design,
2523
2604
  * E2), so the URL can be derived from whatever domain concept the consumer threads through
2524
2605
  * (nice-action passes the action being dispatched; a realm-only client passes e.g. a game id).
2525
2606
  *
@@ -2527,15 +2608,21 @@ async function normalizeFrame(data) {
2527
2608
  * dynamic endpoints need no socket-construction hook for the URL. `createWebSocket` exists for
2528
2609
  * **testability** — injecting a controllable socket (it is not a URL mechanism).
2529
2610
  *
2530
- * `createRequest` may return **`null`** to mean "no valid endpoint right now" (resilience-surface
2531
- * §6) — a dynamic-endpoint carrier whose mutable dial context was torn down (`matchId` cleared)
2611
+ * `createRequest` may return **`null`** to mean "no valid endpoint right now" — a dynamic-endpoint
2612
+ * carrier whose mutable dial context was torn down (`matchId` cleared)
2532
2613
  * signals that instead of dialing garbage. The dial throws `dial_unavailable`, which a keep-alive
2533
2614
  * redial loop parks on (resuming at the next explicit `connect()`/dispatch) — so teardown ordering
2534
2615
  * stops mattering.
2535
2616
  */
2536
- function wsCarrier$1(createRequest, options = {}) {
2617
+ function wsCarrier$1(request, options = {}) {
2618
+ const createRequest = (params) => {
2619
+ const resolved = typeof request === "string" ? request : request(params);
2620
+ if (resolved == null) return null;
2621
+ return typeof resolved === "string" ? { url: resolved } : resolved;
2622
+ };
2537
2623
  const construct = options.createWebSocket ?? ((url) => new WebSocket(url));
2538
2624
  return {
2625
+ secure: options.secure,
2539
2626
  carrierLabel: "ws",
2540
2627
  open: (params) => {
2541
2628
  const request = createRequest(params);
@@ -2566,8 +2653,13 @@ function wsCarrier$1(createRequest, options = {}) {
2566
2653
  * HTML page pasted into an error is worse DX than no preview at all.
2567
2654
  */
2568
2655
  const BODY_PREVIEW_LIMIT = 200;
2569
- /** C0 + DEL + C1 — a raw control character in an error message corrupts terminals and log lines. */
2570
- const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]+/g;
2656
+ /** Replace C0, DEL, and C1 characters that would corrupt terminals and log lines. */
2657
+ function replaceControlCharacters(raw) {
2658
+ return Array.from(raw, (character) => {
2659
+ const codePoint = character.codePointAt(0);
2660
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
2661
+ }).join("");
2662
+ }
2571
2663
  /**
2572
2664
  * A bounded, single-line, control-character-free head of whatever a non-protocol endpoint sent
2573
2665
  * back — enough to recognize an HTML error page or a proxy banner on sight. Only the *response* is
@@ -2575,11 +2667,28 @@ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]+/g;
2575
2667
  */
2576
2668
  function describeNonProtocolBody(raw) {
2577
2669
  if (typeof raw !== "string") return void 0;
2578
- const flattened = raw.replace(CONTROL_CHARS, " ").replace(/\s+/g, " ").trim();
2670
+ const flattened = replaceControlCharacters(raw).replace(/\s+/g, " ").trim();
2579
2671
  if (flattened.length === 0) return void 0;
2580
2672
  return flattened.length > BODY_PREVIEW_LIMIT ? `${flattened.slice(0, BODY_PREVIEW_LIMIT)}…` : flattened;
2581
2673
  }
2582
2674
  /**
2675
+ * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can
2676
+ * contain secrets, so connection errors retain only the scheme, host, port, and path.
2677
+ */
2678
+ function sanitizeEndpoint(raw) {
2679
+ if (raw == null) return void 0;
2680
+ try {
2681
+ const url = new URL(raw);
2682
+ url.username = "";
2683
+ url.password = "";
2684
+ url.search = "";
2685
+ url.hash = "";
2686
+ return url.toString();
2687
+ } catch {
2688
+ return raw.split(/[?#]/, 1)[0];
2689
+ }
2690
+ }
2691
+ /**
2583
2692
  * Classify a dial failure. Reads typed ids only — the ids are raised at the layer that still holds
2584
2693
  * the evidence precisely so this never has to sniff message text.
2585
2694
  */
@@ -2587,6 +2696,8 @@ function classifyConnectFailure(error) {
2587
2696
  if (!err_wire_connect.isExact(error)) return "unknown";
2588
2697
  if (error.hasId("endpoint_answered_non_protocol")) return "endpoint_answered_non_protocol";
2589
2698
  if (error.hasId("endpoint_unreachable")) return "endpoint_unreachable";
2699
+ if (error.hasId("protocol_version_mismatch")) return "protocol_version_mismatch";
2700
+ if (error.hasId("peer_identity_mismatch")) return "peer_identity_mismatch";
2590
2701
  if (error.hasId("identity_pin_mismatch") || error.hasId("handshake_rejected")) return "handshake_rejected";
2591
2702
  return "unknown";
2592
2703
  }
@@ -2595,12 +2706,13 @@ function endpointFromConnectFailure(error) {
2595
2706
  if (!err_wire_connect.isExact(error)) return void 0;
2596
2707
  if (error.hasId("endpoint_answered_non_protocol")) return error.getContext("endpoint_answered_non_protocol").url;
2597
2708
  if (error.hasId("endpoint_unreachable")) return error.getContext("endpoint_unreachable").url;
2709
+ if (error.hasId("peer_identity_mismatch")) return error.getContext("peer_identity_mismatch").endpoint;
2598
2710
  }
2599
2711
  //#endregion
2600
2712
  //#region ../nice-wire/src/Connect/ConnectionTransportManager.ts
2601
2713
  /**
2602
2714
  * Preference-ordered transport selection over a shared connection cache — moved from nice-action
2603
- * (shared-base-connect plan, Phase 2) with the routing params (`RP`), finalized methods
2715
+ * with the routing params (`RP`), finalized methods
2604
2716
  * (`METHODS`), and connection type (`CONN`) generic. Behavior is byte-for-byte the pre-move
2605
2717
  * logic: strict preference order with parallel warm-up, cache adoption guarded against teardown
2606
2718
  * races, and disconnect-driven eviction.
@@ -2716,10 +2828,20 @@ var ConnectionTransportManager$1 = class {
2716
2828
  for (const candidate of candidates) try {
2717
2829
  return await candidate.promise;
2718
2830
  } catch (e) {
2831
+ if (err_wire_connect.isExact(e) && e.hasId("peer_identity_mismatch")) {
2832
+ const context = e.getContext("peer_identity_mismatch");
2833
+ const endpoint = sanitizeEndpoint(candidate.transport.getRouteInfo(input)?.url);
2834
+ if (endpoint != null && context.endpoint == null) throw err_wire_connect.fromId("peer_identity_mismatch", {
2835
+ ...context,
2836
+ endpoint
2837
+ }).withOriginError(e);
2838
+ throw e;
2839
+ }
2840
+ if (err_wire_connect.isExact(e) && e.hasId("protocol_version_mismatch")) throw e;
2719
2841
  lastError = e;
2720
2842
  lastTransport = candidate.transport;
2721
2843
  }
2722
- if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch"))) throw lastError;
2844
+ 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;
2723
2845
  throw this._errors.initializationFailed(input, {
2724
2846
  cause: describeTransportFailure(lastError),
2725
2847
  endpoint: endpointFromConnectFailure(lastError) ?? lastTransport?.getRouteInfo(input)?.url,
@@ -3949,6 +4071,25 @@ function literal(literal_, message$1) {
3949
4071
  };
3950
4072
  }
3951
4073
  /* @__NO_SIDE_EFFECTS__ */
4074
+ function number(message$1) {
4075
+ return {
4076
+ kind: "schema",
4077
+ type: "number",
4078
+ reference: number,
4079
+ expects: "number",
4080
+ async: false,
4081
+ message: message$1,
4082
+ get "~standard"() {
4083
+ return /* @__PURE__ */ _getStandardProps(this);
4084
+ },
4085
+ "~run"(dataset, config$1) {
4086
+ if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
4087
+ else _addIssue(this, "type", dataset, config$1);
4088
+ return dataset;
4089
+ }
4090
+ };
4091
+ }
4092
+ /* @__NO_SIDE_EFFECTS__ */
3952
4093
  function object(entries$1, message$1) {
3953
4094
  return {
3954
4095
  kind: "schema",
@@ -5086,6 +5227,11 @@ function nanoid(size = 21) {
5086
5227
  for (let i = poolOffset - size; i < poolOffset; i++) id += urlAlphabet[pool[i] & 63];
5087
5228
  return id;
5088
5229
  }
5230
+ /**
5231
+ * Protocol generations this build can actually speak, newest first. This release has one codec,
5232
+ * so it advertises only v1; the intended future window is the current and previous generation.
5233
+ */
5234
+ const WIRE_SUPPORTED_PROTOCOL_VERSIONS = [1];
5089
5235
  const UNSET_RUNTIME_ENV_ID = "_unset_";
5090
5236
  //#endregion
5091
5237
  //#region ../nice-wire/src/utils/runtimeCoordinateToStringIds.ts
@@ -5102,6 +5248,14 @@ var RuntimeCoordinate = class RuntimeCoordinate {
5102
5248
  envId;
5103
5249
  perId;
5104
5250
  insId;
5251
+ /** Readable alias for {@link perId}; the serialized own field remains `perId`. */
5252
+ get persistentId() {
5253
+ return this.perId;
5254
+ }
5255
+ /** Readable alias for {@link insId}; the serialized own field remains `insId`. */
5256
+ get instanceId() {
5257
+ return this.insId;
5258
+ }
5105
5259
  static get unknown() {
5106
5260
  return new RuntimeCoordinate({ envId: UNSET_RUNTIME_ENV_ID });
5107
5261
  }
@@ -5109,7 +5263,7 @@ var RuntimeCoordinate = class RuntimeCoordinate {
5109
5263
  return new RuntimeCoordinate({ envId });
5110
5264
  }
5111
5265
  /**
5112
- * Env + persistent instance id — but not *merely* a routing name: on a secure connection this id
5266
+ * Env + persistent id — but not *merely* a routing name: on a secure connection this id
5113
5267
  * keys the server's trust-on-first-use verify-key pin (see {@link IRuntimeCoordinateSpecifics.perId}).
5114
5268
  * Pair it only with a crypto-identity `storage` that persists at least as long as the id itself,
5115
5269
  * or every reload presents a new key for a pinned id and is rejected (`identity_pin_mismatch`).
@@ -5216,7 +5370,8 @@ var RuntimeCoordinate = class RuntimeCoordinate {
5216
5370
  * handler drive the I/O and the connection phase (Step 4). Keep `none`-level connections from ever
5217
5371
  * reaching here — they skip the handshake entirely.
5218
5372
  */
5219
- const HANDSHAKE_PROTOCOL = "nice-ws-hs/1";
5373
+ const HANDSHAKE_PROTOCOL = `nice-ws-hs/1`;
5374
+ const HANDSHAKE_PROTOCOL_PREFIX = "nice-ws-hs/";
5220
5375
  /**
5221
5376
  * Capability advertised by both peers in the handshake (`hello.caps` / `welcome.caps`) when they understand
5222
5377
  * the reliable-delivery wire (the 7-slot reliability frame). It lets a `.reliable()` sender detect a peer
@@ -5293,7 +5448,11 @@ const vHandshakeMessage = /* @__PURE__ */ variant("t", [
5293
5448
  * feedback §3). Additive + optional: an old peer neither sends nor reads it (unknown keys are
5294
5449
  * stripped on decode), so the frame stays wire-compatible in both directions.
5295
5450
  */
5296
- id: /* @__PURE__ */ optional(/* @__PURE__ */ string())
5451
+ id: /* @__PURE__ */ optional(/* @__PURE__ */ string()),
5452
+ /** The unsupported generation observed by the rejecting peer, when the tag was well formed. */
5453
+ observedProtocolVersion: /* @__PURE__ */ optional(/* @__PURE__ */ number()),
5454
+ /** The generations the rejecting peer can actually speak, newest first. */
5455
+ supportedProtocolVersions: /* @__PURE__ */ optional(/* @__PURE__ */ array(/* @__PURE__ */ number()))
5297
5456
  })
5298
5457
  ]);
5299
5458
  /** Serialize a handshake message for the wire (handshake frames are JSON — they aren't the hot path). */
@@ -5359,6 +5518,15 @@ function reject(reason, id) {
5359
5518
  * is unusable with this key: clear the client's identity storage / mint a new persistent id".
5360
5519
  */
5361
5520
  const HANDSHAKE_REJECT_ID_PIN_MISMATCH = "identity_pin_mismatch";
5521
+ /** Machine-readable rejection for peers with no common first-party wire generation. */
5522
+ const HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH = "protocol_version_mismatch";
5523
+ function handshakeProtocolVersion(protocol) {
5524
+ if (!protocol.startsWith(HANDSHAKE_PROTOCOL_PREFIX)) return void 0;
5525
+ const raw = protocol.slice(11);
5526
+ if (!/^(0|[1-9]\d*)$/.test(raw)) return void 0;
5527
+ const parsed = Number(raw);
5528
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
5529
+ }
5362
5530
  function tofuPinKey(client) {
5363
5531
  return `${client.envId}::${client.perId ?? client.insId ?? "_"}`;
5364
5532
  }
@@ -5489,6 +5657,17 @@ function createClientHandshake(config) {
5489
5657
  if (welcome.dictionaryVersion !== dictionaryVersion) throw new Error("[ws-handshake] server dictionary version mismatch");
5490
5658
  if (welcome.securityLevel !== securityLevel) throw new Error("[ws-handshake] server security level mismatch");
5491
5659
  if (wantsEncryption && welcome.exchangePublicKey == null) throw new Error("[ws-handshake] server did not provide an exchange key for encryption");
5660
+ const expectedPeer = config.expectedPeer;
5661
+ if (expectedPeer != null && (welcome.server.envId !== expectedPeer.envId || expectedPeer.perId != null && welcome.server.perId !== expectedPeer.perId)) throw err_wire_connect.fromId("peer_identity_mismatch", {
5662
+ expected: {
5663
+ envId: expectedPeer.envId,
5664
+ perId: expectedPeer.perId
5665
+ },
5666
+ actual: {
5667
+ envId: welcome.server.envId,
5668
+ perId: welcome.server.perId
5669
+ }
5670
+ });
5492
5671
  const linkedServerId = runtimeLinkId(welcome.server);
5493
5672
  await link.linkClient({
5494
5673
  linkedClientId: linkedServerId,
@@ -5559,7 +5738,14 @@ function createServerHandshake(config) {
5559
5738
  let result;
5560
5739
  return {
5561
5740
  async onHello(hello) {
5562
- if (hello.protocol !== HANDSHAKE_PROTOCOL) return reject("unsupported handshake protocol");
5741
+ if (hello.protocol !== HANDSHAKE_PROTOCOL) {
5742
+ const observedProtocolVersion = handshakeProtocolVersion(hello.protocol);
5743
+ return {
5744
+ ...reject(`unsupported handshake protocol; this server supports wire protocol v${WIRE_SUPPORTED_PROTOCOL_VERSIONS.join(", v")}`, HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH),
5745
+ observedProtocolVersion,
5746
+ supportedProtocolVersions: [...WIRE_SUPPORTED_PROTOCOL_VERSIONS]
5747
+ };
5748
+ }
5563
5749
  const dictionaryVersion = typeof config.dictionaryVersion === "function" ? config.dictionaryVersion(hello) : config.dictionaryVersion;
5564
5750
  if (dictionaryVersion == null) return reject("unknown or unserved channel");
5565
5751
  if (hello.dictionaryVersion !== dictionaryVersion) return reject("dictionary version mismatch");
@@ -5685,8 +5871,8 @@ function securityLevelMeets(actual, required) {
5685
5871
  //#endregion
5686
5872
  //#region ../nice-wire/src/Connect/WireClient.ts
5687
5873
  /**
5688
- * The carrier said "no valid endpoint right now" (`createRequest` returned null — resilience-surface
5689
- * §6). A policy signal, not a failure: the redial loop PARKS on it (no backoff churn, no garbage
5874
+ * The carrier said "no valid endpoint right now" (`createRequest` returned null). A policy signal,
5875
+ * not a failure: the redial loop PARKS on it (no backoff churn, no garbage
5690
5876
  * dial) and resumes at the next explicit `connect()`/dispatch. The transport selection rethrows it
5691
5877
  * unwrapped so this check is reliable.
5692
5878
  */
@@ -5694,12 +5880,13 @@ const isDialUnavailable = (e) => err_wire_connect.isExact(e) && e.hasId("dial_un
5694
5880
  /**
5695
5881
  * A dial failure the backoff ladder must PARK on instead of retrying: either no endpoint exists
5696
5882
  * right now ({@link isDialUnavailable}), or the peer rejected the handshake with
5697
- * `identity_pin_mismatch` (Inteleport feedback §3) — the peer has a *different* verify key pinned
5698
- * for this client identity, so every retry re-runs the same doomed handshake. Parking is not
5699
- * terminal: the next explicit `connect()`/dispatch may try again (and re-park). Other handshake
5700
- * rejections (e.g. a dictionary-version mismatch) keep the ladder — a deploy can heal those.
5883
+ * `identity_pin_mismatch` (the peer has a different key pinned) or
5884
+ * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation).
5885
+ * Parking is not terminal: the next explicit `connect()`/dispatch may try again after the app has
5886
+ * upgraded or changed endpoints. Other handshake rejections (e.g. a dictionary mismatch) retain
5887
+ * the existing retry behavior because a matching deploy can heal them.
5701
5888
  */
5702
- const isParkedDialRejection = (e) => isDialUnavailable(e) || err_wire_connect.isExact(e) && e.hasId("identity_pin_mismatch");
5889
+ 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"));
5703
5890
  /**
5704
5891
  * The dial-out connection: owns the transport cache, preference-ordered selection, the protocol mux,
5705
5892
  * and the whole **connection lifecycle** — establishment bookkeeping, the keep-alive redial ladder
@@ -5741,19 +5928,19 @@ var WireClient = class {
5741
5928
  * outage, and it emits `link_down` at close.
5742
5929
  */
5743
5930
  _tornDown = false;
5744
- /** Explicit opt-out; `undefined` = auto (on for a protocol-carrying duplex link — see `_keepLinkAlive`). */
5745
- _keepLinkAliveOption;
5746
- /** Connections we've hooked a keep-alive disconnect listener onto (once per connection). */
5747
- _keepAliveHooked = /* @__PURE__ */ new WeakSet();
5931
+ /** Explicit opt-out; `undefined` = auto (on for a protocol-carrying duplex link). */
5932
+ _reconnectOption;
5933
+ /** Connections we've hooked a reconnect listener onto (once per connection). */
5934
+ _reconnectHooked = /* @__PURE__ */ new WeakSet();
5748
5935
  _redialTimer;
5749
5936
  _redialAttempts = 0;
5750
5937
  /** Set by an explicit teardown so the resulting disconnect doesn't auto-redial; cleared on a fresh establish. */
5751
5938
  _suppressRedial = false;
5752
- /** Timer ending a `debug.dropLink` suppression window (resilience-surface §2). */
5939
+ /** Timer ending a `debug.dropLink` suppression window. */
5753
5940
  _debugResumeTimer;
5754
5941
  _disposed = false;
5755
5942
  /**
5756
- * Chaos/QA surface (resilience-surface §2) — stable API, but never for production control flow.
5943
+ * Chaos/QA surface — stable API, but never for production control flow.
5757
5944
  * The "simulate airplane mode" button: manual QA and consumer resilience tests use it to force
5758
5945
  * the outages that page-level interception can't (the keep-alive redial heals straight through
5759
5946
  * a `window.WebSocket` patch).
@@ -5812,7 +5999,8 @@ dropLink: async (opts) => {
5812
5999
  this.localCoordinate = options.localCoordinate;
5813
6000
  this.securityLevel = options.securityLevel ?? "none";
5814
6001
  this.canPush = options.canPush;
5815
- this._keepLinkAliveOption = options.keepLinkAlive;
6002
+ if (options.reconnect != null && options.keepLinkAlive != null) throw err_wire_connect.fromId("conflicting_connect_options", { detail: "WireClient: pass only `reconnect`; `keepLinkAlive` is deprecated" });
6003
+ this._reconnectOption = options.reconnect ?? options.keepLinkAlive;
5816
6004
  this._buildConnectInput = options.buildConnectInput;
5817
6005
  this._defaultLocalCoordinate = options.defaultLocalCoordinate;
5818
6006
  this._manager = options.createManager(this._cache);
@@ -5845,16 +6033,12 @@ dropLink: async (opts) => {
5845
6033
  get wireMux() {
5846
6034
  return this.mux;
5847
6035
  }
5848
- /**
5849
- * The peer this connection dials — the `IRealmWireLink.peerClient` surface a realm reads for
5850
- * devtools topology attribution (observational only). An alias of {@link peer}; the two names are
5851
- * reconciled to one in the final-form surface pass (plan Phase 3.4).
5852
- */
6036
+ /** @deprecated Use {@link peer}. */
5853
6037
  get peerClient() {
5854
6038
  return this.peer;
5855
6039
  }
5856
6040
  /**
5857
- * The re-dial hook a realm client rides (DESYNC F6 / Phase 8a — the `IRealmWireLink` seam):
6041
+ * The re-dial hook a realm client rides:
5858
6042
  * `realmConnection(client)` reads it and hands it to the realm engine as the connection
5859
6043
  * adapter's `requestReconnect`, invoked on an unanswered staleness probe. A bound closure, so it
5860
6044
  * survives being detached from `this` (the realm stores the reference and calls it later).
@@ -5863,9 +6047,9 @@ dropLink: async (opts) => {
5863
6047
  return () => void this.reconnectLink();
5864
6048
  }
5865
6049
  /** Keep-alive is active for a protocol-carrying duplex link (a realm) unless opted out (Phase 8b). */
5866
- get _keepLinkAlive() {
6050
+ get _shouldReconnect() {
5867
6051
  if (this._disposed || !this.canPush) return false;
5868
- if (this._keepLinkAliveOption != null) return this._keepLinkAliveOption;
6052
+ if (this._reconnectOption != null) return this._reconnectOption;
5869
6053
  return (this.mux?.localCaps().length ?? 0) > 0;
5870
6054
  }
5871
6055
  /** Called on every fresh link establishment (`connect()` / a redial): re-enable + hook keep-alive. */
@@ -5889,8 +6073,8 @@ dropLink: async (opts) => {
5889
6073
  }
5890
6074
  /** Attach the auto-redial disconnect listener to one connection, once (Phase 8b). */
5891
6075
  _hookKeepAlive(methods) {
5892
- if (methods.addOnDisconnectListener == null || this._keepAliveHooked.has(methods)) return;
5893
- this._keepAliveHooked.add(methods);
6076
+ if (methods.addOnDisconnectListener == null || this._reconnectHooked.has(methods)) return;
6077
+ this._reconnectHooked.add(methods);
5894
6078
  methods.addOnDisconnectListener(() => {
5895
6079
  if (methods !== this._currentLinkMethods) return;
5896
6080
  if (this._tornDown) return;
@@ -5898,12 +6082,12 @@ dropLink: async (opts) => {
5898
6082
  this._downSince = Date.now();
5899
6083
  this._emitLinkEvent({ type: "link_down" });
5900
6084
  }
5901
- if (this._keepLinkAlive && !this._suppressRedial) this._scheduleRedial();
6085
+ if (this._shouldReconnect && !this._suppressRedial) this._scheduleRedial();
5902
6086
  });
5903
6087
  }
5904
6088
  /** Schedule one backoff+jitter re-dial (Phase 8b); idempotent — one attempt pending at a time. */
5905
6089
  _scheduleRedial() {
5906
- if (!this._keepLinkAlive || this._suppressRedial || this._redialTimer != null) return;
6090
+ if (!this._shouldReconnect || this._suppressRedial || this._redialTimer != null) return;
5907
6091
  const ceiling = Math.min(1e3 * 2 ** this._redialAttempts, 3e4);
5908
6092
  const delay = ceiling / 2 + Math.random() * (ceiling / 2);
5909
6093
  this._redialAttempts += 1;
@@ -5965,7 +6149,7 @@ dropLink: async (opts) => {
5965
6149
  }
5966
6150
  }
5967
6151
  /**
5968
- * Tear down the (possibly half-open) duplex link and immediately re-dial it (DESYNC F6 / Phase
6152
+ * Tear down the (possibly half-open) duplex link and immediately re-dial it (the reconnect contract / Phase
5969
6153
  * 8b). Surfaced to a realm client as the connection adapter's `requestReconnect` (via
5970
6154
  * {@link requestReconnect}) — the staleness-probe escalation calls it when a probe goes
5971
6155
  * unanswered. On a successful re-dial the mux re-attaches and every realm re-hellos; a failure
@@ -5988,7 +6172,7 @@ dropLink: async (opts) => {
5988
6172
  }
5989
6173
  /**
5990
6174
  * Stop the keep-alive auto-redial and release the current link — the intention-revealing
5991
- * teardown counterpart of `keepLinkAlive`. Call this when a session is
6175
+ * teardown counterpart of `reconnect`. Call this when a session is
5992
6176
  * over (leaving a match, logging out): the link closes and stays closed until the next explicit
5993
6177
  * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the client is reusable.
5994
6178
  */
@@ -8457,7 +8641,7 @@ function createActionFrameCrypto({ link, keyMaterial }) {
8457
8641
  //#endregion
8458
8642
  //#region ../nice-wire/src/Mux/protocolFrame.ts
8459
8643
  /**
8460
- * Frame-protocol prefix bytes (realm plan §3.1). A registered protocol frame is
8644
+ * Frame-protocol prefix bytes (realm protocol design §3.1). A registered protocol frame is
8461
8645
  * `[prefixByte, ...payload]` with the prefix drawn from the reserved range `0x00`–`0x0F` —
8462
8646
  * bytes no legacy frame can start with: binary action envelopes are msgpack fixarrays
8463
8647
  * (`0x96`–`0x98`), control frames are msgpack maps (`0x80`–`0x8f`, `0xde`, `0xdf`), and
@@ -8613,17 +8797,34 @@ function wireFrameByteSize(frame) {
8613
8797
  }
8614
8798
  //#endregion
8615
8799
  //#region ../nice-wire/src/Connect/handshakeRejectError.ts
8800
+ const sanitizeVersions = (versions) => {
8801
+ if (versions == null) return void 0;
8802
+ const safe = [];
8803
+ for (const version of versions) {
8804
+ if (Number.isSafeInteger(version) && version >= 1 && version <= 65535) safe.push(version);
8805
+ if (safe.length === 2) break;
8806
+ }
8807
+ return safe.length > 0 ? safe : void 0;
8808
+ };
8616
8809
  /**
8617
- * Map a peer's handshake reject frame to the error the dialing side throws (Inteleport feedback
8618
- * §3). A reject carrying a machine-readable `id` becomes the matching typed `err_wire_connect`
8619
- * error — today `identity_pin_mismatch`, which the transport selection rethrows UNWRAPPED (like
8620
- * `dial_unavailable`) so `err.hasId("identity_pin_mismatch")` works at the `connect()`/dispatch
8621
- * caller and the keep-alive redial loop can park on it. A reject without an id (an older peer,
8810
+ * Map a peer's handshake reject frame to the error the dialing side throws. A reject carrying a machine-readable `id` becomes the matching typed `err_wire_connect`
8811
+ * error — `identity_pin_mismatch` or `protocol_version_mismatch` — which transport selection
8812
+ * rethrows unwrapped so callers can branch on it and the keep-alive redial loop can park. A
8813
+ * reject without an id (an older peer,
8622
8814
  * whose frames never carry one) becomes `handshake_rejected` — same message text, now typed, so
8623
8815
  * `classifyConnectFailure` can tell "the backend said no" from "wrong address" (feedback W3).
8624
8816
  */
8625
8817
  function handshakeRejectError(stage, rejectFrame) {
8626
8818
  if (rejectFrame.id === "identity_pin_mismatch") return err_wire_connect.fromId("identity_pin_mismatch", { reason: rejectFrame.reason });
8819
+ if (rejectFrame.id === "protocol_version_mismatch") {
8820
+ const observedProtocolVersion = sanitizeVersions(rejectFrame.observedProtocolVersion == null ? void 0 : [rejectFrame.observedProtocolVersion])?.[0];
8821
+ return err_wire_connect.fromId("protocol_version_mismatch", {
8822
+ reason: rejectFrame.reason,
8823
+ observedProtocolVersion,
8824
+ localSupportedProtocolVersions: [...WIRE_SUPPORTED_PROTOCOL_VERSIONS],
8825
+ remoteSupportedProtocolVersions: sanitizeVersions(rejectFrame.supportedProtocolVersions)
8826
+ });
8827
+ }
8627
8828
  return err_wire_connect.fromId("handshake_rejected", {
8628
8829
  stage,
8629
8830
  reason: rejectFrame.reason
@@ -8647,7 +8848,7 @@ function wrongHandshakeFrame(channel, expected, receivedKind) {
8647
8848
  const KEEPALIVE_PING$1 = "ping";
8648
8849
  const KEEPALIVE_PONG$1 = "pong";
8649
8850
  /** One keepalive loop per live link — created by the session, stopped with it. */
8650
- function startLinkKeepalive(channel, config, tap) {
8851
+ function startHeartbeat(channel, config, tap) {
8651
8852
  let lastInboundAt = Date.now();
8652
8853
  let pingSentAt;
8653
8854
  let timer;
@@ -8743,11 +8944,11 @@ function establishPlainDuplexSession(ctx) {
8743
8944
  const pipe = makePipe(channel, void 0, tap);
8744
8945
  const port = makeLanePort(channel, pipe);
8745
8946
  const mux = ctx.mux;
8746
- const keepalive = ctx.keepalive != null ? startLinkKeepalive(channel, ctx.keepalive, tap) : void 0;
8747
- if (keepalive != null) disconnectListeners.push(keepalive.stop);
8947
+ const heartbeat = ctx.heartbeat != null ? startHeartbeat(channel, ctx.heartbeat, tap) : void 0;
8948
+ if (heartbeat != null) disconnectListeners.push(heartbeat.stop);
8748
8949
  channel.attach({
8749
8950
  onMessage: (frame) => {
8750
- keepalive?.noteInbound();
8951
+ heartbeat?.noteInbound();
8751
8952
  if (frame === KEEPALIVE_PONG$1) {
8752
8953
  tap?.({
8753
8954
  dir: "in",
@@ -8786,11 +8987,11 @@ async function establishSecureDuplexSession(ctx) {
8786
8987
  const handshakeWaiters = [];
8787
8988
  const pendingFrames = [];
8788
8989
  let nonProtocolFrame;
8789
- let keepalive;
8990
+ let heartbeat;
8790
8991
  const mux = ctx.mux;
8791
8992
  channel.attach({
8792
8993
  onMessage: (frame) => {
8793
- keepalive?.noteInbound();
8994
+ heartbeat?.noteInbound();
8794
8995
  if (frame === KEEPALIVE_PONG$1) {
8795
8996
  tap?.({
8796
8997
  dir: "in",
@@ -8856,9 +9057,9 @@ async function establishSecureDuplexSession(ctx) {
8856
9057
  active = true;
8857
9058
  for (const frame of pendingFrames) await handleIncomingFrame(pipe, frame, mux, ctx.lane, port, tap);
8858
9059
  pendingFrames.length = 0;
8859
- if (ctx.keepalive != null) {
8860
- keepalive = startLinkKeepalive(channel, ctx.keepalive, tap);
8861
- disconnectListeners.push(keepalive.stop);
9060
+ if (ctx.heartbeat != null) {
9061
+ heartbeat = startHeartbeat(channel, ctx.heartbeat, tap);
9062
+ disconnectListeners.push(heartbeat.stop);
8862
9063
  }
8863
9064
  return makeSession$1(channel, pipe, disconnectListeners, remoteCaps);
8864
9065
  }
@@ -8913,6 +9114,7 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
8913
9114
  const handshake = createClientHandshake({
8914
9115
  link: secure.link,
8915
9116
  localCoordinate: secure.localCoordinate,
9117
+ expectedPeer: secure.expectedPeer,
8916
9118
  dictionaryVersion: handshakeConfig.dictionaryVersion,
8917
9119
  securityLevel: secure.securityLevel,
8918
9120
  channelTags: handshakeConfig.channels,
@@ -8966,7 +9168,7 @@ let transportOrd = 0;
8966
9168
  /**
8967
9169
  * Live, per-handler transport runtime built from a reusable transport definition. Holds the
8968
9170
  * connection-scoped state (ordinal, initialized config, sockets / abort sets) that must not be shared
8969
- * across handlers. Moved from nice-action (shared-base-connect plan, Phase 2) with the action types
9171
+ * across handlers. Moved from nice-action with the action types
8970
9172
  * inverted into generics: `RP` (per-dispatch routing params), `RD` (the raw ready-data a definition
8971
9173
  * yields), and `METHODS` (the finalized send surface subclasses build) are opaque to wire.
8972
9174
  */
@@ -9011,7 +9213,7 @@ var TransportConnection$1 = class {
9011
9213
  return this._finalizeTransportMethods(readyData);
9012
9214
  }
9013
9215
  _getCacheKey(input) {
9014
- const parts = this.initialized.getTransportCacheKey?.(input);
9216
+ const parts = this.initialized.getCacheKey?.(input);
9015
9217
  if (parts == null) return null;
9016
9218
  return parts.join("\0");
9017
9219
  }
@@ -9161,56 +9363,60 @@ var WireProtocolMux = class {
9161
9363
  //#endregion
9162
9364
  //#region ../nice-wire/src/Connect/wireConnectionParts.ts
9163
9365
  /** 8b.3 defaults: ≈20 s worst-case half-open detection, quiet enough for a healthy idle tab. */
9164
- const DEFAULT_LINK_KEEPALIVE_IDLE_MS = 15e3;
9165
- const DEFAULT_LINK_KEEPALIVE_PONG_TIMEOUT_MS = 5e3;
9366
+ const DEFAULT_HEARTBEAT_IDLE_MS = 15e3;
9367
+ const DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS = 5e3;
9166
9368
  const ephemeralIdentityWarned = /* @__PURE__ */ new Set();
9167
9369
  /**
9168
- * The ephemeral-identity trap (Inteleport feedback §1): a coordinate with a persistent id whose
9370
+ * The ephemeral-identity trap: a coordinate with a persistent id whose
9169
9371
  * crypto identity lives in non-durable storage keys the peer's trust-on-first-use verify-key pin but
9170
9372
  * regenerates a new key on every reload — so every reload after the first is rejected
9171
9373
  * `identity_pin_mismatch`, forever. It type-checks and the first load works, so nothing else surfaces
9172
9374
  * it. Warn once per pinned identity (module-global dedupe — one warning per identity per process, not
9173
- * per connection). `durable === undefined` (a custom adapter) stays silent; a deliberately
9375
+ * per connection). Both `durable === false` and unknown durability are warning-worthy; a deliberately
9174
9376
  * per-session id opts out with `ephemeralIdentity: true`. Shared by every dial-out entry point
9175
9377
  * (`createWireClient`, `connectChannel`), so the check lives once.
9176
9378
  */
9177
9379
  function warnOnEphemeralPinnedIdentity(callerName, coordinate, storage) {
9178
- if (storage.durable !== false || coordinate.perId == null) return;
9380
+ if (storage.durable === true || coordinate.perId == null) return;
9179
9381
  const pinKey = `${coordinate.envId}::${coordinate.perId}`;
9180
9382
  if (ephemeralIdentityWarned.has(pinKey)) return;
9181
9383
  ephemeralIdentityWarned.add(pinKey);
9182
- 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 durable (memory/session-backed), so this client's crypto identity regenerates on every 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.`);
9384
+ 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.`);
9183
9385
  }
9184
9386
  /**
9185
9387
  * Assemble the connection facts a dial-out entry point shares — the one implementation of "how a
9186
9388
  * wire connection's mux, crypto identity, keepalive, and traffic tap are set up" (first-production
9187
- * plan Phase 1.6). `createWireClient` and `connectChannel` both call this; each then builds its own
9389
+ * the connection design). `createWireClient` and `connectChannel` both call this; each then builds its own
9188
9390
  * transports (mux-only `WireLinkConnection`s vs action `Transport`s with the codec lane) around the
9189
9391
  * shared result, so a fix to any of these lands once.
9190
9392
  */
9191
9393
  function assembleWireConnectionParts(options) {
9192
9394
  const mux = options.mux ?? new WireProtocolMux();
9395
+ if (options.reconnect != null && options.keepLinkAlive != null) throw err_wire_connect.fromId("conflicting_connect_options", { detail: `${options.callerName}: pass only \`reconnect\`; \`keepLinkAlive\` is deprecated` });
9396
+ if (options.heartbeat != null && options.linkKeepalive != null) throw err_wire_connect.fromId("conflicting_connect_options", { detail: `${options.callerName}: pass only \`heartbeat\`; \`linkKeepalive\` is deprecated` });
9397
+ const reconnect = options.reconnect ?? options.keepLinkAlive;
9398
+ const heartbeat = options.heartbeat ?? options.linkKeepalive;
9193
9399
  for (const protocol of options.protocols ?? []) mux.registerProtocol(protocol);
9194
9400
  let link = options.link;
9195
9401
  if (options.anySecure && link == null) {
9196
- if (options.storage == null) throw new Error(`${options.callerName}: a secure transport requires \`storage\` (or \`link\`) for the crypto identity. Pass it, or set \`secure: false\` on the transport for a plain connection.`);
9197
- if (options.ephemeralIdentity !== true) warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);
9198
- link = new ClientCryptoKeyLink({ storageAdapter: options.storage });
9199
- }
9200
- const resolveLinkKeepalive = () => {
9201
- if (options.linkKeepalive === false) return void 0;
9202
- const explicit = options.linkKeepalive;
9203
- if (!(explicit != null || options.keepLinkAlive === true || options.keepLinkAlive !== false && mux.localCaps().length > 0)) return void 0;
9402
+ 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.`);
9403
+ if (options.storage != null && options.ephemeralIdentity !== true) warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);
9404
+ link = new ClientCryptoKeyLink(options.storage != null ? { storageAdapter: options.storage } : {});
9405
+ }
9406
+ const resolveHeartbeat = () => {
9407
+ if (heartbeat === false) return void 0;
9408
+ const explicit = heartbeat;
9409
+ if (!(explicit != null || reconnect === true || reconnect !== false && mux.localCaps().length > 0)) return void 0;
9204
9410
  return {
9205
- idleMs: explicit?.idleMs ?? DEFAULT_LINK_KEEPALIVE_IDLE_MS,
9206
- pongTimeoutMs: explicit?.pongTimeoutMs ?? DEFAULT_LINK_KEEPALIVE_PONG_TIMEOUT_MS
9411
+ idleMs: explicit?.idleMs ?? DEFAULT_HEARTBEAT_IDLE_MS,
9412
+ pongTimeoutMs: explicit?.pongTimeoutMs ?? DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS
9207
9413
  };
9208
9414
  };
9209
9415
  const wireTap = options.wireTap != null ? withLinkIdTap(options.wireTap, options.peer.stringId) : void 0;
9210
9416
  return {
9211
9417
  mux,
9212
9418
  link,
9213
- resolveLinkKeepalive,
9419
+ resolveHeartbeat,
9214
9420
  wireTap
9215
9421
  };
9216
9422
  }
@@ -9321,6 +9527,7 @@ async function runConnectorExchangeHandshake(carrier, secure, lane) {
9321
9527
  const handshake = createClientHandshake({
9322
9528
  link: secure.link,
9323
9529
  localCoordinate: secure.localCoordinate,
9530
+ expectedPeer: secure.expectedPeer,
9324
9531
  dictionaryVersion: lane.dictionaryVersion,
9325
9532
  securityLevel: secure.securityLevel,
9326
9533
  channelTags: lane.channels
@@ -9545,7 +9752,7 @@ var AcceptorSecureSession = class {
9545
9752
  //#endregion
9546
9753
  //#region ../nice-wire/src/Connect/WireAcceptor.ts
9547
9754
  /**
9548
- * Wire-level keepalive (plan §6.1): the acceptor answers a literal `"ping"` text frame with
9755
+ * Wire-level keepalive: the acceptor answers a literal `"ping"` text frame with
9549
9756
  * `"pong"` before any other dispatch, so connection health never involves the lane or a protocol.
9550
9757
  * On Cloudflare the DO host answers it below this layer (`setWebSocketAutoResponse`) and the frame
9551
9758
  * never reaches {@link WireAcceptor.receive} — this path makes every other host behave the same.
@@ -9553,12 +9760,12 @@ var AcceptorSecureSession = class {
9553
9760
  const KEEPALIVE_PING = "ping";
9554
9761
  const KEEPALIVE_PONG = "pong";
9555
9762
  /**
9556
- * The acceptor backbone (plan Phase 4, §3.1): everything between "an inbound frame arrived on a
9763
+ * The acceptor backbone: everything between "an inbound frame arrived on a
9557
9764
  * connection" and "a protocol module (or the lane) may handle it" — handshake accept +
9558
9765
  * secure-session-per-connection, security levels, the client-identity registry, the protocol
9559
- * registry with prefix dispatch, the **security gate** (review A.6: protocol traffic requires an
9766
+ * registry with prefix dispatch, the **security gate** (the connection contract: protocol traffic requires an
9560
9767
  * authenticated connection unless the protocol opts into `allowPlain`), the **un-gated lifecycle
9561
- * fan-out** (review A.2.3: attach/detach fire for every registered protocol the gate admits, not
9768
+ * fan-out** (the connection contract: attach/detach fire for every registered protocol the gate admits, not
9562
9769
  * just the caps-advertised ones — both hooks are idempotent by contract, so a missing cap is a
9563
9770
  * non-event instead of a silent liveness hole), the versioned {@link IWireConnectionBinding}
9564
9771
  * persistence + {@link rehydrate} (hibernation), and the wire keepalive.
@@ -9615,6 +9822,16 @@ var WireAcceptor = class {
9615
9822
  this._receivePlain(connection, frame, wireBytes);
9616
9823
  return;
9617
9824
  }
9825
+ if (!this._sessionByConn.has(connection)) {
9826
+ const prefix = peekProtocolPrefix(frame);
9827
+ const protocol = prefix == null ? void 0 : this._protocols.get(prefix);
9828
+ if (protocol?.allowPlain === true) {
9829
+ this._tapIn(connection, wireBytes, protocol.id);
9830
+ const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame);
9831
+ protocol.onFrame(connection, bytes.subarray(1), this.protocolSendFor(connection, protocol), this._protocolContext(connection));
9832
+ return;
9833
+ }
9834
+ }
9618
9835
  this._sessionFor(connection, security).receive(frame, wireBytes);
9619
9836
  }
9620
9837
  _receivePlain(connection, frame, wireBytes = 0) {
@@ -9710,7 +9927,7 @@ var WireAcceptor = class {
9710
9927
  return true;
9711
9928
  }
9712
9929
  const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame);
9713
- protocol.onFrame(connection, bytes.subarray(1), this.protocolSendFor(connection, protocol));
9930
+ protocol.onFrame(connection, bytes.subarray(1), this.protocolSendFor(connection, protocol), this._protocolContext(connection));
9714
9931
  return true;
9715
9932
  }
9716
9933
  /**
@@ -9724,7 +9941,7 @@ var WireAcceptor = class {
9724
9941
  this._protoIdsByConn.set(connection, advertisedIds);
9725
9942
  for (const protocol of this._protocols.values()) {
9726
9943
  if (!this._gateAdmits(connection, protocol)) continue;
9727
- protocol.onAttach?.(connection, this.protocolSendFor(connection, protocol));
9944
+ protocol.onAttach?.(connection, this.protocolSendFor(connection, protocol), this._protocolContext(connection));
9728
9945
  }
9729
9946
  }
9730
9947
  /**
@@ -9823,6 +10040,8 @@ var WireAcceptor = class {
9823
10040
  this._onConnectionBound?.(connection, binding);
9824
10041
  }
9825
10042
  _bind(connection, client) {
10043
+ const previous = this._clientByConn.get(connection);
10044
+ if (previous != null && previous.stringId !== client.stringId && this._connByClient.get(previous.stringId) === connection) this._connByClient.delete(previous.stringId);
9826
10045
  this._connByClient.set(client.stringId, connection);
9827
10046
  this._clientByConn.set(connection, client);
9828
10047
  }
@@ -9836,7 +10055,7 @@ var WireAcceptor = class {
9836
10055
  const client = this._clientByConn.get(connection);
9837
10056
  if (client != null && this._connByClient.get(client.stringId) === connection) this._connByClient.delete(client.stringId);
9838
10057
  this._lane.onDrop?.(connection, client);
9839
- for (const protocol of this._protocols.values()) protocol.onDetach?.(connection);
10058
+ for (const protocol of this._protocols.values()) protocol.onDetach?.(connection, this._protocolContext(connection));
9840
10059
  this._protoIdsByConn.delete(connection);
9841
10060
  this._clientByConn.delete(connection);
9842
10061
  this._sessionByConn.delete(connection);
@@ -9882,6 +10101,12 @@ var WireAcceptor = class {
9882
10101
  levelFor(connection) {
9883
10102
  return this._levelByConn.get(connection) ?? "none";
9884
10103
  }
10104
+ _protocolContext(connection) {
10105
+ return {
10106
+ client: this._clientByConn.get(connection),
10107
+ level: this._levelByConn.get(connection) ?? "none"
10108
+ };
10109
+ }
9885
10110
  /** The last persisted (or rehydrated) binding for a connection, if any. */
9886
10111
  bindingFor(connection) {
9887
10112
  return this._bindingByConn.get(connection);
@@ -9955,7 +10180,7 @@ const textEncoder = new TextEncoder();
9955
10180
  const textDecoder = new TextDecoder();
9956
10181
  /**
9957
10182
  * The exchange (request/reply) acceptor backbone — the HTTP counterpart to `WireAcceptor`'s
9958
- * duplex sessions, re-homed from nice-action's `ExchangeAcceptor` (shared-base-connect plan,
10183
+ * duplex sessions, re-homed from nice-action's `ExchangeAcceptor` (shared connection design,
9959
10184
  * Phase 6). Each POST body is one exchange envelope; the acceptor drives the server handshake
9960
10185
  * over the two `hs` POSTs, mints a session **token** on accept, and on every later `act` POST
9961
10186
  * resolves the session by token, decrypts the body (at `encrypted`), hands the opened lane wire
@@ -10588,6 +10813,7 @@ var ActionContext = class extends ActionBase {
10588
10813
  * the sending side. Never serialized (see {@link IHandledReliability}).
10589
10814
  */
10590
10815
  reliability;
10816
+ _receiverMetadata;
10591
10817
  constructor(_domain, id, hydrationData) {
10592
10818
  super("context", _domain, id);
10593
10819
  this._domain = _domain;
@@ -10595,7 +10821,25 @@ var ActionContext = class extends ActionBase {
10595
10821
  this.cuid = hydrationData.cuid;
10596
10822
  this._routing = hydrationData.routing;
10597
10823
  this.originClient = hydrationData.originClient;
10598
- this.reliability = hydrationData.reliability;
10824
+ this.reliability = void 0;
10825
+ }
10826
+ /** @internal Installed by the receiving runtime from out-of-band transport facts. */
10827
+ _setReceiverMetadata(metadata) {
10828
+ Object.defineProperty(this, "_receiverMetadata", {
10829
+ configurable: true,
10830
+ enumerable: false,
10831
+ value: metadata,
10832
+ writable: true
10833
+ });
10834
+ Object.defineProperty(this, "reliability", {
10835
+ configurable: true,
10836
+ enumerable: false,
10837
+ value: metadata.reliability
10838
+ });
10839
+ }
10840
+ /** @internal Read only by the acceptor that owns the arrival. */
10841
+ _getReceiverMetadata() {
10842
+ return this._receiverMetadata;
10599
10843
  }
10600
10844
  _setOriginClient(client) {
10601
10845
  this.originClient = client;
@@ -10824,7 +11068,6 @@ var ActionPayload_Request = class extends ActionPayload {
10824
11068
  return (await this.runToResultPayload(options)).result;
10825
11069
  }
10826
11070
  async run(options) {
10827
- if (this._callSite == null) this._callSite = (/* @__PURE__ */ new Error()).stack;
10828
11071
  return this._domain.runAction(this, options);
10829
11072
  }
10830
11073
  };
@@ -11159,9 +11402,15 @@ const err_nice_action = err_nice.createChildDomain({
11159
11402
  ["no_action_execution_handler"]: err({ message: ({ domain, actionId, specifiedClient }) => `${specifiedClient ? ` The targeted client runtime [${specifiedClient.stringId}] has no` : "No"} action handler registered for "${actionId}" in domain "${domain}".` }),
11160
11403
  ["wire_action_not_payload"]: err({ message: ({ domain, actionId, actionState }) => `Cannot handle wire for action "${actionId}" in domain "${domain}": expected action form of "data" and type of "request", "progress" or "result", got "${actionState}".` }),
11161
11404
  ["wire_not_action_data"]: err({ message: () => `Cannot handle wire for action: expected an object with a "domain" property of type string, a "form" property of "data" and a "type" property of "request", "progress" or "result".` }),
11405
+ ["connection_required"]: err({ message: ({ operation }) => `Cannot ${operation}: this action did not arrive on a live duplex connection.` }),
11162
11406
  ["runtime_reset"]: err({ message: () => `Runtime has been reset.` }),
11163
- ["client_runtime_already_registered"]: err({ message: ({ context, client }) => `Environment is already registered${context?.domain ? ` on domain "${context.domain}"` : ""} for client [${client.stringId}]. Each client specifier (exact match on all properties) may only be registered once.` }),
11164
- ["client_runtime_not_registered"]: err({ message: ({ context, clientStringId }) => `No runtime registered${context?.domain ? ` on domain "${context.domain}"` : ""} for client [${clientStringId}].` }),
11407
+ ["runtime_disposed"]: err({ message: ({ runtime }) => `Action runtime [${runtime}] has been disposed and cannot be reused.` }),
11408
+ ["ambiguous_action_runtime"]: err({ message: ({ domain, actionId, runtimes }) => `Several runtimes can execute "${domain}:${actionId}" (${runtimes.join(", ")}). Target one explicitly with runtime.run(request) or request.run({ targetLocalRuntime: runtime }).` }),
11409
+ ["invalid_server_runtime_scope"]: err({ message: ({ runtime, actualScope }) => `Server runtime [${runtime}] has scope "${actualScope}". Server hosts require new ActionRuntime(identity, { scope: "instance" }) so isolate-local instances never enter global dispatch.` }),
11410
+ ["conflicting_server_options"]: err({ message: ({ detail }) => `Invalid server construction options: ${detail}` }),
11411
+ ["conflicting_connect_options"]: err({ message: ({ detail }) => `Invalid connection options: ${detail}` }),
11412
+ ["duplicate_action_executor"]: err({ message: ({ route }) => `More than one local executor was registered for the same route priority (${route}). Keep one executor at that exact route; an action-specific executor may still override a domain fallback.` }),
11413
+ ["peer_handler_already_bound"]: err({ message: () => `A stateful peer handler is already bound to another runtime. Create one connector or acceptor per runtime.` }),
11165
11414
  ["no_client_runtimes_registered"]: err({ message: ({ context }) => `No runtimes registered${context?.domain ? ` on domain "${context.domain}"` : ""}. Add handlers to a runtime via runtime.addHandlers([handler]) before executing actions.` }),
11166
11415
  ["action_input_validation_failed"]: err({
11167
11416
  message: ({ domain, actionId, validationMessage }) => `Input validation failed for action "${actionId}" in domain "${domain}":\n${validationMessage}`,
@@ -12685,6 +12934,12 @@ const actionSchema = () => {
12685
12934
  return new ActionSchema();
12686
12935
  };
12687
12936
  //#endregion
12937
+ //#region ../nice-action/src/diagnostics/callSite.ts
12938
+ /** Capture a diagnostic caller stack. Callers must apply the opt-in policy before invoking this. */
12939
+ function captureDiagnosticCallSite() {
12940
+ return (/* @__PURE__ */ new Error()).stack;
12941
+ }
12942
+ //#endregion
12688
12943
  //#region ../../node_modules/std-env/dist/index.mjs
12689
12944
  const e = globalThis.process?.env || Object.create(null), t$1 = globalThis.process || { env: e }, n = t$1 !== void 0 && t$1.env && t$1.env.NODE_ENV || void 0, r = [
12690
12945
  [`claude`, [`CLAUDECODE`, `CLAUDE_CODE`]],
@@ -12926,10 +13181,10 @@ const err_nice_transport = err_nice_action.createChildDomain({
12926
13181
  //#region ../nice-action/src/ActionRuntime/Transport/ConnectionTransportManager.ts
12927
13182
  /**
12928
13183
  * Preference-ordered transport selection for action dispatch — wire's generic
12929
- * `ConnectionTransportManager` (shared-base-connect plan, Phase 2) pinned to the action routing
13184
+ * `ConnectionTransportManager` pinned to the action routing
12930
13185
  * params + methods, with the selection failures expressed in action's own `err_nice_transport`
12931
13186
  * vocabulary (the exact errors thrown before the move). An actionless dial
12932
- * (`ChannelConnector.connect()`, review A.1) reports as `"connect()"` in the failure messages.
13187
+ * (`ChannelConnector.connect()`, the connection contract) reports as `"connect()"` in the failure messages.
12933
13188
  */
12934
13189
  var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
12935
13190
  constructor(cache) {
@@ -12949,16 +13204,22 @@ var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
12949
13204
  //#region ../nice-action/src/ActionRuntime/ActionDomainManager.ts
12950
13205
  var ActionDomainManager = class {
12951
13206
  _domains = /* @__PURE__ */ new Map();
12952
- addDomain(domain) {
13207
+ assertCanAddDomain(domain) {
12953
13208
  const existing = this._domains.get(domain.domain);
12954
- if (existing === domain) return;
13209
+ if (existing === domain || existing == null) return;
12955
13210
  if (existing != null) throw err_nice_action.fromId("domain_name_collision", {
12956
13211
  domain: domain.domain,
12957
13212
  existingParentDomains: existing.allDomains,
12958
13213
  incomingParentDomains: domain.allDomains
12959
13214
  });
13215
+ }
13216
+ addDomain(domain) {
13217
+ this.assertCanAddDomain(domain);
12960
13218
  this._domains.set(domain.domain, domain);
12961
13219
  }
13220
+ removeDomain(domain) {
13221
+ if (this._domains.get(domain.domain) === domain) this._domains.delete(domain.domain);
13222
+ }
12962
13223
  getDomains() {
12963
13224
  return [...this._domains.values()];
12964
13225
  }
@@ -12996,6 +13257,7 @@ var ActionRouter = class {
12996
13257
  for (const [matchKey, routeDataEntries] of actionRouter.actionRouteData.entries()) this.actionRouteData.set(matchKey, [...routeDataEntries]);
12997
13258
  }
12998
13259
  addDomainsFromOther(actionRouter) {
13260
+ for (const domain of actionRouter.getDomains()) this.domainManager.assertCanAddDomain(domain);
12999
13261
  for (const domain of actionRouter.getDomains()) this.domainManager.addDomain(domain);
13000
13262
  }
13001
13263
  /** All FNs registered for an action, ID-specific entries first then domain wildcard. */
@@ -13107,6 +13369,19 @@ var ActionRouter = class {
13107
13369
  this._push(key, routeData);
13108
13370
  return this;
13109
13371
  }
13372
+ /** Remove one route-data object from every key; used by scoped installation teardown. */
13373
+ removeRouteData(routeData) {
13374
+ for (const [key, entries] of this.actionRouteData) {
13375
+ const remaining = entries.filter((entry) => entry !== routeData);
13376
+ if (remaining.length === 0) this.actionRouteData.delete(key);
13377
+ else if (remaining.length !== entries.length) this.actionRouteData.set(key, remaining);
13378
+ }
13379
+ const registeredKeys = [...this.actionRouteData.keys()];
13380
+ for (const domain of this.domainManager.getDomains()) {
13381
+ const prefix = `dom[${domain.domain}]id[`;
13382
+ if (!registeredKeys.some((key) => key.startsWith(prefix))) this.domainManager.removeDomain(domain);
13383
+ }
13384
+ }
13110
13385
  _push(key, routeData) {
13111
13386
  const existing = this.actionRouteData.get(key);
13112
13387
  if (existing != null) existing.push(routeData);
@@ -13116,9 +13391,10 @@ var ActionRouter = class {
13116
13391
  //#endregion
13117
13392
  //#region ../nice-action/src/ActionRuntime/Handler/ActionHandler.ts
13118
13393
  var ActionHandler = class {
13119
- cuid;
13120
- constructor() {
13121
- this.cuid = nanoid();
13394
+ _cuid;
13395
+ get cuid() {
13396
+ this._cuid ??= nanoid();
13397
+ return this._cuid;
13122
13398
  }
13123
13399
  getActionRouter() {
13124
13400
  return this.actionRouter;
@@ -13141,17 +13417,22 @@ var ActionHandler = class {
13141
13417
  */
13142
13418
  var PeerLink = class extends ActionHandler {
13143
13419
  /** The peer runtime this handler links to (an env-only coordinate for an accept-in handler). */
13144
- peerClient;
13420
+ peer;
13145
13421
  handlerType = "peer";
13146
13422
  actionRouter = new ActionRouter({
13147
13423
  contextType: "handler_route",
13148
13424
  handler: this
13149
13425
  });
13150
13426
  /** Listeners installed by the runtime (`resolveIncomingActionPayload`) for inbound peer frames. */
13151
- _incomingActionDataListeners = [];
13427
+ _incomingRuntime;
13428
+ _incomingActionDataListener;
13152
13429
  constructor(peerCoordinate) {
13153
13430
  super();
13154
- this.peerClient = peerCoordinate;
13431
+ this.peer = peerCoordinate;
13432
+ }
13433
+ /** @deprecated Use {@link peer}. */
13434
+ get peerClient() {
13435
+ return this.peer;
13155
13436
  }
13156
13437
  forDomain(domain) {
13157
13438
  this.actionRouter.forDomain(domain, true);
@@ -13165,12 +13446,19 @@ var PeerLink = class extends ActionHandler {
13165
13446
  this.actionRouter.forActionIds(domain, ids, true);
13166
13447
  return this;
13167
13448
  }
13168
- _setIncomingActionDataListener(listener) {
13169
- this._incomingActionDataListeners.push(listener);
13449
+ _setIncomingActionDataListener(runtime, listener) {
13450
+ if (this._incomingRuntime != null && this._incomingRuntime !== runtime) throw err_nice_action.fromId("peer_handler_already_bound");
13451
+ this._incomingRuntime = runtime;
13452
+ this._incomingActionDataListener = listener;
13453
+ return () => {
13454
+ if (this._incomingRuntime !== runtime || this._incomingActionDataListener !== listener) return;
13455
+ this._incomingRuntime = void 0;
13456
+ this._incomingActionDataListener = void 0;
13457
+ };
13170
13458
  }
13171
13459
  /** Hand a decoded inbound frame to the runtime (called by each specialization's receive path). */
13172
- _emitIncoming(json) {
13173
- for (const listener of this._incomingActionDataListeners) listener(json);
13460
+ _emitIncoming(json, metadata) {
13461
+ this._incomingActionDataListener?.(json, metadata);
13174
13462
  }
13175
13463
  /**
13176
13464
  * Whether this handler currently holds a *live* connection bound to `origin`. The runtime's return-path
@@ -13417,7 +13705,7 @@ var ChannelConnector = class extends PeerLink {
13417
13705
  return this._wire.wireMux;
13418
13706
  }
13419
13707
  /**
13420
- * The re-dial hook a realm client rides (DESYNC F6 / Phase 8a — the `IRealmWireLink` seam):
13708
+ * The re-dial hook a realm client rides:
13421
13709
  * `realmConnection(connector)` hands it to the engine as `requestReconnect`, invoked on an
13422
13710
  * unanswered staleness probe.
13423
13711
  */
@@ -13461,30 +13749,30 @@ var ChannelConnector = class extends PeerLink {
13461
13749
  _controlMethods;
13462
13750
  /** Stream-level reliable-delivery observers (see {@link TReliableStreamEvent}). */
13463
13751
  _reliableEventListeners = /* @__PURE__ */ new Set();
13464
- constructor({ runtimeCoordinate: peerSpecifier, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, connectionIdentity, securityLevel, keepLinkAlive }) {
13465
- super(peerSpecifier);
13752
+ constructor({ peer, runtimeCoordinate, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, connectionIdentity, securityLevel, reconnect, keepLinkAlive }) {
13753
+ super(peer ?? runtimeCoordinate);
13466
13754
  this._connectionIdentity = connectionIdentity;
13467
13755
  this._defaultTimeout = defaultTimeout ?? 1e4;
13468
13756
  this._reliableTimeout = reliableActionTimeout ?? DEFAULT_RELIABLE_ACTION_TIMEOUT;
13469
13757
  this._wire = new WireClient({
13470
13758
  createManager: (cache) => new ConnectionTransportManager(cache),
13471
13759
  mux: wireMux,
13472
- peer: this.peerClient,
13760
+ peer: this.peer,
13473
13761
  localCoordinate: connectionIdentity ?? localCoordinate,
13474
13762
  securityLevel,
13475
13763
  canPush: transports.some((transport) => transport.type === "duplex"),
13476
- keepLinkAlive,
13764
+ reconnect: reconnect ?? keepLinkAlive,
13477
13765
  buildConnectInput: (pair) => pair,
13478
13766
  defaultLocalCoordinate: () => ActionRuntime.getDefault().coordinate
13479
13767
  });
13480
13768
  for (const transport of transports) {
13481
13769
  const connection = transport._createConnection({ resolvers: {
13482
13770
  onIncomingActionDataJson: (json, reliability) => {
13483
- if (reliability?.ack != null) this._applyAck(reliableStreamId(this.peerClient, json.domain, json.id, reliability.streamKey), reliability.ack);
13771
+ if (reliability?.ack != null) this._applyAck(reliableStreamId(this.peer, json.domain, json.id, reliability.streamKey), reliability.ack);
13484
13772
  this._emitIncoming(json);
13485
13773
  },
13486
13774
  onControlMessage: (message) => {
13487
- const streamId = reliableStreamId(this.peerClient, message.domain, message.id, message.k);
13775
+ const streamId = reliableStreamId(this.peer, message.domain, message.id, message.k);
13488
13776
  if (message.$c === "rack") this._applyAck(streamId, message.ack);
13489
13777
  else if (message.$c === "rsync") {
13490
13778
  this._streamSkips.delete(streamId);
@@ -13511,7 +13799,7 @@ var ChannelConnector = class extends PeerLink {
13511
13799
  await this._wire.connect({ localCoordinate: this._connectionIdentity ?? config?.targetLocalRuntime?.coordinate });
13512
13800
  }
13513
13801
  /**
13514
- * Tear down the (possibly half-open) duplex link and immediately re-dial it (DESYNC F6 / Phase
13802
+ * Tear down the (possibly half-open) duplex link and immediately re-dial it (the reconnect contract / Phase
13515
13803
  * 8b) — surfaced to a realm client as `requestReconnect`, called by the staleness-probe
13516
13804
  * escalation. **Awaitable** — resolves when the fresh link's handshake completes.
13517
13805
  */
@@ -13532,11 +13820,11 @@ var ChannelConnector = class extends PeerLink {
13532
13820
  if (this._connectionIdentity != null) action.context._setOriginClient(this._connectionIdentity);
13533
13821
  const incomingTimeout = config?.timeout ?? this._defaultTimeout;
13534
13822
  const parentCuid = peekHandlerCuid();
13535
- const callSite = action._callSite ?? (/* @__PURE__ */ new Error()).stack;
13823
+ const callSite = localRuntime._captureActionCallSite(action, config?.captureCallSites);
13536
13824
  const routeParams = {
13537
13825
  action,
13538
13826
  localClient,
13539
- externalClient: this.peerClient
13827
+ externalClient: this.peer
13540
13828
  };
13541
13829
  const preferredTransport = this._wire.getPreferredTransport();
13542
13830
  const routeItem = preferredTransport != null ? {
@@ -13554,7 +13842,7 @@ var ChannelConnector = class extends PeerLink {
13554
13842
  localRuntime.registerRunningAction(runningAction);
13555
13843
  if (action.schema.reliabilityTier !== "none") {
13556
13844
  const streamKey = config?.streamKey;
13557
- const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);
13845
+ const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);
13558
13846
  const prepared = this._outbox.prepare(streamId, () => {
13559
13847
  if (runningAction.isAborted) return;
13560
13848
  this._dispatchWhenTransportReady(runningAction, routeParams, routeItem, incomingTimeout);
@@ -13787,7 +14075,7 @@ var ChannelConnector = class extends PeerLink {
13787
14075
  * normal mid-stream re-sync. Closing a stream this connection never sent on is a no-op.
13788
14076
  */
13789
14077
  closeReliableStream(action, streamKey) {
13790
- const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);
14078
+ const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);
13791
14079
  const highest = this._outbox.highestSeq(streamId);
13792
14080
  if (highest == null) return;
13793
14081
  const reason = err_nice_transport.fromId("reliable_stream_closed", {
@@ -13813,7 +14101,7 @@ var ChannelConnector = class extends PeerLink {
13813
14101
  }
13814
14102
  reliablePending(action, streamKey) {
13815
14103
  if (action == null) return this._outbox.size;
13816
- const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);
14104
+ const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);
13817
14105
  const oldest = this._outbox.oldestPreparedAt(streamId);
13818
14106
  return {
13819
14107
  unackedCount: this._outbox.pendingCount(streamId),
@@ -13834,12 +14122,12 @@ var ChannelConnector = class extends PeerLink {
13834
14122
  const { methods } = await this._wire.getReadyTransport({
13835
14123
  action: payload,
13836
14124
  localClient,
13837
- externalClient: this.peerClient
14125
+ externalClient: this.peer
13838
14126
  });
13839
14127
  if (methods.sendReturnData == null) return false;
13840
14128
  methods.sendReturnData(payload, {
13841
14129
  localClient,
13842
- externalClient: this.peerClient
14130
+ externalClient: this.peer
13843
14131
  });
13844
14132
  return true;
13845
14133
  } catch {
@@ -13849,13 +14137,13 @@ var ChannelConnector = class extends PeerLink {
13849
14137
  toJsonObject() {
13850
14138
  return {
13851
14139
  type: this.handlerType,
13852
- client: this.peerClient
14140
+ client: this.peer
13853
14141
  };
13854
14142
  }
13855
14143
  toHandlerRouteItem(transport, input) {
13856
14144
  return {
13857
14145
  type: this.handlerType,
13858
- client: this.peerClient,
14146
+ client: this.peer,
13859
14147
  transOrd: transport.transOrd,
13860
14148
  transShape: transport.type,
13861
14149
  transInfo: transport.getRouteInfo(input)
@@ -13863,7 +14151,7 @@ var ChannelConnector = class extends PeerLink {
13863
14151
  }
13864
14152
  /**
13865
14153
  * Stop the keep-alive auto-redial and release the current link — the intention-revealing
13866
- * teardown counterpart of `keepLinkAlive`. Call this when a session is
14154
+ * teardown counterpart of `reconnect`. Call this when a session is
13867
14155
  * over (leaving a match, logging out): the link closes and stays closed until the next explicit
13868
14156
  * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the connector is reusable.
13869
14157
  *
@@ -13887,12 +14175,18 @@ var ActionRuntime = class {
13887
14175
  actionRouter;
13888
14176
  _pendingRunningActions = /* @__PURE__ */ new Map();
13889
14177
  _registeredPeerHandlers = [];
13890
- _applied = false;
14178
+ _registeredRoots = /* @__PURE__ */ new Set();
14179
+ _handlerOwnership = /* @__PURE__ */ new Map();
14180
+ _disposed = false;
14181
+ captureCallSites;
14182
+ scope;
13891
14183
  static getDefault() {
13892
14184
  return getDefaultActionRuntime();
13893
14185
  }
13894
- constructor(coordinate) {
13895
- this._coordinate = coordinate.specifyIfUnset({ insId: nanoid(14) });
14186
+ constructor(coordinate, options = {}) {
14187
+ this._coordinate = coordinate;
14188
+ this.captureCallSites = options.captureCallSites ?? false;
14189
+ this.scope = options.scope ?? "global";
13896
14190
  this.timeCreated = Date.now();
13897
14191
  this.actionRouter = new ActionRouter({
13898
14192
  contextType: "runtime_to_handler",
@@ -13900,34 +14194,57 @@ var ActionRuntime = class {
13900
14194
  });
13901
14195
  }
13902
14196
  get coordinate() {
14197
+ if (this._coordinate.insId == null) this._coordinate = this._coordinate.specify({ insId: nanoid(14) });
13903
14198
  return this._coordinate;
13904
14199
  }
14200
+ get disposed() {
14201
+ return this._disposed;
14202
+ }
14203
+ /** @internal */
14204
+ _assertActive() {
14205
+ if (this._disposed) throw err_nice_action.fromId("runtime_disposed", { runtime: this.coordinate.stringId });
14206
+ }
14207
+ /** @internal Apply the runtime/request diagnostic policy without replacing a supplied stack. */
14208
+ _captureActionCallSite(action, override) {
14209
+ if (action._callSite == null && (override ?? this.captureCallSites)) action._callSite = captureDiagnosticCallSite();
14210
+ return action._callSite;
14211
+ }
13905
14212
  specifyRuntimeCoordinate(specifics) {
14213
+ this._assertActive();
13906
14214
  if (specifics.envId != null && this._coordinate.envId !== specifics.envId) throw err_nice_action.fromId("not_implemented", { label: `updating RuntimeCoordinate with a different "envId" ("${this._coordinate.envId}" → "${specifics.envId}")` });
13907
14215
  this._coordinate = this._coordinate.specify(specifics);
13908
- this.apply();
13909
14216
  }
13910
14217
  registerRunningAction(ra) {
14218
+ this._assertActive();
13911
14219
  this._pendingRunningActions.set(ra.cuid, ra);
13912
14220
  ra.addUpdateListeners([(update) => {
13913
14221
  if (update.type === "finished") this._pendingRunningActions.delete(ra.cuid);
13914
14222
  }]);
13915
14223
  }
13916
- resolveIncomingActionPayload(json) {
14224
+ resolveIncomingActionPayload(json, metadata) {
14225
+ if (this._disposed) return;
13917
14226
  if (json.type === "request") {
13918
- this.handleActionPayloadWire(json).catch((err) => {
14227
+ this._handleActionPayloadWireFromReceiver(json, metadata).catch((err) => {
13919
14228
  console.error(`[ActionRuntime] Incoming action [${json.domain}:${json.id}:${json.form}:${json.type}] unhandled:`, err);
13920
14229
  });
13921
14230
  return;
13922
14231
  }
13923
14232
  this._pendingRunningActions.get(json.context.cuid)?._resolveFromJson(json);
13924
14233
  }
13925
- async handleActionPayloadWire(wire) {
13926
- let action;
13927
- if (isActionPayload_Any_JsonObject(wire)) action = this.actionRouter.domainManager.getActionDomainOrThrow(wire).hydrateAnyAction(wire);
13928
- if (action == null) throw err_nice_action.fromId("wire_not_action_data");
14234
+ /** @internal Hydrate a wire request and attach receiver-owned metadata before application dispatch. */
14235
+ async _handleActionPayloadWireFromReceiver(wire, metadata) {
14236
+ const action = this._hydrateActionPayloadWire(wire);
14237
+ if (metadata != null) action.context._setReceiverMetadata(metadata);
13929
14238
  return this.handleActionPayload(action);
13930
14239
  }
14240
+ _hydrateActionPayloadWire(wire) {
14241
+ if (isActionPayload_Any_JsonObject(wire)) return this.actionRouter.domainManager.getActionDomainOrThrow(wire).hydrateAnyAction(wire);
14242
+ throw err_nice_action.fromId("wire_not_action_data");
14243
+ }
14244
+ async handleActionPayloadWire(wire) {
14245
+ this._assertActive();
14246
+ return this.handleActionPayload(this._hydrateActionPayloadWire(wire));
14247
+ }
13931
14248
  /**
13932
14249
  * The declared {@link EActionResponseMode} for a wire frame's action, looked up from its registered
13933
14250
  * domain — `undefined` if the route isn't registered. Lets a transport decide, without executing the
@@ -13965,6 +14282,7 @@ var ActionRuntime = class {
13965
14282
  }
13966
14283
  }
13967
14284
  async handleActionPayload(action, options) {
14285
+ this._assertActive();
13968
14286
  if (action.type === "request") {
13969
14287
  const observers = action.context._domain._collectActionObservers();
13970
14288
  let handlerForAction;
@@ -14009,26 +14327,17 @@ var ActionRuntime = class {
14009
14327
  * Return the first handler registered for the given action, or `undefined`
14010
14328
  * if none has been registered (action-ID-specific beats domain-wildcard).
14011
14329
  */
14012
- _getHandlerForAction(action, options) {
14013
- const handlers = this.actionRouter.getRouteDataEntriesForAction(action);
14014
- const targetPeer = options?.targetPeer;
14015
- const possibleHandlers = handlers.filter((handler) => {
14016
- if (handler.handlerType === "peer") {
14017
- if (targetPeer && !targetPeer.isSameFor(handler.peerClient).id) return false;
14018
- return true;
14019
- }
14020
- if (targetPeer != null) return false;
14021
- if (action.type === "request") return true;
14022
- return false;
14330
+ _getHandlerForAction(action, _options) {
14331
+ const possibleHandlers = this.actionRouter.getRouteDataEntriesForAction(action).filter((handler) => {
14332
+ return handler.handlerType === "peer" || handler.handlerType === "local" && action.type === "request";
14023
14333
  });
14024
14334
  if (possibleHandlers.length === 0) return;
14025
- const scoringPeer = targetPeer ?? RuntimeCoordinate.unknown;
14026
14335
  let handlerScore = -1;
14027
14336
  let handler;
14028
14337
  for (const possibleHandler of possibleHandlers) {
14029
14338
  if (possibleHandler.handlerType === "local") return possibleHandler;
14030
14339
  if (possibleHandler.handlerType === "peer") {
14031
- const score = scoringPeer.similarityLevel(possibleHandler.peerClient);
14340
+ const score = RuntimeCoordinate.unknown.similarityLevel(possibleHandler.peer);
14032
14341
  if (score > handlerScore) {
14033
14342
  handlerScore = score;
14034
14343
  handler = possibleHandler;
@@ -14041,8 +14350,7 @@ var ActionRuntime = class {
14041
14350
  const handler = this._getHandlerForAction(action, options);
14042
14351
  if (handler == null) throw err_nice_action.fromId("no_action_execution_handler", {
14043
14352
  actionId: action.id,
14044
- domain: action.domain,
14045
- specifiedClient: options?.targetPeer
14353
+ domain: action.domain
14046
14354
  });
14047
14355
  return handler;
14048
14356
  }
@@ -14050,20 +14358,91 @@ var ActionRuntime = class {
14050
14358
  * Register one or more handlers. Each handler's own `actionRouter` defines
14051
14359
  * which domains/actions it handles — those routing keys are mirrored into
14052
14360
  * this runtime's router so the same action can be served by multiple handlers.
14053
- * Duplicate registrations (same handler cuid for the same key) are skipped.
14361
+ * Re-adding the same handler object is idempotent. Global runtimes register with the affected root
14362
+ * domains automatically; instance runtimes remain private and require explicit dispatch.
14054
14363
  */
14055
14364
  addHandlers(handlers) {
14365
+ this._addHandlers(handlers, {
14366
+ persistent: true,
14367
+ register: true
14368
+ });
14369
+ return this;
14370
+ }
14371
+ /** @internal Install handlers for a host and return an idempotent ownership release. */
14372
+ _installHandlers(handlers, options = {}) {
14373
+ this._assertActive();
14374
+ const lease = Symbol("action-runtime-handler-installation");
14375
+ try {
14376
+ this._addHandlers(handlers, {
14377
+ persistent: false,
14378
+ register: options.register ?? false,
14379
+ lease
14380
+ });
14381
+ } catch (error) {
14382
+ this._releaseHandlerLease(lease);
14383
+ throw error;
14384
+ }
14385
+ let released = false;
14386
+ return () => {
14387
+ if (released) return;
14388
+ released = true;
14389
+ this._releaseHandlerLease(lease);
14390
+ };
14391
+ }
14392
+ _addHandlers(handlers, options) {
14393
+ this._assertActive();
14394
+ this._assertNoDuplicateLocalExecutors(handlers);
14395
+ for (const handler of handlers) {
14396
+ let ownership = this._handlerOwnership.get(handler);
14397
+ if (ownership == null) {
14398
+ const handlerRouter = handler.getActionRouter();
14399
+ ownership = {
14400
+ persistent: false,
14401
+ leases: /* @__PURE__ */ new Set()
14402
+ };
14403
+ try {
14404
+ this.actionRouter.addDomainsFromOther(handlerRouter);
14405
+ if (handler.handlerType === "peer") {
14406
+ ownership.unbind = handler._setIncomingActionDataListener(this, (json, metadata) => this.resolveIncomingActionPayload(json, metadata));
14407
+ this._registeredPeerHandlers.push(handler);
14408
+ }
14409
+ for (const key of handlerRouter.getRegisteredKeys()) this.actionRouter.addForKey(key, handler);
14410
+ } catch (error) {
14411
+ ownership.unbind?.();
14412
+ this.actionRouter.removeRouteData(handler);
14413
+ const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14414
+ if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14415
+ throw error;
14416
+ }
14417
+ this._handlerOwnership.set(handler, ownership);
14418
+ }
14419
+ if (options.persistent) ownership.persistent = true;
14420
+ if (options.lease != null) ownership.leases.add(options.lease);
14421
+ }
14422
+ if (options.register) this._registerWithRoutedRoots();
14423
+ }
14424
+ _assertNoDuplicateLocalExecutors(handlers) {
14425
+ for (const handler of handlers) for (const domain of handler.getActionRouter().getDomains()) this.actionRouter.domainManager.assertCanAddDomain(domain);
14426
+ const staged = /* @__PURE__ */ new Map();
14056
14427
  for (const handler of handlers) {
14057
- if (handler.handlerType === "peer") {
14058
- handler._setIncomingActionDataListener((json) => this.resolveIncomingActionPayload(json));
14059
- this._registeredPeerHandlers.push(handler);
14428
+ if (handler.handlerType !== "local" || this._handlerOwnership.has(handler)) continue;
14429
+ for (const key of handler.getActionRouter().getRegisteredKeys()) {
14430
+ const duplicate = this.actionRouter.getForKey(key).find((candidate) => candidate.handlerType === "local") ?? staged.get(key);
14431
+ if (duplicate != null && duplicate !== handler) throw err_nice_action.fromId("duplicate_action_executor", { route: key });
14432
+ staged.set(key, handler);
14060
14433
  }
14061
- const handlerRouter = handler.getActionRouter();
14062
- this.actionRouter.addDomainsFromOther(handlerRouter);
14063
- if (this._applied) this.apply();
14064
- for (const key of handlerRouter.getRegisteredKeys()) if (!this.actionRouter.getForKey(key).some((h) => h.cuid === handler.cuid)) this.actionRouter.addForKey(key, handler);
14065
14434
  }
14066
- return this;
14435
+ }
14436
+ _releaseHandlerLease(lease) {
14437
+ for (const [handler, ownership] of this._handlerOwnership) {
14438
+ ownership.leases.delete(lease);
14439
+ if (ownership.persistent || ownership.leases.size > 0) continue;
14440
+ ownership.unbind?.();
14441
+ this.actionRouter.removeRouteData(handler);
14442
+ const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14443
+ if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14444
+ this._handlerOwnership.delete(handler);
14445
+ }
14067
14446
  }
14068
14447
  /**
14069
14448
  * @internal Low-level primitive — the public way to open a connection is `connectChannel`, which
@@ -14071,15 +14450,15 @@ var ActionRuntime = class {
14071
14450
  * block it sits on (it restates domain lists by hand) and is not part of the supported surface.
14072
14451
  *
14073
14452
  * Declare an external "backend client" in one call: build an
14074
- * {@link ChannelConnector} for `externalCoordinate` carrying the given
14453
+ * {@link ChannelConnector} for `peer` carrying the given
14075
14454
  * `transports`, route the listed `domains`/`actions` to it, register it (plus any
14076
14455
  * `localHandlers` — e.g. server→client push handlers that share the same channel)
14077
- * on this runtime, and `apply()`. Returns the external handler so the caller can
14456
+ * on this runtime. Returns the external handler so the caller can
14078
14457
  * later `clearTransportCache()` it.
14079
14458
  */
14080
- connectTo(externalCoordinate, options) {
14459
+ connectTo(peer, options) {
14081
14460
  const handler = new ChannelConnector({
14082
- runtimeCoordinate: externalCoordinate,
14461
+ peer,
14083
14462
  transports: options.transports,
14084
14463
  defaultTimeout: options.defaultTimeout,
14085
14464
  reliableActionTimeout: options.reliableActionTimeout,
@@ -14087,28 +14466,40 @@ var ActionRuntime = class {
14087
14466
  localCoordinate: this.coordinate,
14088
14467
  connectionIdentity: options.connectionIdentity,
14089
14468
  securityLevel: options.securityLevel,
14090
- keepLinkAlive: options.keepLinkAlive
14469
+ reconnect: options.reconnect ?? options.keepLinkAlive
14091
14470
  });
14092
14471
  for (const domain of options.domains ?? []) handler.forDomain(domain);
14093
14472
  for (const action of options.actions ?? []) handler.forAction(action);
14094
14473
  this.addHandlers([handler, ...options.localHandlers ?? []]);
14095
- this.apply();
14096
14474
  return handler;
14097
14475
  }
14098
14476
  applyRuntimeForDomain(domain) {
14099
14477
  const rootDomain = domain.rootDomain;
14100
- if (!rootDomain._hasRuntime(this)) rootDomain._registerRuntime(this);
14478
+ if (!rootDomain._hasRuntime(this)) {
14479
+ rootDomain._registerRuntime(this);
14480
+ this._registeredRoots.add(rootDomain);
14481
+ }
14482
+ }
14483
+ _registerWithRoutedRoots() {
14484
+ if (this.scope === "instance") return;
14485
+ for (const domain of this.actionRouter.getDomains()) this.applyRuntimeForDomain(domain);
14101
14486
  }
14102
14487
  /**
14103
- * Register this runtime with all root domains covered by its currently-added handlers,
14104
- * making it eligible to execute actions dispatched from those domains.
14105
- * After apply() is called, any subsequent addHandlers() calls also auto-register.
14488
+ * @deprecated Handler installation registers global runtimes automatically. Retained as an
14489
+ * idempotent migration shim; it never registers an instance-scoped runtime.
14106
14490
  */
14107
14491
  apply() {
14108
- this._applied = true;
14109
- for (const domain of this.actionRouter.getDomains()) this.applyRuntimeForDomain(domain);
14492
+ this._assertActive();
14493
+ this._registerWithRoutedRoots();
14110
14494
  return this;
14111
14495
  }
14496
+ async run(request, options) {
14497
+ this._assertActive();
14498
+ return request.run({
14499
+ ...options,
14500
+ targetLocalRuntime: this
14501
+ });
14502
+ }
14112
14503
  /**
14113
14504
  * Find the best registered external handler that can reach `originClient` directly.
14114
14505
  * Used to locate the return-path channel for dispatching results back to the action origin.
@@ -14116,11 +14507,9 @@ var ActionRuntime = class {
14116
14507
  *
14117
14508
  * A handler that currently holds the origin's *live* connection always wins, regardless of its
14118
14509
  * coordinate score — owning the live socket bound to the origin's exact coordinate (set from the
14119
- * handshake) is a strictly more precise match than any env-level `peerClient` score. This lets one
14120
- * server accept clients of *several* envs over a single acceptor (a multi-role Durable Object): the
14121
- * result/push routes back over the carrier the client actually connected on even when the handler's
14122
- * `clientEnv` is unset or names a different env. Only when no handler owns a live connection do we fall
14123
- * back to the plain best-coordinate-score pick (the offline-return and connector-only cases).
14510
+ * handshake) is a strictly more precise match than a connector's declared `peer` score. This lets
14511
+ * one server accept clients of several environments over a single acceptor. Only when no handler owns a
14512
+ * live connection do we fall back to connector coordinate scoring.
14124
14513
  */
14125
14514
  getReturnHandlerForOrigin(originClient) {
14126
14515
  if (originClient.envId === "_unset_") return void 0;
@@ -14130,7 +14519,7 @@ var ActionRuntime = class {
14130
14519
  let bestOwnedHandler;
14131
14520
  for (const handler of this._registeredPeerHandlers) {
14132
14521
  if (!handler.canPush) continue;
14133
- const score = originClient.similarityLevel(handler.peerClient);
14522
+ const score = originClient.similarityLevel(handler.peer);
14134
14523
  if (score > bestScore) {
14135
14524
  bestScore = score;
14136
14525
  bestHandler = handler;
@@ -14144,18 +14533,60 @@ var ActionRuntime = class {
14144
14533
  return bestScore > 0 ? bestHandler : void 0;
14145
14534
  }
14146
14535
  resetRuntime() {
14536
+ this._assertActive();
14147
14537
  for (const ra of this._pendingRunningActions.values()) ra._abort(err_nice_action.fromId("runtime_reset"));
14148
14538
  for (const handler of this._registeredPeerHandlers) handler.clearTransportCache();
14149
14539
  }
14540
+ dispose() {
14541
+ if (this._disposed) return;
14542
+ this._disposed = true;
14543
+ for (const root of this._registeredRoots) root._unregisterRuntime(this);
14544
+ this._registeredRoots.clear();
14545
+ if (this._pendingRunningActions.size > 0) {
14546
+ const error = err_nice_action.fromId("runtime_disposed", { runtime: this.coordinate.stringId });
14547
+ for (const running of this._pendingRunningActions.values()) running._abort(error);
14548
+ }
14549
+ this._pendingRunningActions.clear();
14550
+ for (const handler of this._registeredPeerHandlers) {
14551
+ const disposable = handler;
14552
+ if (typeof disposable.dispose === "function") disposable.dispose();
14553
+ else handler.clearTransportCache();
14554
+ }
14555
+ for (const [handler, ownership] of this._handlerOwnership) {
14556
+ ownership.unbind?.();
14557
+ this.actionRouter.removeRouteData(handler);
14558
+ }
14559
+ this._handlerOwnership.clear();
14560
+ this._registeredPeerHandlers.length = 0;
14561
+ }
14150
14562
  _trySetupReturnDispatch(runningAction) {
14151
14563
  if (runningAction.context.schema.responseMode === "none") return;
14152
14564
  const originClient = runningAction.context.originClient;
14153
14565
  if (originClient.envId === "_unset_" || originClient.isSameFor(this._coordinate).id) return;
14566
+ const arrival = runningAction.context._getReceiverMetadata();
14154
14567
  runningAction.addUpdateListeners([(update) => {
14155
- if (update.type === "finished" && update.finishType === "success") this.getReturnHandlerForOrigin(originClient)?.sendReturnPayload(update.response, { targetLocalRuntime: this }).catch(() => {});
14568
+ if (update.type === "finished" && update.finishType === "success") {
14569
+ if (this._disposed) return;
14570
+ const returnHandler = arrival?.receiver instanceof PeerLink ? this._registeredPeerHandlers.includes(arrival.receiver) && arrival.receiver.canPush ? arrival.receiver : void 0 : this.getReturnHandlerForOrigin(originClient);
14571
+ if (returnHandler == null || !canReturnToOrigin(arrival, returnHandler)) return;
14572
+ returnHandler.sendReturnPayload(update.response, { targetLocalRuntime: this }).catch(() => {});
14573
+ }
14156
14574
  }]);
14157
14575
  }
14158
14576
  };
14577
+ /**
14578
+ * May a result be routed back to the action's *claimed* origin over `returnHandler`?
14579
+ *
14580
+ * - No arrival facts (a locally dispatched action, or an advanced caller supplying its own wire):
14581
+ * unchanged behaviour.
14582
+ * - The frame arrived on this very handler: always — that is answering on the link it came from.
14583
+ * - Otherwise the origin coordinate is only trustworthy when the arrival was authenticated; an
14584
+ * unauthenticated claim must never select a different connection.
14585
+ */
14586
+ function canReturnToOrigin(arrival, returnHandler) {
14587
+ if (arrival == null || arrival.receiver === returnHandler) return true;
14588
+ return arrival.securityLevel != null && arrival.securityLevel !== "none";
14589
+ }
14159
14590
  const runtimeState = {
14160
14591
  defaultLocalRuntime: void 0,
14161
14592
  assumedRuntimeInfo: void 0
@@ -14196,6 +14627,9 @@ var ActionLocalHandler = class extends ActionHandler {
14196
14627
  return this;
14197
14628
  }
14198
14629
  /**
14630
+ * @deprecated Prefer `forAction`, `forDomainActionCases`, or an exhaustive
14631
+ * `domain.wrapAsLocalHandler` map. Retained for this migration release.
14632
+ *
14199
14633
  * Register a handler for multiple action IDs (first-match-wins among cases).
14200
14634
  * Receives the full primed action narrowed to the union of those IDs.
14201
14635
  * Use `act.coreAction.id` to branch on which action was dispatched.
@@ -14232,19 +14666,28 @@ var ActionLocalHandler = class extends ActionHandler {
14232
14666
  context: action.context,
14233
14667
  request: action,
14234
14668
  parentCuid: peekHandlerCuid(),
14235
- callSite: action._callSite ?? (/* @__PURE__ */ new Error()).stack
14669
+ callSite: targetLocalRuntime._captureActionCallSite(action, config?.captureCallSites)
14236
14670
  });
14237
- this._handleRunningAction(handler, runningAction);
14671
+ this._handleRunningAction(handler, runningAction, targetLocalRuntime);
14238
14672
  return runningAction;
14239
14673
  }
14240
- async _handleRunningAction(handler, runningAction) {
14674
+ async _handleRunningAction(handler, runningAction, runtime) {
14241
14675
  const state = runningAction.state;
14242
14676
  if (state.result != null) return;
14243
14677
  await Promise.resolve();
14244
14678
  pushHandlerCuid(runningAction.cuid);
14245
14679
  try {
14246
14680
  const ran = await niceTryAsync(async () => {
14247
- const rawResult = await handler(state.request);
14681
+ const securityLevel = state.request.context._getReceiverMetadata()?.securityLevel;
14682
+ const context = {
14683
+ runtime,
14684
+ origin: state.request.context.originClient,
14685
+ authenticatedOrigin: securityLevel != null && securityLevel !== "none" ? state.request.context.originClient : void 0,
14686
+ securityLevel,
14687
+ reliability: state.request.context.reliability,
14688
+ run: (request, options) => runtime.run(request, options)
14689
+ };
14690
+ const rawResult = await handler(state.request, context);
14248
14691
  if (rawResult instanceof ActionPayload_Result) return rawResult;
14249
14692
  if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) return this.actionRouter.domainManager.getActionDomainOrThrow(state.request).hydrateResultPayload(rawResult);
14250
14693
  return state.request.successResult(rawResult);
@@ -14331,90 +14774,68 @@ var ActionDomainBase = class {
14331
14774
  };
14332
14775
  //#endregion
14333
14776
  //#region ../nice-action/src/ActionRuntime/ActionRuntimeManager.ts
14777
+ /** Root-domain registry. Object identity is the key; coordinates may legitimately match. */
14334
14778
  var ActionRuntimeManager = class {
14335
- _runtimes = /* @__PURE__ */ new Map();
14336
- _preferredRuntimeClientId = null;
14779
+ _runtimes = /* @__PURE__ */ new Set();
14337
14780
  _context;
14338
14781
  constructor(context) {
14339
14782
  this._context = context ?? {};
14340
14783
  }
14341
14784
  registerRuntime(runtime) {
14342
- const runtimeId = runtime.coordinate.stringId;
14343
- if (this._runtimes.has(runtimeId)) throw err_nice_action.fromId("client_runtime_already_registered", {
14344
- context: this._context,
14345
- client: runtime.coordinate
14346
- });
14347
- for (const id of runtime.coordinate.toStringIds()) {
14348
- if (this._runtimes.has(id)) continue;
14349
- this._runtimes.set(id, runtime);
14350
- }
14785
+ runtime._assertActive();
14786
+ this._runtimes.add(runtime);
14787
+ }
14788
+ unregisterRuntime(runtime) {
14789
+ this._runtimes.delete(runtime);
14351
14790
  }
14352
14791
  getRuntimeAndHandlerForAction(action, options, throwOnIssue) {
14353
14792
  const localRuntime = options?.targetLocalRuntime;
14354
14793
  if (localRuntime != null) {
14355
- const runtime = throwOnIssue ? this.getBestRuntimeOrThrow(options?.targetLocalRuntime?.coordinate) : this.getBestRuntime(options?.targetLocalRuntime?.coordinate);
14356
- if (runtime == null) return;
14357
- const handler = runtime._getHandlerForAction(action, options);
14794
+ localRuntime._assertActive();
14795
+ const handler = localRuntime._getHandlerForAction(action, options);
14358
14796
  if (handler != null) return {
14359
14797
  handler,
14360
- runtime
14798
+ runtime: localRuntime
14361
14799
  };
14362
14800
  if (throwOnIssue) throw err_nice_action.fromId("no_action_execution_handler", {
14363
14801
  domain: action.domain,
14364
14802
  actionId: action.id,
14365
14803
  specifiedClient: localRuntime.coordinate
14366
14804
  });
14805
+ return;
14367
14806
  }
14368
- for (const runtime of this._runtimes.values()) {
14807
+ let selected;
14808
+ let ambiguousRuntimeIds;
14809
+ for (const runtime of this._runtimes) {
14810
+ if (runtime.disposed) continue;
14369
14811
  const handler = runtime._getHandlerForAction(action);
14370
- if (handler) return {
14812
+ if (handler == null) continue;
14813
+ if (selected == null) selected = {
14371
14814
  handler,
14372
14815
  runtime
14373
14816
  };
14817
+ else {
14818
+ ambiguousRuntimeIds ??= [selected.runtime.coordinate.stringId];
14819
+ ambiguousRuntimeIds.push(runtime.coordinate.stringId);
14820
+ }
14374
14821
  }
14375
- if (throwOnIssue) throw err_nice_action.fromId("no_action_execution_handler", {
14822
+ if (ambiguousRuntimeIds != null) throw err_nice_action.fromId("ambiguous_action_runtime", {
14376
14823
  domain: action.domain,
14377
14824
  actionId: action.id,
14378
- specifiedClient: options?.targetLocalRuntime?.coordinate
14825
+ runtimes: ambiguousRuntimeIds
14826
+ });
14827
+ if (selected != null) return selected;
14828
+ if (throwOnIssue && this._runtimes.size === 0) throw err_nice_action.fromId("no_client_runtimes_registered", { context: this._context });
14829
+ if (throwOnIssue) throw err_nice_action.fromId("no_action_execution_handler", {
14830
+ domain: action.domain,
14831
+ actionId: action.id
14379
14832
  });
14380
14833
  }
14381
14834
  getRuntimeAndHandlerForActionOrThrow(action, options) {
14382
14835
  return this.getRuntimeAndHandlerForAction(action, options, true);
14383
14836
  }
14384
- setPreferredRuntime(runtime) {
14385
- const runtimeId = runtime.coordinate.stringId;
14386
- this._preferredRuntimeClientId = runtimeId;
14387
- }
14388
- getPreferredRuntime() {
14389
- if (this._preferredRuntimeClientId) {
14390
- const runtime = this._runtimes.get(this._preferredRuntimeClientId);
14391
- if (runtime) return runtime;
14392
- }
14393
- return this._runtimes.values().next().value;
14394
- }
14395
- getBestRuntimeForSpecifier(clientSpecifier) {
14396
- const ids = new RuntimeCoordinate(clientSpecifier).toStringIds();
14397
- for (const id of ids) {
14398
- const runtime = this._runtimes.get(id);
14399
- if (runtime) return runtime;
14400
- }
14401
- }
14402
- getBestRuntime(clientSpecifier) {
14403
- return clientSpecifier != null ? this.getBestRuntimeForSpecifier(clientSpecifier) : this.getPreferredRuntime();
14404
- }
14405
14837
  hasRuntime(runtime) {
14406
- return this._runtimes.has(runtime.coordinate.stringId);
14407
- }
14408
- getBestRuntimeOrThrow(specifier) {
14409
- const runtime = this.getBestRuntime(specifier);
14410
- if (!runtime) {
14411
- if (specifier == null) throw err_nice_action.fromId("no_client_runtimes_registered", { context: this._context });
14412
- throw err_nice_action.fromId("client_runtime_not_registered", {
14413
- context: this._context,
14414
- clientStringId: runtimeCoordinateToStringIds(specifier)[0]
14415
- });
14416
- }
14417
- return runtime;
14838
+ return this._runtimes.has(runtime);
14418
14839
  }
14419
14840
  };
14420
14841
  //#endregion
@@ -14447,12 +14868,12 @@ var ActionRootDomain = class extends ActionDomainBase {
14447
14868
  _registerRuntime(runtime) {
14448
14869
  this._actionRuntimeManager.registerRuntime(runtime);
14449
14870
  }
14871
+ _unregisterRuntime(runtime) {
14872
+ this._actionRuntimeManager.unregisterRuntime(runtime);
14873
+ }
14450
14874
  _hasRuntime(runtime) {
14451
14875
  return this._actionRuntimeManager.hasRuntime(runtime);
14452
14876
  }
14453
- getRuntime(clientSpecifier) {
14454
- return this._actionRuntimeManager.getBestRuntimeForSpecifier(clientSpecifier);
14455
- }
14456
14877
  async _runAction(actionPayload, options) {
14457
14878
  const allListeners = [...this._listeners, ...options?.listeners ?? []];
14458
14879
  let handlerAndRuntime;
@@ -14469,10 +14890,13 @@ var ActionRootDomain = class extends ActionDomainBase {
14469
14890
  throw err;
14470
14891
  }
14471
14892
  const { handler, runtime } = handlerAndRuntime;
14893
+ runtime._captureActionCallSite(actionPayload, options?.captureCallSites);
14472
14894
  actionPayload.context._setOriginClient(runtime.coordinate);
14473
14895
  const runningAction = await handler.handleActionRequest(actionPayload, {
14474
14896
  targetLocalRuntime: runtime,
14475
- streamKey: options?.streamKey
14897
+ timeout: options?.timeout,
14898
+ streamKey: options?.streamKey,
14899
+ captureCallSites: options?.captureCallSites
14476
14900
  });
14477
14901
  runningAction.addUpdateListeners(allListeners);
14478
14902
  return runningAction;
@@ -14534,14 +14958,14 @@ var ActionDomain = class ActionDomain extends ActionDomainBase {
14534
14958
  const executor = wrappedActionExecutor;
14535
14959
  for (const actionKey in wrappedActionExecutor) {
14536
14960
  if (!this.actionSchema[actionKey]) continue;
14537
- _handler.forAction(this.actionForId(actionKey), (request) => executor[request.id](request.input));
14961
+ _handler.forAction(this.actionForId(actionKey), (request, context) => executor[request.id](request.input, context));
14538
14962
  }
14539
14963
  return _handler;
14540
14964
  }
14541
14965
  wrapAsLocalHandler(wrappedActionExecutor) {
14542
14966
  const _handler = new ActionLocalHandler();
14543
14967
  const executor = wrappedActionExecutor;
14544
- return _handler.forDomain(this, (request) => executor[request.id](request.input));
14968
+ return _handler.forDomain(this, (request, context) => executor[request.id](request.input, context));
14545
14969
  }
14546
14970
  hydrateContext(id, contextData) {
14547
14971
  return new ActionContext(this, id, {
@@ -14554,8 +14978,7 @@ var ActionDomain = class ActionDomain extends ActionDomainBase {
14554
14978
  time: item.time
14555
14979
  };
14556
14980
  }),
14557
- originClient: contextData.originClient ? new RuntimeCoordinate(contextData.originClient) : RuntimeCoordinate.unknown,
14558
- reliability: contextData.reliability
14981
+ originClient: contextData.originClient ? new RuntimeCoordinate(contextData.originClient) : RuntimeCoordinate.unknown
14559
14982
  });
14560
14983
  }
14561
14984
  isDomainAction(action) {
@@ -14684,7 +15107,7 @@ function serveResultErrorInfo(error) {
14684
15107
  * been served, to `console` (or any `sink` you pass). Drop it straight into `serveChannel` so a "host and
14685
15108
  * forget" backend gets request/response feedback with no extra wiring:
14686
15109
  * ```ts
14687
- * serveChannel(runtime, channel, { storage, carriers, logger: createDefaultServeLogger() });
15110
+ * serveChannel(channel, { identity, storage, carriers, logger: createDefaultServeLogger() });
14688
15111
  * // → [nice-action] ▶ demo_basic/greet via http from envId[web_app]… [encrypted]
14689
15112
  * // ← [nice-action] ✓ demo_basic/greet ok via http 12ms
14690
15113
  * ```
@@ -14751,7 +15174,7 @@ function readLaneBindingState(lane) {
14751
15174
  * (WebSockets, Durable Objects, …). It is transport-agnostic: you feed it inbound frames with
14752
15175
  * {@link receive} and tell it how to write outbound frames via the `send` option.
14753
15176
  *
14754
- * Since plan Phase 4 this class is the **action lane** over a wire-owned {@link WireAcceptor}
15177
+ * Since the connection design this class is the **action lane** over a wire-owned {@link WireAcceptor}
14755
15178
  * (reachable as {@link wireAcceptor}): the backbone — handshake accept + secure sessions, security
14756
15179
  * levels, the client-identity registry, frame-protocol registration/dispatch/lifecycle, versioned
14757
15180
  * binding persistence + rehydrate, and keepalive — lives in wire; this handler keeps the action
@@ -14760,21 +15183,21 @@ function readLaneBindingState(lane) {
14760
15183
  *
14761
15184
  * Add it alongside your local execution handler:
14762
15185
  * ```ts
14763
- * const serverHandler = createChannelAcceptor({ clientEnv, formatMessage, send: (ws, f) => ws.send(f) });
15186
+ * const serverHandler = createChannelAcceptor({ formatMessage, send: (ws, f) => ws.send(f) });
14764
15187
  * runtime.addHandlers([localHandler, serverHandler]);
14765
15188
  * // per inbound message (e.g. a Durable Object's webSocketMessage):
14766
15189
  * serverHandler.receive(ws, message);
14767
15190
  * ```
14768
15191
  *
14769
15192
  * Inbound requests route to your local handler; the runtime's return dispatch then calls this
14770
- * handler back (it is an external handler keyed to `clientEnv`) to send the result to the originating
15193
+ * handler back (it owns the originating live connection) to send the result to the originating
14771
15194
  * connection. It registers an empty action router, so it is never chosen to *execute* an inbound
14772
15195
  * request — only to ferry results/pushes back out.
14773
15196
  */
14774
- var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15197
+ var ChannelAcceptor = class extends PeerLink {
14775
15198
  /** Accept-in over a live (duplex) connection registry — it pushes results/broadcasts to bound sockets. */
14776
15199
  canPush = true;
14777
- /** The wire-owned acceptor backbone this lane composes on (plan Phase 4). */
15200
+ /** The wire-owned acceptor backbone this lane composes on. */
14778
15201
  wireAcceptor;
14779
15202
  _formatMessage;
14780
15203
  _createFormatMessage;
@@ -14787,7 +15210,17 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14787
15210
  _connTags = /* @__PURE__ */ new Map();
14788
15211
  _inbox = new ReliableInbox();
14789
15212
  _persistedReceiver;
14790
- _replyStreamKeys = /* @__PURE__ */ new Map();
15213
+ /** Trusted arrival facts live beside decoded objects, never in attacker-controlled wire JSON. */
15214
+ _receiverMetadataByWire = /* @__PURE__ */ new WeakMap();
15215
+ /**
15216
+ * Reliable stores may reconstruct buffered JSON as a new object. Retain the matching trusted
15217
+ * arrival beside the receiver-owned stream/sequence address while this acceptor remains alive.
15218
+ * A wake deliberately loses this non-serializable socket fact, so restored frames execute with
15219
+ * no live connection context rather than borrowing whichever socket happened to fill the gap.
15220
+ */
15221
+ _receiverMetadataByReliableStream = /* @__PURE__ */ new Map();
15222
+ /** A token per live binding prevents an in-flight handler from borrowing a dropped/rebound socket. */
15223
+ _bindingGenerationByConnection = /* @__PURE__ */ new Map();
14791
15224
  _keyedStreamsByClient = /* @__PURE__ */ new Map();
14792
15225
  _keyedCapWarned = /* @__PURE__ */ new Set();
14793
15226
  _maxKeyedStreams;
@@ -14796,7 +15229,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14796
15229
  _transportLabel;
14797
15230
  _pendingReports = /* @__PURE__ */ new Map();
14798
15231
  constructor(options) {
14799
- super(options.clientEnv ?? RuntimeCoordinate.unknown);
15232
+ super(RuntimeCoordinate.unknown);
14800
15233
  this._formatMessage = options.formatMessage;
14801
15234
  this._createFormatMessage = options.createFormatMessage;
14802
15235
  this._resolveCodec = options.resolveCodec;
@@ -14864,6 +15297,14 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14864
15297
  admitted.add(streamId);
14865
15298
  return true;
14866
15299
  }
15300
+ _setIncomingActionDataListener(runtime, listener) {
15301
+ runtime._assertActive();
15302
+ if (runtime.scope !== "instance") throw err_nice_action.fromId("invalid_server_runtime_scope", {
15303
+ runtime: runtime.coordinate.stringId,
15304
+ actualScope: runtime.scope
15305
+ });
15306
+ return super._setIncomingActionDataListener(runtime, listener);
15307
+ }
14867
15308
  /**
14868
15309
  * Log an inbound request (basic action/transport/origin facts) before it executes, stashing the returned
14869
15310
  * reporter by `cuid` so {@link _reportServed} can pair it with the result. Only requests are logged;
@@ -14942,7 +15383,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14942
15383
  /**
14943
15384
  * Register a frame protocol (M1 multiplex seam) on the wire acceptor: every connection can then
14944
15385
  * exchange the protocol's prefixed frames beside action frames (subject to the wire security
14945
- * gate, review A.6). Register before serving; protocols are advertised in the handshake welcome.
15386
+ * gate, the connection contract). Register before serving; protocols are advertised in the handshake welcome.
14946
15387
  */
14947
15388
  registerFrameProtocol(protocol) {
14948
15389
  this.wireAcceptor.registerProtocol(protocol);
@@ -14984,6 +15425,19 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14984
15425
  * encoded bytes the codec re-reads for the reliability slot.
14985
15426
  */
14986
15427
  _dispatchInbound(connection, wire, codec, frame, level) {
15428
+ if (wire.type === "request") {
15429
+ let bindingGeneration = this._bindingGenerationByConnection.get(connection);
15430
+ if (bindingGeneration == null) {
15431
+ bindingGeneration = {};
15432
+ this._bindingGenerationByConnection.set(connection, bindingGeneration);
15433
+ }
15434
+ this._receiverMetadataByWire.set(wire, {
15435
+ receiver: this,
15436
+ connection,
15437
+ bindingGeneration,
15438
+ securityLevel: level
15439
+ });
15440
+ }
14987
15441
  const reliability = wire.type === "request" ? codec.incomingReliability?.(frame) : void 0;
14988
15442
  const bytes = this._logger != null ? wireFrameByteSize(frame) : void 0;
14989
15443
  if (reliability?.seq != null) {
@@ -14991,25 +15445,26 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14991
15445
  return;
14992
15446
  }
14993
15447
  this._logRequestIn(connection, wire, level, void 0, bytes);
14994
- this._emitIncoming(wire);
15448
+ this._emitIncomingFromReceiver(wire);
14995
15449
  }
14996
15450
  /** Ordered/dedup dispatch of one reliable request via the inbox (see {@link _dispatchInbound}). */
14997
15451
  _dispatchReliableRequest(connection, wire, seq, level, streamKey, bytes) {
14998
15452
  const client = this.wireAcceptor.clientForConnection(connection);
14999
15453
  if (client == null) {
15000
15454
  this._logRequestIn(connection, wire, level, void 0, bytes);
15001
- this._emitIncoming(wire);
15455
+ this._emitIncomingFromReceiver(wire);
15002
15456
  return;
15003
15457
  }
15004
15458
  const streamId = reliableStreamId(client, wire.domain, wire.id, streamKey);
15005
15459
  if (streamKey != null && !this._admitKeyedStream(client, streamId)) {
15006
15460
  this._logRequestIn(connection, wire, level, void 0, bytes);
15007
- this._emitIncoming(wire);
15461
+ this._emitIncomingFromReceiver(wire);
15008
15462
  return;
15009
15463
  }
15010
15464
  const receiver = this._receiverForWire(wire);
15011
15465
  const { deliver, duplicate, needsResync } = receiver.receive(streamId, seq, wire);
15012
15466
  if (needsResync) {
15467
+ this._forgetReliableReceiverMetadata(streamId, seq);
15013
15468
  if (!this._resyncRequested.has(streamId)) {
15014
15469
  this._resyncRequested.add(streamId);
15015
15470
  this._sendControl(connection, streamKey == null ? {
@@ -15033,8 +15488,12 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15033
15488
  ack,
15034
15489
  redelivered: duplicate
15035
15490
  };
15491
+ if (!duplicate && deliver.length === 0 && ack != null && seq > ack && seq - ack <= 1024) {
15492
+ const arrival = this._receiverMetadataByWire.get(wire);
15493
+ if (arrival != null) this._rememberReliableReceiverMetadata(streamId, seq, arrival);
15494
+ }
15036
15495
  if (this._runtime?.responseModeForWire(wire) === "none") {
15037
- this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey);
15496
+ this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes, this._receiverMetadataByWire.get(wire), streamId);
15038
15497
  this._sendControl(connection, streamKey == null ? {
15039
15498
  $c: "rack",
15040
15499
  domain: wire.domain,
@@ -15049,17 +15508,20 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15049
15508
  });
15050
15509
  return;
15051
15510
  }
15052
- if (streamKey != null) {
15053
- this._stashReplyStreamKey(wire.context.cuid, streamKey);
15054
- for (const delivered of deliver) if (delivered !== wire) this._stashReplyStreamKey(delivered.context.cuid, streamKey);
15055
- }
15056
15511
  if (duplicate) {
15057
- this._stampHandledReliability(wire, seq, streamKey, true);
15058
15512
  this._logRequestIn(connection, wire, level, receivedReliability, bytes);
15059
- this._emitIncoming(wire);
15513
+ this._emitIncomingFromReceiver(wire, streamKey == null ? {
15514
+ seq,
15515
+ redelivered: true
15516
+ } : {
15517
+ seq,
15518
+ streamKey,
15519
+ redelivered: true
15520
+ });
15521
+ this._forgetReliableReceiverMetadata(streamId, seq);
15060
15522
  return;
15061
15523
  }
15062
- this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes);
15524
+ this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes, this._receiverMetadataByWire.get(wire), streamId);
15063
15525
  }
15064
15526
  /**
15065
15527
  * Stamp the receiver-side reliability facts onto a delivered frame's **local** context (the
@@ -15067,15 +15529,16 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15067
15529
  * — the free idempotency key. Local-only: `toJsonObject()` never writes the field, so a reply built off
15068
15530
  * this context is byte-identical with and without the stamp.
15069
15531
  */
15070
- _stampHandledReliability(wire, seq, streamKey, redelivered) {
15071
- wire.context.reliability = streamKey == null ? {
15072
- seq,
15073
- redelivered
15074
- } : {
15075
- seq,
15076
- streamKey,
15077
- redelivered
15078
- };
15532
+ _emitIncomingFromReceiver(wire, reliability, arrivalOverride) {
15533
+ const arrival = arrivalOverride ?? this._receiverMetadataByWire.get(wire);
15534
+ this._receiverMetadataByWire.delete(wire);
15535
+ this._emitIncoming(wire, {
15536
+ receiver: this,
15537
+ connection: arrival?.connection,
15538
+ bindingGeneration: arrival?.bindingGeneration,
15539
+ securityLevel: arrival?.securityLevel,
15540
+ reliability
15541
+ });
15079
15542
  }
15080
15543
  /**
15081
15544
  * Log + emit each frame the receiver decided to deliver in this receive. Only the **first** (the frame
@@ -15084,12 +15547,23 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15084
15547
  * frame is stamped with its **own** seq for the executing handler, though — delivered frames are a
15085
15548
  * contiguous run ending at the new high-water (`ack`), so frame `i` carries `ack - (length - 1 - i)`.
15086
15549
  */
15087
- _emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes) {
15550
+ _emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes, receivedArrival, streamId) {
15088
15551
  const ack = receivedReliability.ack;
15089
15552
  deliver.forEach((delivered, index) => {
15090
- if (ack != null) this._stampHandledReliability(delivered, ack - (deliver.length - 1 - index), streamKey, false);
15553
+ const deliveredSeq = ack != null ? ack - (deliver.length - 1 - index) : void 0;
15554
+ const arrivalOverride = deliveredSeq != null && deliveredSeq === receivedReliability.seq ? receivedArrival : deliveredSeq != null && streamId != null ? this._takeReliableReceiverMetadata(streamId, deliveredSeq) : void 0;
15091
15555
  this._logRequestIn(connection, delivered, level, index === 0 ? receivedReliability : void 0, index === 0 ? bytes : void 0);
15092
- this._emitIncoming(delivered);
15556
+ if (ack != null) {
15557
+ const reliability = streamKey == null ? {
15558
+ seq: ack - (deliver.length - 1 - index),
15559
+ redelivered: false
15560
+ } : {
15561
+ seq: ack - (deliver.length - 1 - index),
15562
+ streamKey,
15563
+ redelivered: false
15564
+ };
15565
+ this._emitIncomingFromReceiver(delivered, reliability, arrivalOverride);
15566
+ } else this._emitIncomingFromReceiver(delivered, void 0, arrivalOverride);
15093
15567
  });
15094
15568
  }
15095
15569
  /**
@@ -15123,6 +15597,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15123
15597
  this._inbox.forget(streamId);
15124
15598
  this._resyncRequested.delete(streamId);
15125
15599
  if (message.k != null) this._keyedStreamsByClient.get(client.stringId)?.delete(streamId);
15600
+ this._receiverMetadataByReliableStream.delete(streamId);
15126
15601
  return;
15127
15602
  }
15128
15603
  if (message.$c !== "rskip") return;
@@ -15131,8 +15606,9 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15131
15606
  const streamId = reliableStreamId(client, message.domain, message.id, message.k);
15132
15607
  if (message.k != null && !this._admitKeyedStream(client, streamId)) return;
15133
15608
  const { deliver, ack } = this._receiverForRoute(message.domain, message.id).skipTo(streamId, message.seq);
15609
+ this._forgetReliableReceiverMetadataThrough(streamId, message.seq);
15134
15610
  this._resyncRequested.delete(streamId);
15135
- this._emitReliableDelivered(connection, deliver, this.wireAcceptor.levelFor(connection), { ack });
15611
+ this._emitReliableDelivered(connection, deliver, this.wireAcceptor.levelFor(connection), { ack }, message.k, void 0, void 0, streamId);
15136
15612
  this._sendControl(connection, message.k == null ? {
15137
15613
  $c: "rack",
15138
15614
  domain: message.domain,
@@ -15146,19 +15622,29 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15146
15622
  k: message.k
15147
15623
  });
15148
15624
  }
15149
- /** How long a stashed reply streamKey survives without its reply being sent (sweep bound). */
15150
- static _REPLY_STREAMKEY_TTL_MS = 5 * 6e4;
15151
- /** Remember a dispatched keyed reply-carrying request's streamKey until its reply goes out. */
15152
- _stashReplyStreamKey(cuid, streamKey) {
15153
- const now = Date.now();
15154
- for (const [key, entry] of this._replyStreamKeys) {
15155
- if (now - entry.time <= ChannelAcceptor._REPLY_STREAMKEY_TTL_MS) break;
15156
- this._replyStreamKeys.delete(key);
15157
- }
15158
- this._replyStreamKeys.set(cuid, {
15159
- streamKey,
15160
- time: now
15161
- });
15625
+ _rememberReliableReceiverMetadata(streamId, seq, metadata) {
15626
+ let bySeq = this._receiverMetadataByReliableStream.get(streamId);
15627
+ if (bySeq == null) {
15628
+ bySeq = /* @__PURE__ */ new Map();
15629
+ this._receiverMetadataByReliableStream.set(streamId, bySeq);
15630
+ }
15631
+ if (!bySeq.has(seq)) bySeq.set(seq, metadata);
15632
+ }
15633
+ _takeReliableReceiverMetadata(streamId, seq) {
15634
+ const bySeq = this._receiverMetadataByReliableStream.get(streamId);
15635
+ const metadata = bySeq?.get(seq);
15636
+ bySeq?.delete(seq);
15637
+ if (bySeq?.size === 0) this._receiverMetadataByReliableStream.delete(streamId);
15638
+ return metadata;
15639
+ }
15640
+ _forgetReliableReceiverMetadata(streamId, seq) {
15641
+ this._takeReliableReceiverMetadata(streamId, seq);
15642
+ }
15643
+ _forgetReliableReceiverMetadataThrough(streamId, through) {
15644
+ const bySeq = this._receiverMetadataByReliableStream.get(streamId);
15645
+ if (bySeq == null) return;
15646
+ for (const seq of bySeq.keys()) if (seq <= through) bySeq.delete(seq);
15647
+ if (bySeq.size === 0) this._receiverMetadataByReliableStream.delete(streamId);
15162
15648
  }
15163
15649
  /** Encode + send a transport {@link TControlMessage} to a connection (through its secure session if any). */
15164
15650
  _sendControl(connection, message) {
@@ -15173,7 +15659,10 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15173
15659
  _resolveRequestIdentity(connection, wire) {
15174
15660
  const wireOrigin = wire.context.originClient;
15175
15661
  if (wireOrigin != null && wireOrigin.envId !== "_unset_") {
15176
- this.wireAcceptor.bindPlainConnection(connection, new RuntimeCoordinate(wireOrigin));
15662
+ const client = new RuntimeCoordinate(wireOrigin);
15663
+ const previous = this.wireAcceptor.clientForConnection(connection);
15664
+ if (previous != null && previous.stringId !== client.stringId) this._bindingGenerationByConnection.delete(connection);
15665
+ this.wireAcceptor.bindPlainConnection(connection, client);
15177
15666
  return;
15178
15667
  }
15179
15668
  const bound = this.wireAcceptor.clientForConnection(connection);
@@ -15192,13 +15681,13 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15192
15681
  toJsonObject() {
15193
15682
  return {
15194
15683
  type: this.handlerType,
15195
- client: this.peerClient
15684
+ client: this.peer
15196
15685
  };
15197
15686
  }
15198
15687
  toHandlerRouteItem() {
15199
15688
  return {
15200
15689
  type: this.handlerType,
15201
- client: this.peerClient,
15690
+ client: this.peer,
15202
15691
  transShape: "duplex",
15203
15692
  transOrd: 0
15204
15693
  };
@@ -15220,6 +15709,16 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15220
15709
  this._connEncoding.delete(connection);
15221
15710
  this._codecByConn.delete(connection);
15222
15711
  this._connTags.delete(connection);
15712
+ this._bindingGenerationByConnection.delete(connection);
15713
+ for (const bySeq of this._receiverMetadataByReliableStream.values()) for (const metadata of bySeq.values()) {
15714
+ if (metadata.connection !== connection) continue;
15715
+ metadata.connection = void 0;
15716
+ metadata.bindingGeneration = void 0;
15717
+ }
15718
+ }
15719
+ _liveArrivalConnection(metadata) {
15720
+ const connection = metadata.connection;
15721
+ return metadata.receiver === this && connection != null && metadata.bindingGeneration != null && this._bindingGenerationByConnection.get(connection) === metadata.bindingGeneration && this.wireAcceptor.hasConnection(connection) ? connection : void 0;
15223
15722
  }
15224
15723
  /** Live connection for a client coordinate, if currently registered. */
15225
15724
  getConnectionForClient(client) {
@@ -15273,8 +15772,11 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15273
15772
  if (!ownedIds.has(id)) continue;
15274
15773
  const caseFn = cases[id];
15275
15774
  if (caseFn == null) continue;
15276
- wrapped[id] = (request) => {
15277
- return caseFn(request, mapContext(this.getConnectionForClient(request.context.originClient), request));
15775
+ wrapped[id] = (request, execution) => {
15776
+ const metadata = request.context._getReceiverMetadata();
15777
+ const connection = metadata == null ? void 0 : this._liveArrivalConnection(metadata);
15778
+ const isConnectionLive = () => connection != null && this._bindingGenerationByConnection.get(connection) === metadata?.bindingGeneration && this.wireAcceptor.hasConnection(connection);
15779
+ return caseFn(request, mapContext(connection, request, isConnectionLive, execution));
15278
15780
  };
15279
15781
  }
15280
15782
  handler.forDomainActionCases(domain, wrapped);
@@ -15303,7 +15805,8 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15303
15805
  }
15304
15806
  }
15305
15807
  async sendReturnPayload(payload, config) {
15306
- const connection = this.wireAcceptor.connectionForClient(payload.context.originClient.stringId);
15808
+ const arrival = payload.context._getReceiverMetadata();
15809
+ const connection = arrival?.receiver === this ? this._liveArrivalConnection(arrival) : this.wireAcceptor.connectionForClient(payload.context.originClient.stringId);
15307
15810
  if (connection == null) return false;
15308
15811
  const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate);
15309
15812
  this._reportServed(payload, bytes);
@@ -15366,9 +15869,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15366
15869
  const encoding = this._connEncoding.get(connection) ?? "binary";
15367
15870
  let rel = reliability;
15368
15871
  if (rel == null && payload.type === "result") {
15369
- const stashedKey = this._replyStreamKeys.get(payload.context.cuid);
15370
- if (stashedKey != null) this._replyStreamKeys.delete(payload.context.cuid);
15371
- const streamKey = stashedKey?.streamKey;
15872
+ const streamKey = payload.context.reliability?.streamKey;
15372
15873
  const streamId = reliableStreamId(payload.context.originClient, payload.domain, payload.id, streamKey);
15373
15874
  const receiver = this._persistedReceiver?.hasStream(streamId) ? this._persistedReceiver : this._inbox.hasStream(streamId) ? this._inbox : void 0;
15374
15875
  if (receiver != null) {
@@ -15386,7 +15887,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15386
15887
  const frame = encoding === "json" ? JSON.stringify(payload.toJsonObject()) : this._codecFor(connection).outgoing({
15387
15888
  action: payload,
15388
15889
  localClient,
15389
- externalClient: this.peerClient,
15890
+ externalClient: this.peer,
15390
15891
  reliability: rel
15391
15892
  });
15392
15893
  this.wireAcceptor.sendTo(connection, frame);
@@ -15428,6 +15929,11 @@ const DEFAULT_SERVER_SECURITY_LEVELS$1 = [
15428
15929
  * {@link createHibernatableWsServerAdapter} to wire persistence + replay.
15429
15930
  */
15430
15931
  function createSecureChannelAcceptor(options) {
15932
+ options.runtime._assertActive();
15933
+ if (options.runtime.scope !== "instance") throw err_nice_action.fromId("invalid_server_runtime_scope", {
15934
+ runtime: options.runtime.coordinate.stringId,
15935
+ actualScope: options.runtime.scope
15936
+ });
15431
15937
  const link = options.link ?? new ClientCryptoKeyLink({ storageAdapter: options.storage });
15432
15938
  const resolveChannel = options.resolveChannel;
15433
15939
  const baseSecurity = {
@@ -15437,7 +15943,6 @@ function createSecureChannelAcceptor(options) {
15437
15943
  verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(options.storage)
15438
15944
  };
15439
15945
  const baseOptions = {
15440
- clientEnv: options.clientEnv,
15441
15946
  send: options.send,
15442
15947
  runtime: options.runtime,
15443
15948
  defaultTimeout: options.defaultTimeout,
@@ -15466,6 +15971,14 @@ function createSecureChannelAcceptor(options) {
15466
15971
  }
15467
15972
  //#endregion
15468
15973
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/Carrier.types.ts
15974
+ /** Convert action routing data into wire's generic carrier dial shape. */
15975
+ function toActionDialParams(input) {
15976
+ return {
15977
+ localClient: input.localClient,
15978
+ externalClient: input.externalClient,
15979
+ dialContext: input
15980
+ };
15981
+ }
15469
15982
  /**
15470
15983
  * Narrow a carrier source to the exchange shape via its `shape` discriminant — the one branch the
15471
15984
  * internal `transport()` factory uses to pick the duplex vs exchange transport. A duplex source carries
@@ -15840,7 +16353,7 @@ async function runExchange(session, inputs) {
15840
16353
  //#region ../nice-action/src/ActionRuntime/Transport/TransportConnection.ts
15841
16354
  /**
15842
16355
  * Live, per-handler transport runtime built from a reusable {@link Transport} definition — the
15843
- * action instantiation of wire's generic `TransportConnection` (shared-base-connect plan,
16356
+ * action instantiation of wire's generic `TransportConnection` (shared connection design,
15844
16357
  * Phase 2): routing params pinned to {@link ITransportRouteActionParams} and the finalized
15845
16358
  * methods to {@link IActionTransportReadyData_Methods}. The machinery (status processing, cache
15846
16359
  * keys, async bring-up hooks) lives in wire; subclasses (`LinkConnection`, `ExchangeConnection`)
@@ -15862,7 +16375,7 @@ var ExchangeConnection = class extends TransportConnection {
15862
16375
  });
15863
16376
  }
15864
16377
  _getCacheKey(input) {
15865
- return this.initialized.getTransportCacheKey?.(input).join("\0") ?? "";
16378
+ return this.initialized.getCacheKey?.(input).join("\0") ?? "";
15866
16379
  }
15867
16380
  _needsAsyncBringUp(data) {
15868
16381
  return data.secureChannel != null && data.secureChannel.securityLevel !== "none";
@@ -15907,7 +16420,7 @@ var ExchangeTransport = class ExchangeTransport extends Transport {
15907
16420
  _createConnection(_ctx) {
15908
16421
  const options = this.options;
15909
16422
  return new ExchangeConnection({ initialize: () => ({
15910
- getTransportCacheKey: options.getTransportCacheKey,
16423
+ getCacheKey: options.getCacheKey,
15911
16424
  isAvailable: options.available,
15912
16425
  getTransport: (input) => {
15913
16426
  assertProtocolsRideDuplex(options);
@@ -15965,7 +16478,7 @@ function finalizePlainLinkMethods(ctx) {
15965
16478
  return buildSendMethods(ctx, establishPlainDuplexSession({
15966
16479
  channel: ctx.channel,
15967
16480
  lane: connectorLaneEndpoint(ctx, abortSet),
15968
- keepalive: ctx.linkKeepalive,
16481
+ heartbeat: ctx.heartbeat,
15969
16482
  tap: ctx.wireTap
15970
16483
  }), abortSet);
15971
16484
  }
@@ -15990,7 +16503,7 @@ async function finalizeSecureLinkMethods(ctx) {
15990
16503
  secure: ctx.secure,
15991
16504
  lane,
15992
16505
  mux: ctx.secure.mux,
15993
- keepalive: ctx.linkKeepalive,
16506
+ heartbeat: ctx.heartbeat,
15994
16507
  tap: ctx.wireTap
15995
16508
  });
15996
16509
  return buildSendMethods(ctx, session, abortSet, session.remoteCaps?.includes("reliable") ?? false, session.remoteCaps?.includes("reliable-streamkey") ?? false);
@@ -16093,7 +16606,7 @@ var LinkConnection = class extends TransportConnection {
16093
16606
  this.resolvers = resolvers ?? createUnsetTransportResolvers("link");
16094
16607
  }
16095
16608
  _getCacheKey(input) {
16096
- return this.initialized.getTransportCacheKey?.(input).join("\0") ?? "";
16609
+ return this.initialized.getCacheKey?.(input).join("\0") ?? "";
16097
16610
  }
16098
16611
  _needsAsyncBringUp() {
16099
16612
  return true;
@@ -16116,7 +16629,7 @@ var LinkConnection = class extends TransportConnection {
16116
16629
  formatMessage: data.formatMessage,
16117
16630
  updateRunConfig: data.updateRunConfig,
16118
16631
  makeDisconnectError: linkDisconnectError,
16119
- linkKeepalive: data.linkKeepalive,
16632
+ heartbeat: data.heartbeat,
16120
16633
  wireTap: data.wireTap
16121
16634
  };
16122
16635
  }
@@ -16145,7 +16658,7 @@ var LinkTransport = class LinkTransport extends Transport {
16145
16658
  _createConnection(ctx) {
16146
16659
  const options = this.options;
16147
16660
  return new LinkConnection({ initialize: () => ({
16148
- getTransportCacheKey: options.getTransportCacheKey,
16661
+ getCacheKey: options.getCacheKey,
16149
16662
  isAvailable: options.available,
16150
16663
  getTransport: (input) => ({
16151
16664
  status: "ready",
@@ -16154,7 +16667,7 @@ var LinkTransport = class LinkTransport extends Transport {
16154
16667
  formatMessage: options.createFormatMessage?.() ?? options.formatMessage,
16155
16668
  updateRunConfig: options.updateRunConfig,
16156
16669
  secureChannel: options.security,
16157
- linkKeepalive: options.linkKeepalive?.(),
16670
+ heartbeat: options.heartbeat?.(),
16158
16671
  wireTap: options.wireTap
16159
16672
  }
16160
16673
  })
@@ -16173,6 +16686,8 @@ var LinkTransport = class LinkTransport extends Transport {
16173
16686
  function transport(options) {
16174
16687
  const { carrier, channel, available, label } = options;
16175
16688
  const labelFor = label ?? carrier.carrierLabel;
16689
+ const carrierGetCacheKey = carrier.getCacheKey;
16690
+ const carrierGetRouteInfo = carrier.getRouteInfo;
16176
16691
  let security;
16177
16692
  if (options.secure) {
16178
16693
  const link = options.link ?? (options.storage != null ? new ClientCryptoKeyLink({ storageAdapter: options.storage }) : void 0);
@@ -16181,16 +16696,17 @@ function transport(options) {
16181
16696
  securityLevel: options.securityLevel ?? "authenticated",
16182
16697
  link,
16183
16698
  localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),
16699
+ expectedPeer: options.expectedPeer?.toJsonObject(),
16184
16700
  dictionaryVersion: channel.dictionaryVersion,
16185
16701
  channelTags: channel.tags,
16186
16702
  mux: options.mux
16187
16703
  };
16188
16704
  }
16189
16705
  if (isExchangeCarrierSource(carrier)) return ExchangeTransport.create({
16190
- openCarrier: carrier.open,
16191
- getTransportCacheKey: carrier.getCacheKey,
16192
- available,
16193
- getRouteInfo: carrier.getRouteInfo,
16706
+ openCarrier: (input) => carrier.open(toActionDialParams(input)),
16707
+ getCacheKey: carrierGetCacheKey == null ? void 0 : (input) => carrierGetCacheKey(toActionDialParams(input)),
16708
+ available: available ?? carrier.available,
16709
+ getRouteInfo: carrierGetRouteInfo == null ? void 0 : (input) => carrierGetRouteInfo(toActionDialParams(input)),
16194
16710
  label: labelFor,
16195
16711
  security,
16196
16712
  mux: options.mux,
@@ -16198,14 +16714,14 @@ function transport(options) {
16198
16714
  wireTap: options.wireTap
16199
16715
  });
16200
16716
  return LinkTransport.create({
16201
- openChannel: carrier.open,
16717
+ openChannel: (input) => carrier.open(toActionDialParams(input)),
16202
16718
  createFormatMessage: channel.createCodec,
16203
- getTransportCacheKey: carrier.getCacheKey,
16204
- available,
16205
- getRouteInfo: carrier.getRouteInfo,
16719
+ getCacheKey: carrierGetCacheKey == null ? void 0 : (input) => carrierGetCacheKey(toActionDialParams(input)),
16720
+ available: available ?? carrier.available,
16721
+ getRouteInfo: carrierGetRouteInfo == null ? void 0 : (input) => carrierGetRouteInfo(toActionDialParams(input)),
16206
16722
  label: labelFor,
16207
16723
  security,
16208
- linkKeepalive: options.linkKeepalive,
16724
+ heartbeat: options.heartbeat,
16209
16725
  wireTap: options.wireTap
16210
16726
  });
16211
16727
  }
@@ -16295,24 +16811,32 @@ function warnOnSharedConnectionIdentity(runtime, peer, identity) {
16295
16811
  * the single source of truth for *what* is routed (`toAcceptor` domains forwarded to the peer,
16296
16812
  * `toConnector` pushes handled locally from `onPush`); the call binds the shared facts — the channel's
16297
16813
  * codec/dictionary version, the runtime, and one crypto identity (a {@link ClientCryptoKeyLink} over
16298
- * `storage`) — into every transport in `transports`, so none of them restate the channel or runtime.
16299
- * List several transports to make the path transport-agnostic (secure WS preferred, HTTP fallback):
16814
+ * `storage`) — into every carrier. List carriers in preference order (secure WS preferred, plain HTTP
16815
+ * fallback):
16300
16816
  * ```ts
16301
16817
  * const connector = connectChannel(runtime, lobbyChannel, {
16302
16818
  * peer: runtime_coordinate_lobby_do,
16303
16819
  * storage,
16304
- * transports: [{ carrier: wsCarrier(() => ({ url })) }, { carrier: httpCarrier(...), secure: false }],
16820
+ * carriers: [wsCarrier(url), httpCarrier(httpUrl, { secure: false })],
16305
16821
  * onPush: { player_joined: (p) => { … } },
16306
16822
  * });
16307
16823
  * ```
16308
16824
  * Returns the {@link ChannelConnector} so the caller can later `clearTransportCache()` it.
16309
16825
  */
16310
16826
  function connectChannel(runtime, channel, options) {
16827
+ 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`" });
16828
+ const transports = options.carriers?.map((carrier) => ({
16829
+ carrier,
16830
+ secure: carrier.secure,
16831
+ securityLevel: carrier.securityLevel,
16832
+ available: carrier.available,
16833
+ label: carrier.label
16834
+ })) ?? options.transports;
16311
16835
  const securityLevel = options.securityLevel ?? "authenticated";
16312
- const anySecure = options.transports.some((transport) => transport.secure ?? true);
16836
+ const anySecure = transports.some((transport) => transport.secure ?? true);
16313
16837
  const connectionIdentity = options.connectionId != null ? runtime.coordinate.withConnectionId(options.connectionId) : void 0;
16314
- if (options.transports.some((descriptor) => !isExchangeCarrierSource(descriptor.carrier))) warnOnSharedConnectionIdentity(runtime, options.peer, connectionIdentity ?? runtime.coordinate);
16315
- const { mux: wireMux, link, resolveLinkKeepalive, wireTap } = assembleWireConnectionParts({
16838
+ if (transports.some((descriptor) => !isExchangeCarrierSource(descriptor.carrier))) warnOnSharedConnectionIdentity(runtime, options.peer, connectionIdentity ?? runtime.coordinate);
16839
+ const { mux: wireMux, link, resolveHeartbeat, wireTap } = assembleWireConnectionParts({
16316
16840
  callerName: "connectChannel",
16317
16841
  peer: options.peer,
16318
16842
  identity: connectionIdentity ?? runtime.coordinate,
@@ -16322,16 +16846,19 @@ function connectChannel(runtime, channel, options) {
16322
16846
  storage: options.storage,
16323
16847
  link: options.link,
16324
16848
  ephemeralIdentity: options.ephemeralIdentity,
16849
+ reconnect: options.reconnect,
16850
+ heartbeat: options.heartbeat,
16325
16851
  keepLinkAlive: options.keepLinkAlive,
16326
16852
  linkKeepalive: options.linkKeepalive,
16327
16853
  wireTap: options.wireTap
16328
16854
  });
16329
- const exchangeOnlyConnection = options.transports.every((descriptor) => isExchangeCarrierSource(descriptor.carrier));
16330
- const transports = options.transports.map((descriptor) => transport({
16855
+ const exchangeOnlyConnection = transports.every((descriptor) => isExchangeCarrierSource(descriptor.carrier));
16856
+ const builtTransports = transports.map((descriptor) => transport({
16331
16857
  carrier: descriptor.carrier,
16332
16858
  channel,
16333
16859
  runtime,
16334
16860
  identity: connectionIdentity,
16861
+ expectedPeer: options.peer,
16335
16862
  secure: descriptor.secure ?? true,
16336
16863
  link,
16337
16864
  securityLevel: descriptor.securityLevel ?? securityLevel,
@@ -16339,21 +16866,21 @@ function connectChannel(runtime, channel, options) {
16339
16866
  label: descriptor.label,
16340
16867
  mux: wireMux,
16341
16868
  exchangeOnlyConnection,
16342
- linkKeepalive: resolveLinkKeepalive,
16869
+ heartbeat: resolveHeartbeat,
16343
16870
  wireTap
16344
16871
  }));
16345
16872
  const pushHandlers = options.onPush != null ? channel.toConnectorDomains.map((domain) => domain.wrapAsPartialLocalHandler(options.onPush)) : [];
16346
- const duplexSecurityLevels = options.transports.filter((descriptor) => !isExchangeCarrierSource(descriptor.carrier)).map((descriptor) => descriptor.secure ?? true ? descriptor.securityLevel ?? securityLevel : "none");
16873
+ const duplexSecurityLevels = transports.filter((descriptor) => !isExchangeCarrierSource(descriptor.carrier)).map((descriptor) => descriptor.secure ?? true ? descriptor.securityLevel ?? securityLevel : "none");
16347
16874
  const connectionSecurityLevel = duplexSecurityLevels.length === 0 ? "none" : duplexSecurityLevels.reduce((floor, level) => securityLevelMeets(level, floor) ? floor : level);
16348
16875
  const handler = runtime.connectTo(options.peer, {
16349
- transports,
16876
+ transports: builtTransports,
16350
16877
  domains: [...channel.toAcceptorDomains],
16351
16878
  localHandlers: pushHandlers,
16352
16879
  defaultTimeout: options.defaultTimeout,
16353
16880
  reliableActionTimeout: options.reliableActionTimeout,
16354
16881
  wireMux,
16355
16882
  securityLevel: connectionSecurityLevel,
16356
- keepLinkAlive: options.keepLinkAlive,
16883
+ reconnect: options.reconnect ?? options.keepLinkAlive,
16357
16884
  connectionIdentity
16358
16885
  });
16359
16886
  if (options.onReliableEvent != null) handler.addReliableEventListener(options.onReliableEvent);
@@ -16392,7 +16919,8 @@ function combineChannels(channels) {
16392
16919
  * dictionary version, the `security` block from the runtime coordinate) but takes the `(runtime, channel,
16393
16920
  * options)` shape of the channel family. Pair it with {@link acceptChannelConnections} for execution:
16394
16921
  * ```ts
16395
- * const acceptor = acceptChannel(runtime, gameChannel, { clientEnv, storage, send });
16922
+ * const runtime = new ActionRuntime(serverCoordinate, { scope: "instance" });
16923
+ * const acceptor = acceptChannel(runtime, gameChannel, { storage, send });
16396
16924
  * runtime.addHandlers([acceptChannelConnections(acceptor, gameChannel, { … }), acceptor]);
16397
16925
  * ```
16398
16926
  */
@@ -16406,7 +16934,7 @@ function acceptChannel(runtime, channel, options) {
16406
16934
  //#endregion
16407
16935
  //#region ../nice-action/src/ActionRuntime/Transport/SecureSession/exchangeAcceptor.ts
16408
16936
  /**
16409
- * The action lane over wire's {@link WireExchangeAcceptor} (shared-base-connect plan, Phase 6) —
16937
+ * The action lane over wire's {@link WireExchangeAcceptor} —
16410
16938
  * the HTTP counterpart to `ChannelAcceptor` composing on `WireAcceptor`. Wire owns the exchange
16411
16939
  * mechanics: the envelope, the server handshake over the two `hs` POSTs, the sealed `hsc`/`t`
16412
16940
  * tokens that make the whole endpoint **stateless** across isolates, and the per-session frame
@@ -16461,7 +16989,10 @@ var ExchangeAcceptor = class {
16461
16989
  origin: client?.stringId
16462
16990
  })) : void 0;
16463
16991
  const startedAt = Date.now();
16464
- const result = await (await this._runtime.handleActionPayloadWire(wire)).waitForResultPayload();
16992
+ const result = await (await this._runtime._handleActionPayloadWireFromReceiver(wire, {
16993
+ receiver: this,
16994
+ securityLevel: request.securityLevel
16995
+ })).waitForResultPayload();
16465
16996
  const resultWire = result.toJsonObject();
16466
16997
  if (report != null) {
16467
16998
  const returnedVia = request.encrypted ? `${this._transportLabel} (encrypted)` : this._transportLabel;
@@ -16571,7 +17102,10 @@ function createActionFetchHandler(runtime, options = {}) {
16571
17102
  const startedAt = Date.now();
16572
17103
  let running;
16573
17104
  try {
16574
- running = await runtime.handleActionPayloadWire(body);
17105
+ running = await runtime._handleActionPayloadWireFromReceiver(body, {
17106
+ receiver: runtime,
17107
+ securityLevel: "none"
17108
+ });
16575
17109
  } catch (error) {
16576
17110
  if (error instanceof NiceError && error.getIds().some((id) => id === "wire_not_action_data" || id === "wire_action_not_payload")) {
16577
17111
  report?.({
@@ -16745,64 +17279,6 @@ function createHibernatableWsServerAdapter(options) {
16745
17279
  //#endregion
16746
17280
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/AcceptorCarrier.types.ts
16747
17281
  /**
16748
- * Build the inert lifecycle slot a duplex carrier factory spreads into its handle: `receive`/`drop` throw
16749
- * (or no-op) until `serveChannel` calls `_activate` with the carrier's live router. Shared by every duplex
16750
- * carrier factory (`wsAcceptorCarrier`, a WebRTC carrier, the Cloudflare DO helper, …) so the
16751
- * stateful-handle wiring lives in exactly one place.
16752
- */
16753
- function createDuplexCarrierLifecycle(limits) {
16754
- let router;
16755
- let disposed = false;
16756
- const windows = /* @__PURE__ */ new Map();
16757
- const maxFrameBytes = limits?.maxFrameBytes;
16758
- const rate = limits?.rate;
16759
- if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
16760
- if (rate != null && (!Number.isSafeInteger(rate.maxMessages) || rate.maxMessages <= 0 || !Number.isSafeInteger(rate.windowMs) || rate.windowMs <= 0)) throw new Error("inbound rate limits must be positive safe integers");
16761
- const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
16762
- return {
16763
- receive(connection, frame) {
16764
- if (disposed) return;
16765
- if (router == null) throw new Error("acceptor carrier not served yet — pass it to serveChannel() before feeding frames");
16766
- if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
16767
- limits?.onExceeded(connection, "frame_bytes");
16768
- return;
16769
- }
16770
- if (rate != null) {
16771
- const now = Date.now();
16772
- let window = windows.get(connection);
16773
- if (window == null || now - window.startedAt >= rate.windowMs) {
16774
- window = {
16775
- count: 0,
16776
- startedAt: now
16777
- };
16778
- windows.set(connection, window);
16779
- }
16780
- window.count++;
16781
- if (window.count > rate.maxMessages) {
16782
- limits?.onExceeded(connection, "message_rate");
16783
- return;
16784
- }
16785
- }
16786
- router.receive(connection, frame);
16787
- },
16788
- drop(connection) {
16789
- if (disposed) return;
16790
- windows.delete(connection);
16791
- router?.drop(connection);
16792
- },
16793
- _activate(liveRouter) {
16794
- if (disposed) throw new Error("acceptor carrier already disposed");
16795
- router = liveRouter;
16796
- },
16797
- _dispose() {
16798
- if (disposed) return;
16799
- disposed = true;
16800
- router = void 0;
16801
- windows.clear();
16802
- }
16803
- };
16804
- }
16805
- /**
16806
17282
  * Narrow an acceptor carrier to the exchange shape via its `shape` discriminant — the one branch
16807
17283
  * `serveChannel` uses to pick the duplex (push-capable) vs exchange (request/reply) wiring. A duplex
16808
17284
  * carrier carries `shape: ETransportShape.duplex`, so the `else` branch is the duplex one.
@@ -16847,212 +17323,220 @@ const DEFAULT_SERVER_SECURITY_LEVELS = [
16847
17323
  "authenticated",
16848
17324
  "encrypted"
16849
17325
  ];
16850
- function serveChannel(runtime, channel, options) {
16851
- const duplexCarriers = options.carriers.filter((carrier) => !isExchangeAcceptorCarrier(carrier));
16852
- const exchangeCarriers = options.carriers.filter(isExchangeAcceptorCarrier);
16853
- if (exchangeCarriers.length > 1) throw new Error("serveChannel: at most one exchange carrier is supported");
16854
- const exchangeCarrier = exchangeCarriers[0];
16855
- const singleDuplex = duplexCarriers.length === 1;
16856
- if (options.connectionState != null && !singleDuplex) throw new Error("serveChannel: `connectionState` requires exactly one duplex carrier");
16857
- if (options.channelCases != null && !singleDuplex) throw new Error("serveChannel: `channelCases` requires exactly one duplex carrier");
16858
- const exchangeSecure = exchangeCarrier != null && (exchangeCarrier.secure ?? true);
16859
- const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
16860
- const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
16861
- const registry = options.channels;
16862
- const resolveChannel = registry != null && registry.length > 1 ? buildChannelSubsetResolver(channel, registry) : void 0;
16863
- let secure;
16864
- if (anyDuplexSecure || exchangeSecure) {
16865
- const storage = options.storage;
16866
- if (storage == null) throw new Error("serveChannel: a secure carrier requires `storage`. Pass it, or set `secure: false` on the carrier for a plain endpoint.");
16867
- secure = {
16868
- storage,
16869
- link: options.link ?? new ClientCryptoKeyLink({ storageAdapter: storage }),
16870
- verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(storage)
16871
- };
16872
- }
16873
- const plainRouter = (handler) => ({
16874
- receive: (connection, frame) => handler.receive(connection, frame),
16875
- drop: (connection) => handler.drop(connection)
17326
+ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
17327
+ const modern = !(runtimeOrChannel instanceof ActionRuntime);
17328
+ const channel = modern ? runtimeOrChannel : channelOrOptions;
17329
+ const rawOptions = modern ? channelOrOptions : legacyOptions;
17330
+ if (rawOptions == null) throw err_nice_action.fromId("conflicting_server_options", { detail: "serveChannel requires server options" });
17331
+ const suppliedRuntime = modern ? rawOptions.runtime : runtimeOrChannel;
17332
+ const identity = modern ? rawOptions.identity : void 0;
17333
+ if (modern && suppliedRuntime == null === (identity == null)) throw err_nice_action.fromId("conflicting_server_options", { detail: "pass exactly one of `identity` or `runtime`" });
17334
+ if (!modern && rawOptions.identity != null) throw err_nice_action.fromId("conflicting_server_options", { detail: "the deprecated `serveChannel(runtime, channel, options)` form cannot take `identity` — use `serveChannel(channel, { identity, … })`" });
17335
+ const ownsRuntime = suppliedRuntime == null;
17336
+ const runtime = suppliedRuntime ?? new ActionRuntime(identity, { scope: "instance" });
17337
+ const { identity: _identity, runtime: _runtime, ...options } = rawOptions;
17338
+ runtime._assertActive();
17339
+ if (runtime.scope !== "instance") throw err_nice_action.fromId("invalid_server_runtime_scope", {
17340
+ runtime: runtime.coordinate.stringId,
17341
+ actualScope: runtime.scope
16876
17342
  });
16877
- const asObject = (value) => typeof value === "object" && value != null ? value : {};
16878
- const acceptors = [];
16879
- let connections;
16880
- for (const carrier of duplexCarriers) {
16881
- const handler = (carrier.secure ?? true) && secure != null ? acceptChannel(runtime, channel, {
16882
- clientEnv: options.clientEnv,
16883
- storage: secure.storage,
16884
- link: secure.link,
16885
- verifyKeyResolver: secure.verifyKeyResolver,
16886
- securityLevel,
16887
- send: carrier.send,
16888
- defaultTimeout: options.defaultTimeout,
16889
- resolveChannel,
16890
- logger: options.logger,
16891
- wireTap: options.wireTap,
16892
- transportLabel: carrier.carrierLabel,
16893
- persistedReceiver: options.reliableStore,
16894
- maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
16895
- }) : createChannelAcceptor({
16896
- clientEnv: options.clientEnv,
16897
- createFormatMessage: channel.createCodec,
16898
- send: carrier.send,
16899
- runtime,
16900
- defaultTimeout: options.defaultTimeout,
16901
- logger: options.logger,
16902
- wireTap: options.wireTap,
16903
- transportLabel: carrier.carrierLabel,
16904
- persistedReceiver: options.reliableStore,
16905
- maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
17343
+ try {
17344
+ const duplexCarriers = options.carriers.filter((carrier) => !isExchangeAcceptorCarrier(carrier));
17345
+ const exchangeCarriers = options.carriers.filter((carrier) => isExchangeAcceptorCarrier(carrier));
17346
+ if (exchangeCarriers.length > 1) throw new Error("serveChannel: at most one exchange carrier is supported");
17347
+ const exchangeCarrier = exchangeCarriers[0];
17348
+ const singleDuplex = duplexCarriers.length === 1;
17349
+ if (options.connectionState != null && !singleDuplex) throw new Error("serveChannel: `connectionState` requires exactly one duplex carrier");
17350
+ if (options.channelCases != null && !singleDuplex) throw new Error("serveChannel: `channelCases` requires exactly one duplex carrier");
17351
+ const exchangeSecure = exchangeCarrier != null && (exchangeCarrier.secure ?? true);
17352
+ const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
17353
+ const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
17354
+ const registry = options.channels;
17355
+ const resolveChannel = registry != null && registry.length > 1 ? buildChannelSubsetResolver(channel, registry) : void 0;
17356
+ let secure;
17357
+ if (anyDuplexSecure || exchangeSecure) {
17358
+ const storage = options.storage;
17359
+ if (storage == null) throw new Error("serveChannel: a secure carrier requires `storage`. Pass it, or set `secure: false` on the carrier for a plain endpoint.");
17360
+ secure = {
17361
+ storage,
17362
+ link: options.link ?? new ClientCryptoKeyLink({ storageAdapter: storage }),
17363
+ verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(storage)
17364
+ };
17365
+ }
17366
+ const plainRouter = (handler) => ({
17367
+ receive: (connection, frame) => handler.receive(connection, frame),
17368
+ drop: (connection) => handler.drop(connection)
16906
17369
  });
16907
- for (const protocol of options.protocols ?? []) handler.registerFrameProtocol(protocol);
16908
- const attach = carrier.attachmentStore;
16909
- let router;
16910
- if (attach == null) router = plainRouter(handler);
16911
- else if (options.connectionState != null) {
16912
- connections = createConnectionStateStore(handler, {
16913
- schema: options.connectionState.schema,
17370
+ const asObject = (value) => typeof value === "object" && value != null ? value : {};
17371
+ const acceptors = [];
17372
+ let connections;
17373
+ for (const carrier of duplexCarriers) {
17374
+ const handler = (carrier.secure ?? true) && secure != null ? acceptChannel(runtime, channel, {
17375
+ storage: secure.storage,
17376
+ link: secure.link,
17377
+ verifyKeyResolver: secure.verifyKeyResolver,
17378
+ securityLevel,
17379
+ send: carrier.send,
17380
+ defaultTimeout: options.defaultTimeout,
17381
+ resolveChannel,
17382
+ logger: options.logger,
17383
+ wireTap: options.wireTap,
17384
+ transportLabel: carrier.carrierLabel,
17385
+ persistedReceiver: options.reliableStore,
17386
+ maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
17387
+ }) : createChannelAcceptor({
17388
+ createFormatMessage: channel.createCodec,
17389
+ send: carrier.send,
17390
+ runtime,
17391
+ defaultTimeout: options.defaultTimeout,
17392
+ logger: options.logger,
17393
+ wireTap: options.wireTap,
17394
+ transportLabel: carrier.carrierLabel,
17395
+ persistedReceiver: options.reliableStore,
17396
+ maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
17397
+ });
17398
+ for (const protocol of options.protocols ?? []) handler.registerFrameProtocol(protocol);
17399
+ const attach = carrier.attachmentStore;
17400
+ let router;
17401
+ if (attach == null) router = plainRouter(handler);
17402
+ else if (options.connectionState != null) {
17403
+ connections = createConnectionStateStore(handler, {
17404
+ schema: options.connectionState.schema,
17405
+ getConnections: attach.getConnections,
17406
+ read: attach.read,
17407
+ write: attach.write
17408
+ });
17409
+ router = plainRouter(handler);
17410
+ } else router = createHibernatableWsServerAdapter({
17411
+ handler,
16914
17412
  getConnections: attach.getConnections,
16915
- read: attach.read,
16916
- write: attach.write
17413
+ getAttachment: (connection) => attach.read(connection)?.binding,
17414
+ setAttachment: (connection, binding) => attach.write(connection, {
17415
+ ...asObject(attach.read(connection)),
17416
+ binding
17417
+ })
16917
17418
  });
16918
- router = plainRouter(handler);
16919
- } else router = createHibernatableWsServerAdapter({
16920
- handler,
16921
- getConnections: attach.getConnections,
16922
- getAttachment: (connection) => attach.read(connection)?.binding,
16923
- setAttachment: (connection, binding) => attach.write(connection, {
16924
- ...asObject(attach.read(connection)),
16925
- binding
16926
- })
16927
- });
16928
- carrier._activate(router);
16929
- acceptors.push(handler);
16930
- }
16931
- runtime.addHandlers([...options.handlers ?? [], ...acceptors]);
16932
- const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
16933
- let disposed = false;
16934
- const receive = (connection, frame) => {
16935
- if (disposed) return;
16936
- if (soleDuplex == null) throw new Error(duplexCarriers.length === 0 ? "serveChannel: no duplex carrier to receive on (this server has no socket transport)" : "serveChannel: several duplex carriers — feed each carrier handle's receive() directly");
16937
- soleDuplex.receive(connection, frame);
16938
- };
16939
- const drop = (connection) => {
16940
- if (disposed) return;
16941
- soleDuplex?.drop(connection);
16942
- };
16943
- const pushToClient = (target, request, pushOptions) => {
16944
- if (disposed) throw new Error("serveChannel: server disposed");
16945
- const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
16946
- if (owner == null) throw err_nice_transport.fromId("not_found", { actionId: target instanceof RuntimeCoordinate ? target.stringId : "push-target-connection" });
16947
- return owner.pushToClient(runtime, target, request, pushOptions);
16948
- };
16949
- const broadcast = (makeRequest, broadcastOptions) => {
16950
- if (disposed) throw new Error("serveChannel: server disposed");
16951
- if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead");
16952
- acceptors[0].broadcast(makeRequest, {
16953
- runtime,
16954
- ...broadcastOptions
17419
+ carrier._activate(router);
17420
+ acceptors.push(handler);
17421
+ }
17422
+ const installedHandlers = [...options.handlers ?? [], ...acceptors];
17423
+ const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
17424
+ let disposed = false;
17425
+ const receive = (connection, frame) => {
17426
+ if (disposed) return;
17427
+ if (soleDuplex == null) throw new Error(duplexCarriers.length === 0 ? "serveChannel: no duplex carrier to receive on (this server has no socket transport)" : "serveChannel: several duplex carriers — feed each carrier handle's receive() directly");
17428
+ soleDuplex.receive(connection, frame);
17429
+ };
17430
+ const drop = (connection) => {
17431
+ if (disposed) return;
17432
+ soleDuplex?.drop(connection);
17433
+ };
17434
+ const pushToClient = (target, request, pushOptions) => {
17435
+ if (disposed) throw new Error("serveChannel: server disposed");
17436
+ const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
17437
+ if (owner == null) throw err_nice_transport.fromId("not_found", { actionId: target instanceof RuntimeCoordinate ? target.stringId : "push-target-connection" });
17438
+ return owner.pushToClient(runtime, target, request, pushOptions);
17439
+ };
17440
+ const broadcast = (makeRequest, broadcastOptions) => {
17441
+ if (disposed) throw new Error("serveChannel: server disposed");
17442
+ if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead");
17443
+ acceptors[0].broadcast(makeRequest, {
17444
+ runtime,
17445
+ ...broadcastOptions
17446
+ });
17447
+ };
17448
+ const makeConnectionContext = (connection, _request, isConnectionLive, execution) => ({
17449
+ ...execution,
17450
+ get connection() {
17451
+ return connection != null && isConnectionLive() ? connection : null;
17452
+ },
17453
+ get state() {
17454
+ return connection != null && isConnectionLive() && connections != null ? connections.get(connection) : null;
17455
+ },
17456
+ setState(value) {
17457
+ if (connection == null || !isConnectionLive()) throw err_nice_action.fromId("connection_required", { operation: "set connection state" });
17458
+ if (connections != null) connections.set(connection, value);
17459
+ },
17460
+ clearState() {
17461
+ if (connection == null || !isConnectionLive()) throw err_nice_action.fromId("connection_required", { operation: "clear connection state" });
17462
+ if (connections != null) connections.clearApp(connection);
17463
+ },
17464
+ broadcast(makeRequest, contextOptions) {
17465
+ broadcast(makeRequest, {
17466
+ except: contextOptions?.exceptSelf && isConnectionLive() ? connection ?? null : null,
17467
+ where: contextOptions?.where,
17468
+ timeout: contextOptions?.timeout,
17469
+ onError: contextOptions?.onError
17470
+ });
17471
+ },
17472
+ pushBack(pushRequest, pushOptions) {
17473
+ if (connection == null || !isConnectionLive()) throw err_nice_action.fromId("connection_required", { operation: "push back to the client" });
17474
+ return pushToClient(connection, pushRequest, pushOptions);
17475
+ }
16955
17476
  });
16956
- };
16957
- const makeConnectionContext = (connection, request) => ({
16958
- connection: connection ?? null,
16959
- origin: request.context.originClient,
16960
- reliability: request.context.reliability,
16961
- get state() {
16962
- return connection != null && connections != null ? connections.get(connection) : null;
16963
- },
16964
- setState(value) {
16965
- if (connection != null && connections != null) connections.set(connection, value);
16966
- },
16967
- clearState() {
16968
- if (connection != null && connections != null) connections.clearApp(connection);
16969
- },
16970
- broadcast(makeRequest, contextOptions) {
16971
- broadcast(makeRequest, {
16972
- except: contextOptions?.exceptSelf ? connection ?? null : null,
16973
- where: contextOptions?.where,
16974
- timeout: contextOptions?.timeout,
16975
- onError: contextOptions?.onError
17477
+ if (options.channelCases != null) installedHandlers.push(acceptors[0].forConnectionDomainCasesMulti(channel.toAcceptorDomains, options.channelCases, makeConnectionContext));
17478
+ let releaseRuntimeHandlers;
17479
+ try {
17480
+ releaseRuntimeHandlers = runtime._installHandlers(installedHandlers);
17481
+ } catch (error) {
17482
+ for (const carrier of duplexCarriers) carrier._dispose?.();
17483
+ for (const acceptor of acceptors) acceptor.dispose();
17484
+ throw error;
17485
+ }
17486
+ const exchangeSecurity = exchangeSecure && secure != null ? {
17487
+ link: secure.link,
17488
+ verifyKeyResolver: secure.verifyKeyResolver,
17489
+ localCoordinate: runtime.coordinate.toJsonObject(),
17490
+ dictionaryVersion: resolveChannel != null ? (hello) => resolveChannel(hello.channels)?.dictionaryVersion ?? null : channel.dictionaryVersion,
17491
+ securityLevel
17492
+ } : void 0;
17493
+ const defaultIsUpgrade = (request) => request.headers.get("Upgrade") === "websocket";
17494
+ const upgraders = [];
17495
+ for (const carrier of duplexCarriers) {
17496
+ if (carrier.upgrade == null) continue;
17497
+ upgraders.push({
17498
+ isUpgrade: carrier.isUpgrade ?? defaultIsUpgrade,
17499
+ upgrade: carrier.upgrade
16976
17500
  });
16977
- },
16978
- pushBack(pushRequest, pushOptions) {
16979
- if (connection == null) throw new Error("serveChannel: connection context has no live socket to push back to (HTTP-exchange path)");
16980
- return pushToClient(connection, pushRequest, pushOptions);
16981
17501
  }
16982
- });
16983
- if (options.channelCases != null) runtime.addHandlers([acceptors[0].forConnectionDomainCasesMulti(channel.toAcceptorDomains, options.channelCases, makeConnectionContext)]);
16984
- const exchangeSecurity = exchangeSecure && secure != null ? {
16985
- link: secure.link,
16986
- verifyKeyResolver: secure.verifyKeyResolver,
16987
- localCoordinate: runtime.coordinate.toJsonObject(),
16988
- dictionaryVersion: resolveChannel != null ? (hello) => resolveChannel(hello.channels)?.dictionaryVersion ?? null : channel.dictionaryVersion,
16989
- securityLevel
16990
- } : void 0;
16991
- const defaultIsUpgrade = (request) => request.headers.get("Upgrade") === "websocket";
16992
- const upgraders = [];
16993
- for (const carrier of duplexCarriers) {
16994
- if (carrier.upgrade == null) continue;
16995
- upgraders.push({
16996
- isUpgrade: carrier.isUpgrade ?? defaultIsUpgrade,
16997
- upgrade: carrier.upgrade
17502
+ const activeFetch = createActionFetchHandler(runtime, {
17503
+ cors: exchangeCarrier?.cors,
17504
+ onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
17505
+ isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
17506
+ isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
17507
+ security: exchangeSecurity,
17508
+ useErrorStatus: exchangeCarrier?.useErrorStatus,
17509
+ logger: options.logger,
17510
+ transportLabel: exchangeCarrier?.carrierLabel
16998
17511
  });
17512
+ const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
17513
+ status: 503,
17514
+ headers: { "cache-control": "no-store" }
17515
+ })) : activeFetch(request);
17516
+ const dispose = () => {
17517
+ if (disposed) return;
17518
+ disposed = true;
17519
+ for (const carrier of duplexCarriers) carrier._dispose?.();
17520
+ for (const acceptor of acceptors) acceptor.dispose();
17521
+ releaseRuntimeHandlers();
17522
+ if (ownsRuntime) runtime.dispose();
17523
+ };
17524
+ return {
17525
+ runtime,
17526
+ acceptors,
17527
+ fetch,
17528
+ receive,
17529
+ drop,
17530
+ dispose,
17531
+ pushToClient,
17532
+ broadcast,
17533
+ connections
17534
+ };
17535
+ } catch (error) {
17536
+ for (const carrier of options.carriers ?? []) if (!isExchangeAcceptorCarrier(carrier)) carrier._dispose?.();
17537
+ if (ownsRuntime) runtime.dispose();
17538
+ throw error;
16999
17539
  }
17000
- const activeFetch = createActionFetchHandler(runtime, {
17001
- cors: exchangeCarrier?.cors,
17002
- onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
17003
- isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
17004
- isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
17005
- security: exchangeSecurity,
17006
- useErrorStatus: exchangeCarrier?.useErrorStatus,
17007
- logger: options.logger,
17008
- transportLabel: exchangeCarrier?.carrierLabel
17009
- });
17010
- const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
17011
- status: 503,
17012
- headers: { "cache-control": "no-store" }
17013
- })) : activeFetch(request);
17014
- const dispose = () => {
17015
- if (disposed) return;
17016
- disposed = true;
17017
- for (const carrier of duplexCarriers) carrier._dispose?.();
17018
- for (const acceptor of acceptors) acceptor.dispose();
17019
- };
17020
- return {
17021
- acceptors,
17022
- fetch,
17023
- receive,
17024
- drop,
17025
- dispose,
17026
- pushToClient,
17027
- broadcast,
17028
- connections
17029
- };
17030
- }
17031
- //#endregion
17032
- //#region ../nice-action/src/ActionRuntime/Transport/Carrier/adaptWireCarrierSource.ts
17033
- /**
17034
- * The E2 bridge (shared-base-connect plan, Phase 2): wire's carrier sources are generalized over
17035
- * an opaque dial context, and nice-action's domain concept for it is the whole per-dispatch
17036
- * routing params — the action being sent decides the URL/cache key (e.g. the pixel demo keys its
17037
- * socket by the action's game id). These adapters wrap a wire source instantiated with
17038
- * `TDial = TTransportRouteParams` back into the action-shaped sources the transport
17039
- * factory (and hand-written test carriers) already speak, so consumer code compiles unchanged.
17040
- */
17041
- function toActionDialParams(input) {
17042
- return {
17043
- localClient: input.localClient,
17044
- externalClient: input.externalClient,
17045
- dialContext: input
17046
- };
17047
- }
17048
- function adaptWireDuplexCarrierSource(source) {
17049
- const { getCacheKey, getRouteInfo } = source;
17050
- return {
17051
- carrierLabel: source.carrierLabel,
17052
- open: (input) => source.open(toActionDialParams(input)),
17053
- getCacheKey: getCacheKey == null ? void 0 : (input) => getCacheKey(toActionDialParams(input)),
17054
- getRouteInfo: getRouteInfo == null ? void 0 : (input) => getRouteInfo(toActionDialParams(input))
17055
- };
17056
17540
  }
17057
17541
  err_nice_transport.createChildDomain({
17058
17542
  domain: "err_nice_transport_ws",
@@ -17063,44 +17547,31 @@ err_nice_transport.createChildDomain({
17063
17547
  }
17064
17548
  });
17065
17549
  //#endregion
17066
- //#region ../nice-action/src/ActionRuntime/Transport/Carrier/duplex/ws/wsAcceptorCarrier.ts
17067
- /**
17068
- * A WebSocket {@link IDuplexAcceptorCarrier}: the accept-in dual of {@link wsCarrier}. It describes how to
17069
- * write frames back to a live socket, how to upgrade an inbound request into one, and (optionally) how to
17070
- * persist bindings across hibernation. Hand it to `serveChannel`'s `carriers` list — the secure session,
17071
- * codec, and crypto identity are supplied centrally there, so this only carries the WS-specific surface.
17072
- */
17073
- function wsAcceptorCarrier(options) {
17074
- return {
17075
- ...createDuplexCarrierLifecycle(options.inboundLimits),
17076
- shape: "duplex",
17077
- carrierLabel: options.carrierLabel ?? "ws",
17078
- secure: options.secure,
17079
- send: options.send,
17080
- upgrade: options.upgrade,
17081
- isUpgrade: options.isUpgrade ?? ((request) => request.headers.get("Upgrade") === "websocket"),
17082
- attachmentStore: options.attachmentStore
17083
- };
17084
- }
17085
- //#endregion
17086
17550
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/duplex/ws/wsCarrier.ts
17087
17551
  /**
17088
17552
  * A WebSocket {@link IDuplexCarrierSource}: the action instantiation of wire's `wsCarrier`
17089
- * (shared-base-connect plan, Phase 2 / E2) — the dial context is the per-action routing params,
17553
+ * — the dial context is the per-action routing params,
17090
17554
  * so `createRequest` still derives the socket URL per action exactly as before. Pass it as a
17091
17555
  * `carrier` to `connectChannel`.
17092
17556
  *
17093
- * `createRequest` may return `null` for "no valid endpoint right now" (resilience-surface §6) —
17557
+ * `createRequest` may return `null` for "no valid endpoint right now" —
17094
17558
  * the keep-alive redial then PARKS instead of dialing garbage, so a dynamic-endpoint teardown
17095
17559
  * (`_activeMatchId = undefined`) needs no careful ordering against `releaseLink()`.
17096
17560
  */
17097
- function wsCarrier(createRequest, options = {}) {
17098
- const { getTransportCacheKey, getRouteInfo, createWebSocket } = options;
17099
- return adaptWireDuplexCarrierSource(wsCarrier$1((params) => createRequest(params.dialContext), {
17100
- getCacheKey: getTransportCacheKey == null ? void 0 : (params) => getTransportCacheKey(params.dialContext),
17101
- getRouteInfo: getRouteInfo == null ? void 0 : (params) => getRouteInfo(params.dialContext),
17102
- createWebSocket
17103
- }));
17561
+ function wsCarrier(request, options = {}) {
17562
+ if (options.getCacheKey != null && options.getTransportCacheKey != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "wsCarrier: pass only `getCacheKey`; `getTransportCacheKey` is deprecated" });
17563
+ const getCacheKey = options.getCacheKey ?? options.getTransportCacheKey;
17564
+ const getRouteInfo = options.getRouteInfo;
17565
+ return {
17566
+ ...wsCarrier$1(typeof request === "string" ? request : (params) => request(params.dialContext), {
17567
+ secure: options.secure,
17568
+ getCacheKey: getCacheKey == null ? void 0 : (params) => getCacheKey(params.dialContext),
17569
+ getRouteInfo: getRouteInfo == null ? void 0 : (params) => getRouteInfo(params.dialContext),
17570
+ createWebSocket: options.createWebSocket
17571
+ }),
17572
+ available: options.available,
17573
+ label: options.label
17574
+ };
17104
17575
  }
17105
17576
  //#endregion
17106
17577
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/exchange/http/httpAcceptorCarrier.ts
@@ -18848,7 +19319,7 @@ function update(store, updater, patchesCallback) {
18848
19319
  //#endregion
18849
19320
  //#region ../nice-realm/src/RealmDefinition/errors/err_realm.ts
18850
19321
  /**
18851
- * The realm base error domain (plan §4.4). Rejection frames carry `packError` output (a msgpack
19322
+ * The realm base error domain. Rejection frames carry `packError` output (a msgpack
18852
19323
  * map), never positional tuples — rejections are the rare path, so they stay fully descriptive
18853
19324
  * and hydratable. User realms define their own domains for rule/intent rejections; these are the
18854
19325
  * engine's own errors. (`protocol_unsupported` lives in `@nice-code/wire` — it is a link-level
@@ -18869,7 +19340,7 @@ const err_realm = err_nice.createChildDomain({
18869
19340
  message: ({ avatarType, expected }) => `Client type "${avatarType}" is not permitted here (expected: ${expected.join(", ")}).`,
18870
19341
  context: { required: true }
18871
19342
  }),
18872
- /** The connection's identity could not be resolved to a realm avatar (review A.7): the
19343
+ /** The connection's identity could not be resolved to a realm avatar: the
18873
19344
  * server's `resolveAvatar`/`avatarType` mapping returned nothing for this connection. */
18874
19345
  avatar_unresolved: err({
18875
19346
  message: ({ realmId }) => `This connection's identity could not be resolved to an avatar of realm "${realmId}" — the server's resolveAvatar returned undefined (or the attachment carries no coordinate).`,
@@ -18877,7 +19348,7 @@ const err_realm = err_nice.createChildDomain({
18877
19348
  }),
18878
19349
  /**
18879
19350
  * The connection's negotiated wire security level is below the realm's declared minimum
18880
- * (PLAN-security §5.2). Fail-closed at attach: the avatar never attaches, so no avatar data
19351
+ *. Fail-closed at attach: the avatar never attaches, so no avatar data
18881
19352
  * flows below the required level. Raise the connection's `securityLevel` (e.g. `encrypted`) to
18882
19353
  * attach — the realm requires it.
18883
19354
  */
@@ -18914,7 +19385,7 @@ const err_realm = err_nice.createChildDomain({
18914
19385
  }),
18915
19386
  /**
18916
19387
  * The optimistic frame expired / was rolled back before an authoritative answer arrived — an
18917
- * **unknown outcome**, NOT proof the server rejected it (DESYNC review app-contract §1). The
19388
+ * **unknown outcome**, NOT proof the server rejected it. The
18918
19389
  * write may have committed on the server while the ack was lost, or the link dropped mid-flight.
18919
19390
  * Do not blindly re-issue a non-idempotent **intent** on this error — re-read state (it
18920
19391
  * converges via the next replay/hydrate) and decide. A rules rejection, by contrast, is a
@@ -18924,7 +19395,7 @@ const err_realm = err_nice.createChildDomain({
18924
19395
  message: ({ basisVersion }) => `The optimistic frame (basis ${basisVersion}) expired before it could be confirmed — outcome unknown (it may have committed; re-read state rather than re-issuing a non-idempotent intent).`,
18925
19396
  context: { required: true }
18926
19397
  }),
18927
- /** The durable-write backlog cap (PLAN-FEATURE-COMPLETE §4): too many unconfirmed
19398
+ /** The durable-write backlog cap: too many unconfirmed
18928
19399
  * `durability: "reassert"` frames accumulated (a long outage). The app's cue to fall back to
18929
19400
  * its own source-of-truth re-sync instead of queueing more. */
18930
19401
  durable_backlog_overflow: err({
@@ -18943,7 +19414,7 @@ const err_realm = err_nice.createChildDomain({
18943
19414
  * frame was well-formed, the state simply moved out from under it. A predicted optimistic write
18944
19415
  * on this path rolls back; the app should re-read state (an assert-on-resume re-creates a
18945
19416
  * pruned own-entry) rather than re-issue blindly. Additive since 0.46 — pre-0.46 servers send
18946
- * `frame_invalid` for this case. (REVIEW-frame-invalid-issue §5.8.)
19417
+ * `frame_invalid` for this case.
18947
19418
  */
18948
19419
  write_target_missing: err({
18949
19420
  message: ({ path }) => `The write to "${path}" could not be applied — its parent no longer exists (a pruned entry or a transient region reset since the write's basis). Re-read state instead of re-issuing.`,
@@ -19081,7 +19552,7 @@ function validateValue(node, value) {
19081
19552
  //#endregion
19082
19553
  //#region ../nice-realm/src/RealmWire/keyDict.ts
19083
19554
  /**
19084
- * Dynamic record-key interning (plan §7 / proposal §7.9): record keys are arbitrary strings
19555
+ * Dynamic record-key interning: record keys are arbitrary strings
19085
19556
  * (nanoids, user ids); after their first appearance they travel as small ints. The server owns id
19086
19557
  * assignment (eager, on first committed write touching the key) and sends each connection the
19087
19558
  * `keyDict` delta entries it hasn't seen before any frame that uses them; clients only ever
@@ -19128,7 +19599,7 @@ var RealmKeyDict = class {
19128
19599
  //#endregion
19129
19600
  //#region ../nice-realm/src/RealmWire/realmFrame.types.ts
19130
19601
  /**
19131
- * The realm wire protocol (plan §7): every frame is a msgpack fixarray `[kind, slot, …]` riding
19602
+ * The realm wire protocol: every frame is a msgpack fixarray `[kind, slot, …]` riding
19132
19603
  * the wire frame-protocol port at prefix `0x01` (M1 seam). The **slot** is a client-assigned small
19133
19604
  * int established by `hello`, so several realms — or several instances — share one peer link with
19134
19605
  * a one-byte discriminator per frame.
@@ -19148,7 +19619,7 @@ const REALM_FRAME_KIND = {
19148
19619
  keyDict: 7,
19149
19620
  detach: 8,
19150
19621
  /**
19151
- * Client→server capability advertisement (PLAN-REALM-MESSAGE-OVERLOAD Phase 1). Sent right after
19622
+ * Client→server capability advertisement. Sent right after
19152
19623
  * every `hello` (fresh attach, reconnect, probe) so a hibernation-woken server — which lost the
19153
19624
  * per-session feature state — re-learns them for free. An old server decodes an unknown kind →
19154
19625
  * drops it → never emits the features it names; a new server with a client that never sends this
@@ -19183,7 +19654,7 @@ const REALM_DETACH_REASON_REHELLO = "rehello";
19183
19654
  //#endregion
19184
19655
  //#region ../nice-realm/src/RealmWire/realmFrameCodec.ts
19185
19656
  /**
19186
- * The realm frame codec (plan §7 / M3): encode side builds each frame's msgpack fixarray; decode
19657
+ * The realm frame codec: encode side builds each frame's msgpack fixarray; decode
19187
19658
  * side strictly validates shape and rejects with a typed `err_realm.frame_invalid` — garbage bytes
19188
19659
  * never throw-through as raw msgpackr/TypeErrors into the engines (the fuzz gate).
19189
19660
  */
@@ -19483,7 +19954,7 @@ function decodeRealmFrame(payload) {
19483
19954
  //#endregion
19484
19955
  //#region ../nice-realm/src/RealmWire/unsafeKey.ts
19485
19956
  /**
19486
- * Prototype-pollution deny-list for dynamic record keys (PLAN-security Phase 5 / §4). Wire segments
19957
+ * Prototype-pollution deny-list for dynamic record keys. Wire segments
19487
19958
  * become object keys in the state tree — on server apply and on client/replica projection. Three of
19488
19959
  * them are never legitimate `t.id()` record keys and are actively dangerous as object keys:
19489
19960
  *
@@ -19525,7 +19996,7 @@ function valueHasUnsafeKey(value) {
19525
19996
  //#endregion
19526
19997
  //#region ../nice-realm/src/RealmWire/wirePatch.ts
19527
19998
  /**
19528
- * Immer patches ↔ realm wire ops (plan §7). Wire ops always use **name-space string paths**
19999
+ * Immer patches ↔ realm wire ops. Wire ops always use **name-space string paths**
19529
20000
  * tokenized through the realm's token map; immer patches on realm state only ever contain string
19530
20001
  * segments *except* inside arrays — and arrays are leaf-replace-only on the wire (proposal §7.8),
19531
20002
  * so {@link canonicalizeStatePatches} lifts any array-interior patch to a whole-array `replace`
@@ -19605,7 +20076,7 @@ function canonicalizeStatePatches(patches, stateAfter, schemaRoot) {
19605
20076
  }
19606
20077
  /**
19607
20078
  * Conflate an ORDERED run of authoritative patch ops to the shortest final-state-equivalent run
19608
- * (PLAN-REALM-MESSAGE-OVERLOAD Phase 3). Used for replay: a reconnect inside the log window merges
20079
+ *. Used for replay: a reconnect inside the log window merges
19609
20080
  * every missed version's ops, which for a 60 Hz cursor is ~1000 dead intermediate positions in one
19610
20081
  * frame. Server→client ops are absolute-value ops (`add`/`replace` carry the whole subtree; `remove`
19611
20082
  * deletes it), so a later op at path `P` makes every earlier op AT `P` OR UNDER `P` redundant — the
@@ -19670,7 +20141,7 @@ function wireOpsToNamePatches(ops, tokens, resolveKey) {
19670
20141
  //#endregion
19671
20142
  //#region ../nice-realm/src/RealmClient/assertRealmSecurity.ts
19672
20143
  /**
19673
- * The client-side security floor (PLAN-security Phase 4 / §3b). The server's attach gate stops
20144
+ * The client-side security floor. The server's attach gate stops
19674
20145
  * *routing* an under-secured avatar — it does NOT stop this client from *sending*. So only this
19675
20146
  * local check keeps avatar identity/state from leaving the device as app-layer plaintext when a
19676
20147
  * realm marked `security: "encrypted"` is connected over an `authenticated` link (a misconfigured
@@ -19679,7 +20150,7 @@ function wireOpsToNamePatches(ops, tokens, resolveKey) {
19679
20150
  *
19680
20151
  * Shared by {@link connectRealm} and {@link connectRealmReplica} so the two connect paths can't
19681
20152
  * drift — the replica is the highest-value leak (an "everything" view of the realm) and a wholly
19682
- * separate code path (review §4).
20153
+ * separate code path.
19683
20154
  */
19684
20155
  /** Map the realm-local policy level to the wire enum for ranking (no `as`, per the code guide). */
19685
20156
  function realmLevelToWire(level) {
@@ -19718,7 +20189,7 @@ function computeRealmSecurityShortfall(adapter, realm, connectOverride) {
19718
20189
  //#endregion
19719
20190
  //#region ../nice-realm/src/RealmClient/diffProjected.ts
19720
20191
  /**
19721
- * Structural diff between two projections (review C.2): the generic version of what imperative
20192
+ * Structural diff between two projections: the generic version of what imperative
19722
20193
  * renderers used to hand-roll per consumer (the pixel demo's 40-line identity-gated record
19723
20194
  * diff). Immer's structural sharing makes it cheap: an unchanged subtree keeps its reference
19724
20195
  * across `applyPatches`/rebase, so `prev === next` prunes it in O(1) — the walk only descends
@@ -19783,12 +20254,12 @@ function evalAlterCond(cond, context, serverExtras) {
19783
20254
  }
19784
20255
  /** The slicer's signature-group key — view rules may not read `instanceId` (see module doc). */
19785
20256
  function viewSignatureKey(avatar) {
19786
- return `${avatar.type}${avatar.persistentId}`;
20257
+ return `${avatar.type}\0${avatar.persistentId}`;
19787
20258
  }
19788
20259
  //#endregion
19789
20260
  //#region ../nice-realm/src/RealmServer/expandWrite.ts
19790
20261
  /**
19791
- * Subtree-write expansion (plan §6.1, locked semantics): an object-valued patch — including a
20262
+ * Subtree-write expansion: an object-valued patch — including a
19792
20263
  * whole record-entry `add`/`remove` — expands to **every leaf path it covers**, and the write
19793
20264
  * passes only if every covered leaf's own most-specific rule passes. Creation is just the first
19794
20265
  * write; deletion is a `remove` through the same gate; rules never need "create" clauses.
@@ -19844,7 +20315,7 @@ function expandWriteToLeaves(options) {
19844
20315
  //#endregion
19845
20316
  //#region ../nice-realm/src/RealmClient/predict.ts
19846
20317
  /**
19847
- * Client-side write prediction (plan §6.1 step 2): the same expansion + rule pipeline the server
20318
+ * Client-side write prediction: the same expansion + rule pipeline the server
19848
20319
  * runs, minus everything server-only — `r.serverChecked` parts auto-pass (that is exactly the
19849
20320
  * slice of optimism that can later roll back), `prev`/`state` come from the writer's projected
19850
20321
  * view. A NiceError here rejects the write in the same tick, before anything renders.
@@ -19928,7 +20399,7 @@ function getAtPath$4(state, path) {
19928
20399
  * throw `path doesn't resolve` on the child patch, far from the cause. Fixed containers are
19929
20400
  * structural (the schema ships to every client), so synthesizing an empty shell reveals nothing.
19930
20401
  *
19931
- * It deliberately does NOT synthesize a missing **dynamic record entry** (DESYNC F5): a missing
20402
+ * It deliberately does NOT synthesize a missing **dynamic record entry**: a missing
19932
20403
  * entry means a missed `add <entry> = {…}`, and fabricating a `{}` shell would produce a silent
19933
20404
  * partial entry (missing the add's fields) that persists until the next reconnect. There, the
19934
20405
  * throw is the right outcome — the Phase-3 inbound wrap turns it into a resync that re-fetches the
@@ -20060,17 +20531,17 @@ function provesSyncHealth(frame) {
20060
20531
  }
20061
20532
  const DEFAULT_PENDING_EXPIRY_MS = 1e4;
20062
20533
  const DEFAULT_STALE_PROBE_AFTER_MS = 25e3;
20063
- /** How long a probe may go unanswered before the link is presumed dead (DESYNC F6 / 8a). */
20534
+ /** How long a probe may go unanswered before the link is presumed dead. */
20064
20535
  const DEFAULT_PROBE_REPLY_TIMEOUT_MS = 1e4;
20065
20536
  /**
20066
- * Attach a realm client to a connection (plan §9). The store starts empty and fills on hydrate;
20537
+ * Attach a realm client to a connection. The store starts empty and fills on hydrate;
20067
20538
  * `realm.update()` is the blessed write API (LWW absolute-set contract — read-modify-write
20068
- * belongs in an intent, plan §6.1).
20539
+ * belongs in an intent, the protocol contract).
20069
20540
  */
20070
20541
  function connectRealm(realm, options) {
20071
20542
  const coordinate = options.connection.coordinate;
20072
20543
  const persistentId = options.avatar.persistentId ?? coordinate?.perId;
20073
- if (persistentId == null) throw new Error("connectRealm: no avatar identity — the connection carries no persistent id. Give it one where you open the connection (identity: coord.specify({ perId })), or pass avatar.persistentId explicitly.");
20544
+ if (persistentId == null) throw new Error("connectRealm: no avatar identity — the connection carries no persistent id. Give it one where you open the connection (identity: coord.withPersistentId(id)), or pass avatar.persistentId explicitly.");
20074
20545
  const avatar = {
20075
20546
  type: options.avatar.type,
20076
20547
  persistentId,
@@ -20087,9 +20558,9 @@ function connectRealm(realm, options) {
20087
20558
  const pendingListeners = /* @__PURE__ */ new Set();
20088
20559
  let confirmed = {};
20089
20560
  let confirmedVersion = -1;
20090
- /** The log epoch `confirmedVersion` belongs to (review B.3) — echoed in every hello. */
20561
+ /** The log epoch `confirmedVersion` belongs to — echoed in every hello. */
20091
20562
  let serverEpoch;
20092
- /** Server-advertised ingress limits off the hydrate (review B.2) — drives flush splitting. */
20563
+ /** Server-advertised ingress limits off the hydrate — drives flush splitting. */
20093
20564
  let advertisedLimits;
20094
20565
  let identityWarned = false;
20095
20566
  let status = "connecting";
@@ -20103,7 +20574,7 @@ function connectRealm(realm, options) {
20103
20574
  const warnTag = () => serverEpoch == null ? `[realm:${realm.id}]` : `[realm:${realm.id}#${serverEpoch.slice(0, 8)}]`;
20104
20575
  /** Status-transition listeners: `subscribeStatus` subscribers + the `whenLive` waiters (B.4). */
20105
20576
  const statusListeners = /* @__PURE__ */ new Set();
20106
- /** Latched on the first `live` and never reset (resilience-surface §4) — joining vs reconnecting. */
20577
+ /** Latched on the first `live` and never reset — joining vs reconnecting. */
20107
20578
  let hasBeenLive = false;
20108
20579
  const setStatus = (next) => {
20109
20580
  if (status === next) return;
@@ -20120,7 +20591,7 @@ function connectRealm(realm, options) {
20120
20591
  let projecting = false;
20121
20592
  let port;
20122
20593
  /**
20123
- * Staleness-probe clocks (review B.1).
20594
+ * Staleness-probe clocks.
20124
20595
  *
20125
20596
  * `lastSyncInboundAt` is deliberately a **sync-health** clock, not a liveness one: only a frame
20126
20597
  * carrying real server sync information stamps it (see {@link provesSyncHealth}). A `reject`
@@ -20128,16 +20599,16 @@ function connectRealm(realm, options) {
20128
20599
  * suppress the probe. That distinction matters because the two used to be one clock, and the
20129
20600
  * failure it allowed was self-sealing: a pathological reject loop is exactly the situation the
20130
20601
  * staleness probe exists to heal, and every reject in it pushed the probe further away
20131
- * (REVIEW F2).
20602
+ *.
20132
20603
  *
20133
20604
  * There is no separate *liveness* clock here because nothing at this layer needs one — liveness is
20134
- * the wire's job (`connectChannel({ linkKeepalive })`, which counts any inbound frame and drops a
20605
+ * the wire's job (`connectChannel({ heartbeat })`, which counts any inbound frame and drops a
20135
20606
  * silent link). The realm's probe is purely "am I still in sync?". If server-initiated liveness
20136
20607
  * ever lands and wants a pure inbound clock, it adds one then rather than re-merging these.
20137
20608
  */
20138
20609
  let lastSyncInboundAt = Date.now();
20139
20610
  let lastProbeAt = 0;
20140
- /** One-shot probe-reply deadline (DESYNC F6 / 8a) — armed after a probe, cleared by any inbound. */
20611
+ /** One-shot probe-reply deadline — armed after a probe, cleared by any inbound. */
20141
20612
  let probeDeadline;
20142
20613
  /** An attach/recovery hello is out and unanswered — non-continuous frames drop, never apply. */
20143
20614
  let helloInFlight = false;
@@ -20145,7 +20616,7 @@ function connectRealm(realm, options) {
20145
20616
  /** Suppress duplicate recovery hellos only while one is plausibly still being answered. */
20146
20617
  const HELLO_REPLY_GRACE_MS = 1e4;
20147
20618
  const warnedDiagnostics = /* @__PURE__ */ new Set();
20148
- /** `subscribeDiagnostics` listeners (devtools plan 4.2) — additive observers, multi-listener. */
20619
+ /** `subscribeDiagnostics` listeners — additive observers, multi-listener. */
20149
20620
  const diagnosticListeners = /* @__PURE__ */ new Set();
20150
20621
  const onDiagnostic = (event) => {
20151
20622
  devtools?.onDiagnostic?.(event);
@@ -20224,7 +20695,7 @@ function connectRealm(realm, options) {
20224
20695
  });
20225
20696
  };
20226
20697
  /**
20227
- * Declare lost-sync and heal via re-hello (DESYNC F2): the recovery hello is **probe-flavored**
20698
+ * Declare lost-sync and heal via re-hello: the recovery hello is **probe-flavored**
20228
20699
  * — no status flap, since on a live link the heal is one round-trip (the server replays exactly
20229
20700
  * the missed span from `confirmedVersion`, or full-hydrates when out of window / epoch
20230
20701
  * mismatch). Safe in every trigger scenario because `applyConfirmed` is immutable — a detected
@@ -20298,7 +20769,7 @@ function connectRealm(realm, options) {
20298
20769
  }
20299
20770
  }
20300
20771
  };
20301
- /** Backoff retry for a recovery whose ANSWER failed to apply (DESYNC F3): never a tight loop,
20772
+ /** Backoff retry for a recovery whose ANSWER failed to apply: never a tight loop,
20302
20773
  * never a silent give-up — each retry re-emits the `resync` diagnostic via `requestResync`. */
20303
20774
  let resyncAttempts = 0;
20304
20775
  let resyncTimer;
@@ -20323,7 +20794,7 @@ function connectRealm(realm, options) {
20323
20794
  const notifyPending = () => {
20324
20795
  for (const listener of pendingListeners) listener();
20325
20796
  };
20326
- /** Patch-feed listeners (review C.2) + the last projection they were told about. */
20797
+ /** Patch-feed listeners + the last projection they were told about. */
20327
20798
  const patchListeners = /* @__PURE__ */ new Set();
20328
20799
  let lastProjected = {};
20329
20800
  /**
@@ -20510,7 +20981,7 @@ function connectRealm(realm, options) {
20510
20981
  return part;
20511
20982
  };
20512
20983
  /**
20513
- * Split one over-limit write frame into consecutive ≤`limit` parts (review B.2): each part is
20984
+ * Split one over-limit write frame into consecutive ≤`limit` parts: each part is
20514
20985
  * atomic on the server; every settle handle rides the LAST part, so read-your-writes holds
20515
20986
  * (acks are ordered). The trade — a split flush loses whole-flush atomicity — is documented on
20516
20987
  * `update()`. Replaces `frame` in the pending queue in place, preserving projection order.
@@ -20784,7 +21255,7 @@ function connectRealm(realm, options) {
20784
21255
  return controller.handle;
20785
21256
  };
20786
21257
  /**
20787
- * `limits_exceeded` recovery (review B.2): a well-behaved client must survive a breach — even
21258
+ * `limits_exceeded` recovery: a well-behaved client must survive a breach — even
20788
21259
  * a mis-advertised limit — instead of settling the write as a fatal reject (and, ×10, being
20789
21260
  * forcibly detached). Frame-size breaches re-split against a halved local ceiling; a rate
20790
21261
  * breach resends after a backoff. Bounded by {@link MAX_LIMIT_RETRIES} and the frame's own
@@ -21002,14 +21473,14 @@ function connectRealm(realm, options) {
21002
21473
  }
21003
21474
  };
21004
21475
  /**
21005
- * The defensive inbound boundary (DESYNC F3): every inbound frame runs through `handleFrame`
21476
+ * The defensive inbound boundary: every inbound frame runs through `handleFrame`
21006
21477
  * inside this wrap. A decode/apply throw — an unknown interned key id (`detokenizePath`), a
21007
21478
  * patch that can't resolve its parent (`applyConfirmed`) — must NOT escape into the wire mux,
21008
21479
  * silently drop the frame, or (inside a batch) abort its siblings. On any failure we heal the
21009
21480
  * same way a version gap does: re-hello with backoff. `lastSyncInboundAt` is stamped only AFTER a
21010
21481
  * clean handling, so a throwing frame no longer fools the staleness probe into thinking the
21011
- * link is healthy (review F1.3) — and only for a frame that actually carries sync information
21012
- * ({@link provesSyncHealth}), so a reject cannot either (REVIEW F2).
21482
+ * link is healthy — and only for a frame that actually carries sync information
21483
+ * ({@link provesSyncHealth}), so a reject cannot either.
21013
21484
  */
21014
21485
  const onFrame = (frame, byteSize) => {
21015
21486
  devtools?.onFrame?.("in", REALM_FRAME_KIND_NAME[frame.kind] ?? String(frame.kind), byteSize ?? 0);
@@ -21034,7 +21505,7 @@ function connectRealm(realm, options) {
21034
21505
  }
21035
21506
  };
21036
21507
  /**
21037
- * The identity echo check (review A.4.2): the hydrate names the avatar the server resolved —
21508
+ * The identity echo check: the hydrate names the avatar the server resolved —
21038
21509
  * the one verdicts and view slicing run against. A disagreement with our own ref is the
21039
21510
  * silent-flicker bug class (prediction passes locally, the server rejects every time), so it
21040
21511
  * warns loudly, once per handle.
@@ -21044,7 +21515,7 @@ function connectRealm(realm, options) {
21044
21515
  if (type === avatar.type && persistentId === avatar.persistentId && instanceId === avatar.instanceId) return;
21045
21516
  if (identityWarned) return;
21046
21517
  identityWarned = true;
21047
- console.warn(`${warnTag()} identity mismatch — this client predicts as ${avatar.type}/${avatar.persistentId}/${avatar.instanceId} but the server resolved it as ${type}/${persistentId}/${instanceId} (review A.4.2). Prediction and view slicing run against DIFFERENT identities: owner-gated writes will pass locally and reject on the server. Fix the server's resolveAvatar/avatarType, or the avatar passed to connectRealm.`);
21518
+ console.warn(`${warnTag()} identity mismatch — this client predicts as ${avatar.type}/${avatar.persistentId}/${avatar.instanceId} but the server resolved it as ${type}/${persistentId}/${instanceId}. Prediction and view slicing run against DIFFERENT identities: owner-gated writes will pass locally and reject on the server. Fix the server's resolveAvatar/avatarType, or the avatar passed to connectRealm.`);
21048
21519
  };
21049
21520
  /**
21050
21521
  * The reassert lane (Phase 2 / Overshot Issue 2): ride a recovery hello with a re-own WRITE so a
@@ -21115,7 +21586,7 @@ function connectRealm(realm, options) {
21115
21586
  * - A **probe** hello (staleness probe, wake rehello, `write_target_missing` resync) keeps `live`
21116
21587
  * status (no HUD flap on a link that never dropped) and KEEPS the dict: it rides the same-or-woken
21117
21588
  * session where the server re-sends a delta before first use of any id and `RealmKeyDict.load`
21118
- * overwrites, so a reassigned id is corrected before it is ever resolved (DESYNC F4). It arms the
21589
+ * overwrites, so a reassigned id is corrected before it is ever resolved. It arms the
21119
21590
  * escalation deadline instead — no inbound within the window ⇒ the link is genuinely dead and
21120
21591
  * status flips to `connecting` truthfully (Phase 1.2).
21121
21592
  */
@@ -21320,11 +21791,11 @@ function connectRealm(realm, options) {
21320
21791
  realmId: realm.id,
21321
21792
  slot,
21322
21793
  avatar,
21323
- peer: options.connection.peerCoordinate?.envId
21794
+ peer: (options.connection.peer ?? options.connection.peerCoordinate)?.envId
21324
21795
  });
21325
21796
  return handle;
21326
21797
  }
21327
- /** Last write wins per exact path inside one coalesced frame (plan §9.1). */
21798
+ /** Last write wins per exact path inside one coalesced frame. */
21328
21799
  function dedupeByPath(patches) {
21329
21800
  const byPath = /* @__PURE__ */ new Map();
21330
21801
  for (const patch of patches) byPath.set(patch.path.join(" "), patch);
@@ -21347,7 +21818,7 @@ enablePatches();
21347
21818
  //#endregion
21348
21819
  //#region ../nice-realm/src/RealmClient/realmMuxClient.ts
21349
21820
  const managers = /* @__PURE__ */ new WeakMap();
21350
- /** Grace period before a released slot number may be recycled (DESYNC F7) — see `release()`. */
21821
+ /** Grace period before a released slot number may be recycled — see `release()`. */
21351
21822
  const SLOT_QUARANTINE_MS = 5e3;
21352
21823
  function managerFor(mux) {
21353
21824
  let manager = managers.get(mux);
@@ -21433,7 +21904,7 @@ function realmConnection(source) {
21433
21904
  const mux = isMux ? source : source.wireMux;
21434
21905
  if (mux == null) throw new Error("realmConnection: this link has no frame-protocol mux — connect it via connectChannel (which creates one per connection) or pass a WireProtocolMux directly.");
21435
21906
  const coordinate = isMux ? void 0 : source.localCoordinate;
21436
- const peerCoordinate = isMux ? void 0 : source.peerClient;
21907
+ const peer = isMux ? void 0 : "peer" in source ? source.peer : source.peerClient;
21437
21908
  const securityLevel = isMux ? void 0 : source.securityLevel;
21438
21909
  const requestReconnect = isMux ? void 0 : source.requestReconnect;
21439
21910
  const linkEventSource = isMux ? void 0 : source.addLinkEventListener?.bind(source);
@@ -21445,7 +21916,8 @@ function realmConnection(source) {
21445
21916
  return {
21446
21917
  slot,
21447
21918
  coordinate,
21448
- peerCoordinate,
21919
+ peer,
21920
+ peerCoordinate: peer,
21449
21921
  securityLevel,
21450
21922
  requestReconnect,
21451
21923
  subscribeLinkEvents: linkEventSource,
@@ -21556,7 +22028,7 @@ function assertRulePatternsMatchSchema(root, patterns) {
21556
22028
  }
21557
22029
  }
21558
22030
  /**
21559
- * Validate + parse a realm's `transient` region paths (PLAN-REALM-MESSAGE-OVERLOAD Phase 5). v1
22031
+ * Validate + parse a realm's `transient` region paths. v1
21560
22032
  * accepts only **concrete, wildcard-free** dot-paths, each naming a subtree root that exists in the
21561
22033
  * schema (`"presence"`, `"board.cursors"`). Wildcards (`$var`, `*`, `**`, `{a,b}`) are rejected —
21562
22034
  * snapshot-strip and the replay refresh are a trivial root walk, not a pattern projection (that is a
@@ -21712,7 +22184,7 @@ var RealmRuleTrie = class {
21712
22184
  //#endregion
21713
22185
  //#region ../nice-realm/src/RealmDefinition/Schema/schemaHash.ts
21714
22186
  /**
21715
- * The realm schema hash (plan §4.1/§7.1-of-proposal): SHA-256 over a canonical serialization of
22187
+ * The realm schema hash: SHA-256 over a canonical serialization of
21716
22188
  * everything both sides must agree on for the wire to be meaningful — realm id, state shape
21717
22189
  * (sorted), client-type names, intent names + input shapes, and rule path patterns. It rides the
21718
22190
  * realm `hello` and hard-fails a mismatch (`err_realm.schema_mismatch`): silent token skew on a
@@ -21832,7 +22304,7 @@ var RealmTokenMap = class {
21832
22304
  }
21833
22305
  /**
21834
22306
  * Name path → wire path (object keys → ints; record keys pass through as strings, or as
21835
- * interned ids when `internKey` resolves one — plan §7.9 key interning).
22307
+ * interned ids when `internKey` resolves one — the protocol contract key interning).
21836
22308
  */
21837
22309
  tokenizePath(path, internKey) {
21838
22310
  const out = [];
@@ -21950,7 +22422,7 @@ function union(...args) {
21950
22422
  };
21951
22423
  }
21952
22424
  /**
21953
- * The realm schema builder — `t.*` (plan §4.1). One `defineRealm` block uses these to declare the
22425
+ * The realm schema builder — `t.*`. One `defineRealm` block uses these to declare the
21954
22426
  * state shape; from that single declaration the library derives the TS types, the token map, the
21955
22427
  * schema hash, and (M4) the server-side value validator.
21956
22428
  */
@@ -22030,7 +22502,7 @@ const t = {
22030
22502
  };
22031
22503
  },
22032
22504
  /**
22033
- * Declare the server-only context TYPE (plan §5). The value is injected at
22505
+ * Declare the server-only context TYPE. The value is injected at
22034
22506
  * `createRealmServerEngine(realm, { ctx })` time — nothing here exists in client bundles, and
22035
22507
  * nothing secret may be closed over in the definition module.
22036
22508
  */
@@ -22289,7 +22761,7 @@ function pruneNode(ctx, node, value, path) {
22289
22761
  anyVisible: true
22290
22762
  } : OMIT;
22291
22763
  }
22292
- /** The avatar's sliced view of the whole state — the hydrate payload (plan §8.1). */
22764
+ /** The avatar's sliced view of the whole state — the hydrate payload. */
22293
22765
  function sliceStateForAvatar(ctx, state) {
22294
22766
  const out = {};
22295
22767
  for (const [key, node] of Object.entries(ctx.schemaRoot)) out[key] = pruneNode(ctx, node, state[key], [key]).value ?? {};
@@ -22377,7 +22849,7 @@ function clientKey(avatar) {
22377
22849
  return `${avatar.type} ${avatar.persistentId}`;
22378
22850
  }
22379
22851
  /**
22380
- * Mint a log epoch (review B.3): a random id identifying one history of one realm instance.
22852
+ * Mint a log epoch: a random id identifying one history of one realm instance.
22381
22853
  * Uniqueness only needs to hold across *rebuilds of the same realm* (wiped storage, re-created
22382
22854
  * DO, migration) — collision means a stale avatar silently replays a foreign diff, so time +
22383
22855
  * randomness is plenty. Platform-clean on purpose (no `crypto` dependency).
@@ -22396,7 +22868,7 @@ var RealmServerEngine = class {
22396
22868
  _hasBounds;
22397
22869
  _version = 0;
22398
22870
  _mutating = false;
22399
- /** The log epoch (review B.3): identifies this history — replay requires an exact match. */
22871
+ /** The log epoch: identifies this history — replay requires an exact match. */
22400
22872
  _epoch;
22401
22873
  _log;
22402
22874
  _logWindow;
@@ -22434,10 +22906,10 @@ var RealmServerEngine = class {
22434
22906
  */
22435
22907
  _pendingAcks = [];
22436
22908
  /**
22437
- * Replay/duplicate high-water per connection **key** (PLAN-security §5.2b) — the highest
22909
+ * Replay/duplicate high-water per connection **key** — the highest
22438
22910
  * `clientSeq` accepted for processing on a `connKey`. Kept **outside** the `IEngineConnection`
22439
22911
  * record on purpose: a same-avatar re-hello swaps the conn record in place (`attach()`'s
22440
- * reattach path, DESYNC F3 — it no longer detaches at all), so a per-record counter would reset
22912
+ * reattach path, the reconnect contract — it no longer detaches at all), so a per-record counter would reset
22441
22913
  * to `-1` and a replayed `hello` could reopen the window (Fact B). This map survives the
22442
22914
  * re-attach trivially; `detachConnection` clears it on a *real* close. Phase 3b persists this
22443
22915
  * across a hibernation wake (Fact C).
@@ -22496,7 +22968,7 @@ var RealmServerEngine = class {
22496
22968
  get instanceId() {
22497
22969
  return this._instanceId;
22498
22970
  }
22499
- /** The log epoch (review B.3) — minted at genesis/migrate, persisted by the platform host. */
22971
+ /** The log epoch — minted at genesis/migrate, persisted by the platform host. */
22500
22972
  get epoch() {
22501
22973
  return this._epoch;
22502
22974
  }
@@ -22515,7 +22987,7 @@ var RealmServerEngine = class {
22515
22987
  * Calling it for a `connKey` that is already attached with the **same avatar** is a
22516
22988
  * **re-attach** (staleness probe / wake rehello): the connection record is swapped in place —
22517
22989
  * fresh `sentKeyIds`/`features`, preserved rate bucket, migrated window acks — and the avatar
22518
- * lifecycle hooks do NOT fire (DESYNC F3: the avatar never left). A different avatar on the
22990
+ * lifecycle hooks do NOT fire. A different avatar on the
22519
22991
  * same `connKey` first runs the old avatar's full detach bookkeeping.
22520
22992
  */
22521
22993
  attach(connKey, options) {
@@ -22622,7 +23094,7 @@ var RealmServerEngine = class {
22622
23094
  * per socket — so this is pure cleanup, not correctness). `preserveReplayHighWater` is retained
22623
23095
  * for compatibility but no longer has an internal caller: a same-realm re-hello no longer
22624
23096
  * detaches at all — `attach()` swaps the connection record in place without firing the avatar
22625
- * lifecycle (DESYNC F3), and the high-water survives trivially.
23097
+ * lifecycle, and the high-water survives trivially.
22626
23098
  */
22627
23099
  detachConnection(connKey, reason = "detached", notifyPeer = false, preserveReplayHighWater = false, bypassGrace = false) {
22628
23100
  const conn = this._connections.get(connKey);
@@ -22642,7 +23114,7 @@ var RealmServerEngine = class {
22642
23114
  this._deferOrFireDetach(conn.avatar, reason, bypassGrace);
22643
23115
  } else this._avatarConnCounts.set(ck, count - 1);
22644
23116
  }
22645
- /** Forced detach / revocation (plan §8.3): drop every connection of a persistent avatar. */
23117
+ /** Forced detach / revocation: drop every connection of a persistent avatar. */
22646
23118
  detachAvatar(persistentId, reason = "revoked") {
22647
23119
  for (const conn of [...this._connections.values()]) if (conn.avatar.persistentId === persistentId) this.detachConnection(conn.key, reason, true, false, true);
22648
23120
  for (const [ck, pending] of [...this._pendingDetaches]) {
@@ -22655,7 +23127,7 @@ var RealmServerEngine = class {
22655
23127
  /**
22656
23128
  * Park the per-avatar detach for the grace window (or fire it now with no/ bypassed grace) —
22657
23129
  * the one funnel every last-connection departure goes through, `reportAvatarLost` included.
22658
- * Dispatch stays microtask-deferred (review B.5) so the hook may freely `engine.update()`.
23130
+ * Dispatch stays microtask-deferred so the hook may freely `engine.update()`.
22659
23131
  */
22660
23132
  _deferOrFireDetach(avatar, reason, bypassGrace) {
22661
23133
  if (!bypassGrace && this._detachGraceMs > 0) {
@@ -22753,7 +23225,7 @@ var RealmServerEngine = class {
22753
23225
  return this._connections.size;
22754
23226
  }
22755
23227
  /**
22756
- * The engine's traffic totals since construction (devtools plan §5.1): ingress frames/bytes,
23228
+ * The engine's traffic totals since construction: ingress frames/bytes,
22757
23229
  * egress **messages** (the per-message billing unit) vs frames (pre-coalescing) and bytes.
22758
23230
  * `egressCoalesceRatio` is the batch-envelope + broadcast-tick win made measurable — frames
22759
23231
  * folded per WS message. Plain data; hosts expose it however they like (a dev-only debug
@@ -22797,7 +23269,7 @@ var RealmServerEngine = class {
22797
23269
  }
22798
23270
  /**
22799
23271
  * The egress features a connection advertised via `clientCaps`
22800
- * (PLAN-REALM-MESSAGE-OVERLOAD Phase 1), or `undefined` when the connKey is not attached. Phase 2
23272
+ *, or `undefined` when the connKey is not attached. Phase 2
22801
23273
  * consumes `REALM_FEATURE.batch` here to gate the `batch` envelope; exposed for hosts/tests.
22802
23274
  */
22803
23275
  connectionFeatures(connKey) {
@@ -22834,9 +23306,9 @@ var RealmServerEngine = class {
22834
23306
  }
22835
23307
  /**
22836
23308
  * Mutate authoritative state from server code (`r.serverOnly` paths — game ticks, fulfilment;
22837
- * plan §8.2). Flows through the same version/log/slice tail, so server writes broadcast
23309
+ * the protocol contract). Flows through the same version/log/slice tail, so server writes broadcast
22838
23310
  * identically. Throws when called re-entrantly from an intent `apply` or a rule (single-writer
22839
- * invariant, plan §8.3).
23311
+ * invariant, the protocol contract).
22840
23312
  */
22841
23313
  update(fn) {
22842
23314
  this._guardReentrancy();
@@ -23301,7 +23773,7 @@ var RealmServerEngine = class {
23301
23773
  return false;
23302
23774
  }
23303
23775
  /**
23304
- * The replay/duplicate high-water gate (PLAN-security §5.2b, Facts A/B). Returns `false` — caller
23776
+ * The replay/duplicate high-water gate. Returns `false` — caller
23305
23777
  * must stop — when `clientSeq` is at or below the connection's high-water: the frame is either a
23306
23778
  * replay (a captured frame re-injected into the framing layer) or a benign ack-lost resend, which
23307
23779
  * by seq alone are indistinguishable and both safe to treat as already-processed. It is settled
@@ -23323,7 +23795,7 @@ var RealmServerEngine = class {
23323
23795
  return true;
23324
23796
  }
23325
23797
  /**
23326
- * Advance the connection's replay high-water and persist it (PLAN-security §5.2b Fact C). Persist
23798
+ * Advance the connection's replay high-water and persist it. Persist
23327
23799
  * runs per accepted frame so the durable value never lags an arbitrary hibernation point (a
23328
23800
  * lagging value would reopen the wake-replay window). Cost: one host-side upsert per accepted
23329
23801
  * `write`/`intent` — see the host's `persistSeqHighWater`, which may batch if it proves hot.
@@ -23362,7 +23834,7 @@ var RealmServerEngine = class {
23362
23834
  /**
23363
23835
  * Send a rejection to one connection. The wire carries **only** the error's public
23364
23836
  * `toJsonObject()` (ids, user-provided error context, message, stack) — never the realm's
23365
- * `serverContext` (`ctx`), which the engine never places on an error (PLAN-security Phase 6
23837
+ * `serverContext` (`ctx`), which the engine never places on an error (the protocol contract
23366
23838
  * secret-scrub, verified). Discipline this implies for realm authors: a rule/intent error's
23367
23839
  * **context and message are wire-visible**, so they must not embed server secrets (`ctx` values,
23368
23840
  * internal ids) — the same rule as the client bundle. Documented in the security guide (Phase 8).
@@ -23473,14 +23945,14 @@ function pathsOverlap(a, b) {
23473
23945
  for (let i = 0; i < len; i++) if (a[i] !== b[i]) return false;
23474
23946
  return true;
23475
23947
  }
23476
- /** Factory with full inference from the realm definition (plan §8.2). */
23948
+ /** Factory with full inference from the realm definition. */
23477
23949
  function createRealmServerEngine(realm, options) {
23478
23950
  return new RealmServerEngine(realm, options);
23479
23951
  }
23480
23952
  //#endregion
23481
23953
  //#region ../nice-realm/src/RealmServer/realmAcceptorProtocol.ts
23482
23954
  function createRealmAcceptor(options) {
23483
- if (options.levelFor == null && Object.values(options.realms).some((hosted) => hosted.minSecurity != null)) console.warn("[realm] a hosted realm declares `minSecurity` but createRealmAcceptor received no `levelFor` — the security minimum is NOT enforced (only the coarse wire gate, which blocks `none`, applies). Wire a `levelFor` (serveRealmDurableObject does this for you).");
23955
+ for (const [realmId, hosted] of Object.entries(options.realms)) if (hosted.resolveAvatar == null === (hosted.avatarType == null)) throw new Error(`createRealmAcceptor: realm "${realmId}" requires exactly one of \`resolveAvatar\` or \`avatarType\``);
23484
23956
  const connStates = /* @__PURE__ */ new WeakMap();
23485
23957
  let connCounter = 0;
23486
23958
  const stateFor = (connection) => {
@@ -23499,7 +23971,11 @@ function createRealmAcceptor(options) {
23499
23971
  return {
23500
23972
  id: "realm",
23501
23973
  prefixByte: WIRE_PROTOCOL_PREFIX.realm,
23502
- onFrame(connection, payload, send) {
23974
+ onFrame(connection, payload, send, suppliedContext) {
23975
+ const context = suppliedContext ?? {
23976
+ client: void 0,
23977
+ level: options.levelFor?.(connection) ?? "none"
23978
+ };
23503
23979
  let frame;
23504
23980
  try {
23505
23981
  frame = decodeRealmFrame(payload);
@@ -23517,7 +23993,11 @@ function createRealmAcceptor(options) {
23517
23993
  }));
23518
23994
  return;
23519
23995
  }
23520
- const avatar = hosted.resolveAvatar(connection);
23996
+ const avatar = hosted.resolveAvatar?.(connection, context) ?? (hosted.avatarType != null && context.client?.perId != null ? {
23997
+ type: hosted.avatarType,
23998
+ persistentId: context.client.perId,
23999
+ instanceId: context.client.insId ?? "default"
24000
+ } : void 0);
23521
24001
  if (avatar == null) {
23522
24002
  send(encodeReject({
23523
24003
  slot: frame.slot,
@@ -23526,8 +24006,8 @@ function createRealmAcceptor(options) {
23526
24006
  }));
23527
24007
  return;
23528
24008
  }
23529
- if (hosted.minSecurity != null && options.levelFor != null) {
23530
- const actual = options.levelFor(connection);
24009
+ if (hosted.minSecurity != null) {
24010
+ const actual = context.level;
23531
24011
  if (!securityLevelMeets(actual, hosted.minSecurity)) {
23532
24012
  send(encodeReject({
23533
24013
  slot: frame.slot,
@@ -23877,7 +24357,7 @@ var CommanderDaemonBootError = class extends Error {
23877
24357
  */
23878
24358
  async function replaceSkewedDaemon(paths, skewed) {
23879
24359
  const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v6${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
23880
- let liveIds = [];
24360
+ let liveIds;
23881
24361
  try {
23882
24362
  liveIds = (await openProcessLedger({
23883
24363
  dir: paths.stateDir,
@@ -24380,11 +24860,11 @@ async function connectDaemon(handle) {
24380
24860
  ephemeralIdentity: true,
24381
24861
  securityLevel: "authenticated",
24382
24862
  defaultTimeout: COMMANDER_CONTROL_TIMEOUT_MS,
24383
- keepLinkAlive: false,
24863
+ reconnect: false,
24384
24864
  onLinkEvent: (event) => {
24385
24865
  if (process.env["NICE_COMMANDER_DEBUG"] != null) process.stderr.write(`[link] ${JSON.stringify(event)}\n`);
24386
24866
  },
24387
- transports: [{ carrier: wsCarrier(() => ({ url: `ws://127.0.0.1:${record.port}${COMMANDER_WS_PATH}` }), { createWebSocket: (url) => {
24867
+ carriers: [wsCarrier(() => ({ url: `ws://127.0.0.1:${record.port}${COMMANDER_WS_PATH}` }), { createWebSocket: (url) => {
24388
24868
  if (process.env["NICE_COMMANDER_DEBUG"] != null) process.stderr.write(`[ws] dialing ${url}\n`);
24389
24869
  const socket = new WebSocket$1(url, [`${COMMANDER_TICKET_PROTOCOL_PREFIX}${ticket}`]);
24390
24870
  if (process.env["NICE_COMMANDER_DEBUG"] != null) {
@@ -24393,7 +24873,7 @@ async function connectDaemon(handle) {
24393
24873
  socket.on("close", (code) => process.stderr.write(`[ws] close ${code}\n`));
24394
24874
  }
24395
24875
  return socket;
24396
- } }) }]
24876
+ } })]
24397
24877
  });
24398
24878
  const realm = connectRealm(commanderStatusRealm, {
24399
24879
  onDiagnostic: (event) => {
@@ -24766,7 +25246,7 @@ async function listeners(port) {
24766
25246
  } catch (error) {
24767
25247
  const e = error;
24768
25248
  if (Number(e.code) === 1 && !e.stderr?.trim()) return parseLsof(e.stdout ?? "");
24769
- throw new Error(`Cannot inspect TCP ${port}: ${e.code === "ENOENT" ? "install lsof and retry" : e.message}`);
25249
+ throw new Error(`Cannot inspect TCP ${port}: ${e.code === "ENOENT" ? "install lsof and retry" : e.message}`, { cause: error });
24770
25250
  }
24771
25251
  }
24772
25252
  async function localAddresses(host) {
@@ -26450,7 +26930,7 @@ async function withTimeout(ctx, run) {
26450
26930
  async function main() {
26451
26931
  const argv = process.argv.slice(2);
26452
26932
  if (argv[0] === "daemon") {
26453
- const { runCommanderDaemon } = await import("./main-BBH2T2OI.mjs");
26933
+ const { runCommanderDaemon } = await import("./main-DCr__iZh.mjs");
26454
26934
  return runCommanderDaemon(argv.slice(1));
26455
26935
  }
26456
26936
  const parsed = parseCliArgs(argv);
@@ -26495,6 +26975,6 @@ main().then((code) => {
26495
26975
  process.exitCode = EXIT.failure;
26496
26976
  });
26497
26977
  //#endregion
26498
- export { ActionRuntime as A, stopSetWithDependencies as B, resolveCommanderDataDir as C, wsAcceptorCarrier as D, httpAcceptorCarrier as E, envVarViews as F, removeInstanceRecord as G, savedFilterId as H, overrideFingerprint as I, writeInstanceRecord as K, hashCanonical as L, createMemoryStorageAdapter_json as M, validateCommanderConfig as N, serveChannel as O, effectiveEnv as P, loadCommanderConfigFile as R, ensureStateDir as S, createRealmServerEngine as T, readInstanceRecord as U, withDependencies as V, recordDaemonAlive as W, COMMANDER_WS_PATH as _, parseLogsClientMessage as a, commanderPackageVersion as b, countOverrides as c, commanderControlDomain as d, COMMANDER_BOOTSTRAP_PATH as f, COMMANDER_TICKET_PROTOCOL_PREFIX as g, COMMANDER_TICKET_PATH as h, runTaskPool as i, RuntimeCoordinate as j, createDefaultServeLogger as k, readEnvOverrides as l, COMMANDER_LOGS_PATH as m, readSavedFilters as n, createPortInspector as o, COMMANDER_HEALTH_PATH as p, writeSavedFilters as r, applyEnvMutation as s, mutateSavedFilters as t, commanderChannel as u, commanderStatusRealm as v, createRealmAcceptor as w, commanderStatePaths as x, commanderRuntimeError as y, orderByDependency as z };
26978
+ export { createMemoryStorageAdapter_json as A, withDependencies as B, resolveCommanderDataDir as C, serveChannel as D, httpAcceptorCarrier as E, overrideFingerprint as F, writeInstanceRecord as G, readInstanceRecord as H, hashCanonical as I, loadCommanderConfigFile as L, validateCommanderConfig as M, effectiveEnv as N, createDefaultServeLogger as O, envVarViews as P, orderByDependency as R, ensureStateDir as S, createRealmServerEngine as T, recordDaemonAlive as U, savedFilterId as V, removeInstanceRecord as W, COMMANDER_WS_PATH as _, parseLogsClientMessage as a, commanderPackageVersion as b, countOverrides as c, commanderControlDomain as d, COMMANDER_BOOTSTRAP_PATH as f, COMMANDER_TICKET_PROTOCOL_PREFIX as g, COMMANDER_TICKET_PATH as h, runTaskPool as i, wsAcceptorCarrier as j, RuntimeCoordinate as k, readEnvOverrides as l, COMMANDER_LOGS_PATH as m, readSavedFilters as n, createPortInspector as o, COMMANDER_HEALTH_PATH as p, writeSavedFilters as r, applyEnvMutation as s, mutateSavedFilters as t, commanderChannel as u, commanderStatusRealm as v, createRealmAcceptor as w, commanderStatePaths as x, commanderRuntimeError as y, stopSetWithDependencies as z };
26499
26979
 
26500
26980
  //# sourceMappingURL=cli.mjs.map