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