@nice-code/commander 0.96.0 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/cli.mjs CHANGED
@@ -445,6 +445,29 @@ function withDependencies(processes, ids) {
445
445
  return closed;
446
446
  }
447
447
  /**
448
+ * What stopping `direct` AND its dependencies may take down. A dependency is kept when a live
449
+ * process outside the stop set still needs it — and keeping one keeps what IT needs, hence the
450
+ * loop. Dependencies that simply are not running are not reported either way.
451
+ */
452
+ function stopSetWithDependencies(processes, direct, isLive) {
453
+ const stop = withDependencies(processes, direct);
454
+ const kept = [];
455
+ for (let changed = true; changed;) {
456
+ changed = false;
457
+ const needed = withDependencies(processes, processes.filter((proc) => !stop.has(proc.id) && isLive(proc.id)).map((proc) => proc.id));
458
+ for (const id of [...stop]) {
459
+ if (direct.includes(id) || !needed.has(id)) continue;
460
+ stop.delete(id);
461
+ if (isLive(id)) kept.push(id);
462
+ changed = true;
463
+ }
464
+ }
465
+ return {
466
+ stop: orderByDependency(processes, stop),
467
+ kept
468
+ };
469
+ }
470
+ /**
448
471
  * Resolve CLI/UI selection terms against the model. An empty `terms` is the caller's problem
449
472
  * (bare `up` consults `defaultSelection` before ever reaching here).
450
473
  */
@@ -1290,6 +1313,74 @@ function staggerFor(config, terms) {
1290
1313
  return stagger;
1291
1314
  }
1292
1315
  //#endregion
1316
+ //#region ../nice-wire/src/Carrier/AcceptorCarrier.ts
1317
+ /** Build the inert lifecycle slot shared by duplex acceptor carrier factories. */
1318
+ function createDuplexCarrierLifecycle(limits) {
1319
+ let router;
1320
+ let disposed = false;
1321
+ const windows = /* @__PURE__ */ new Map();
1322
+ const maxFrameBytes = limits?.maxFrameBytes;
1323
+ const rate = limits?.rate;
1324
+ if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
1325
+ if (rate != null && (!Number.isSafeInteger(rate.maxMessages) || rate.maxMessages <= 0 || !Number.isSafeInteger(rate.windowMs) || rate.windowMs <= 0)) throw new Error("inbound rate limits must be positive safe integers");
1326
+ const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
1327
+ return {
1328
+ receive(connection, frame) {
1329
+ if (disposed) return;
1330
+ if (router == null) throw new Error("acceptor carrier not served yet — activate it before feeding frames");
1331
+ if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
1332
+ limits?.onExceeded(connection, "frame_bytes");
1333
+ return;
1334
+ }
1335
+ if (rate != null) {
1336
+ const now = Date.now();
1337
+ let window = windows.get(connection);
1338
+ if (window == null || now - window.startedAt >= rate.windowMs) {
1339
+ window = {
1340
+ count: 0,
1341
+ startedAt: now
1342
+ };
1343
+ windows.set(connection, window);
1344
+ }
1345
+ window.count += 1;
1346
+ if (window.count > rate.maxMessages) {
1347
+ limits?.onExceeded(connection, "message_rate");
1348
+ return;
1349
+ }
1350
+ }
1351
+ router.receive(connection, frame);
1352
+ },
1353
+ drop(connection) {
1354
+ if (disposed) return;
1355
+ windows.delete(connection);
1356
+ router?.drop(connection);
1357
+ },
1358
+ _activate(liveRouter) {
1359
+ if (disposed) throw new Error("acceptor carrier already disposed");
1360
+ router = liveRouter;
1361
+ },
1362
+ _dispose() {
1363
+ if (disposed) return;
1364
+ disposed = true;
1365
+ router = void 0;
1366
+ windows.clear();
1367
+ }
1368
+ };
1369
+ }
1370
+ /** Build a WebSocket acceptor carrier for `serveWire` or `serveChannel`. */
1371
+ function wsAcceptorCarrier(options) {
1372
+ return {
1373
+ ...createDuplexCarrierLifecycle(options.inboundLimits),
1374
+ shape: "duplex",
1375
+ carrierLabel: options.carrierLabel ?? "ws",
1376
+ secure: options.secure,
1377
+ send: options.send,
1378
+ upgrade: options.upgrade,
1379
+ isUpgrade: options.isUpgrade ?? ((request) => request.headers.get("Upgrade") === "websocket"),
1380
+ attachmentStore: options.attachmentStore
1381
+ };
1382
+ }
1383
+ //#endregion
1293
1384
  //#region ../nice-error/src/internal/internal_errors.ts
1294
1385
  let _build;
1295
1386
  /** Wired once by `nice_core_errors` at module init to avoid an import cycle. */
@@ -2301,7 +2392,7 @@ async function niceTryAsync(fn) {
2301
2392
  //#endregion
2302
2393
  //#region ../nice-wire/src/Connect/err_wire_connect.ts
2303
2394
  /**
2304
- * The Connect layer's error domain (shared-base-connect plan, Phase 1). Declared with the types
2395
+ * The Connect layer's error domain. Declared with the types
2305
2396
  * so Phases 2–6 throw against a fixed vocabulary instead of inventing ad-hoc `Error`s per phase;
2306
2397
  * each id notes the phase that starts raising it. (`protocol_unsupported` is the link-level
2307
2398
  * error `nice-realm`'s `err_realm` doc already points at as living here.)
@@ -2320,12 +2411,13 @@ const err_wire_connect = err_nice.createChildDomain({
2320
2411
  */
2321
2412
  dial_failed: err({ message: ({ peerId, carrierLabel, reason, endpoint }) => `Dialing peer [${peerId}] over "${carrierLabel}"${endpoint != null ? ` against ${endpoint}` : ""} failed: ${reason}` }),
2322
2413
  /**
2323
- * Resilience-surface §6 — the carrier has **no valid endpoint right now** (`createRequest`
2414
+ * the resilience contract — the carrier has **no valid endpoint right now** (`createRequest`
2324
2415
  * returned `null`, e.g. a torn-down session's mutable dial context). Not a failure: a policy
2325
2416
  * signal. The transport selection rethrows it unwrapped, and a keep-alive redial loop PARKS on
2326
2417
  * it — no dialing garbage, no backoff churn — until the next explicit `connect()`/dispatch.
2327
2418
  */
2328
2419
  dial_unavailable: err({ message: ({ carrierLabel }) => `Dial over "${carrierLabel}" unavailable — createRequest returned null (no valid endpoint right now). A keep-alive redial parks on this until the next explicit connect()/dispatch.` }),
2420
+ conflicting_connect_options: err({ message: ({ detail }) => `Conflicting connection options: ${detail}` }),
2329
2421
  /**
2330
2422
  * Consumer feedback (meteor-connect-bridge W1/W3) — **something answered, and it is not
2331
2423
  * nice-wire**. The dominant real-world causes are a wrong URL/port, an intercepting proxy or
@@ -2354,11 +2446,23 @@ const err_wire_connect = err_nice.createChildDomain({
2354
2446
  * `identity_pin_mismatch` stays its own id: it is permanent and the redial loop parks on it.
2355
2447
  */
2356
2448
  handshake_rejected: err({ message: ({ stage, reason }) => `[${stage}] rejected by peer: ${reason}` }),
2449
+ /**
2450
+ * The peer explicitly reported that the secure handshake has no compatible first-party wire
2451
+ * generation. This is terminal for the current builds: transport fallback and automatic
2452
+ * redial park until the application explicitly retries after an upgrade or rollback.
2453
+ */
2454
+ protocol_version_mismatch: err({ message: ({ reason, observedProtocolVersion, localSupportedProtocolVersions, remoteSupportedProtocolVersions }) => `Handshake protocol version mismatch: ${reason}. Local support: [${localSupportedProtocolVersions.join(", ")}]${remoteSupportedProtocolVersions != null ? `; remote support: [${remoteSupportedProtocolVersions.join(", ")}]` : ""}${observedProtocolVersion != null ? `; observed version: ${observedProtocolVersion}` : ""}. Carrier fallback and automatic redial are parked until an explicit retry.` }),
2455
+ /**
2456
+ * A secure endpoint answered as nice-wire but advertised a different runtime identity from the
2457
+ * one the caller selected. This is terminal for the current endpoint selection, so fallback and
2458
+ * automatic redial park until an explicit retry after the route or expectation changes.
2459
+ */
2460
+ peer_identity_mismatch: err({ message: ({ expected, actual, endpoint }) => `Secure peer identity mismatch: expected envId=${JSON.stringify(expected.envId)}${expected.perId != null ? `, perId=${JSON.stringify(expected.perId)}` : ""}; received envId=${JSON.stringify(actual.envId)}${actual.perId != null ? `, perId=${JSON.stringify(actual.perId)}` : ""}. ${endpoint != null ? `Dialed ${endpoint}. ` : ""}Carrier fallback and automatic redial are parked until an explicit retry.` }),
2357
2461
  /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */
2358
2462
  protocol_unsupported: err({ message: ({ protocolId }) => `Protocol "${protocolId}" cannot speak on this connection — the peer did not advertise "proto:${protocolId}" (or it is not registered here).` }),
2359
- /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; plan D-11). */
2463
+ /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; the protocol contract). */
2360
2464
  protocol_on_exchange_only: err({ message: ({ protocolId }) => `Protocol "${protocolId}" needs a duplex transport — this connection is exchange-only (request/reply), which carries only the lane.` }),
2361
- /** Phase 4 — the acceptor security gate (review A.6): protocol frame on a non-authenticated connection without `allowPlain`. */
2465
+ /** Phase 4 — the acceptor security gate: protocol frame on a non-authenticated connection without `allowPlain`. */
2362
2466
  protocol_security_blocked: err({ message: ({ protocolId, securityLevel }) => `Protocol "${protocolId}" frame blocked: connection is at security level "${securityLevel}" and the protocol did not opt into allowPlain.` }),
2363
2467
  /** Phase 4 — rehydrate saw a binding with an unknown schema version: treat the socket as fresh. */
2364
2468
  binding_version_mismatch: err({ message: ({ found, expected }) => `Persisted connection binding has schema version ${JSON.stringify(found)} (this build reads v${expected}) — the binding is invalidated; the connection must re-handshake.` }),
@@ -2496,7 +2600,7 @@ async function normalizeFrame(data) {
2496
2600
  //#region ../nice-wire/src/Carrier/duplex/ws/wsCarrier.ts
2497
2601
  /**
2498
2602
  * A WebSocket {@link IWireDuplexCarrierSource}: opens an `arraybuffer` socket (cached per endpoint)
2499
- * and adapts it to a carrier — generalized over an opaque dial context (shared-base-connect plan,
2603
+ * and adapts it to a carrier — generalized over an opaque dial context (shared connection design,
2500
2604
  * E2), so the URL can be derived from whatever domain concept the consumer threads through
2501
2605
  * (nice-action passes the action being dispatched; a realm-only client passes e.g. a game id).
2502
2606
  *
@@ -2504,15 +2608,21 @@ async function normalizeFrame(data) {
2504
2608
  * dynamic endpoints need no socket-construction hook for the URL. `createWebSocket` exists for
2505
2609
  * **testability** — injecting a controllable socket (it is not a URL mechanism).
2506
2610
  *
2507
- * `createRequest` may return **`null`** to mean "no valid endpoint right now" (resilience-surface
2508
- * §6) — a dynamic-endpoint carrier whose mutable dial context was torn down (`matchId` cleared)
2611
+ * `createRequest` may return **`null`** to mean "no valid endpoint right now" — a dynamic-endpoint
2612
+ * carrier whose mutable dial context was torn down (`matchId` cleared)
2509
2613
  * signals that instead of dialing garbage. The dial throws `dial_unavailable`, which a keep-alive
2510
2614
  * redial loop parks on (resuming at the next explicit `connect()`/dispatch) — so teardown ordering
2511
2615
  * stops mattering.
2512
2616
  */
2513
- function wsCarrier$1(createRequest, options = {}) {
2617
+ function wsCarrier$1(request, options = {}) {
2618
+ const createRequest = (params) => {
2619
+ const resolved = typeof request === "string" ? request : request(params);
2620
+ if (resolved == null) return null;
2621
+ return typeof resolved === "string" ? { url: resolved } : resolved;
2622
+ };
2514
2623
  const construct = options.createWebSocket ?? ((url) => new WebSocket(url));
2515
2624
  return {
2625
+ secure: options.secure,
2516
2626
  carrierLabel: "ws",
2517
2627
  open: (params) => {
2518
2628
  const request = createRequest(params);
@@ -2543,8 +2653,13 @@ function wsCarrier$1(createRequest, options = {}) {
2543
2653
  * HTML page pasted into an error is worse DX than no preview at all.
2544
2654
  */
2545
2655
  const BODY_PREVIEW_LIMIT = 200;
2546
- /** C0 + DEL + C1 — a raw control character in an error message corrupts terminals and log lines. */
2547
- const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]+/g;
2656
+ /** Replace C0, DEL, and C1 characters that would corrupt terminals and log lines. */
2657
+ function replaceControlCharacters(raw) {
2658
+ return Array.from(raw, (character) => {
2659
+ const codePoint = character.codePointAt(0);
2660
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
2661
+ }).join("");
2662
+ }
2548
2663
  /**
2549
2664
  * A bounded, single-line, control-character-free head of whatever a non-protocol endpoint sent
2550
2665
  * back — enough to recognize an HTML error page or a proxy banner on sight. Only the *response* is
@@ -2552,11 +2667,28 @@ const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]+/g;
2552
2667
  */
2553
2668
  function describeNonProtocolBody(raw) {
2554
2669
  if (typeof raw !== "string") return void 0;
2555
- const flattened = raw.replace(CONTROL_CHARS, " ").replace(/\s+/g, " ").trim();
2670
+ const flattened = replaceControlCharacters(raw).replace(/\s+/g, " ").trim();
2556
2671
  if (flattened.length === 0) return void 0;
2557
2672
  return flattened.length > BODY_PREVIEW_LIMIT ? `${flattened.slice(0, BODY_PREVIEW_LIMIT)}…` : flattened;
2558
2673
  }
2559
2674
  /**
2675
+ * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can
2676
+ * contain secrets, so connection errors retain only the scheme, host, port, and path.
2677
+ */
2678
+ function sanitizeEndpoint(raw) {
2679
+ if (raw == null) return void 0;
2680
+ try {
2681
+ const url = new URL(raw);
2682
+ url.username = "";
2683
+ url.password = "";
2684
+ url.search = "";
2685
+ url.hash = "";
2686
+ return url.toString();
2687
+ } catch {
2688
+ return raw.split(/[?#]/, 1)[0];
2689
+ }
2690
+ }
2691
+ /**
2560
2692
  * Classify a dial failure. Reads typed ids only — the ids are raised at the layer that still holds
2561
2693
  * the evidence precisely so this never has to sniff message text.
2562
2694
  */
@@ -2564,6 +2696,8 @@ function classifyConnectFailure(error) {
2564
2696
  if (!err_wire_connect.isExact(error)) return "unknown";
2565
2697
  if (error.hasId("endpoint_answered_non_protocol")) return "endpoint_answered_non_protocol";
2566
2698
  if (error.hasId("endpoint_unreachable")) return "endpoint_unreachable";
2699
+ if (error.hasId("protocol_version_mismatch")) return "protocol_version_mismatch";
2700
+ if (error.hasId("peer_identity_mismatch")) return "peer_identity_mismatch";
2567
2701
  if (error.hasId("identity_pin_mismatch") || error.hasId("handshake_rejected")) return "handshake_rejected";
2568
2702
  return "unknown";
2569
2703
  }
@@ -2572,12 +2706,13 @@ function endpointFromConnectFailure(error) {
2572
2706
  if (!err_wire_connect.isExact(error)) return void 0;
2573
2707
  if (error.hasId("endpoint_answered_non_protocol")) return error.getContext("endpoint_answered_non_protocol").url;
2574
2708
  if (error.hasId("endpoint_unreachable")) return error.getContext("endpoint_unreachable").url;
2709
+ if (error.hasId("peer_identity_mismatch")) return error.getContext("peer_identity_mismatch").endpoint;
2575
2710
  }
2576
2711
  //#endregion
2577
2712
  //#region ../nice-wire/src/Connect/ConnectionTransportManager.ts
2578
2713
  /**
2579
2714
  * Preference-ordered transport selection over a shared connection cache — moved from nice-action
2580
- * (shared-base-connect plan, Phase 2) with the routing params (`RP`), finalized methods
2715
+ * with the routing params (`RP`), finalized methods
2581
2716
  * (`METHODS`), and connection type (`CONN`) generic. Behavior is byte-for-byte the pre-move
2582
2717
  * logic: strict preference order with parallel warm-up, cache adoption guarded against teardown
2583
2718
  * races, and disconnect-driven eviction.
@@ -2693,10 +2828,20 @@ var ConnectionTransportManager$1 = class {
2693
2828
  for (const candidate of candidates) try {
2694
2829
  return await candidate.promise;
2695
2830
  } catch (e) {
2831
+ if (err_wire_connect.isExact(e) && e.hasId("peer_identity_mismatch")) {
2832
+ const context = e.getContext("peer_identity_mismatch");
2833
+ const endpoint = sanitizeEndpoint(candidate.transport.getRouteInfo(input)?.url);
2834
+ if (endpoint != null && context.endpoint == null) throw err_wire_connect.fromId("peer_identity_mismatch", {
2835
+ ...context,
2836
+ endpoint
2837
+ }).withOriginError(e);
2838
+ throw e;
2839
+ }
2840
+ if (err_wire_connect.isExact(e) && e.hasId("protocol_version_mismatch")) throw e;
2696
2841
  lastError = e;
2697
2842
  lastTransport = candidate.transport;
2698
2843
  }
2699
- if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch"))) throw lastError;
2844
+ if (err_wire_connect.isExact(lastError) && (lastError.hasId("dial_unavailable") || lastError.hasId("identity_pin_mismatch") || lastError.hasId("protocol_version_mismatch") || lastError.hasId("peer_identity_mismatch"))) throw lastError;
2700
2845
  throw this._errors.initializationFailed(input, {
2701
2846
  cause: describeTransportFailure(lastError),
2702
2847
  endpoint: endpointFromConnectFailure(lastError) ?? lastTransport?.getRouteInfo(input)?.url,
@@ -3926,6 +4071,25 @@ function literal(literal_, message$1) {
3926
4071
  };
3927
4072
  }
3928
4073
  /* @__NO_SIDE_EFFECTS__ */
4074
+ function number(message$1) {
4075
+ return {
4076
+ kind: "schema",
4077
+ type: "number",
4078
+ reference: number,
4079
+ expects: "number",
4080
+ async: false,
4081
+ message: message$1,
4082
+ get "~standard"() {
4083
+ return /* @__PURE__ */ _getStandardProps(this);
4084
+ },
4085
+ "~run"(dataset, config$1) {
4086
+ if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
4087
+ else _addIssue(this, "type", dataset, config$1);
4088
+ return dataset;
4089
+ }
4090
+ };
4091
+ }
4092
+ /* @__NO_SIDE_EFFECTS__ */
3929
4093
  function object(entries$1, message$1) {
3930
4094
  return {
3931
4095
  kind: "schema",
@@ -5063,6 +5227,11 @@ function nanoid(size = 21) {
5063
5227
  for (let i = poolOffset - size; i < poolOffset; i++) id += urlAlphabet[pool[i] & 63];
5064
5228
  return id;
5065
5229
  }
5230
+ /**
5231
+ * Protocol generations this build can actually speak, newest first. This release has one codec,
5232
+ * so it advertises only v1; the intended future window is the current and previous generation.
5233
+ */
5234
+ const WIRE_SUPPORTED_PROTOCOL_VERSIONS = [1];
5066
5235
  const UNSET_RUNTIME_ENV_ID = "_unset_";
5067
5236
  //#endregion
5068
5237
  //#region ../nice-wire/src/utils/runtimeCoordinateToStringIds.ts
@@ -5079,6 +5248,14 @@ var RuntimeCoordinate = class RuntimeCoordinate {
5079
5248
  envId;
5080
5249
  perId;
5081
5250
  insId;
5251
+ /** Readable alias for {@link perId}; the serialized own field remains `perId`. */
5252
+ get persistentId() {
5253
+ return this.perId;
5254
+ }
5255
+ /** Readable alias for {@link insId}; the serialized own field remains `insId`. */
5256
+ get instanceId() {
5257
+ return this.insId;
5258
+ }
5082
5259
  static get unknown() {
5083
5260
  return new RuntimeCoordinate({ envId: UNSET_RUNTIME_ENV_ID });
5084
5261
  }
@@ -5086,7 +5263,7 @@ var RuntimeCoordinate = class RuntimeCoordinate {
5086
5263
  return new RuntimeCoordinate({ envId });
5087
5264
  }
5088
5265
  /**
5089
- * Env + persistent instance id — but not *merely* a routing name: on a secure connection this id
5266
+ * Env + persistent id — but not *merely* a routing name: on a secure connection this id
5090
5267
  * keys the server's trust-on-first-use verify-key pin (see {@link IRuntimeCoordinateSpecifics.perId}).
5091
5268
  * Pair it only with a crypto-identity `storage` that persists at least as long as the id itself,
5092
5269
  * or every reload presents a new key for a pinned id and is rejected (`identity_pin_mismatch`).
@@ -5193,7 +5370,8 @@ var RuntimeCoordinate = class RuntimeCoordinate {
5193
5370
  * handler drive the I/O and the connection phase (Step 4). Keep `none`-level connections from ever
5194
5371
  * reaching here — they skip the handshake entirely.
5195
5372
  */
5196
- const HANDSHAKE_PROTOCOL = "nice-ws-hs/1";
5373
+ const HANDSHAKE_PROTOCOL = `nice-ws-hs/1`;
5374
+ const HANDSHAKE_PROTOCOL_PREFIX = "nice-ws-hs/";
5197
5375
  /**
5198
5376
  * Capability advertised by both peers in the handshake (`hello.caps` / `welcome.caps`) when they understand
5199
5377
  * the reliable-delivery wire (the 7-slot reliability frame). It lets a `.reliable()` sender detect a peer
@@ -5270,7 +5448,11 @@ const vHandshakeMessage = /* @__PURE__ */ variant("t", [
5270
5448
  * feedback §3). Additive + optional: an old peer neither sends nor reads it (unknown keys are
5271
5449
  * stripped on decode), so the frame stays wire-compatible in both directions.
5272
5450
  */
5273
- id: /* @__PURE__ */ optional(/* @__PURE__ */ string())
5451
+ id: /* @__PURE__ */ optional(/* @__PURE__ */ string()),
5452
+ /** The unsupported generation observed by the rejecting peer, when the tag was well formed. */
5453
+ observedProtocolVersion: /* @__PURE__ */ optional(/* @__PURE__ */ number()),
5454
+ /** The generations the rejecting peer can actually speak, newest first. */
5455
+ supportedProtocolVersions: /* @__PURE__ */ optional(/* @__PURE__ */ array(/* @__PURE__ */ number()))
5274
5456
  })
5275
5457
  ]);
5276
5458
  /** Serialize a handshake message for the wire (handshake frames are JSON — they aren't the hot path). */
@@ -5336,6 +5518,15 @@ function reject(reason, id) {
5336
5518
  * is unusable with this key: clear the client's identity storage / mint a new persistent id".
5337
5519
  */
5338
5520
  const HANDSHAKE_REJECT_ID_PIN_MISMATCH = "identity_pin_mismatch";
5521
+ /** Machine-readable rejection for peers with no common first-party wire generation. */
5522
+ const HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH = "protocol_version_mismatch";
5523
+ function handshakeProtocolVersion(protocol) {
5524
+ if (!protocol.startsWith(HANDSHAKE_PROTOCOL_PREFIX)) return void 0;
5525
+ const raw = protocol.slice(11);
5526
+ if (!/^(0|[1-9]\d*)$/.test(raw)) return void 0;
5527
+ const parsed = Number(raw);
5528
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
5529
+ }
5339
5530
  function tofuPinKey(client) {
5340
5531
  return `${client.envId}::${client.perId ?? client.insId ?? "_"}`;
5341
5532
  }
@@ -5466,6 +5657,17 @@ function createClientHandshake(config) {
5466
5657
  if (welcome.dictionaryVersion !== dictionaryVersion) throw new Error("[ws-handshake] server dictionary version mismatch");
5467
5658
  if (welcome.securityLevel !== securityLevel) throw new Error("[ws-handshake] server security level mismatch");
5468
5659
  if (wantsEncryption && welcome.exchangePublicKey == null) throw new Error("[ws-handshake] server did not provide an exchange key for encryption");
5660
+ const expectedPeer = config.expectedPeer;
5661
+ if (expectedPeer != null && (welcome.server.envId !== expectedPeer.envId || expectedPeer.perId != null && welcome.server.perId !== expectedPeer.perId)) throw err_wire_connect.fromId("peer_identity_mismatch", {
5662
+ expected: {
5663
+ envId: expectedPeer.envId,
5664
+ perId: expectedPeer.perId
5665
+ },
5666
+ actual: {
5667
+ envId: welcome.server.envId,
5668
+ perId: welcome.server.perId
5669
+ }
5670
+ });
5469
5671
  const linkedServerId = runtimeLinkId(welcome.server);
5470
5672
  await link.linkClient({
5471
5673
  linkedClientId: linkedServerId,
@@ -5536,7 +5738,14 @@ function createServerHandshake(config) {
5536
5738
  let result;
5537
5739
  return {
5538
5740
  async onHello(hello) {
5539
- if (hello.protocol !== HANDSHAKE_PROTOCOL) return reject("unsupported handshake protocol");
5741
+ if (hello.protocol !== HANDSHAKE_PROTOCOL) {
5742
+ const observedProtocolVersion = handshakeProtocolVersion(hello.protocol);
5743
+ return {
5744
+ ...reject(`unsupported handshake protocol; this server supports wire protocol v${WIRE_SUPPORTED_PROTOCOL_VERSIONS.join(", v")}`, HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH),
5745
+ observedProtocolVersion,
5746
+ supportedProtocolVersions: [...WIRE_SUPPORTED_PROTOCOL_VERSIONS]
5747
+ };
5748
+ }
5540
5749
  const dictionaryVersion = typeof config.dictionaryVersion === "function" ? config.dictionaryVersion(hello) : config.dictionaryVersion;
5541
5750
  if (dictionaryVersion == null) return reject("unknown or unserved channel");
5542
5751
  if (hello.dictionaryVersion !== dictionaryVersion) return reject("dictionary version mismatch");
@@ -5662,8 +5871,8 @@ function securityLevelMeets(actual, required) {
5662
5871
  //#endregion
5663
5872
  //#region ../nice-wire/src/Connect/WireClient.ts
5664
5873
  /**
5665
- * The carrier said "no valid endpoint right now" (`createRequest` returned null — resilience-surface
5666
- * §6). A policy signal, not a failure: the redial loop PARKS on it (no backoff churn, no garbage
5874
+ * The carrier said "no valid endpoint right now" (`createRequest` returned null). A policy signal,
5875
+ * not a failure: the redial loop PARKS on it (no backoff churn, no garbage
5667
5876
  * dial) and resumes at the next explicit `connect()`/dispatch. The transport selection rethrows it
5668
5877
  * unwrapped so this check is reliable.
5669
5878
  */
@@ -5671,12 +5880,13 @@ const isDialUnavailable = (e) => err_wire_connect.isExact(e) && e.hasId("dial_un
5671
5880
  /**
5672
5881
  * A dial failure the backoff ladder must PARK on instead of retrying: either no endpoint exists
5673
5882
  * right now ({@link isDialUnavailable}), or the peer rejected the handshake with
5674
- * `identity_pin_mismatch` (Inteleport feedback §3) — the peer has a *different* verify key pinned
5675
- * for this client identity, so every retry re-runs the same doomed handshake. Parking is not
5676
- * terminal: the next explicit `connect()`/dispatch may try again (and re-park). Other handshake
5677
- * rejections (e.g. a dictionary-version mismatch) keep the ladder — a deploy can heal those.
5883
+ * `identity_pin_mismatch` (the peer has a different key pinned) or
5884
+ * `protocol_version_mismatch` (the two builds have no compatible secure-wire generation).
5885
+ * Parking is not terminal: the next explicit `connect()`/dispatch may try again after the app has
5886
+ * upgraded or changed endpoints. Other handshake rejections (e.g. a dictionary mismatch) retain
5887
+ * the existing retry behavior because a matching deploy can heal them.
5678
5888
  */
5679
- const isParkedDialRejection = (e) => isDialUnavailable(e) || err_wire_connect.isExact(e) && e.hasId("identity_pin_mismatch");
5889
+ const isParkedDialRejection = (e) => isDialUnavailable(e) || err_wire_connect.isExact(e) && (e.hasId("identity_pin_mismatch") || e.hasId("protocol_version_mismatch") || e.hasId("peer_identity_mismatch"));
5680
5890
  /**
5681
5891
  * The dial-out connection: owns the transport cache, preference-ordered selection, the protocol mux,
5682
5892
  * and the whole **connection lifecycle** — establishment bookkeeping, the keep-alive redial ladder
@@ -5718,19 +5928,19 @@ var WireClient = class {
5718
5928
  * outage, and it emits `link_down` at close.
5719
5929
  */
5720
5930
  _tornDown = false;
5721
- /** Explicit opt-out; `undefined` = auto (on for a protocol-carrying duplex link — see `_keepLinkAlive`). */
5722
- _keepLinkAliveOption;
5723
- /** Connections we've hooked a keep-alive disconnect listener onto (once per connection). */
5724
- _keepAliveHooked = /* @__PURE__ */ new WeakSet();
5931
+ /** Explicit opt-out; `undefined` = auto (on for a protocol-carrying duplex link). */
5932
+ _reconnectOption;
5933
+ /** Connections we've hooked a reconnect listener onto (once per connection). */
5934
+ _reconnectHooked = /* @__PURE__ */ new WeakSet();
5725
5935
  _redialTimer;
5726
5936
  _redialAttempts = 0;
5727
5937
  /** Set by an explicit teardown so the resulting disconnect doesn't auto-redial; cleared on a fresh establish. */
5728
5938
  _suppressRedial = false;
5729
- /** Timer ending a `debug.dropLink` suppression window (resilience-surface §2). */
5939
+ /** Timer ending a `debug.dropLink` suppression window. */
5730
5940
  _debugResumeTimer;
5731
5941
  _disposed = false;
5732
5942
  /**
5733
- * Chaos/QA surface (resilience-surface §2) — stable API, but never for production control flow.
5943
+ * Chaos/QA surface — stable API, but never for production control flow.
5734
5944
  * The "simulate airplane mode" button: manual QA and consumer resilience tests use it to force
5735
5945
  * the outages that page-level interception can't (the keep-alive redial heals straight through
5736
5946
  * a `window.WebSocket` patch).
@@ -5789,7 +5999,8 @@ dropLink: async (opts) => {
5789
5999
  this.localCoordinate = options.localCoordinate;
5790
6000
  this.securityLevel = options.securityLevel ?? "none";
5791
6001
  this.canPush = options.canPush;
5792
- this._keepLinkAliveOption = options.keepLinkAlive;
6002
+ if (options.reconnect != null && options.keepLinkAlive != null) throw err_wire_connect.fromId("conflicting_connect_options", { detail: "WireClient: pass only `reconnect`; `keepLinkAlive` is deprecated" });
6003
+ this._reconnectOption = options.reconnect ?? options.keepLinkAlive;
5793
6004
  this._buildConnectInput = options.buildConnectInput;
5794
6005
  this._defaultLocalCoordinate = options.defaultLocalCoordinate;
5795
6006
  this._manager = options.createManager(this._cache);
@@ -5822,16 +6033,12 @@ dropLink: async (opts) => {
5822
6033
  get wireMux() {
5823
6034
  return this.mux;
5824
6035
  }
5825
- /**
5826
- * The peer this connection dials — the `IRealmWireLink.peerClient` surface a realm reads for
5827
- * devtools topology attribution (observational only). An alias of {@link peer}; the two names are
5828
- * reconciled to one in the final-form surface pass (plan Phase 3.4).
5829
- */
6036
+ /** @deprecated Use {@link peer}. */
5830
6037
  get peerClient() {
5831
6038
  return this.peer;
5832
6039
  }
5833
6040
  /**
5834
- * The re-dial hook a realm client rides (DESYNC F6 / Phase 8a — the `IRealmWireLink` seam):
6041
+ * The re-dial hook a realm client rides:
5835
6042
  * `realmConnection(client)` reads it and hands it to the realm engine as the connection
5836
6043
  * adapter's `requestReconnect`, invoked on an unanswered staleness probe. A bound closure, so it
5837
6044
  * survives being detached from `this` (the realm stores the reference and calls it later).
@@ -5840,9 +6047,9 @@ dropLink: async (opts) => {
5840
6047
  return () => void this.reconnectLink();
5841
6048
  }
5842
6049
  /** Keep-alive is active for a protocol-carrying duplex link (a realm) unless opted out (Phase 8b). */
5843
- get _keepLinkAlive() {
6050
+ get _shouldReconnect() {
5844
6051
  if (this._disposed || !this.canPush) return false;
5845
- if (this._keepLinkAliveOption != null) return this._keepLinkAliveOption;
6052
+ if (this._reconnectOption != null) return this._reconnectOption;
5846
6053
  return (this.mux?.localCaps().length ?? 0) > 0;
5847
6054
  }
5848
6055
  /** Called on every fresh link establishment (`connect()` / a redial): re-enable + hook keep-alive. */
@@ -5866,8 +6073,8 @@ dropLink: async (opts) => {
5866
6073
  }
5867
6074
  /** Attach the auto-redial disconnect listener to one connection, once (Phase 8b). */
5868
6075
  _hookKeepAlive(methods) {
5869
- if (methods.addOnDisconnectListener == null || this._keepAliveHooked.has(methods)) return;
5870
- this._keepAliveHooked.add(methods);
6076
+ if (methods.addOnDisconnectListener == null || this._reconnectHooked.has(methods)) return;
6077
+ this._reconnectHooked.add(methods);
5871
6078
  methods.addOnDisconnectListener(() => {
5872
6079
  if (methods !== this._currentLinkMethods) return;
5873
6080
  if (this._tornDown) return;
@@ -5875,12 +6082,12 @@ dropLink: async (opts) => {
5875
6082
  this._downSince = Date.now();
5876
6083
  this._emitLinkEvent({ type: "link_down" });
5877
6084
  }
5878
- if (this._keepLinkAlive && !this._suppressRedial) this._scheduleRedial();
6085
+ if (this._shouldReconnect && !this._suppressRedial) this._scheduleRedial();
5879
6086
  });
5880
6087
  }
5881
6088
  /** Schedule one backoff+jitter re-dial (Phase 8b); idempotent — one attempt pending at a time. */
5882
6089
  _scheduleRedial() {
5883
- if (!this._keepLinkAlive || this._suppressRedial || this._redialTimer != null) return;
6090
+ if (!this._shouldReconnect || this._suppressRedial || this._redialTimer != null) return;
5884
6091
  const ceiling = Math.min(1e3 * 2 ** this._redialAttempts, 3e4);
5885
6092
  const delay = ceiling / 2 + Math.random() * (ceiling / 2);
5886
6093
  this._redialAttempts += 1;
@@ -5942,7 +6149,7 @@ dropLink: async (opts) => {
5942
6149
  }
5943
6150
  }
5944
6151
  /**
5945
- * Tear down the (possibly half-open) duplex link and immediately re-dial it (DESYNC F6 / Phase
6152
+ * Tear down the (possibly half-open) duplex link and immediately re-dial it (the reconnect contract / Phase
5946
6153
  * 8b). Surfaced to a realm client as the connection adapter's `requestReconnect` (via
5947
6154
  * {@link requestReconnect}) — the staleness-probe escalation calls it when a probe goes
5948
6155
  * unanswered. On a successful re-dial the mux re-attaches and every realm re-hellos; a failure
@@ -5965,7 +6172,7 @@ dropLink: async (opts) => {
5965
6172
  }
5966
6173
  /**
5967
6174
  * Stop the keep-alive auto-redial and release the current link — the intention-revealing
5968
- * teardown counterpart of `keepLinkAlive`. Call this when a session is
6175
+ * teardown counterpart of `reconnect`. Call this when a session is
5969
6176
  * over (leaving a match, logging out): the link closes and stays closed until the next explicit
5970
6177
  * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the client is reusable.
5971
6178
  */
@@ -8434,7 +8641,7 @@ function createActionFrameCrypto({ link, keyMaterial }) {
8434
8641
  //#endregion
8435
8642
  //#region ../nice-wire/src/Mux/protocolFrame.ts
8436
8643
  /**
8437
- * Frame-protocol prefix bytes (realm plan §3.1). A registered protocol frame is
8644
+ * Frame-protocol prefix bytes (realm protocol design §3.1). A registered protocol frame is
8438
8645
  * `[prefixByte, ...payload]` with the prefix drawn from the reserved range `0x00`–`0x0F` —
8439
8646
  * bytes no legacy frame can start with: binary action envelopes are msgpack fixarrays
8440
8647
  * (`0x96`–`0x98`), control frames are msgpack maps (`0x80`–`0x8f`, `0xde`, `0xdf`), and
@@ -8590,17 +8797,34 @@ function wireFrameByteSize(frame) {
8590
8797
  }
8591
8798
  //#endregion
8592
8799
  //#region ../nice-wire/src/Connect/handshakeRejectError.ts
8800
+ const sanitizeVersions = (versions) => {
8801
+ if (versions == null) return void 0;
8802
+ const safe = [];
8803
+ for (const version of versions) {
8804
+ if (Number.isSafeInteger(version) && version >= 1 && version <= 65535) safe.push(version);
8805
+ if (safe.length === 2) break;
8806
+ }
8807
+ return safe.length > 0 ? safe : void 0;
8808
+ };
8593
8809
  /**
8594
- * Map a peer's handshake reject frame to the error the dialing side throws (Inteleport feedback
8595
- * §3). A reject carrying a machine-readable `id` becomes the matching typed `err_wire_connect`
8596
- * error — today `identity_pin_mismatch`, which the transport selection rethrows UNWRAPPED (like
8597
- * `dial_unavailable`) so `err.hasId("identity_pin_mismatch")` works at the `connect()`/dispatch
8598
- * caller and the keep-alive redial loop can park on it. A reject without an id (an older peer,
8810
+ * Map a peer's handshake reject frame to the error the dialing side throws. A reject carrying a machine-readable `id` becomes the matching typed `err_wire_connect`
8811
+ * error — `identity_pin_mismatch` or `protocol_version_mismatch` — which transport selection
8812
+ * rethrows unwrapped so callers can branch on it and the keep-alive redial loop can park. A
8813
+ * reject without an id (an older peer,
8599
8814
  * whose frames never carry one) becomes `handshake_rejected` — same message text, now typed, so
8600
8815
  * `classifyConnectFailure` can tell "the backend said no" from "wrong address" (feedback W3).
8601
8816
  */
8602
8817
  function handshakeRejectError(stage, rejectFrame) {
8603
8818
  if (rejectFrame.id === "identity_pin_mismatch") return err_wire_connect.fromId("identity_pin_mismatch", { reason: rejectFrame.reason });
8819
+ if (rejectFrame.id === "protocol_version_mismatch") {
8820
+ const observedProtocolVersion = sanitizeVersions(rejectFrame.observedProtocolVersion == null ? void 0 : [rejectFrame.observedProtocolVersion])?.[0];
8821
+ return err_wire_connect.fromId("protocol_version_mismatch", {
8822
+ reason: rejectFrame.reason,
8823
+ observedProtocolVersion,
8824
+ localSupportedProtocolVersions: [...WIRE_SUPPORTED_PROTOCOL_VERSIONS],
8825
+ remoteSupportedProtocolVersions: sanitizeVersions(rejectFrame.supportedProtocolVersions)
8826
+ });
8827
+ }
8604
8828
  return err_wire_connect.fromId("handshake_rejected", {
8605
8829
  stage,
8606
8830
  reason: rejectFrame.reason
@@ -8624,7 +8848,7 @@ function wrongHandshakeFrame(channel, expected, receivedKind) {
8624
8848
  const KEEPALIVE_PING$1 = "ping";
8625
8849
  const KEEPALIVE_PONG$1 = "pong";
8626
8850
  /** One keepalive loop per live link — created by the session, stopped with it. */
8627
- function startLinkKeepalive(channel, config, tap) {
8851
+ function startHeartbeat(channel, config, tap) {
8628
8852
  let lastInboundAt = Date.now();
8629
8853
  let pingSentAt;
8630
8854
  let timer;
@@ -8720,11 +8944,11 @@ function establishPlainDuplexSession(ctx) {
8720
8944
  const pipe = makePipe(channel, void 0, tap);
8721
8945
  const port = makeLanePort(channel, pipe);
8722
8946
  const mux = ctx.mux;
8723
- const keepalive = ctx.keepalive != null ? startLinkKeepalive(channel, ctx.keepalive, tap) : void 0;
8724
- if (keepalive != null) disconnectListeners.push(keepalive.stop);
8947
+ const heartbeat = ctx.heartbeat != null ? startHeartbeat(channel, ctx.heartbeat, tap) : void 0;
8948
+ if (heartbeat != null) disconnectListeners.push(heartbeat.stop);
8725
8949
  channel.attach({
8726
8950
  onMessage: (frame) => {
8727
- keepalive?.noteInbound();
8951
+ heartbeat?.noteInbound();
8728
8952
  if (frame === KEEPALIVE_PONG$1) {
8729
8953
  tap?.({
8730
8954
  dir: "in",
@@ -8763,11 +8987,11 @@ async function establishSecureDuplexSession(ctx) {
8763
8987
  const handshakeWaiters = [];
8764
8988
  const pendingFrames = [];
8765
8989
  let nonProtocolFrame;
8766
- let keepalive;
8990
+ let heartbeat;
8767
8991
  const mux = ctx.mux;
8768
8992
  channel.attach({
8769
8993
  onMessage: (frame) => {
8770
- keepalive?.noteInbound();
8994
+ heartbeat?.noteInbound();
8771
8995
  if (frame === KEEPALIVE_PONG$1) {
8772
8996
  tap?.({
8773
8997
  dir: "in",
@@ -8833,9 +9057,9 @@ async function establishSecureDuplexSession(ctx) {
8833
9057
  active = true;
8834
9058
  for (const frame of pendingFrames) await handleIncomingFrame(pipe, frame, mux, ctx.lane, port, tap);
8835
9059
  pendingFrames.length = 0;
8836
- if (ctx.keepalive != null) {
8837
- keepalive = startLinkKeepalive(channel, ctx.keepalive, tap);
8838
- disconnectListeners.push(keepalive.stop);
9060
+ if (ctx.heartbeat != null) {
9061
+ heartbeat = startHeartbeat(channel, ctx.heartbeat, tap);
9062
+ disconnectListeners.push(heartbeat.stop);
8839
9063
  }
8840
9064
  return makeSession$1(channel, pipe, disconnectListeners, remoteCaps);
8841
9065
  }
@@ -8890,6 +9114,7 @@ async function runClientHandshake(ctx, nextHandshakeMessage) {
8890
9114
  const handshake = createClientHandshake({
8891
9115
  link: secure.link,
8892
9116
  localCoordinate: secure.localCoordinate,
9117
+ expectedPeer: secure.expectedPeer,
8893
9118
  dictionaryVersion: handshakeConfig.dictionaryVersion,
8894
9119
  securityLevel: secure.securityLevel,
8895
9120
  channelTags: handshakeConfig.channels,
@@ -8943,7 +9168,7 @@ let transportOrd = 0;
8943
9168
  /**
8944
9169
  * Live, per-handler transport runtime built from a reusable transport definition. Holds the
8945
9170
  * connection-scoped state (ordinal, initialized config, sockets / abort sets) that must not be shared
8946
- * across handlers. Moved from nice-action (shared-base-connect plan, Phase 2) with the action types
9171
+ * across handlers. Moved from nice-action with the action types
8947
9172
  * inverted into generics: `RP` (per-dispatch routing params), `RD` (the raw ready-data a definition
8948
9173
  * yields), and `METHODS` (the finalized send surface subclasses build) are opaque to wire.
8949
9174
  */
@@ -8988,7 +9213,7 @@ var TransportConnection$1 = class {
8988
9213
  return this._finalizeTransportMethods(readyData);
8989
9214
  }
8990
9215
  _getCacheKey(input) {
8991
- const parts = this.initialized.getTransportCacheKey?.(input);
9216
+ const parts = this.initialized.getCacheKey?.(input);
8992
9217
  if (parts == null) return null;
8993
9218
  return parts.join("\0");
8994
9219
  }
@@ -9138,56 +9363,60 @@ var WireProtocolMux = class {
9138
9363
  //#endregion
9139
9364
  //#region ../nice-wire/src/Connect/wireConnectionParts.ts
9140
9365
  /** 8b.3 defaults: ≈20 s worst-case half-open detection, quiet enough for a healthy idle tab. */
9141
- const DEFAULT_LINK_KEEPALIVE_IDLE_MS = 15e3;
9142
- const DEFAULT_LINK_KEEPALIVE_PONG_TIMEOUT_MS = 5e3;
9366
+ const DEFAULT_HEARTBEAT_IDLE_MS = 15e3;
9367
+ const DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS = 5e3;
9143
9368
  const ephemeralIdentityWarned = /* @__PURE__ */ new Set();
9144
9369
  /**
9145
- * The ephemeral-identity trap (Inteleport feedback §1): a coordinate with a persistent id whose
9370
+ * The ephemeral-identity trap: a coordinate with a persistent id whose
9146
9371
  * crypto identity lives in non-durable storage keys the peer's trust-on-first-use verify-key pin but
9147
9372
  * regenerates a new key on every reload — so every reload after the first is rejected
9148
9373
  * `identity_pin_mismatch`, forever. It type-checks and the first load works, so nothing else surfaces
9149
9374
  * it. Warn once per pinned identity (module-global dedupe — one warning per identity per process, not
9150
- * per connection). `durable === undefined` (a custom adapter) stays silent; a deliberately
9375
+ * per connection). Both `durable === false` and unknown durability are warning-worthy; a deliberately
9151
9376
  * per-session id opts out with `ephemeralIdentity: true`. Shared by every dial-out entry point
9152
9377
  * (`createWireClient`, `connectChannel`), so the check lives once.
9153
9378
  */
9154
9379
  function warnOnEphemeralPinnedIdentity(callerName, coordinate, storage) {
9155
- if (storage.durable !== false || coordinate.perId == null) return;
9380
+ if (storage.durable === true || coordinate.perId == null) return;
9156
9381
  const pinKey = `${coordinate.envId}::${coordinate.perId}`;
9157
9382
  if (ephemeralIdentityWarned.has(pinKey)) return;
9158
9383
  ephemeralIdentityWarned.add(pinKey);
9159
- console.warn(`${callerName}: the runtime coordinate [${pinKey}] carries a persistent id, which keys the peer's trust-on-first-use verify-key pin — but the \`storage\` passed here is not durable (memory/session-backed), so this client's crypto identity regenerates on every reload. The peer will pin the first key it sees and reject every reconnect after the first reload (identity_pin_mismatch). Back the connection with a durable adapter (e.g. createWebLocalStorageAdapter) that persists at least as long as the persistent id, or set \`ephemeralIdentity: true\` if the id is minted fresh per session. Memory adapters are for tests.`);
9384
+ console.warn(`${callerName}: the runtime coordinate [${pinKey}] carries a persistent id, which keys the peer's trust-on-first-use verify-key pin — but the \`storage\` passed here is not known to be durable, so this client's crypto identity may regenerate on reload. The peer will pin the first key it sees and reject every reconnect after the first reload (identity_pin_mismatch). Back the connection with a durable adapter (e.g. createWebLocalStorageAdapter) that persists at least as long as the persistent id, or set \`ephemeralIdentity: true\` if the id is minted fresh per session. Memory adapters are for tests.`);
9160
9385
  }
9161
9386
  /**
9162
9387
  * Assemble the connection facts a dial-out entry point shares — the one implementation of "how a
9163
9388
  * wire connection's mux, crypto identity, keepalive, and traffic tap are set up" (first-production
9164
- * plan Phase 1.6). `createWireClient` and `connectChannel` both call this; each then builds its own
9389
+ * the connection design). `createWireClient` and `connectChannel` both call this; each then builds its own
9165
9390
  * transports (mux-only `WireLinkConnection`s vs action `Transport`s with the codec lane) around the
9166
9391
  * shared result, so a fix to any of these lands once.
9167
9392
  */
9168
9393
  function assembleWireConnectionParts(options) {
9169
9394
  const mux = options.mux ?? new WireProtocolMux();
9395
+ if (options.reconnect != null && options.keepLinkAlive != null) throw err_wire_connect.fromId("conflicting_connect_options", { detail: `${options.callerName}: pass only \`reconnect\`; \`keepLinkAlive\` is deprecated` });
9396
+ if (options.heartbeat != null && options.linkKeepalive != null) throw err_wire_connect.fromId("conflicting_connect_options", { detail: `${options.callerName}: pass only \`heartbeat\`; \`linkKeepalive\` is deprecated` });
9397
+ const reconnect = options.reconnect ?? options.keepLinkAlive;
9398
+ const heartbeat = options.heartbeat ?? options.linkKeepalive;
9170
9399
  for (const protocol of options.protocols ?? []) mux.registerProtocol(protocol);
9171
9400
  let link = options.link;
9172
9401
  if (options.anySecure && link == null) {
9173
- 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.`);
9174
- if (options.ephemeralIdentity !== true) warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);
9175
- link = new ClientCryptoKeyLink({ storageAdapter: options.storage });
9176
- }
9177
- const resolveLinkKeepalive = () => {
9178
- if (options.linkKeepalive === false) return void 0;
9179
- const explicit = options.linkKeepalive;
9180
- if (!(explicit != null || options.keepLinkAlive === true || options.keepLinkAlive !== false && mux.localCaps().length > 0)) return void 0;
9402
+ if (options.storage == null && options.ephemeralIdentity !== true) throw new Error(`${options.callerName}: a secure transport requires \`storage\` (or \`link\`) for the crypto identity. Pass it, declare a per-session identity with \`ephemeralIdentity: true\`, or set \`secure: false\` on the carrier for a plain connection.`);
9403
+ if (options.storage != null && options.ephemeralIdentity !== true) warnOnEphemeralPinnedIdentity(options.callerName, options.identity, options.storage);
9404
+ link = new ClientCryptoKeyLink(options.storage != null ? { storageAdapter: options.storage } : {});
9405
+ }
9406
+ const resolveHeartbeat = () => {
9407
+ if (heartbeat === false) return void 0;
9408
+ const explicit = heartbeat;
9409
+ if (!(explicit != null || reconnect === true || reconnect !== false && mux.localCaps().length > 0)) return void 0;
9181
9410
  return {
9182
- idleMs: explicit?.idleMs ?? DEFAULT_LINK_KEEPALIVE_IDLE_MS,
9183
- pongTimeoutMs: explicit?.pongTimeoutMs ?? DEFAULT_LINK_KEEPALIVE_PONG_TIMEOUT_MS
9411
+ idleMs: explicit?.idleMs ?? DEFAULT_HEARTBEAT_IDLE_MS,
9412
+ pongTimeoutMs: explicit?.pongTimeoutMs ?? DEFAULT_HEARTBEAT_PONG_TIMEOUT_MS
9184
9413
  };
9185
9414
  };
9186
9415
  const wireTap = options.wireTap != null ? withLinkIdTap(options.wireTap, options.peer.stringId) : void 0;
9187
9416
  return {
9188
9417
  mux,
9189
9418
  link,
9190
- resolveLinkKeepalive,
9419
+ resolveHeartbeat,
9191
9420
  wireTap
9192
9421
  };
9193
9422
  }
@@ -9298,6 +9527,7 @@ async function runConnectorExchangeHandshake(carrier, secure, lane) {
9298
9527
  const handshake = createClientHandshake({
9299
9528
  link: secure.link,
9300
9529
  localCoordinate: secure.localCoordinate,
9530
+ expectedPeer: secure.expectedPeer,
9301
9531
  dictionaryVersion: lane.dictionaryVersion,
9302
9532
  securityLevel: secure.securityLevel,
9303
9533
  channelTags: lane.channels
@@ -9522,7 +9752,7 @@ var AcceptorSecureSession = class {
9522
9752
  //#endregion
9523
9753
  //#region ../nice-wire/src/Connect/WireAcceptor.ts
9524
9754
  /**
9525
- * Wire-level keepalive (plan §6.1): the acceptor answers a literal `"ping"` text frame with
9755
+ * Wire-level keepalive: the acceptor answers a literal `"ping"` text frame with
9526
9756
  * `"pong"` before any other dispatch, so connection health never involves the lane or a protocol.
9527
9757
  * On Cloudflare the DO host answers it below this layer (`setWebSocketAutoResponse`) and the frame
9528
9758
  * never reaches {@link WireAcceptor.receive} — this path makes every other host behave the same.
@@ -9530,12 +9760,12 @@ var AcceptorSecureSession = class {
9530
9760
  const KEEPALIVE_PING = "ping";
9531
9761
  const KEEPALIVE_PONG = "pong";
9532
9762
  /**
9533
- * The acceptor backbone (plan Phase 4, §3.1): everything between "an inbound frame arrived on a
9763
+ * The acceptor backbone: everything between "an inbound frame arrived on a
9534
9764
  * connection" and "a protocol module (or the lane) may handle it" — handshake accept +
9535
9765
  * secure-session-per-connection, security levels, the client-identity registry, the protocol
9536
- * registry with prefix dispatch, the **security gate** (review A.6: protocol traffic requires an
9766
+ * registry with prefix dispatch, the **security gate** (the connection contract: protocol traffic requires an
9537
9767
  * authenticated connection unless the protocol opts into `allowPlain`), the **un-gated lifecycle
9538
- * fan-out** (review A.2.3: attach/detach fire for every registered protocol the gate admits, not
9768
+ * fan-out** (the connection contract: attach/detach fire for every registered protocol the gate admits, not
9539
9769
  * just the caps-advertised ones — both hooks are idempotent by contract, so a missing cap is a
9540
9770
  * non-event instead of a silent liveness hole), the versioned {@link IWireConnectionBinding}
9541
9771
  * persistence + {@link rehydrate} (hibernation), and the wire keepalive.
@@ -9592,6 +9822,16 @@ var WireAcceptor = class {
9592
9822
  this._receivePlain(connection, frame, wireBytes);
9593
9823
  return;
9594
9824
  }
9825
+ if (!this._sessionByConn.has(connection)) {
9826
+ const prefix = peekProtocolPrefix(frame);
9827
+ const protocol = prefix == null ? void 0 : this._protocols.get(prefix);
9828
+ if (protocol?.allowPlain === true) {
9829
+ this._tapIn(connection, wireBytes, protocol.id);
9830
+ const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame);
9831
+ protocol.onFrame(connection, bytes.subarray(1), this.protocolSendFor(connection, protocol), this._protocolContext(connection));
9832
+ return;
9833
+ }
9834
+ }
9595
9835
  this._sessionFor(connection, security).receive(frame, wireBytes);
9596
9836
  }
9597
9837
  _receivePlain(connection, frame, wireBytes = 0) {
@@ -9687,7 +9927,7 @@ var WireAcceptor = class {
9687
9927
  return true;
9688
9928
  }
9689
9929
  const bytes = frame instanceof Uint8Array ? frame : new Uint8Array(frame);
9690
- protocol.onFrame(connection, bytes.subarray(1), this.protocolSendFor(connection, protocol));
9930
+ protocol.onFrame(connection, bytes.subarray(1), this.protocolSendFor(connection, protocol), this._protocolContext(connection));
9691
9931
  return true;
9692
9932
  }
9693
9933
  /**
@@ -9701,7 +9941,7 @@ var WireAcceptor = class {
9701
9941
  this._protoIdsByConn.set(connection, advertisedIds);
9702
9942
  for (const protocol of this._protocols.values()) {
9703
9943
  if (!this._gateAdmits(connection, protocol)) continue;
9704
- protocol.onAttach?.(connection, this.protocolSendFor(connection, protocol));
9944
+ protocol.onAttach?.(connection, this.protocolSendFor(connection, protocol), this._protocolContext(connection));
9705
9945
  }
9706
9946
  }
9707
9947
  /**
@@ -9800,6 +10040,8 @@ var WireAcceptor = class {
9800
10040
  this._onConnectionBound?.(connection, binding);
9801
10041
  }
9802
10042
  _bind(connection, client) {
10043
+ const previous = this._clientByConn.get(connection);
10044
+ if (previous != null && previous.stringId !== client.stringId && this._connByClient.get(previous.stringId) === connection) this._connByClient.delete(previous.stringId);
9803
10045
  this._connByClient.set(client.stringId, connection);
9804
10046
  this._clientByConn.set(connection, client);
9805
10047
  }
@@ -9813,7 +10055,7 @@ var WireAcceptor = class {
9813
10055
  const client = this._clientByConn.get(connection);
9814
10056
  if (client != null && this._connByClient.get(client.stringId) === connection) this._connByClient.delete(client.stringId);
9815
10057
  this._lane.onDrop?.(connection, client);
9816
- for (const protocol of this._protocols.values()) protocol.onDetach?.(connection);
10058
+ for (const protocol of this._protocols.values()) protocol.onDetach?.(connection, this._protocolContext(connection));
9817
10059
  this._protoIdsByConn.delete(connection);
9818
10060
  this._clientByConn.delete(connection);
9819
10061
  this._sessionByConn.delete(connection);
@@ -9859,6 +10101,12 @@ var WireAcceptor = class {
9859
10101
  levelFor(connection) {
9860
10102
  return this._levelByConn.get(connection) ?? "none";
9861
10103
  }
10104
+ _protocolContext(connection) {
10105
+ return {
10106
+ client: this._clientByConn.get(connection),
10107
+ level: this._levelByConn.get(connection) ?? "none"
10108
+ };
10109
+ }
9862
10110
  /** The last persisted (or rehydrated) binding for a connection, if any. */
9863
10111
  bindingFor(connection) {
9864
10112
  return this._bindingByConn.get(connection);
@@ -9932,7 +10180,7 @@ const textEncoder = new TextEncoder();
9932
10180
  const textDecoder = new TextDecoder();
9933
10181
  /**
9934
10182
  * The exchange (request/reply) acceptor backbone — the HTTP counterpart to `WireAcceptor`'s
9935
- * duplex sessions, re-homed from nice-action's `ExchangeAcceptor` (shared-base-connect plan,
10183
+ * duplex sessions, re-homed from nice-action's `ExchangeAcceptor` (shared connection design,
9936
10184
  * Phase 6). Each POST body is one exchange envelope; the acceptor drives the server handshake
9937
10185
  * over the two `hs` POSTs, mints a session **token** on accept, and on every later `act` POST
9938
10186
  * resolves the session by token, decrypts the body (at `encrypted`), hands the opened lane wire
@@ -10565,6 +10813,7 @@ var ActionContext = class extends ActionBase {
10565
10813
  * the sending side. Never serialized (see {@link IHandledReliability}).
10566
10814
  */
10567
10815
  reliability;
10816
+ _receiverMetadata;
10568
10817
  constructor(_domain, id, hydrationData) {
10569
10818
  super("context", _domain, id);
10570
10819
  this._domain = _domain;
@@ -10572,7 +10821,25 @@ var ActionContext = class extends ActionBase {
10572
10821
  this.cuid = hydrationData.cuid;
10573
10822
  this._routing = hydrationData.routing;
10574
10823
  this.originClient = hydrationData.originClient;
10575
- this.reliability = hydrationData.reliability;
10824
+ this.reliability = void 0;
10825
+ }
10826
+ /** @internal Installed by the receiving runtime from out-of-band transport facts. */
10827
+ _setReceiverMetadata(metadata) {
10828
+ Object.defineProperty(this, "_receiverMetadata", {
10829
+ configurable: true,
10830
+ enumerable: false,
10831
+ value: metadata,
10832
+ writable: true
10833
+ });
10834
+ Object.defineProperty(this, "reliability", {
10835
+ configurable: true,
10836
+ enumerable: false,
10837
+ value: metadata.reliability
10838
+ });
10839
+ }
10840
+ /** @internal Read only by the acceptor that owns the arrival. */
10841
+ _getReceiverMetadata() {
10842
+ return this._receiverMetadata;
10576
10843
  }
10577
10844
  _setOriginClient(client) {
10578
10845
  this.originClient = client;
@@ -10801,7 +11068,6 @@ var ActionPayload_Request = class extends ActionPayload {
10801
11068
  return (await this.runToResultPayload(options)).result;
10802
11069
  }
10803
11070
  async run(options) {
10804
- if (this._callSite == null) this._callSite = (/* @__PURE__ */ new Error()).stack;
10805
11071
  return this._domain.runAction(this, options);
10806
11072
  }
10807
11073
  };
@@ -11136,9 +11402,15 @@ const err_nice_action = err_nice.createChildDomain({
11136
11402
  ["no_action_execution_handler"]: err({ message: ({ domain, actionId, specifiedClient }) => `${specifiedClient ? ` The targeted client runtime [${specifiedClient.stringId}] has no` : "No"} action handler registered for "${actionId}" in domain "${domain}".` }),
11137
11403
  ["wire_action_not_payload"]: err({ message: ({ domain, actionId, actionState }) => `Cannot handle wire for action "${actionId}" in domain "${domain}": expected action form of "data" and type of "request", "progress" or "result", got "${actionState}".` }),
11138
11404
  ["wire_not_action_data"]: err({ message: () => `Cannot handle wire for action: expected an object with a "domain" property of type string, a "form" property of "data" and a "type" property of "request", "progress" or "result".` }),
11405
+ ["connection_required"]: err({ message: ({ operation }) => `Cannot ${operation}: this action did not arrive on a live duplex connection.` }),
11139
11406
  ["runtime_reset"]: err({ message: () => `Runtime has been reset.` }),
11140
- ["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.` }),
11141
- ["client_runtime_not_registered"]: err({ message: ({ context, clientStringId }) => `No runtime registered${context?.domain ? ` on domain "${context.domain}"` : ""} for client [${clientStringId}].` }),
11407
+ ["runtime_disposed"]: err({ message: ({ runtime }) => `Action runtime [${runtime}] has been disposed and cannot be reused.` }),
11408
+ ["ambiguous_action_runtime"]: err({ message: ({ domain, actionId, runtimes }) => `Several runtimes can execute "${domain}:${actionId}" (${runtimes.join(", ")}). Target one explicitly with runtime.run(request) or request.run({ targetLocalRuntime: runtime }).` }),
11409
+ ["invalid_server_runtime_scope"]: err({ message: ({ runtime, actualScope }) => `Server runtime [${runtime}] has scope "${actualScope}". Server hosts require new ActionRuntime(identity, { scope: "instance" }) so isolate-local instances never enter global dispatch.` }),
11410
+ ["conflicting_server_options"]: err({ message: ({ detail }) => `Invalid server construction options: ${detail}` }),
11411
+ ["conflicting_connect_options"]: err({ message: ({ detail }) => `Invalid connection options: ${detail}` }),
11412
+ ["duplicate_action_executor"]: err({ message: ({ route }) => `More than one local executor was registered for the same route priority (${route}). Keep one executor at that exact route; an action-specific executor may still override a domain fallback.` }),
11413
+ ["peer_handler_already_bound"]: err({ message: () => `A stateful peer handler is already bound to another runtime. Create one connector or acceptor per runtime.` }),
11142
11414
  ["no_client_runtimes_registered"]: err({ message: ({ context }) => `No runtimes registered${context?.domain ? ` on domain "${context.domain}"` : ""}. Add handlers to a runtime via runtime.addHandlers([handler]) before executing actions.` }),
11143
11415
  ["action_input_validation_failed"]: err({
11144
11416
  message: ({ domain, actionId, validationMessage }) => `Input validation failed for action "${actionId}" in domain "${domain}":\n${validationMessage}`,
@@ -12662,6 +12934,12 @@ const actionSchema = () => {
12662
12934
  return new ActionSchema();
12663
12935
  };
12664
12936
  //#endregion
12937
+ //#region ../nice-action/src/diagnostics/callSite.ts
12938
+ /** Capture a diagnostic caller stack. Callers must apply the opt-in policy before invoking this. */
12939
+ function captureDiagnosticCallSite() {
12940
+ return (/* @__PURE__ */ new Error()).stack;
12941
+ }
12942
+ //#endregion
12665
12943
  //#region ../../node_modules/std-env/dist/index.mjs
12666
12944
  const e = globalThis.process?.env || Object.create(null), t$1 = globalThis.process || { env: e }, n = t$1 !== void 0 && t$1.env && t$1.env.NODE_ENV || void 0, r = [
12667
12945
  [`claude`, [`CLAUDECODE`, `CLAUDE_CODE`]],
@@ -12903,10 +13181,10 @@ const err_nice_transport = err_nice_action.createChildDomain({
12903
13181
  //#region ../nice-action/src/ActionRuntime/Transport/ConnectionTransportManager.ts
12904
13182
  /**
12905
13183
  * Preference-ordered transport selection for action dispatch — wire's generic
12906
- * `ConnectionTransportManager` (shared-base-connect plan, Phase 2) pinned to the action routing
13184
+ * `ConnectionTransportManager` pinned to the action routing
12907
13185
  * params + methods, with the selection failures expressed in action's own `err_nice_transport`
12908
13186
  * vocabulary (the exact errors thrown before the move). An actionless dial
12909
- * (`ChannelConnector.connect()`, review A.1) reports as `"connect()"` in the failure messages.
13187
+ * (`ChannelConnector.connect()`, the connection contract) reports as `"connect()"` in the failure messages.
12910
13188
  */
12911
13189
  var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
12912
13190
  constructor(cache) {
@@ -12926,16 +13204,22 @@ var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
12926
13204
  //#region ../nice-action/src/ActionRuntime/ActionDomainManager.ts
12927
13205
  var ActionDomainManager = class {
12928
13206
  _domains = /* @__PURE__ */ new Map();
12929
- addDomain(domain) {
13207
+ assertCanAddDomain(domain) {
12930
13208
  const existing = this._domains.get(domain.domain);
12931
- if (existing === domain) return;
13209
+ if (existing === domain || existing == null) return;
12932
13210
  if (existing != null) throw err_nice_action.fromId("domain_name_collision", {
12933
13211
  domain: domain.domain,
12934
13212
  existingParentDomains: existing.allDomains,
12935
13213
  incomingParentDomains: domain.allDomains
12936
13214
  });
13215
+ }
13216
+ addDomain(domain) {
13217
+ this.assertCanAddDomain(domain);
12937
13218
  this._domains.set(domain.domain, domain);
12938
13219
  }
13220
+ removeDomain(domain) {
13221
+ if (this._domains.get(domain.domain) === domain) this._domains.delete(domain.domain);
13222
+ }
12939
13223
  getDomains() {
12940
13224
  return [...this._domains.values()];
12941
13225
  }
@@ -12973,6 +13257,7 @@ var ActionRouter = class {
12973
13257
  for (const [matchKey, routeDataEntries] of actionRouter.actionRouteData.entries()) this.actionRouteData.set(matchKey, [...routeDataEntries]);
12974
13258
  }
12975
13259
  addDomainsFromOther(actionRouter) {
13260
+ for (const domain of actionRouter.getDomains()) this.domainManager.assertCanAddDomain(domain);
12976
13261
  for (const domain of actionRouter.getDomains()) this.domainManager.addDomain(domain);
12977
13262
  }
12978
13263
  /** All FNs registered for an action, ID-specific entries first then domain wildcard. */
@@ -13084,6 +13369,19 @@ var ActionRouter = class {
13084
13369
  this._push(key, routeData);
13085
13370
  return this;
13086
13371
  }
13372
+ /** Remove one route-data object from every key; used by scoped installation teardown. */
13373
+ removeRouteData(routeData) {
13374
+ for (const [key, entries] of this.actionRouteData) {
13375
+ const remaining = entries.filter((entry) => entry !== routeData);
13376
+ if (remaining.length === 0) this.actionRouteData.delete(key);
13377
+ else if (remaining.length !== entries.length) this.actionRouteData.set(key, remaining);
13378
+ }
13379
+ const registeredKeys = [...this.actionRouteData.keys()];
13380
+ for (const domain of this.domainManager.getDomains()) {
13381
+ const prefix = `dom[${domain.domain}]id[`;
13382
+ if (!registeredKeys.some((key) => key.startsWith(prefix))) this.domainManager.removeDomain(domain);
13383
+ }
13384
+ }
13087
13385
  _push(key, routeData) {
13088
13386
  const existing = this.actionRouteData.get(key);
13089
13387
  if (existing != null) existing.push(routeData);
@@ -13093,9 +13391,10 @@ var ActionRouter = class {
13093
13391
  //#endregion
13094
13392
  //#region ../nice-action/src/ActionRuntime/Handler/ActionHandler.ts
13095
13393
  var ActionHandler = class {
13096
- cuid;
13097
- constructor() {
13098
- this.cuid = nanoid();
13394
+ _cuid;
13395
+ get cuid() {
13396
+ this._cuid ??= nanoid();
13397
+ return this._cuid;
13099
13398
  }
13100
13399
  getActionRouter() {
13101
13400
  return this.actionRouter;
@@ -13118,17 +13417,22 @@ var ActionHandler = class {
13118
13417
  */
13119
13418
  var PeerLink = class extends ActionHandler {
13120
13419
  /** The peer runtime this handler links to (an env-only coordinate for an accept-in handler). */
13121
- peerClient;
13420
+ peer;
13122
13421
  handlerType = "peer";
13123
13422
  actionRouter = new ActionRouter({
13124
13423
  contextType: "handler_route",
13125
13424
  handler: this
13126
13425
  });
13127
13426
  /** Listeners installed by the runtime (`resolveIncomingActionPayload`) for inbound peer frames. */
13128
- _incomingActionDataListeners = [];
13427
+ _incomingRuntime;
13428
+ _incomingActionDataListener;
13129
13429
  constructor(peerCoordinate) {
13130
13430
  super();
13131
- this.peerClient = peerCoordinate;
13431
+ this.peer = peerCoordinate;
13432
+ }
13433
+ /** @deprecated Use {@link peer}. */
13434
+ get peerClient() {
13435
+ return this.peer;
13132
13436
  }
13133
13437
  forDomain(domain) {
13134
13438
  this.actionRouter.forDomain(domain, true);
@@ -13142,12 +13446,19 @@ var PeerLink = class extends ActionHandler {
13142
13446
  this.actionRouter.forActionIds(domain, ids, true);
13143
13447
  return this;
13144
13448
  }
13145
- _setIncomingActionDataListener(listener) {
13146
- this._incomingActionDataListeners.push(listener);
13449
+ _setIncomingActionDataListener(runtime, listener) {
13450
+ if (this._incomingRuntime != null && this._incomingRuntime !== runtime) throw err_nice_action.fromId("peer_handler_already_bound");
13451
+ this._incomingRuntime = runtime;
13452
+ this._incomingActionDataListener = listener;
13453
+ return () => {
13454
+ if (this._incomingRuntime !== runtime || this._incomingActionDataListener !== listener) return;
13455
+ this._incomingRuntime = void 0;
13456
+ this._incomingActionDataListener = void 0;
13457
+ };
13147
13458
  }
13148
13459
  /** Hand a decoded inbound frame to the runtime (called by each specialization's receive path). */
13149
- _emitIncoming(json) {
13150
- for (const listener of this._incomingActionDataListeners) listener(json);
13460
+ _emitIncoming(json, metadata) {
13461
+ this._incomingActionDataListener?.(json, metadata);
13151
13462
  }
13152
13463
  /**
13153
13464
  * Whether this handler currently holds a *live* connection bound to `origin`. The runtime's return-path
@@ -13394,7 +13705,7 @@ var ChannelConnector = class extends PeerLink {
13394
13705
  return this._wire.wireMux;
13395
13706
  }
13396
13707
  /**
13397
- * The re-dial hook a realm client rides (DESYNC F6 / Phase 8a — the `IRealmWireLink` seam):
13708
+ * The re-dial hook a realm client rides:
13398
13709
  * `realmConnection(connector)` hands it to the engine as `requestReconnect`, invoked on an
13399
13710
  * unanswered staleness probe.
13400
13711
  */
@@ -13438,30 +13749,30 @@ var ChannelConnector = class extends PeerLink {
13438
13749
  _controlMethods;
13439
13750
  /** Stream-level reliable-delivery observers (see {@link TReliableStreamEvent}). */
13440
13751
  _reliableEventListeners = /* @__PURE__ */ new Set();
13441
- constructor({ runtimeCoordinate: peerSpecifier, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, connectionIdentity, securityLevel, keepLinkAlive }) {
13442
- super(peerSpecifier);
13752
+ constructor({ peer, runtimeCoordinate, transports, defaultTimeout, reliableActionTimeout, wireMux, localCoordinate, connectionIdentity, securityLevel, reconnect, keepLinkAlive }) {
13753
+ super(peer ?? runtimeCoordinate);
13443
13754
  this._connectionIdentity = connectionIdentity;
13444
13755
  this._defaultTimeout = defaultTimeout ?? 1e4;
13445
13756
  this._reliableTimeout = reliableActionTimeout ?? DEFAULT_RELIABLE_ACTION_TIMEOUT;
13446
13757
  this._wire = new WireClient({
13447
13758
  createManager: (cache) => new ConnectionTransportManager(cache),
13448
13759
  mux: wireMux,
13449
- peer: this.peerClient,
13760
+ peer: this.peer,
13450
13761
  localCoordinate: connectionIdentity ?? localCoordinate,
13451
13762
  securityLevel,
13452
13763
  canPush: transports.some((transport) => transport.type === "duplex"),
13453
- keepLinkAlive,
13764
+ reconnect: reconnect ?? keepLinkAlive,
13454
13765
  buildConnectInput: (pair) => pair,
13455
13766
  defaultLocalCoordinate: () => ActionRuntime.getDefault().coordinate
13456
13767
  });
13457
13768
  for (const transport of transports) {
13458
13769
  const connection = transport._createConnection({ resolvers: {
13459
13770
  onIncomingActionDataJson: (json, reliability) => {
13460
- if (reliability?.ack != null) this._applyAck(reliableStreamId(this.peerClient, json.domain, json.id, reliability.streamKey), reliability.ack);
13771
+ if (reliability?.ack != null) this._applyAck(reliableStreamId(this.peer, json.domain, json.id, reliability.streamKey), reliability.ack);
13461
13772
  this._emitIncoming(json);
13462
13773
  },
13463
13774
  onControlMessage: (message) => {
13464
- const streamId = reliableStreamId(this.peerClient, message.domain, message.id, message.k);
13775
+ const streamId = reliableStreamId(this.peer, message.domain, message.id, message.k);
13465
13776
  if (message.$c === "rack") this._applyAck(streamId, message.ack);
13466
13777
  else if (message.$c === "rsync") {
13467
13778
  this._streamSkips.delete(streamId);
@@ -13488,7 +13799,7 @@ var ChannelConnector = class extends PeerLink {
13488
13799
  await this._wire.connect({ localCoordinate: this._connectionIdentity ?? config?.targetLocalRuntime?.coordinate });
13489
13800
  }
13490
13801
  /**
13491
- * Tear down the (possibly half-open) duplex link and immediately re-dial it (DESYNC F6 / Phase
13802
+ * Tear down the (possibly half-open) duplex link and immediately re-dial it (the reconnect contract / Phase
13492
13803
  * 8b) — surfaced to a realm client as `requestReconnect`, called by the staleness-probe
13493
13804
  * escalation. **Awaitable** — resolves when the fresh link's handshake completes.
13494
13805
  */
@@ -13509,11 +13820,11 @@ var ChannelConnector = class extends PeerLink {
13509
13820
  if (this._connectionIdentity != null) action.context._setOriginClient(this._connectionIdentity);
13510
13821
  const incomingTimeout = config?.timeout ?? this._defaultTimeout;
13511
13822
  const parentCuid = peekHandlerCuid();
13512
- const callSite = action._callSite ?? (/* @__PURE__ */ new Error()).stack;
13823
+ const callSite = localRuntime._captureActionCallSite(action, config?.captureCallSites);
13513
13824
  const routeParams = {
13514
13825
  action,
13515
13826
  localClient,
13516
- externalClient: this.peerClient
13827
+ externalClient: this.peer
13517
13828
  };
13518
13829
  const preferredTransport = this._wire.getPreferredTransport();
13519
13830
  const routeItem = preferredTransport != null ? {
@@ -13531,7 +13842,7 @@ var ChannelConnector = class extends PeerLink {
13531
13842
  localRuntime.registerRunningAction(runningAction);
13532
13843
  if (action.schema.reliabilityTier !== "none") {
13533
13844
  const streamKey = config?.streamKey;
13534
- const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);
13845
+ const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);
13535
13846
  const prepared = this._outbox.prepare(streamId, () => {
13536
13847
  if (runningAction.isAborted) return;
13537
13848
  this._dispatchWhenTransportReady(runningAction, routeParams, routeItem, incomingTimeout);
@@ -13764,7 +14075,7 @@ var ChannelConnector = class extends PeerLink {
13764
14075
  * normal mid-stream re-sync. Closing a stream this connection never sent on is a no-op.
13765
14076
  */
13766
14077
  closeReliableStream(action, streamKey) {
13767
- const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);
14078
+ const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);
13768
14079
  const highest = this._outbox.highestSeq(streamId);
13769
14080
  if (highest == null) return;
13770
14081
  const reason = err_nice_transport.fromId("reliable_stream_closed", {
@@ -13790,7 +14101,7 @@ var ChannelConnector = class extends PeerLink {
13790
14101
  }
13791
14102
  reliablePending(action, streamKey) {
13792
14103
  if (action == null) return this._outbox.size;
13793
- const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);
14104
+ const streamId = reliableStreamId(this.peer, action.domain, action.id, streamKey);
13794
14105
  const oldest = this._outbox.oldestPreparedAt(streamId);
13795
14106
  return {
13796
14107
  unackedCount: this._outbox.pendingCount(streamId),
@@ -13811,12 +14122,12 @@ var ChannelConnector = class extends PeerLink {
13811
14122
  const { methods } = await this._wire.getReadyTransport({
13812
14123
  action: payload,
13813
14124
  localClient,
13814
- externalClient: this.peerClient
14125
+ externalClient: this.peer
13815
14126
  });
13816
14127
  if (methods.sendReturnData == null) return false;
13817
14128
  methods.sendReturnData(payload, {
13818
14129
  localClient,
13819
- externalClient: this.peerClient
14130
+ externalClient: this.peer
13820
14131
  });
13821
14132
  return true;
13822
14133
  } catch {
@@ -13826,13 +14137,13 @@ var ChannelConnector = class extends PeerLink {
13826
14137
  toJsonObject() {
13827
14138
  return {
13828
14139
  type: this.handlerType,
13829
- client: this.peerClient
14140
+ client: this.peer
13830
14141
  };
13831
14142
  }
13832
14143
  toHandlerRouteItem(transport, input) {
13833
14144
  return {
13834
14145
  type: this.handlerType,
13835
- client: this.peerClient,
14146
+ client: this.peer,
13836
14147
  transOrd: transport.transOrd,
13837
14148
  transShape: transport.type,
13838
14149
  transInfo: transport.getRouteInfo(input)
@@ -13840,7 +14151,7 @@ var ChannelConnector = class extends PeerLink {
13840
14151
  }
13841
14152
  /**
13842
14153
  * Stop the keep-alive auto-redial and release the current link — the intention-revealing
13843
- * teardown counterpart of `keepLinkAlive`. Call this when a session is
14154
+ * teardown counterpart of `reconnect`. Call this when a session is
13844
14155
  * over (leaving a match, logging out): the link closes and stays closed until the next explicit
13845
14156
  * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the connector is reusable.
13846
14157
  *
@@ -13864,12 +14175,18 @@ var ActionRuntime = class {
13864
14175
  actionRouter;
13865
14176
  _pendingRunningActions = /* @__PURE__ */ new Map();
13866
14177
  _registeredPeerHandlers = [];
13867
- _applied = false;
14178
+ _registeredRoots = /* @__PURE__ */ new Set();
14179
+ _handlerOwnership = /* @__PURE__ */ new Map();
14180
+ _disposed = false;
14181
+ captureCallSites;
14182
+ scope;
13868
14183
  static getDefault() {
13869
14184
  return getDefaultActionRuntime();
13870
14185
  }
13871
- constructor(coordinate) {
13872
- this._coordinate = coordinate.specifyIfUnset({ insId: nanoid(14) });
14186
+ constructor(coordinate, options = {}) {
14187
+ this._coordinate = coordinate;
14188
+ this.captureCallSites = options.captureCallSites ?? false;
14189
+ this.scope = options.scope ?? "global";
13873
14190
  this.timeCreated = Date.now();
13874
14191
  this.actionRouter = new ActionRouter({
13875
14192
  contextType: "runtime_to_handler",
@@ -13877,34 +14194,57 @@ var ActionRuntime = class {
13877
14194
  });
13878
14195
  }
13879
14196
  get coordinate() {
14197
+ if (this._coordinate.insId == null) this._coordinate = this._coordinate.specify({ insId: nanoid(14) });
13880
14198
  return this._coordinate;
13881
14199
  }
14200
+ get disposed() {
14201
+ return this._disposed;
14202
+ }
14203
+ /** @internal */
14204
+ _assertActive() {
14205
+ if (this._disposed) throw err_nice_action.fromId("runtime_disposed", { runtime: this.coordinate.stringId });
14206
+ }
14207
+ /** @internal Apply the runtime/request diagnostic policy without replacing a supplied stack. */
14208
+ _captureActionCallSite(action, override) {
14209
+ if (action._callSite == null && (override ?? this.captureCallSites)) action._callSite = captureDiagnosticCallSite();
14210
+ return action._callSite;
14211
+ }
13882
14212
  specifyRuntimeCoordinate(specifics) {
14213
+ this._assertActive();
13883
14214
  if (specifics.envId != null && this._coordinate.envId !== specifics.envId) throw err_nice_action.fromId("not_implemented", { label: `updating RuntimeCoordinate with a different "envId" ("${this._coordinate.envId}" → "${specifics.envId}")` });
13884
14215
  this._coordinate = this._coordinate.specify(specifics);
13885
- this.apply();
13886
14216
  }
13887
14217
  registerRunningAction(ra) {
14218
+ this._assertActive();
13888
14219
  this._pendingRunningActions.set(ra.cuid, ra);
13889
14220
  ra.addUpdateListeners([(update) => {
13890
14221
  if (update.type === "finished") this._pendingRunningActions.delete(ra.cuid);
13891
14222
  }]);
13892
14223
  }
13893
- resolveIncomingActionPayload(json) {
14224
+ resolveIncomingActionPayload(json, metadata) {
14225
+ if (this._disposed) return;
13894
14226
  if (json.type === "request") {
13895
- this.handleActionPayloadWire(json).catch((err) => {
14227
+ this._handleActionPayloadWireFromReceiver(json, metadata).catch((err) => {
13896
14228
  console.error(`[ActionRuntime] Incoming action [${json.domain}:${json.id}:${json.form}:${json.type}] unhandled:`, err);
13897
14229
  });
13898
14230
  return;
13899
14231
  }
13900
14232
  this._pendingRunningActions.get(json.context.cuid)?._resolveFromJson(json);
13901
14233
  }
13902
- async handleActionPayloadWire(wire) {
13903
- let action;
13904
- if (isActionPayload_Any_JsonObject(wire)) action = this.actionRouter.domainManager.getActionDomainOrThrow(wire).hydrateAnyAction(wire);
13905
- if (action == null) throw err_nice_action.fromId("wire_not_action_data");
14234
+ /** @internal Hydrate a wire request and attach receiver-owned metadata before application dispatch. */
14235
+ async _handleActionPayloadWireFromReceiver(wire, metadata) {
14236
+ const action = this._hydrateActionPayloadWire(wire);
14237
+ if (metadata != null) action.context._setReceiverMetadata(metadata);
13906
14238
  return this.handleActionPayload(action);
13907
14239
  }
14240
+ _hydrateActionPayloadWire(wire) {
14241
+ if (isActionPayload_Any_JsonObject(wire)) return this.actionRouter.domainManager.getActionDomainOrThrow(wire).hydrateAnyAction(wire);
14242
+ throw err_nice_action.fromId("wire_not_action_data");
14243
+ }
14244
+ async handleActionPayloadWire(wire) {
14245
+ this._assertActive();
14246
+ return this.handleActionPayload(this._hydrateActionPayloadWire(wire));
14247
+ }
13908
14248
  /**
13909
14249
  * The declared {@link EActionResponseMode} for a wire frame's action, looked up from its registered
13910
14250
  * domain — `undefined` if the route isn't registered. Lets a transport decide, without executing the
@@ -13942,6 +14282,7 @@ var ActionRuntime = class {
13942
14282
  }
13943
14283
  }
13944
14284
  async handleActionPayload(action, options) {
14285
+ this._assertActive();
13945
14286
  if (action.type === "request") {
13946
14287
  const observers = action.context._domain._collectActionObservers();
13947
14288
  let handlerForAction;
@@ -13986,26 +14327,17 @@ var ActionRuntime = class {
13986
14327
  * Return the first handler registered for the given action, or `undefined`
13987
14328
  * if none has been registered (action-ID-specific beats domain-wildcard).
13988
14329
  */
13989
- _getHandlerForAction(action, options) {
13990
- const handlers = this.actionRouter.getRouteDataEntriesForAction(action);
13991
- const targetPeer = options?.targetPeer;
13992
- const possibleHandlers = handlers.filter((handler) => {
13993
- if (handler.handlerType === "peer") {
13994
- if (targetPeer && !targetPeer.isSameFor(handler.peerClient).id) return false;
13995
- return true;
13996
- }
13997
- if (targetPeer != null) return false;
13998
- if (action.type === "request") return true;
13999
- return false;
14330
+ _getHandlerForAction(action, _options) {
14331
+ const possibleHandlers = this.actionRouter.getRouteDataEntriesForAction(action).filter((handler) => {
14332
+ return handler.handlerType === "peer" || handler.handlerType === "local" && action.type === "request";
14000
14333
  });
14001
14334
  if (possibleHandlers.length === 0) return;
14002
- const scoringPeer = targetPeer ?? RuntimeCoordinate.unknown;
14003
14335
  let handlerScore = -1;
14004
14336
  let handler;
14005
14337
  for (const possibleHandler of possibleHandlers) {
14006
14338
  if (possibleHandler.handlerType === "local") return possibleHandler;
14007
14339
  if (possibleHandler.handlerType === "peer") {
14008
- const score = scoringPeer.similarityLevel(possibleHandler.peerClient);
14340
+ const score = RuntimeCoordinate.unknown.similarityLevel(possibleHandler.peer);
14009
14341
  if (score > handlerScore) {
14010
14342
  handlerScore = score;
14011
14343
  handler = possibleHandler;
@@ -14018,8 +14350,7 @@ var ActionRuntime = class {
14018
14350
  const handler = this._getHandlerForAction(action, options);
14019
14351
  if (handler == null) throw err_nice_action.fromId("no_action_execution_handler", {
14020
14352
  actionId: action.id,
14021
- domain: action.domain,
14022
- specifiedClient: options?.targetPeer
14353
+ domain: action.domain
14023
14354
  });
14024
14355
  return handler;
14025
14356
  }
@@ -14027,20 +14358,91 @@ var ActionRuntime = class {
14027
14358
  * Register one or more handlers. Each handler's own `actionRouter` defines
14028
14359
  * which domains/actions it handles — those routing keys are mirrored into
14029
14360
  * this runtime's router so the same action can be served by multiple handlers.
14030
- * Duplicate registrations (same handler cuid for the same key) are skipped.
14361
+ * Re-adding the same handler object is idempotent. Global runtimes register with the affected root
14362
+ * domains automatically; instance runtimes remain private and require explicit dispatch.
14031
14363
  */
14032
14364
  addHandlers(handlers) {
14365
+ this._addHandlers(handlers, {
14366
+ persistent: true,
14367
+ register: true
14368
+ });
14369
+ return this;
14370
+ }
14371
+ /** @internal Install handlers for a host and return an idempotent ownership release. */
14372
+ _installHandlers(handlers, options = {}) {
14373
+ this._assertActive();
14374
+ const lease = Symbol("action-runtime-handler-installation");
14375
+ try {
14376
+ this._addHandlers(handlers, {
14377
+ persistent: false,
14378
+ register: options.register ?? false,
14379
+ lease
14380
+ });
14381
+ } catch (error) {
14382
+ this._releaseHandlerLease(lease);
14383
+ throw error;
14384
+ }
14385
+ let released = false;
14386
+ return () => {
14387
+ if (released) return;
14388
+ released = true;
14389
+ this._releaseHandlerLease(lease);
14390
+ };
14391
+ }
14392
+ _addHandlers(handlers, options) {
14393
+ this._assertActive();
14394
+ this._assertNoDuplicateLocalExecutors(handlers);
14033
14395
  for (const handler of handlers) {
14034
- if (handler.handlerType === "peer") {
14035
- handler._setIncomingActionDataListener((json) => this.resolveIncomingActionPayload(json));
14036
- this._registeredPeerHandlers.push(handler);
14396
+ let ownership = this._handlerOwnership.get(handler);
14397
+ if (ownership == null) {
14398
+ const handlerRouter = handler.getActionRouter();
14399
+ ownership = {
14400
+ persistent: false,
14401
+ leases: /* @__PURE__ */ new Set()
14402
+ };
14403
+ try {
14404
+ this.actionRouter.addDomainsFromOther(handlerRouter);
14405
+ if (handler.handlerType === "peer") {
14406
+ ownership.unbind = handler._setIncomingActionDataListener(this, (json, metadata) => this.resolveIncomingActionPayload(json, metadata));
14407
+ this._registeredPeerHandlers.push(handler);
14408
+ }
14409
+ for (const key of handlerRouter.getRegisteredKeys()) this.actionRouter.addForKey(key, handler);
14410
+ } catch (error) {
14411
+ ownership.unbind?.();
14412
+ this.actionRouter.removeRouteData(handler);
14413
+ const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14414
+ if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14415
+ throw error;
14416
+ }
14417
+ this._handlerOwnership.set(handler, ownership);
14037
14418
  }
14038
- const handlerRouter = handler.getActionRouter();
14039
- this.actionRouter.addDomainsFromOther(handlerRouter);
14040
- if (this._applied) this.apply();
14041
- for (const key of handlerRouter.getRegisteredKeys()) if (!this.actionRouter.getForKey(key).some((h) => h.cuid === handler.cuid)) this.actionRouter.addForKey(key, handler);
14419
+ if (options.persistent) ownership.persistent = true;
14420
+ if (options.lease != null) ownership.leases.add(options.lease);
14421
+ }
14422
+ if (options.register) this._registerWithRoutedRoots();
14423
+ }
14424
+ _assertNoDuplicateLocalExecutors(handlers) {
14425
+ for (const handler of handlers) for (const domain of handler.getActionRouter().getDomains()) this.actionRouter.domainManager.assertCanAddDomain(domain);
14426
+ const staged = /* @__PURE__ */ new Map();
14427
+ for (const handler of handlers) {
14428
+ if (handler.handlerType !== "local" || this._handlerOwnership.has(handler)) continue;
14429
+ for (const key of handler.getActionRouter().getRegisteredKeys()) {
14430
+ const duplicate = this.actionRouter.getForKey(key).find((candidate) => candidate.handlerType === "local") ?? staged.get(key);
14431
+ if (duplicate != null && duplicate !== handler) throw err_nice_action.fromId("duplicate_action_executor", { route: key });
14432
+ staged.set(key, handler);
14433
+ }
14434
+ }
14435
+ }
14436
+ _releaseHandlerLease(lease) {
14437
+ for (const [handler, ownership] of this._handlerOwnership) {
14438
+ ownership.leases.delete(lease);
14439
+ if (ownership.persistent || ownership.leases.size > 0) continue;
14440
+ ownership.unbind?.();
14441
+ this.actionRouter.removeRouteData(handler);
14442
+ const peerIndex = this._registeredPeerHandlers.indexOf(handler);
14443
+ if (peerIndex >= 0) this._registeredPeerHandlers.splice(peerIndex, 1);
14444
+ this._handlerOwnership.delete(handler);
14042
14445
  }
14043
- return this;
14044
14446
  }
14045
14447
  /**
14046
14448
  * @internal Low-level primitive — the public way to open a connection is `connectChannel`, which
@@ -14048,15 +14450,15 @@ var ActionRuntime = class {
14048
14450
  * block it sits on (it restates domain lists by hand) and is not part of the supported surface.
14049
14451
  *
14050
14452
  * Declare an external "backend client" in one call: build an
14051
- * {@link ChannelConnector} for `externalCoordinate` carrying the given
14453
+ * {@link ChannelConnector} for `peer` carrying the given
14052
14454
  * `transports`, route the listed `domains`/`actions` to it, register it (plus any
14053
14455
  * `localHandlers` — e.g. server→client push handlers that share the same channel)
14054
- * on this runtime, and `apply()`. Returns the external handler so the caller can
14456
+ * on this runtime. Returns the external handler so the caller can
14055
14457
  * later `clearTransportCache()` it.
14056
14458
  */
14057
- connectTo(externalCoordinate, options) {
14459
+ connectTo(peer, options) {
14058
14460
  const handler = new ChannelConnector({
14059
- runtimeCoordinate: externalCoordinate,
14461
+ peer,
14060
14462
  transports: options.transports,
14061
14463
  defaultTimeout: options.defaultTimeout,
14062
14464
  reliableActionTimeout: options.reliableActionTimeout,
@@ -14064,28 +14466,40 @@ var ActionRuntime = class {
14064
14466
  localCoordinate: this.coordinate,
14065
14467
  connectionIdentity: options.connectionIdentity,
14066
14468
  securityLevel: options.securityLevel,
14067
- keepLinkAlive: options.keepLinkAlive
14469
+ reconnect: options.reconnect ?? options.keepLinkAlive
14068
14470
  });
14069
14471
  for (const domain of options.domains ?? []) handler.forDomain(domain);
14070
14472
  for (const action of options.actions ?? []) handler.forAction(action);
14071
14473
  this.addHandlers([handler, ...options.localHandlers ?? []]);
14072
- this.apply();
14073
14474
  return handler;
14074
14475
  }
14075
14476
  applyRuntimeForDomain(domain) {
14076
14477
  const rootDomain = domain.rootDomain;
14077
- if (!rootDomain._hasRuntime(this)) rootDomain._registerRuntime(this);
14478
+ if (!rootDomain._hasRuntime(this)) {
14479
+ rootDomain._registerRuntime(this);
14480
+ this._registeredRoots.add(rootDomain);
14481
+ }
14482
+ }
14483
+ _registerWithRoutedRoots() {
14484
+ if (this.scope === "instance") return;
14485
+ for (const domain of this.actionRouter.getDomains()) this.applyRuntimeForDomain(domain);
14078
14486
  }
14079
14487
  /**
14080
- * Register this runtime with all root domains covered by its currently-added handlers,
14081
- * making it eligible to execute actions dispatched from those domains.
14082
- * After apply() is called, any subsequent addHandlers() calls also auto-register.
14488
+ * @deprecated Handler installation registers global runtimes automatically. Retained as an
14489
+ * idempotent migration shim; it never registers an instance-scoped runtime.
14083
14490
  */
14084
14491
  apply() {
14085
- this._applied = true;
14086
- for (const domain of this.actionRouter.getDomains()) this.applyRuntimeForDomain(domain);
14492
+ this._assertActive();
14493
+ this._registerWithRoutedRoots();
14087
14494
  return this;
14088
14495
  }
14496
+ async run(request, options) {
14497
+ this._assertActive();
14498
+ return request.run({
14499
+ ...options,
14500
+ targetLocalRuntime: this
14501
+ });
14502
+ }
14089
14503
  /**
14090
14504
  * Find the best registered external handler that can reach `originClient` directly.
14091
14505
  * Used to locate the return-path channel for dispatching results back to the action origin.
@@ -14093,11 +14507,9 @@ var ActionRuntime = class {
14093
14507
  *
14094
14508
  * A handler that currently holds the origin's *live* connection always wins, regardless of its
14095
14509
  * coordinate score — owning the live socket bound to the origin's exact coordinate (set from the
14096
- * handshake) is a strictly more precise match than any env-level `peerClient` score. This lets one
14097
- * server accept clients of *several* envs over a single acceptor (a multi-role Durable Object): the
14098
- * result/push routes back over the carrier the client actually connected on even when the handler's
14099
- * `clientEnv` is unset or names a different env. Only when no handler owns a live connection do we fall
14100
- * back to the plain best-coordinate-score pick (the offline-return and connector-only cases).
14510
+ * handshake) is a strictly more precise match than a connector's declared `peer` score. This lets
14511
+ * one server accept clients of several environments over a single acceptor. Only when no handler owns a
14512
+ * live connection do we fall back to connector coordinate scoring.
14101
14513
  */
14102
14514
  getReturnHandlerForOrigin(originClient) {
14103
14515
  if (originClient.envId === "_unset_") return void 0;
@@ -14107,7 +14519,7 @@ var ActionRuntime = class {
14107
14519
  let bestOwnedHandler;
14108
14520
  for (const handler of this._registeredPeerHandlers) {
14109
14521
  if (!handler.canPush) continue;
14110
- const score = originClient.similarityLevel(handler.peerClient);
14522
+ const score = originClient.similarityLevel(handler.peer);
14111
14523
  if (score > bestScore) {
14112
14524
  bestScore = score;
14113
14525
  bestHandler = handler;
@@ -14121,18 +14533,60 @@ var ActionRuntime = class {
14121
14533
  return bestScore > 0 ? bestHandler : void 0;
14122
14534
  }
14123
14535
  resetRuntime() {
14536
+ this._assertActive();
14124
14537
  for (const ra of this._pendingRunningActions.values()) ra._abort(err_nice_action.fromId("runtime_reset"));
14125
14538
  for (const handler of this._registeredPeerHandlers) handler.clearTransportCache();
14126
14539
  }
14540
+ dispose() {
14541
+ if (this._disposed) return;
14542
+ this._disposed = true;
14543
+ for (const root of this._registeredRoots) root._unregisterRuntime(this);
14544
+ this._registeredRoots.clear();
14545
+ if (this._pendingRunningActions.size > 0) {
14546
+ const error = err_nice_action.fromId("runtime_disposed", { runtime: this.coordinate.stringId });
14547
+ for (const running of this._pendingRunningActions.values()) running._abort(error);
14548
+ }
14549
+ this._pendingRunningActions.clear();
14550
+ for (const handler of this._registeredPeerHandlers) {
14551
+ const disposable = handler;
14552
+ if (typeof disposable.dispose === "function") disposable.dispose();
14553
+ else handler.clearTransportCache();
14554
+ }
14555
+ for (const [handler, ownership] of this._handlerOwnership) {
14556
+ ownership.unbind?.();
14557
+ this.actionRouter.removeRouteData(handler);
14558
+ }
14559
+ this._handlerOwnership.clear();
14560
+ this._registeredPeerHandlers.length = 0;
14561
+ }
14127
14562
  _trySetupReturnDispatch(runningAction) {
14128
14563
  if (runningAction.context.schema.responseMode === "none") return;
14129
14564
  const originClient = runningAction.context.originClient;
14130
14565
  if (originClient.envId === "_unset_" || originClient.isSameFor(this._coordinate).id) return;
14566
+ const arrival = runningAction.context._getReceiverMetadata();
14131
14567
  runningAction.addUpdateListeners([(update) => {
14132
- if (update.type === "finished" && update.finishType === "success") this.getReturnHandlerForOrigin(originClient)?.sendReturnPayload(update.response, { targetLocalRuntime: this }).catch(() => {});
14568
+ if (update.type === "finished" && update.finishType === "success") {
14569
+ if (this._disposed) return;
14570
+ const returnHandler = arrival?.receiver instanceof PeerLink ? this._registeredPeerHandlers.includes(arrival.receiver) && arrival.receiver.canPush ? arrival.receiver : void 0 : this.getReturnHandlerForOrigin(originClient);
14571
+ if (returnHandler == null || !canReturnToOrigin(arrival, returnHandler)) return;
14572
+ returnHandler.sendReturnPayload(update.response, { targetLocalRuntime: this }).catch(() => {});
14573
+ }
14133
14574
  }]);
14134
14575
  }
14135
14576
  };
14577
+ /**
14578
+ * May a result be routed back to the action's *claimed* origin over `returnHandler`?
14579
+ *
14580
+ * - No arrival facts (a locally dispatched action, or an advanced caller supplying its own wire):
14581
+ * unchanged behaviour.
14582
+ * - The frame arrived on this very handler: always — that is answering on the link it came from.
14583
+ * - Otherwise the origin coordinate is only trustworthy when the arrival was authenticated; an
14584
+ * unauthenticated claim must never select a different connection.
14585
+ */
14586
+ function canReturnToOrigin(arrival, returnHandler) {
14587
+ if (arrival == null || arrival.receiver === returnHandler) return true;
14588
+ return arrival.securityLevel != null && arrival.securityLevel !== "none";
14589
+ }
14136
14590
  const runtimeState = {
14137
14591
  defaultLocalRuntime: void 0,
14138
14592
  assumedRuntimeInfo: void 0
@@ -14173,6 +14627,9 @@ var ActionLocalHandler = class extends ActionHandler {
14173
14627
  return this;
14174
14628
  }
14175
14629
  /**
14630
+ * @deprecated Prefer `forAction`, `forDomainActionCases`, or an exhaustive
14631
+ * `domain.wrapAsLocalHandler` map. Retained for this migration release.
14632
+ *
14176
14633
  * Register a handler for multiple action IDs (first-match-wins among cases).
14177
14634
  * Receives the full primed action narrowed to the union of those IDs.
14178
14635
  * Use `act.coreAction.id` to branch on which action was dispatched.
@@ -14209,19 +14666,28 @@ var ActionLocalHandler = class extends ActionHandler {
14209
14666
  context: action.context,
14210
14667
  request: action,
14211
14668
  parentCuid: peekHandlerCuid(),
14212
- callSite: action._callSite ?? (/* @__PURE__ */ new Error()).stack
14669
+ callSite: targetLocalRuntime._captureActionCallSite(action, config?.captureCallSites)
14213
14670
  });
14214
- this._handleRunningAction(handler, runningAction);
14671
+ this._handleRunningAction(handler, runningAction, targetLocalRuntime);
14215
14672
  return runningAction;
14216
14673
  }
14217
- async _handleRunningAction(handler, runningAction) {
14674
+ async _handleRunningAction(handler, runningAction, runtime) {
14218
14675
  const state = runningAction.state;
14219
14676
  if (state.result != null) return;
14220
14677
  await Promise.resolve();
14221
14678
  pushHandlerCuid(runningAction.cuid);
14222
14679
  try {
14223
14680
  const ran = await niceTryAsync(async () => {
14224
- const rawResult = await handler(state.request);
14681
+ const securityLevel = state.request.context._getReceiverMetadata()?.securityLevel;
14682
+ const context = {
14683
+ runtime,
14684
+ origin: state.request.context.originClient,
14685
+ authenticatedOrigin: securityLevel != null && securityLevel !== "none" ? state.request.context.originClient : void 0,
14686
+ securityLevel,
14687
+ reliability: state.request.context.reliability,
14688
+ run: (request, options) => runtime.run(request, options)
14689
+ };
14690
+ const rawResult = await handler(state.request, context);
14225
14691
  if (rawResult instanceof ActionPayload_Result) return rawResult;
14226
14692
  if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) return this.actionRouter.domainManager.getActionDomainOrThrow(state.request).hydrateResultPayload(rawResult);
14227
14693
  return state.request.successResult(rawResult);
@@ -14308,90 +14774,68 @@ var ActionDomainBase = class {
14308
14774
  };
14309
14775
  //#endregion
14310
14776
  //#region ../nice-action/src/ActionRuntime/ActionRuntimeManager.ts
14777
+ /** Root-domain registry. Object identity is the key; coordinates may legitimately match. */
14311
14778
  var ActionRuntimeManager = class {
14312
- _runtimes = /* @__PURE__ */ new Map();
14313
- _preferredRuntimeClientId = null;
14779
+ _runtimes = /* @__PURE__ */ new Set();
14314
14780
  _context;
14315
14781
  constructor(context) {
14316
14782
  this._context = context ?? {};
14317
14783
  }
14318
14784
  registerRuntime(runtime) {
14319
- const runtimeId = runtime.coordinate.stringId;
14320
- if (this._runtimes.has(runtimeId)) throw err_nice_action.fromId("client_runtime_already_registered", {
14321
- context: this._context,
14322
- client: runtime.coordinate
14323
- });
14324
- for (const id of runtime.coordinate.toStringIds()) {
14325
- if (this._runtimes.has(id)) continue;
14326
- this._runtimes.set(id, runtime);
14327
- }
14785
+ runtime._assertActive();
14786
+ this._runtimes.add(runtime);
14787
+ }
14788
+ unregisterRuntime(runtime) {
14789
+ this._runtimes.delete(runtime);
14328
14790
  }
14329
14791
  getRuntimeAndHandlerForAction(action, options, throwOnIssue) {
14330
14792
  const localRuntime = options?.targetLocalRuntime;
14331
14793
  if (localRuntime != null) {
14332
- const runtime = throwOnIssue ? this.getBestRuntimeOrThrow(options?.targetLocalRuntime?.coordinate) : this.getBestRuntime(options?.targetLocalRuntime?.coordinate);
14333
- if (runtime == null) return;
14334
- const handler = runtime._getHandlerForAction(action, options);
14794
+ localRuntime._assertActive();
14795
+ const handler = localRuntime._getHandlerForAction(action, options);
14335
14796
  if (handler != null) return {
14336
14797
  handler,
14337
- runtime
14798
+ runtime: localRuntime
14338
14799
  };
14339
14800
  if (throwOnIssue) throw err_nice_action.fromId("no_action_execution_handler", {
14340
14801
  domain: action.domain,
14341
14802
  actionId: action.id,
14342
14803
  specifiedClient: localRuntime.coordinate
14343
14804
  });
14805
+ return;
14344
14806
  }
14345
- for (const runtime of this._runtimes.values()) {
14807
+ let selected;
14808
+ let ambiguousRuntimeIds;
14809
+ for (const runtime of this._runtimes) {
14810
+ if (runtime.disposed) continue;
14346
14811
  const handler = runtime._getHandlerForAction(action);
14347
- if (handler) return {
14812
+ if (handler == null) continue;
14813
+ if (selected == null) selected = {
14348
14814
  handler,
14349
14815
  runtime
14350
14816
  };
14817
+ else {
14818
+ ambiguousRuntimeIds ??= [selected.runtime.coordinate.stringId];
14819
+ ambiguousRuntimeIds.push(runtime.coordinate.stringId);
14820
+ }
14351
14821
  }
14352
- if (throwOnIssue) throw err_nice_action.fromId("no_action_execution_handler", {
14822
+ if (ambiguousRuntimeIds != null) throw err_nice_action.fromId("ambiguous_action_runtime", {
14353
14823
  domain: action.domain,
14354
14824
  actionId: action.id,
14355
- specifiedClient: options?.targetLocalRuntime?.coordinate
14825
+ runtimes: ambiguousRuntimeIds
14826
+ });
14827
+ if (selected != null) return selected;
14828
+ if (throwOnIssue && this._runtimes.size === 0) throw err_nice_action.fromId("no_client_runtimes_registered", { context: this._context });
14829
+ if (throwOnIssue) throw err_nice_action.fromId("no_action_execution_handler", {
14830
+ domain: action.domain,
14831
+ actionId: action.id
14356
14832
  });
14357
14833
  }
14358
14834
  getRuntimeAndHandlerForActionOrThrow(action, options) {
14359
14835
  return this.getRuntimeAndHandlerForAction(action, options, true);
14360
14836
  }
14361
- setPreferredRuntime(runtime) {
14362
- const runtimeId = runtime.coordinate.stringId;
14363
- this._preferredRuntimeClientId = runtimeId;
14364
- }
14365
- getPreferredRuntime() {
14366
- if (this._preferredRuntimeClientId) {
14367
- const runtime = this._runtimes.get(this._preferredRuntimeClientId);
14368
- if (runtime) return runtime;
14369
- }
14370
- return this._runtimes.values().next().value;
14371
- }
14372
- getBestRuntimeForSpecifier(clientSpecifier) {
14373
- const ids = new RuntimeCoordinate(clientSpecifier).toStringIds();
14374
- for (const id of ids) {
14375
- const runtime = this._runtimes.get(id);
14376
- if (runtime) return runtime;
14377
- }
14378
- }
14379
- getBestRuntime(clientSpecifier) {
14380
- return clientSpecifier != null ? this.getBestRuntimeForSpecifier(clientSpecifier) : this.getPreferredRuntime();
14381
- }
14382
14837
  hasRuntime(runtime) {
14383
- return this._runtimes.has(runtime.coordinate.stringId);
14384
- }
14385
- getBestRuntimeOrThrow(specifier) {
14386
- const runtime = this.getBestRuntime(specifier);
14387
- if (!runtime) {
14388
- if (specifier == null) throw err_nice_action.fromId("no_client_runtimes_registered", { context: this._context });
14389
- throw err_nice_action.fromId("client_runtime_not_registered", {
14390
- context: this._context,
14391
- clientStringId: runtimeCoordinateToStringIds(specifier)[0]
14392
- });
14393
- }
14394
- return runtime;
14838
+ return this._runtimes.has(runtime);
14395
14839
  }
14396
14840
  };
14397
14841
  //#endregion
@@ -14424,12 +14868,12 @@ var ActionRootDomain = class extends ActionDomainBase {
14424
14868
  _registerRuntime(runtime) {
14425
14869
  this._actionRuntimeManager.registerRuntime(runtime);
14426
14870
  }
14871
+ _unregisterRuntime(runtime) {
14872
+ this._actionRuntimeManager.unregisterRuntime(runtime);
14873
+ }
14427
14874
  _hasRuntime(runtime) {
14428
14875
  return this._actionRuntimeManager.hasRuntime(runtime);
14429
14876
  }
14430
- getRuntime(clientSpecifier) {
14431
- return this._actionRuntimeManager.getBestRuntimeForSpecifier(clientSpecifier);
14432
- }
14433
14877
  async _runAction(actionPayload, options) {
14434
14878
  const allListeners = [...this._listeners, ...options?.listeners ?? []];
14435
14879
  let handlerAndRuntime;
@@ -14446,10 +14890,13 @@ var ActionRootDomain = class extends ActionDomainBase {
14446
14890
  throw err;
14447
14891
  }
14448
14892
  const { handler, runtime } = handlerAndRuntime;
14893
+ runtime._captureActionCallSite(actionPayload, options?.captureCallSites);
14449
14894
  actionPayload.context._setOriginClient(runtime.coordinate);
14450
14895
  const runningAction = await handler.handleActionRequest(actionPayload, {
14451
14896
  targetLocalRuntime: runtime,
14452
- streamKey: options?.streamKey
14897
+ timeout: options?.timeout,
14898
+ streamKey: options?.streamKey,
14899
+ captureCallSites: options?.captureCallSites
14453
14900
  });
14454
14901
  runningAction.addUpdateListeners(allListeners);
14455
14902
  return runningAction;
@@ -14511,14 +14958,14 @@ var ActionDomain = class ActionDomain extends ActionDomainBase {
14511
14958
  const executor = wrappedActionExecutor;
14512
14959
  for (const actionKey in wrappedActionExecutor) {
14513
14960
  if (!this.actionSchema[actionKey]) continue;
14514
- _handler.forAction(this.actionForId(actionKey), (request) => executor[request.id](request.input));
14961
+ _handler.forAction(this.actionForId(actionKey), (request, context) => executor[request.id](request.input, context));
14515
14962
  }
14516
14963
  return _handler;
14517
14964
  }
14518
14965
  wrapAsLocalHandler(wrappedActionExecutor) {
14519
14966
  const _handler = new ActionLocalHandler();
14520
14967
  const executor = wrappedActionExecutor;
14521
- return _handler.forDomain(this, (request) => executor[request.id](request.input));
14968
+ return _handler.forDomain(this, (request, context) => executor[request.id](request.input, context));
14522
14969
  }
14523
14970
  hydrateContext(id, contextData) {
14524
14971
  return new ActionContext(this, id, {
@@ -14531,8 +14978,7 @@ var ActionDomain = class ActionDomain extends ActionDomainBase {
14531
14978
  time: item.time
14532
14979
  };
14533
14980
  }),
14534
- originClient: contextData.originClient ? new RuntimeCoordinate(contextData.originClient) : RuntimeCoordinate.unknown,
14535
- reliability: contextData.reliability
14981
+ originClient: contextData.originClient ? new RuntimeCoordinate(contextData.originClient) : RuntimeCoordinate.unknown
14536
14982
  });
14537
14983
  }
14538
14984
  isDomainAction(action) {
@@ -14661,7 +15107,7 @@ function serveResultErrorInfo(error) {
14661
15107
  * been served, to `console` (or any `sink` you pass). Drop it straight into `serveChannel` so a "host and
14662
15108
  * forget" backend gets request/response feedback with no extra wiring:
14663
15109
  * ```ts
14664
- * serveChannel(runtime, channel, { storage, carriers, logger: createDefaultServeLogger() });
15110
+ * serveChannel(channel, { identity, storage, carriers, logger: createDefaultServeLogger() });
14665
15111
  * // → [nice-action] ▶ demo_basic/greet via http from envId[web_app]… [encrypted]
14666
15112
  * // ← [nice-action] ✓ demo_basic/greet ok via http 12ms
14667
15113
  * ```
@@ -14728,7 +15174,7 @@ function readLaneBindingState(lane) {
14728
15174
  * (WebSockets, Durable Objects, …). It is transport-agnostic: you feed it inbound frames with
14729
15175
  * {@link receive} and tell it how to write outbound frames via the `send` option.
14730
15176
  *
14731
- * Since plan Phase 4 this class is the **action lane** over a wire-owned {@link WireAcceptor}
15177
+ * Since the connection design this class is the **action lane** over a wire-owned {@link WireAcceptor}
14732
15178
  * (reachable as {@link wireAcceptor}): the backbone — handshake accept + secure sessions, security
14733
15179
  * levels, the client-identity registry, frame-protocol registration/dispatch/lifecycle, versioned
14734
15180
  * binding persistence + rehydrate, and keepalive — lives in wire; this handler keeps the action
@@ -14737,21 +15183,21 @@ function readLaneBindingState(lane) {
14737
15183
  *
14738
15184
  * Add it alongside your local execution handler:
14739
15185
  * ```ts
14740
- * const serverHandler = createChannelAcceptor({ clientEnv, formatMessage, send: (ws, f) => ws.send(f) });
15186
+ * const serverHandler = createChannelAcceptor({ formatMessage, send: (ws, f) => ws.send(f) });
14741
15187
  * runtime.addHandlers([localHandler, serverHandler]);
14742
15188
  * // per inbound message (e.g. a Durable Object's webSocketMessage):
14743
15189
  * serverHandler.receive(ws, message);
14744
15190
  * ```
14745
15191
  *
14746
15192
  * Inbound requests route to your local handler; the runtime's return dispatch then calls this
14747
- * handler back (it is an external handler keyed to `clientEnv`) to send the result to the originating
15193
+ * handler back (it owns the originating live connection) to send the result to the originating
14748
15194
  * connection. It registers an empty action router, so it is never chosen to *execute* an inbound
14749
15195
  * request — only to ferry results/pushes back out.
14750
15196
  */
14751
- var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15197
+ var ChannelAcceptor = class extends PeerLink {
14752
15198
  /** Accept-in over a live (duplex) connection registry — it pushes results/broadcasts to bound sockets. */
14753
15199
  canPush = true;
14754
- /** The wire-owned acceptor backbone this lane composes on (plan Phase 4). */
15200
+ /** The wire-owned acceptor backbone this lane composes on. */
14755
15201
  wireAcceptor;
14756
15202
  _formatMessage;
14757
15203
  _createFormatMessage;
@@ -14764,7 +15210,17 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14764
15210
  _connTags = /* @__PURE__ */ new Map();
14765
15211
  _inbox = new ReliableInbox();
14766
15212
  _persistedReceiver;
14767
- _replyStreamKeys = /* @__PURE__ */ new Map();
15213
+ /** Trusted arrival facts live beside decoded objects, never in attacker-controlled wire JSON. */
15214
+ _receiverMetadataByWire = /* @__PURE__ */ new WeakMap();
15215
+ /**
15216
+ * Reliable stores may reconstruct buffered JSON as a new object. Retain the matching trusted
15217
+ * arrival beside the receiver-owned stream/sequence address while this acceptor remains alive.
15218
+ * A wake deliberately loses this non-serializable socket fact, so restored frames execute with
15219
+ * no live connection context rather than borrowing whichever socket happened to fill the gap.
15220
+ */
15221
+ _receiverMetadataByReliableStream = /* @__PURE__ */ new Map();
15222
+ /** A token per live binding prevents an in-flight handler from borrowing a dropped/rebound socket. */
15223
+ _bindingGenerationByConnection = /* @__PURE__ */ new Map();
14768
15224
  _keyedStreamsByClient = /* @__PURE__ */ new Map();
14769
15225
  _keyedCapWarned = /* @__PURE__ */ new Set();
14770
15226
  _maxKeyedStreams;
@@ -14773,7 +15229,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14773
15229
  _transportLabel;
14774
15230
  _pendingReports = /* @__PURE__ */ new Map();
14775
15231
  constructor(options) {
14776
- super(options.clientEnv ?? RuntimeCoordinate.unknown);
15232
+ super(RuntimeCoordinate.unknown);
14777
15233
  this._formatMessage = options.formatMessage;
14778
15234
  this._createFormatMessage = options.createFormatMessage;
14779
15235
  this._resolveCodec = options.resolveCodec;
@@ -14841,6 +15297,14 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14841
15297
  admitted.add(streamId);
14842
15298
  return true;
14843
15299
  }
15300
+ _setIncomingActionDataListener(runtime, listener) {
15301
+ runtime._assertActive();
15302
+ if (runtime.scope !== "instance") throw err_nice_action.fromId("invalid_server_runtime_scope", {
15303
+ runtime: runtime.coordinate.stringId,
15304
+ actualScope: runtime.scope
15305
+ });
15306
+ return super._setIncomingActionDataListener(runtime, listener);
15307
+ }
14844
15308
  /**
14845
15309
  * Log an inbound request (basic action/transport/origin facts) before it executes, stashing the returned
14846
15310
  * reporter by `cuid` so {@link _reportServed} can pair it with the result. Only requests are logged;
@@ -14919,7 +15383,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14919
15383
  /**
14920
15384
  * Register a frame protocol (M1 multiplex seam) on the wire acceptor: every connection can then
14921
15385
  * exchange the protocol's prefixed frames beside action frames (subject to the wire security
14922
- * gate, review A.6). Register before serving; protocols are advertised in the handshake welcome.
15386
+ * gate, the connection contract). Register before serving; protocols are advertised in the handshake welcome.
14923
15387
  */
14924
15388
  registerFrameProtocol(protocol) {
14925
15389
  this.wireAcceptor.registerProtocol(protocol);
@@ -14961,6 +15425,19 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14961
15425
  * encoded bytes the codec re-reads for the reliability slot.
14962
15426
  */
14963
15427
  _dispatchInbound(connection, wire, codec, frame, level) {
15428
+ if (wire.type === "request") {
15429
+ let bindingGeneration = this._bindingGenerationByConnection.get(connection);
15430
+ if (bindingGeneration == null) {
15431
+ bindingGeneration = {};
15432
+ this._bindingGenerationByConnection.set(connection, bindingGeneration);
15433
+ }
15434
+ this._receiverMetadataByWire.set(wire, {
15435
+ receiver: this,
15436
+ connection,
15437
+ bindingGeneration,
15438
+ securityLevel: level
15439
+ });
15440
+ }
14964
15441
  const reliability = wire.type === "request" ? codec.incomingReliability?.(frame) : void 0;
14965
15442
  const bytes = this._logger != null ? wireFrameByteSize(frame) : void 0;
14966
15443
  if (reliability?.seq != null) {
@@ -14968,25 +15445,26 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
14968
15445
  return;
14969
15446
  }
14970
15447
  this._logRequestIn(connection, wire, level, void 0, bytes);
14971
- this._emitIncoming(wire);
15448
+ this._emitIncomingFromReceiver(wire);
14972
15449
  }
14973
15450
  /** Ordered/dedup dispatch of one reliable request via the inbox (see {@link _dispatchInbound}). */
14974
15451
  _dispatchReliableRequest(connection, wire, seq, level, streamKey, bytes) {
14975
15452
  const client = this.wireAcceptor.clientForConnection(connection);
14976
15453
  if (client == null) {
14977
15454
  this._logRequestIn(connection, wire, level, void 0, bytes);
14978
- this._emitIncoming(wire);
15455
+ this._emitIncomingFromReceiver(wire);
14979
15456
  return;
14980
15457
  }
14981
15458
  const streamId = reliableStreamId(client, wire.domain, wire.id, streamKey);
14982
15459
  if (streamKey != null && !this._admitKeyedStream(client, streamId)) {
14983
15460
  this._logRequestIn(connection, wire, level, void 0, bytes);
14984
- this._emitIncoming(wire);
15461
+ this._emitIncomingFromReceiver(wire);
14985
15462
  return;
14986
15463
  }
14987
15464
  const receiver = this._receiverForWire(wire);
14988
15465
  const { deliver, duplicate, needsResync } = receiver.receive(streamId, seq, wire);
14989
15466
  if (needsResync) {
15467
+ this._forgetReliableReceiverMetadata(streamId, seq);
14990
15468
  if (!this._resyncRequested.has(streamId)) {
14991
15469
  this._resyncRequested.add(streamId);
14992
15470
  this._sendControl(connection, streamKey == null ? {
@@ -15010,8 +15488,12 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15010
15488
  ack,
15011
15489
  redelivered: duplicate
15012
15490
  };
15491
+ if (!duplicate && deliver.length === 0 && ack != null && seq > ack && seq - ack <= 1024) {
15492
+ const arrival = this._receiverMetadataByWire.get(wire);
15493
+ if (arrival != null) this._rememberReliableReceiverMetadata(streamId, seq, arrival);
15494
+ }
15013
15495
  if (this._runtime?.responseModeForWire(wire) === "none") {
15014
- this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey);
15496
+ this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes, this._receiverMetadataByWire.get(wire), streamId);
15015
15497
  this._sendControl(connection, streamKey == null ? {
15016
15498
  $c: "rack",
15017
15499
  domain: wire.domain,
@@ -15026,17 +15508,20 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15026
15508
  });
15027
15509
  return;
15028
15510
  }
15029
- if (streamKey != null) {
15030
- this._stashReplyStreamKey(wire.context.cuid, streamKey);
15031
- for (const delivered of deliver) if (delivered !== wire) this._stashReplyStreamKey(delivered.context.cuid, streamKey);
15032
- }
15033
15511
  if (duplicate) {
15034
- this._stampHandledReliability(wire, seq, streamKey, true);
15035
15512
  this._logRequestIn(connection, wire, level, receivedReliability, bytes);
15036
- this._emitIncoming(wire);
15513
+ this._emitIncomingFromReceiver(wire, streamKey == null ? {
15514
+ seq,
15515
+ redelivered: true
15516
+ } : {
15517
+ seq,
15518
+ streamKey,
15519
+ redelivered: true
15520
+ });
15521
+ this._forgetReliableReceiverMetadata(streamId, seq);
15037
15522
  return;
15038
15523
  }
15039
- this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes);
15524
+ this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes, this._receiverMetadataByWire.get(wire), streamId);
15040
15525
  }
15041
15526
  /**
15042
15527
  * Stamp the receiver-side reliability facts onto a delivered frame's **local** context (the
@@ -15044,15 +15529,16 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15044
15529
  * — the free idempotency key. Local-only: `toJsonObject()` never writes the field, so a reply built off
15045
15530
  * this context is byte-identical with and without the stamp.
15046
15531
  */
15047
- _stampHandledReliability(wire, seq, streamKey, redelivered) {
15048
- wire.context.reliability = streamKey == null ? {
15049
- seq,
15050
- redelivered
15051
- } : {
15052
- seq,
15053
- streamKey,
15054
- redelivered
15055
- };
15532
+ _emitIncomingFromReceiver(wire, reliability, arrivalOverride) {
15533
+ const arrival = arrivalOverride ?? this._receiverMetadataByWire.get(wire);
15534
+ this._receiverMetadataByWire.delete(wire);
15535
+ this._emitIncoming(wire, {
15536
+ receiver: this,
15537
+ connection: arrival?.connection,
15538
+ bindingGeneration: arrival?.bindingGeneration,
15539
+ securityLevel: arrival?.securityLevel,
15540
+ reliability
15541
+ });
15056
15542
  }
15057
15543
  /**
15058
15544
  * Log + emit each frame the receiver decided to deliver in this receive. Only the **first** (the frame
@@ -15061,12 +15547,23 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15061
15547
  * frame is stamped with its **own** seq for the executing handler, though — delivered frames are a
15062
15548
  * contiguous run ending at the new high-water (`ack`), so frame `i` carries `ack - (length - 1 - i)`.
15063
15549
  */
15064
- _emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes) {
15550
+ _emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes, receivedArrival, streamId) {
15065
15551
  const ack = receivedReliability.ack;
15066
15552
  deliver.forEach((delivered, index) => {
15067
- if (ack != null) this._stampHandledReliability(delivered, ack - (deliver.length - 1 - index), streamKey, false);
15553
+ const deliveredSeq = ack != null ? ack - (deliver.length - 1 - index) : void 0;
15554
+ const arrivalOverride = deliveredSeq != null && deliveredSeq === receivedReliability.seq ? receivedArrival : deliveredSeq != null && streamId != null ? this._takeReliableReceiverMetadata(streamId, deliveredSeq) : void 0;
15068
15555
  this._logRequestIn(connection, delivered, level, index === 0 ? receivedReliability : void 0, index === 0 ? bytes : void 0);
15069
- this._emitIncoming(delivered);
15556
+ if (ack != null) {
15557
+ const reliability = streamKey == null ? {
15558
+ seq: ack - (deliver.length - 1 - index),
15559
+ redelivered: false
15560
+ } : {
15561
+ seq: ack - (deliver.length - 1 - index),
15562
+ streamKey,
15563
+ redelivered: false
15564
+ };
15565
+ this._emitIncomingFromReceiver(delivered, reliability, arrivalOverride);
15566
+ } else this._emitIncomingFromReceiver(delivered, void 0, arrivalOverride);
15070
15567
  });
15071
15568
  }
15072
15569
  /**
@@ -15100,6 +15597,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15100
15597
  this._inbox.forget(streamId);
15101
15598
  this._resyncRequested.delete(streamId);
15102
15599
  if (message.k != null) this._keyedStreamsByClient.get(client.stringId)?.delete(streamId);
15600
+ this._receiverMetadataByReliableStream.delete(streamId);
15103
15601
  return;
15104
15602
  }
15105
15603
  if (message.$c !== "rskip") return;
@@ -15108,8 +15606,9 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15108
15606
  const streamId = reliableStreamId(client, message.domain, message.id, message.k);
15109
15607
  if (message.k != null && !this._admitKeyedStream(client, streamId)) return;
15110
15608
  const { deliver, ack } = this._receiverForRoute(message.domain, message.id).skipTo(streamId, message.seq);
15609
+ this._forgetReliableReceiverMetadataThrough(streamId, message.seq);
15111
15610
  this._resyncRequested.delete(streamId);
15112
- this._emitReliableDelivered(connection, deliver, this.wireAcceptor.levelFor(connection), { ack });
15611
+ this._emitReliableDelivered(connection, deliver, this.wireAcceptor.levelFor(connection), { ack }, message.k, void 0, void 0, streamId);
15113
15612
  this._sendControl(connection, message.k == null ? {
15114
15613
  $c: "rack",
15115
15614
  domain: message.domain,
@@ -15123,19 +15622,29 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15123
15622
  k: message.k
15124
15623
  });
15125
15624
  }
15126
- /** How long a stashed reply streamKey survives without its reply being sent (sweep bound). */
15127
- static _REPLY_STREAMKEY_TTL_MS = 5 * 6e4;
15128
- /** Remember a dispatched keyed reply-carrying request's streamKey until its reply goes out. */
15129
- _stashReplyStreamKey(cuid, streamKey) {
15130
- const now = Date.now();
15131
- for (const [key, entry] of this._replyStreamKeys) {
15132
- if (now - entry.time <= ChannelAcceptor._REPLY_STREAMKEY_TTL_MS) break;
15133
- this._replyStreamKeys.delete(key);
15134
- }
15135
- this._replyStreamKeys.set(cuid, {
15136
- streamKey,
15137
- time: now
15138
- });
15625
+ _rememberReliableReceiverMetadata(streamId, seq, metadata) {
15626
+ let bySeq = this._receiverMetadataByReliableStream.get(streamId);
15627
+ if (bySeq == null) {
15628
+ bySeq = /* @__PURE__ */ new Map();
15629
+ this._receiverMetadataByReliableStream.set(streamId, bySeq);
15630
+ }
15631
+ if (!bySeq.has(seq)) bySeq.set(seq, metadata);
15632
+ }
15633
+ _takeReliableReceiverMetadata(streamId, seq) {
15634
+ const bySeq = this._receiverMetadataByReliableStream.get(streamId);
15635
+ const metadata = bySeq?.get(seq);
15636
+ bySeq?.delete(seq);
15637
+ if (bySeq?.size === 0) this._receiverMetadataByReliableStream.delete(streamId);
15638
+ return metadata;
15639
+ }
15640
+ _forgetReliableReceiverMetadata(streamId, seq) {
15641
+ this._takeReliableReceiverMetadata(streamId, seq);
15642
+ }
15643
+ _forgetReliableReceiverMetadataThrough(streamId, through) {
15644
+ const bySeq = this._receiverMetadataByReliableStream.get(streamId);
15645
+ if (bySeq == null) return;
15646
+ for (const seq of bySeq.keys()) if (seq <= through) bySeq.delete(seq);
15647
+ if (bySeq.size === 0) this._receiverMetadataByReliableStream.delete(streamId);
15139
15648
  }
15140
15649
  /** Encode + send a transport {@link TControlMessage} to a connection (through its secure session if any). */
15141
15650
  _sendControl(connection, message) {
@@ -15150,7 +15659,10 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15150
15659
  _resolveRequestIdentity(connection, wire) {
15151
15660
  const wireOrigin = wire.context.originClient;
15152
15661
  if (wireOrigin != null && wireOrigin.envId !== "_unset_") {
15153
- this.wireAcceptor.bindPlainConnection(connection, new RuntimeCoordinate(wireOrigin));
15662
+ const client = new RuntimeCoordinate(wireOrigin);
15663
+ const previous = this.wireAcceptor.clientForConnection(connection);
15664
+ if (previous != null && previous.stringId !== client.stringId) this._bindingGenerationByConnection.delete(connection);
15665
+ this.wireAcceptor.bindPlainConnection(connection, client);
15154
15666
  return;
15155
15667
  }
15156
15668
  const bound = this.wireAcceptor.clientForConnection(connection);
@@ -15169,13 +15681,13 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15169
15681
  toJsonObject() {
15170
15682
  return {
15171
15683
  type: this.handlerType,
15172
- client: this.peerClient
15684
+ client: this.peer
15173
15685
  };
15174
15686
  }
15175
15687
  toHandlerRouteItem() {
15176
15688
  return {
15177
15689
  type: this.handlerType,
15178
- client: this.peerClient,
15690
+ client: this.peer,
15179
15691
  transShape: "duplex",
15180
15692
  transOrd: 0
15181
15693
  };
@@ -15197,6 +15709,16 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15197
15709
  this._connEncoding.delete(connection);
15198
15710
  this._codecByConn.delete(connection);
15199
15711
  this._connTags.delete(connection);
15712
+ this._bindingGenerationByConnection.delete(connection);
15713
+ for (const bySeq of this._receiverMetadataByReliableStream.values()) for (const metadata of bySeq.values()) {
15714
+ if (metadata.connection !== connection) continue;
15715
+ metadata.connection = void 0;
15716
+ metadata.bindingGeneration = void 0;
15717
+ }
15718
+ }
15719
+ _liveArrivalConnection(metadata) {
15720
+ const connection = metadata.connection;
15721
+ return metadata.receiver === this && connection != null && metadata.bindingGeneration != null && this._bindingGenerationByConnection.get(connection) === metadata.bindingGeneration && this.wireAcceptor.hasConnection(connection) ? connection : void 0;
15200
15722
  }
15201
15723
  /** Live connection for a client coordinate, if currently registered. */
15202
15724
  getConnectionForClient(client) {
@@ -15250,8 +15772,11 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15250
15772
  if (!ownedIds.has(id)) continue;
15251
15773
  const caseFn = cases[id];
15252
15774
  if (caseFn == null) continue;
15253
- wrapped[id] = (request) => {
15254
- return caseFn(request, mapContext(this.getConnectionForClient(request.context.originClient), request));
15775
+ wrapped[id] = (request, execution) => {
15776
+ const metadata = request.context._getReceiverMetadata();
15777
+ const connection = metadata == null ? void 0 : this._liveArrivalConnection(metadata);
15778
+ const isConnectionLive = () => connection != null && this._bindingGenerationByConnection.get(connection) === metadata?.bindingGeneration && this.wireAcceptor.hasConnection(connection);
15779
+ return caseFn(request, mapContext(connection, request, isConnectionLive, execution));
15255
15780
  };
15256
15781
  }
15257
15782
  handler.forDomainActionCases(domain, wrapped);
@@ -15280,7 +15805,8 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15280
15805
  }
15281
15806
  }
15282
15807
  async sendReturnPayload(payload, config) {
15283
- const connection = this.wireAcceptor.connectionForClient(payload.context.originClient.stringId);
15808
+ const arrival = payload.context._getReceiverMetadata();
15809
+ const connection = arrival?.receiver === this ? this._liveArrivalConnection(arrival) : this.wireAcceptor.connectionForClient(payload.context.originClient.stringId);
15284
15810
  if (connection == null) return false;
15285
15811
  const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate);
15286
15812
  this._reportServed(payload, bytes);
@@ -15343,9 +15869,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15343
15869
  const encoding = this._connEncoding.get(connection) ?? "binary";
15344
15870
  let rel = reliability;
15345
15871
  if (rel == null && payload.type === "result") {
15346
- const stashedKey = this._replyStreamKeys.get(payload.context.cuid);
15347
- if (stashedKey != null) this._replyStreamKeys.delete(payload.context.cuid);
15348
- const streamKey = stashedKey?.streamKey;
15872
+ const streamKey = payload.context.reliability?.streamKey;
15349
15873
  const streamId = reliableStreamId(payload.context.originClient, payload.domain, payload.id, streamKey);
15350
15874
  const receiver = this._persistedReceiver?.hasStream(streamId) ? this._persistedReceiver : this._inbox.hasStream(streamId) ? this._inbox : void 0;
15351
15875
  if (receiver != null) {
@@ -15363,7 +15887,7 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
15363
15887
  const frame = encoding === "json" ? JSON.stringify(payload.toJsonObject()) : this._codecFor(connection).outgoing({
15364
15888
  action: payload,
15365
15889
  localClient,
15366
- externalClient: this.peerClient,
15890
+ externalClient: this.peer,
15367
15891
  reliability: rel
15368
15892
  });
15369
15893
  this.wireAcceptor.sendTo(connection, frame);
@@ -15405,6 +15929,11 @@ const DEFAULT_SERVER_SECURITY_LEVELS$1 = [
15405
15929
  * {@link createHibernatableWsServerAdapter} to wire persistence + replay.
15406
15930
  */
15407
15931
  function createSecureChannelAcceptor(options) {
15932
+ options.runtime._assertActive();
15933
+ if (options.runtime.scope !== "instance") throw err_nice_action.fromId("invalid_server_runtime_scope", {
15934
+ runtime: options.runtime.coordinate.stringId,
15935
+ actualScope: options.runtime.scope
15936
+ });
15408
15937
  const link = options.link ?? new ClientCryptoKeyLink({ storageAdapter: options.storage });
15409
15938
  const resolveChannel = options.resolveChannel;
15410
15939
  const baseSecurity = {
@@ -15414,7 +15943,6 @@ function createSecureChannelAcceptor(options) {
15414
15943
  verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(options.storage)
15415
15944
  };
15416
15945
  const baseOptions = {
15417
- clientEnv: options.clientEnv,
15418
15946
  send: options.send,
15419
15947
  runtime: options.runtime,
15420
15948
  defaultTimeout: options.defaultTimeout,
@@ -15443,6 +15971,14 @@ function createSecureChannelAcceptor(options) {
15443
15971
  }
15444
15972
  //#endregion
15445
15973
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/Carrier.types.ts
15974
+ /** Convert action routing data into wire's generic carrier dial shape. */
15975
+ function toActionDialParams(input) {
15976
+ return {
15977
+ localClient: input.localClient,
15978
+ externalClient: input.externalClient,
15979
+ dialContext: input
15980
+ };
15981
+ }
15446
15982
  /**
15447
15983
  * Narrow a carrier source to the exchange shape via its `shape` discriminant — the one branch the
15448
15984
  * internal `transport()` factory uses to pick the duplex vs exchange transport. A duplex source carries
@@ -15817,7 +16353,7 @@ async function runExchange(session, inputs) {
15817
16353
  //#region ../nice-action/src/ActionRuntime/Transport/TransportConnection.ts
15818
16354
  /**
15819
16355
  * Live, per-handler transport runtime built from a reusable {@link Transport} definition — the
15820
- * action instantiation of wire's generic `TransportConnection` (shared-base-connect plan,
16356
+ * action instantiation of wire's generic `TransportConnection` (shared connection design,
15821
16357
  * Phase 2): routing params pinned to {@link ITransportRouteActionParams} and the finalized
15822
16358
  * methods to {@link IActionTransportReadyData_Methods}. The machinery (status processing, cache
15823
16359
  * keys, async bring-up hooks) lives in wire; subclasses (`LinkConnection`, `ExchangeConnection`)
@@ -15839,7 +16375,7 @@ var ExchangeConnection = class extends TransportConnection {
15839
16375
  });
15840
16376
  }
15841
16377
  _getCacheKey(input) {
15842
- return this.initialized.getTransportCacheKey?.(input).join("\0") ?? "";
16378
+ return this.initialized.getCacheKey?.(input).join("\0") ?? "";
15843
16379
  }
15844
16380
  _needsAsyncBringUp(data) {
15845
16381
  return data.secureChannel != null && data.secureChannel.securityLevel !== "none";
@@ -15884,7 +16420,7 @@ var ExchangeTransport = class ExchangeTransport extends Transport {
15884
16420
  _createConnection(_ctx) {
15885
16421
  const options = this.options;
15886
16422
  return new ExchangeConnection({ initialize: () => ({
15887
- getTransportCacheKey: options.getTransportCacheKey,
16423
+ getCacheKey: options.getCacheKey,
15888
16424
  isAvailable: options.available,
15889
16425
  getTransport: (input) => {
15890
16426
  assertProtocolsRideDuplex(options);
@@ -15942,7 +16478,7 @@ function finalizePlainLinkMethods(ctx) {
15942
16478
  return buildSendMethods(ctx, establishPlainDuplexSession({
15943
16479
  channel: ctx.channel,
15944
16480
  lane: connectorLaneEndpoint(ctx, abortSet),
15945
- keepalive: ctx.linkKeepalive,
16481
+ heartbeat: ctx.heartbeat,
15946
16482
  tap: ctx.wireTap
15947
16483
  }), abortSet);
15948
16484
  }
@@ -15967,7 +16503,7 @@ async function finalizeSecureLinkMethods(ctx) {
15967
16503
  secure: ctx.secure,
15968
16504
  lane,
15969
16505
  mux: ctx.secure.mux,
15970
- keepalive: ctx.linkKeepalive,
16506
+ heartbeat: ctx.heartbeat,
15971
16507
  tap: ctx.wireTap
15972
16508
  });
15973
16509
  return buildSendMethods(ctx, session, abortSet, session.remoteCaps?.includes("reliable") ?? false, session.remoteCaps?.includes("reliable-streamkey") ?? false);
@@ -16070,7 +16606,7 @@ var LinkConnection = class extends TransportConnection {
16070
16606
  this.resolvers = resolvers ?? createUnsetTransportResolvers("link");
16071
16607
  }
16072
16608
  _getCacheKey(input) {
16073
- return this.initialized.getTransportCacheKey?.(input).join("\0") ?? "";
16609
+ return this.initialized.getCacheKey?.(input).join("\0") ?? "";
16074
16610
  }
16075
16611
  _needsAsyncBringUp() {
16076
16612
  return true;
@@ -16093,7 +16629,7 @@ var LinkConnection = class extends TransportConnection {
16093
16629
  formatMessage: data.formatMessage,
16094
16630
  updateRunConfig: data.updateRunConfig,
16095
16631
  makeDisconnectError: linkDisconnectError,
16096
- linkKeepalive: data.linkKeepalive,
16632
+ heartbeat: data.heartbeat,
16097
16633
  wireTap: data.wireTap
16098
16634
  };
16099
16635
  }
@@ -16122,7 +16658,7 @@ var LinkTransport = class LinkTransport extends Transport {
16122
16658
  _createConnection(ctx) {
16123
16659
  const options = this.options;
16124
16660
  return new LinkConnection({ initialize: () => ({
16125
- getTransportCacheKey: options.getTransportCacheKey,
16661
+ getCacheKey: options.getCacheKey,
16126
16662
  isAvailable: options.available,
16127
16663
  getTransport: (input) => ({
16128
16664
  status: "ready",
@@ -16131,7 +16667,7 @@ var LinkTransport = class LinkTransport extends Transport {
16131
16667
  formatMessage: options.createFormatMessage?.() ?? options.formatMessage,
16132
16668
  updateRunConfig: options.updateRunConfig,
16133
16669
  secureChannel: options.security,
16134
- linkKeepalive: options.linkKeepalive?.(),
16670
+ heartbeat: options.heartbeat?.(),
16135
16671
  wireTap: options.wireTap
16136
16672
  }
16137
16673
  })
@@ -16150,6 +16686,8 @@ var LinkTransport = class LinkTransport extends Transport {
16150
16686
  function transport(options) {
16151
16687
  const { carrier, channel, available, label } = options;
16152
16688
  const labelFor = label ?? carrier.carrierLabel;
16689
+ const carrierGetCacheKey = carrier.getCacheKey;
16690
+ const carrierGetRouteInfo = carrier.getRouteInfo;
16153
16691
  let security;
16154
16692
  if (options.secure) {
16155
16693
  const link = options.link ?? (options.storage != null ? new ClientCryptoKeyLink({ storageAdapter: options.storage }) : void 0);
@@ -16158,16 +16696,17 @@ function transport(options) {
16158
16696
  securityLevel: options.securityLevel ?? "authenticated",
16159
16697
  link,
16160
16698
  localCoordinate: (options.identity ?? options.runtime.coordinate).toJsonObject(),
16699
+ expectedPeer: options.expectedPeer?.toJsonObject(),
16161
16700
  dictionaryVersion: channel.dictionaryVersion,
16162
16701
  channelTags: channel.tags,
16163
16702
  mux: options.mux
16164
16703
  };
16165
16704
  }
16166
16705
  if (isExchangeCarrierSource(carrier)) return ExchangeTransport.create({
16167
- openCarrier: carrier.open,
16168
- getTransportCacheKey: carrier.getCacheKey,
16169
- available,
16170
- getRouteInfo: carrier.getRouteInfo,
16706
+ openCarrier: (input) => carrier.open(toActionDialParams(input)),
16707
+ getCacheKey: carrierGetCacheKey == null ? void 0 : (input) => carrierGetCacheKey(toActionDialParams(input)),
16708
+ available: available ?? carrier.available,
16709
+ getRouteInfo: carrierGetRouteInfo == null ? void 0 : (input) => carrierGetRouteInfo(toActionDialParams(input)),
16171
16710
  label: labelFor,
16172
16711
  security,
16173
16712
  mux: options.mux,
@@ -16175,14 +16714,14 @@ function transport(options) {
16175
16714
  wireTap: options.wireTap
16176
16715
  });
16177
16716
  return LinkTransport.create({
16178
- openChannel: carrier.open,
16717
+ openChannel: (input) => carrier.open(toActionDialParams(input)),
16179
16718
  createFormatMessage: channel.createCodec,
16180
- getTransportCacheKey: carrier.getCacheKey,
16181
- available,
16182
- getRouteInfo: carrier.getRouteInfo,
16719
+ getCacheKey: carrierGetCacheKey == null ? void 0 : (input) => carrierGetCacheKey(toActionDialParams(input)),
16720
+ available: available ?? carrier.available,
16721
+ getRouteInfo: carrierGetRouteInfo == null ? void 0 : (input) => carrierGetRouteInfo(toActionDialParams(input)),
16183
16722
  label: labelFor,
16184
16723
  security,
16185
- linkKeepalive: options.linkKeepalive,
16724
+ heartbeat: options.heartbeat,
16186
16725
  wireTap: options.wireTap
16187
16726
  });
16188
16727
  }
@@ -16272,24 +16811,32 @@ function warnOnSharedConnectionIdentity(runtime, peer, identity) {
16272
16811
  * the single source of truth for *what* is routed (`toAcceptor` domains forwarded to the peer,
16273
16812
  * `toConnector` pushes handled locally from `onPush`); the call binds the shared facts — the channel's
16274
16813
  * codec/dictionary version, the runtime, and one crypto identity (a {@link ClientCryptoKeyLink} over
16275
- * `storage`) — into every transport in `transports`, so none of them restate the channel or runtime.
16276
- * List several transports to make the path transport-agnostic (secure WS preferred, HTTP fallback):
16814
+ * `storage`) — into every carrier. List carriers in preference order (secure WS preferred, plain HTTP
16815
+ * fallback):
16277
16816
  * ```ts
16278
16817
  * const connector = connectChannel(runtime, lobbyChannel, {
16279
16818
  * peer: runtime_coordinate_lobby_do,
16280
16819
  * storage,
16281
- * transports: [{ carrier: wsCarrier(() => ({ url })) }, { carrier: httpCarrier(...), secure: false }],
16820
+ * carriers: [wsCarrier(url), httpCarrier(httpUrl, { secure: false })],
16282
16821
  * onPush: { player_joined: (p) => { … } },
16283
16822
  * });
16284
16823
  * ```
16285
16824
  * Returns the {@link ChannelConnector} so the caller can later `clearTransportCache()` it.
16286
16825
  */
16287
16826
  function connectChannel(runtime, channel, options) {
16827
+ if (options.carriers == null === (options.transports == null)) throw err_nice_action.fromId("conflicting_connect_options", { detail: "connectChannel requires exactly one of `carriers` or deprecated `transports`" });
16828
+ const transports = options.carriers?.map((carrier) => ({
16829
+ carrier,
16830
+ secure: carrier.secure,
16831
+ securityLevel: carrier.securityLevel,
16832
+ available: carrier.available,
16833
+ label: carrier.label
16834
+ })) ?? options.transports;
16288
16835
  const securityLevel = options.securityLevel ?? "authenticated";
16289
- const anySecure = options.transports.some((transport) => transport.secure ?? true);
16836
+ const anySecure = transports.some((transport) => transport.secure ?? true);
16290
16837
  const connectionIdentity = options.connectionId != null ? runtime.coordinate.withConnectionId(options.connectionId) : void 0;
16291
- if (options.transports.some((descriptor) => !isExchangeCarrierSource(descriptor.carrier))) warnOnSharedConnectionIdentity(runtime, options.peer, connectionIdentity ?? runtime.coordinate);
16292
- const { mux: wireMux, link, resolveLinkKeepalive, wireTap } = assembleWireConnectionParts({
16838
+ if (transports.some((descriptor) => !isExchangeCarrierSource(descriptor.carrier))) warnOnSharedConnectionIdentity(runtime, options.peer, connectionIdentity ?? runtime.coordinate);
16839
+ const { mux: wireMux, link, resolveHeartbeat, wireTap } = assembleWireConnectionParts({
16293
16840
  callerName: "connectChannel",
16294
16841
  peer: options.peer,
16295
16842
  identity: connectionIdentity ?? runtime.coordinate,
@@ -16299,16 +16846,19 @@ function connectChannel(runtime, channel, options) {
16299
16846
  storage: options.storage,
16300
16847
  link: options.link,
16301
16848
  ephemeralIdentity: options.ephemeralIdentity,
16849
+ reconnect: options.reconnect,
16850
+ heartbeat: options.heartbeat,
16302
16851
  keepLinkAlive: options.keepLinkAlive,
16303
16852
  linkKeepalive: options.linkKeepalive,
16304
16853
  wireTap: options.wireTap
16305
16854
  });
16306
- const exchangeOnlyConnection = options.transports.every((descriptor) => isExchangeCarrierSource(descriptor.carrier));
16307
- const transports = options.transports.map((descriptor) => transport({
16855
+ const exchangeOnlyConnection = transports.every((descriptor) => isExchangeCarrierSource(descriptor.carrier));
16856
+ const builtTransports = transports.map((descriptor) => transport({
16308
16857
  carrier: descriptor.carrier,
16309
16858
  channel,
16310
16859
  runtime,
16311
16860
  identity: connectionIdentity,
16861
+ expectedPeer: options.peer,
16312
16862
  secure: descriptor.secure ?? true,
16313
16863
  link,
16314
16864
  securityLevel: descriptor.securityLevel ?? securityLevel,
@@ -16316,21 +16866,21 @@ function connectChannel(runtime, channel, options) {
16316
16866
  label: descriptor.label,
16317
16867
  mux: wireMux,
16318
16868
  exchangeOnlyConnection,
16319
- linkKeepalive: resolveLinkKeepalive,
16869
+ heartbeat: resolveHeartbeat,
16320
16870
  wireTap
16321
16871
  }));
16322
16872
  const pushHandlers = options.onPush != null ? channel.toConnectorDomains.map((domain) => domain.wrapAsPartialLocalHandler(options.onPush)) : [];
16323
- const duplexSecurityLevels = options.transports.filter((descriptor) => !isExchangeCarrierSource(descriptor.carrier)).map((descriptor) => descriptor.secure ?? true ? descriptor.securityLevel ?? securityLevel : "none");
16873
+ const duplexSecurityLevels = transports.filter((descriptor) => !isExchangeCarrierSource(descriptor.carrier)).map((descriptor) => descriptor.secure ?? true ? descriptor.securityLevel ?? securityLevel : "none");
16324
16874
  const connectionSecurityLevel = duplexSecurityLevels.length === 0 ? "none" : duplexSecurityLevels.reduce((floor, level) => securityLevelMeets(level, floor) ? floor : level);
16325
16875
  const handler = runtime.connectTo(options.peer, {
16326
- transports,
16876
+ transports: builtTransports,
16327
16877
  domains: [...channel.toAcceptorDomains],
16328
16878
  localHandlers: pushHandlers,
16329
16879
  defaultTimeout: options.defaultTimeout,
16330
16880
  reliableActionTimeout: options.reliableActionTimeout,
16331
16881
  wireMux,
16332
16882
  securityLevel: connectionSecurityLevel,
16333
- keepLinkAlive: options.keepLinkAlive,
16883
+ reconnect: options.reconnect ?? options.keepLinkAlive,
16334
16884
  connectionIdentity
16335
16885
  });
16336
16886
  if (options.onReliableEvent != null) handler.addReliableEventListener(options.onReliableEvent);
@@ -16369,7 +16919,8 @@ function combineChannels(channels) {
16369
16919
  * dictionary version, the `security` block from the runtime coordinate) but takes the `(runtime, channel,
16370
16920
  * options)` shape of the channel family. Pair it with {@link acceptChannelConnections} for execution:
16371
16921
  * ```ts
16372
- * const acceptor = acceptChannel(runtime, gameChannel, { clientEnv, storage, send });
16922
+ * const runtime = new ActionRuntime(serverCoordinate, { scope: "instance" });
16923
+ * const acceptor = acceptChannel(runtime, gameChannel, { storage, send });
16373
16924
  * runtime.addHandlers([acceptChannelConnections(acceptor, gameChannel, { … }), acceptor]);
16374
16925
  * ```
16375
16926
  */
@@ -16383,7 +16934,7 @@ function acceptChannel(runtime, channel, options) {
16383
16934
  //#endregion
16384
16935
  //#region ../nice-action/src/ActionRuntime/Transport/SecureSession/exchangeAcceptor.ts
16385
16936
  /**
16386
- * The action lane over wire's {@link WireExchangeAcceptor} (shared-base-connect plan, Phase 6) —
16937
+ * The action lane over wire's {@link WireExchangeAcceptor} —
16387
16938
  * the HTTP counterpart to `ChannelAcceptor` composing on `WireAcceptor`. Wire owns the exchange
16388
16939
  * mechanics: the envelope, the server handshake over the two `hs` POSTs, the sealed `hsc`/`t`
16389
16940
  * tokens that make the whole endpoint **stateless** across isolates, and the per-session frame
@@ -16438,7 +16989,10 @@ var ExchangeAcceptor = class {
16438
16989
  origin: client?.stringId
16439
16990
  })) : void 0;
16440
16991
  const startedAt = Date.now();
16441
- const result = await (await this._runtime.handleActionPayloadWire(wire)).waitForResultPayload();
16992
+ const result = await (await this._runtime._handleActionPayloadWireFromReceiver(wire, {
16993
+ receiver: this,
16994
+ securityLevel: request.securityLevel
16995
+ })).waitForResultPayload();
16442
16996
  const resultWire = result.toJsonObject();
16443
16997
  if (report != null) {
16444
16998
  const returnedVia = request.encrypted ? `${this._transportLabel} (encrypted)` : this._transportLabel;
@@ -16548,7 +17102,10 @@ function createActionFetchHandler(runtime, options = {}) {
16548
17102
  const startedAt = Date.now();
16549
17103
  let running;
16550
17104
  try {
16551
- running = await runtime.handleActionPayloadWire(body);
17105
+ running = await runtime._handleActionPayloadWireFromReceiver(body, {
17106
+ receiver: runtime,
17107
+ securityLevel: "none"
17108
+ });
16552
17109
  } catch (error) {
16553
17110
  if (error instanceof NiceError && error.getIds().some((id) => id === "wire_not_action_data" || id === "wire_action_not_payload")) {
16554
17111
  report?.({
@@ -16722,64 +17279,6 @@ function createHibernatableWsServerAdapter(options) {
16722
17279
  //#endregion
16723
17280
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/AcceptorCarrier.types.ts
16724
17281
  /**
16725
- * Build the inert lifecycle slot a duplex carrier factory spreads into its handle: `receive`/`drop` throw
16726
- * (or no-op) until `serveChannel` calls `_activate` with the carrier's live router. Shared by every duplex
16727
- * carrier factory (`wsAcceptorCarrier`, a WebRTC carrier, the Cloudflare DO helper, …) so the
16728
- * stateful-handle wiring lives in exactly one place.
16729
- */
16730
- function createDuplexCarrierLifecycle(limits) {
16731
- let router;
16732
- let disposed = false;
16733
- const windows = /* @__PURE__ */ new Map();
16734
- const maxFrameBytes = limits?.maxFrameBytes;
16735
- const rate = limits?.rate;
16736
- if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
16737
- 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");
16738
- const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
16739
- return {
16740
- receive(connection, frame) {
16741
- if (disposed) return;
16742
- if (router == null) throw new Error("acceptor carrier not served yet — pass it to serveChannel() before feeding frames");
16743
- if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
16744
- limits?.onExceeded(connection, "frame_bytes");
16745
- return;
16746
- }
16747
- if (rate != null) {
16748
- const now = Date.now();
16749
- let window = windows.get(connection);
16750
- if (window == null || now - window.startedAt >= rate.windowMs) {
16751
- window = {
16752
- count: 0,
16753
- startedAt: now
16754
- };
16755
- windows.set(connection, window);
16756
- }
16757
- window.count++;
16758
- if (window.count > rate.maxMessages) {
16759
- limits?.onExceeded(connection, "message_rate");
16760
- return;
16761
- }
16762
- }
16763
- router.receive(connection, frame);
16764
- },
16765
- drop(connection) {
16766
- if (disposed) return;
16767
- windows.delete(connection);
16768
- router?.drop(connection);
16769
- },
16770
- _activate(liveRouter) {
16771
- if (disposed) throw new Error("acceptor carrier already disposed");
16772
- router = liveRouter;
16773
- },
16774
- _dispose() {
16775
- if (disposed) return;
16776
- disposed = true;
16777
- router = void 0;
16778
- windows.clear();
16779
- }
16780
- };
16781
- }
16782
- /**
16783
17282
  * Narrow an acceptor carrier to the exchange shape via its `shape` discriminant — the one branch
16784
17283
  * `serveChannel` uses to pick the duplex (push-capable) vs exchange (request/reply) wiring. A duplex
16785
17284
  * carrier carries `shape: ETransportShape.duplex`, so the `else` branch is the duplex one.
@@ -16824,212 +17323,220 @@ const DEFAULT_SERVER_SECURITY_LEVELS = [
16824
17323
  "authenticated",
16825
17324
  "encrypted"
16826
17325
  ];
16827
- function serveChannel(runtime, channel, options) {
16828
- const duplexCarriers = options.carriers.filter((carrier) => !isExchangeAcceptorCarrier(carrier));
16829
- const exchangeCarriers = options.carriers.filter(isExchangeAcceptorCarrier);
16830
- if (exchangeCarriers.length > 1) throw new Error("serveChannel: at most one exchange carrier is supported");
16831
- const exchangeCarrier = exchangeCarriers[0];
16832
- const singleDuplex = duplexCarriers.length === 1;
16833
- if (options.connectionState != null && !singleDuplex) throw new Error("serveChannel: `connectionState` requires exactly one duplex carrier");
16834
- if (options.channelCases != null && !singleDuplex) throw new Error("serveChannel: `channelCases` requires exactly one duplex carrier");
16835
- const exchangeSecure = exchangeCarrier != null && (exchangeCarrier.secure ?? true);
16836
- const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
16837
- const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
16838
- const registry = options.channels;
16839
- const resolveChannel = registry != null && registry.length > 1 ? buildChannelSubsetResolver(channel, registry) : void 0;
16840
- let secure;
16841
- if (anyDuplexSecure || exchangeSecure) {
16842
- const storage = options.storage;
16843
- 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.");
16844
- secure = {
16845
- storage,
16846
- link: options.link ?? new ClientCryptoKeyLink({ storageAdapter: storage }),
16847
- verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(storage)
16848
- };
16849
- }
16850
- const plainRouter = (handler) => ({
16851
- receive: (connection, frame) => handler.receive(connection, frame),
16852
- drop: (connection) => handler.drop(connection)
17326
+ function serveChannel(runtimeOrChannel, channelOrOptions, legacyOptions) {
17327
+ const modern = !(runtimeOrChannel instanceof ActionRuntime);
17328
+ const channel = modern ? runtimeOrChannel : channelOrOptions;
17329
+ const rawOptions = modern ? channelOrOptions : legacyOptions;
17330
+ if (rawOptions == null) throw err_nice_action.fromId("conflicting_server_options", { detail: "serveChannel requires server options" });
17331
+ const suppliedRuntime = modern ? rawOptions.runtime : runtimeOrChannel;
17332
+ const identity = modern ? rawOptions.identity : void 0;
17333
+ if (modern && suppliedRuntime == null === (identity == null)) throw err_nice_action.fromId("conflicting_server_options", { detail: "pass exactly one of `identity` or `runtime`" });
17334
+ if (!modern && rawOptions.identity != null) throw err_nice_action.fromId("conflicting_server_options", { detail: "the deprecated `serveChannel(runtime, channel, options)` form cannot take `identity` — use `serveChannel(channel, { identity, … })`" });
17335
+ const ownsRuntime = suppliedRuntime == null;
17336
+ const runtime = suppliedRuntime ?? new ActionRuntime(identity, { scope: "instance" });
17337
+ const { identity: _identity, runtime: _runtime, ...options } = rawOptions;
17338
+ runtime._assertActive();
17339
+ if (runtime.scope !== "instance") throw err_nice_action.fromId("invalid_server_runtime_scope", {
17340
+ runtime: runtime.coordinate.stringId,
17341
+ actualScope: runtime.scope
16853
17342
  });
16854
- const asObject = (value) => typeof value === "object" && value != null ? value : {};
16855
- const acceptors = [];
16856
- let connections;
16857
- for (const carrier of duplexCarriers) {
16858
- const handler = (carrier.secure ?? true) && secure != null ? acceptChannel(runtime, channel, {
16859
- clientEnv: options.clientEnv,
16860
- storage: secure.storage,
16861
- link: secure.link,
16862
- verifyKeyResolver: secure.verifyKeyResolver,
16863
- securityLevel,
16864
- send: carrier.send,
16865
- defaultTimeout: options.defaultTimeout,
16866
- resolveChannel,
16867
- logger: options.logger,
16868
- wireTap: options.wireTap,
16869
- transportLabel: carrier.carrierLabel,
16870
- persistedReceiver: options.reliableStore,
16871
- maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
16872
- }) : createChannelAcceptor({
16873
- clientEnv: options.clientEnv,
16874
- createFormatMessage: channel.createCodec,
16875
- send: carrier.send,
16876
- runtime,
16877
- defaultTimeout: options.defaultTimeout,
16878
- logger: options.logger,
16879
- wireTap: options.wireTap,
16880
- transportLabel: carrier.carrierLabel,
16881
- persistedReceiver: options.reliableStore,
16882
- maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
17343
+ try {
17344
+ const duplexCarriers = options.carriers.filter((carrier) => !isExchangeAcceptorCarrier(carrier));
17345
+ const exchangeCarriers = options.carriers.filter((carrier) => isExchangeAcceptorCarrier(carrier));
17346
+ if (exchangeCarriers.length > 1) throw new Error("serveChannel: at most one exchange carrier is supported");
17347
+ const exchangeCarrier = exchangeCarriers[0];
17348
+ const singleDuplex = duplexCarriers.length === 1;
17349
+ if (options.connectionState != null && !singleDuplex) throw new Error("serveChannel: `connectionState` requires exactly one duplex carrier");
17350
+ if (options.channelCases != null && !singleDuplex) throw new Error("serveChannel: `channelCases` requires exactly one duplex carrier");
17351
+ const exchangeSecure = exchangeCarrier != null && (exchangeCarrier.secure ?? true);
17352
+ const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
17353
+ const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
17354
+ const registry = options.channels;
17355
+ const resolveChannel = registry != null && registry.length > 1 ? buildChannelSubsetResolver(channel, registry) : void 0;
17356
+ let secure;
17357
+ if (anyDuplexSecure || exchangeSecure) {
17358
+ const storage = options.storage;
17359
+ if (storage == null) throw new Error("serveChannel: a secure carrier requires `storage`. Pass it, or set `secure: false` on the carrier for a plain endpoint.");
17360
+ secure = {
17361
+ storage,
17362
+ link: options.link ?? new ClientCryptoKeyLink({ storageAdapter: storage }),
17363
+ verifyKeyResolver: options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(storage)
17364
+ };
17365
+ }
17366
+ const plainRouter = (handler) => ({
17367
+ receive: (connection, frame) => handler.receive(connection, frame),
17368
+ drop: (connection) => handler.drop(connection)
16883
17369
  });
16884
- for (const protocol of options.protocols ?? []) handler.registerFrameProtocol(protocol);
16885
- const attach = carrier.attachmentStore;
16886
- let router;
16887
- if (attach == null) router = plainRouter(handler);
16888
- else if (options.connectionState != null) {
16889
- connections = createConnectionStateStore(handler, {
16890
- schema: options.connectionState.schema,
17370
+ const asObject = (value) => typeof value === "object" && value != null ? value : {};
17371
+ const acceptors = [];
17372
+ let connections;
17373
+ for (const carrier of duplexCarriers) {
17374
+ const handler = (carrier.secure ?? true) && secure != null ? acceptChannel(runtime, channel, {
17375
+ storage: secure.storage,
17376
+ link: secure.link,
17377
+ verifyKeyResolver: secure.verifyKeyResolver,
17378
+ securityLevel,
17379
+ send: carrier.send,
17380
+ defaultTimeout: options.defaultTimeout,
17381
+ resolveChannel,
17382
+ logger: options.logger,
17383
+ wireTap: options.wireTap,
17384
+ transportLabel: carrier.carrierLabel,
17385
+ persistedReceiver: options.reliableStore,
17386
+ maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
17387
+ }) : createChannelAcceptor({
17388
+ createFormatMessage: channel.createCodec,
17389
+ send: carrier.send,
17390
+ runtime,
17391
+ defaultTimeout: options.defaultTimeout,
17392
+ logger: options.logger,
17393
+ wireTap: options.wireTap,
17394
+ transportLabel: carrier.carrierLabel,
17395
+ persistedReceiver: options.reliableStore,
17396
+ maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient
17397
+ });
17398
+ for (const protocol of options.protocols ?? []) handler.registerFrameProtocol(protocol);
17399
+ const attach = carrier.attachmentStore;
17400
+ let router;
17401
+ if (attach == null) router = plainRouter(handler);
17402
+ else if (options.connectionState != null) {
17403
+ connections = createConnectionStateStore(handler, {
17404
+ schema: options.connectionState.schema,
17405
+ getConnections: attach.getConnections,
17406
+ read: attach.read,
17407
+ write: attach.write
17408
+ });
17409
+ router = plainRouter(handler);
17410
+ } else router = createHibernatableWsServerAdapter({
17411
+ handler,
16891
17412
  getConnections: attach.getConnections,
16892
- read: attach.read,
16893
- write: attach.write
17413
+ getAttachment: (connection) => attach.read(connection)?.binding,
17414
+ setAttachment: (connection, binding) => attach.write(connection, {
17415
+ ...asObject(attach.read(connection)),
17416
+ binding
17417
+ })
16894
17418
  });
16895
- router = plainRouter(handler);
16896
- } else router = createHibernatableWsServerAdapter({
16897
- handler,
16898
- getConnections: attach.getConnections,
16899
- getAttachment: (connection) => attach.read(connection)?.binding,
16900
- setAttachment: (connection, binding) => attach.write(connection, {
16901
- ...asObject(attach.read(connection)),
16902
- binding
16903
- })
16904
- });
16905
- carrier._activate(router);
16906
- acceptors.push(handler);
16907
- }
16908
- runtime.addHandlers([...options.handlers ?? [], ...acceptors]);
16909
- const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
16910
- let disposed = false;
16911
- const receive = (connection, frame) => {
16912
- if (disposed) return;
16913
- 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");
16914
- soleDuplex.receive(connection, frame);
16915
- };
16916
- const drop = (connection) => {
16917
- if (disposed) return;
16918
- soleDuplex?.drop(connection);
16919
- };
16920
- const pushToClient = (target, request, pushOptions) => {
16921
- if (disposed) throw new Error("serveChannel: server disposed");
16922
- const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
16923
- if (owner == null) throw err_nice_transport.fromId("not_found", { actionId: target instanceof RuntimeCoordinate ? target.stringId : "push-target-connection" });
16924
- return owner.pushToClient(runtime, target, request, pushOptions);
16925
- };
16926
- const broadcast = (makeRequest, broadcastOptions) => {
16927
- if (disposed) throw new Error("serveChannel: server disposed");
16928
- if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead");
16929
- acceptors[0].broadcast(makeRequest, {
16930
- runtime,
16931
- ...broadcastOptions
17419
+ carrier._activate(router);
17420
+ acceptors.push(handler);
17421
+ }
17422
+ const installedHandlers = [...options.handlers ?? [], ...acceptors];
17423
+ const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
17424
+ let disposed = false;
17425
+ const receive = (connection, frame) => {
17426
+ if (disposed) return;
17427
+ if (soleDuplex == null) throw new Error(duplexCarriers.length === 0 ? "serveChannel: no duplex carrier to receive on (this server has no socket transport)" : "serveChannel: several duplex carriers — feed each carrier handle's receive() directly");
17428
+ soleDuplex.receive(connection, frame);
17429
+ };
17430
+ const drop = (connection) => {
17431
+ if (disposed) return;
17432
+ soleDuplex?.drop(connection);
17433
+ };
17434
+ const pushToClient = (target, request, pushOptions) => {
17435
+ if (disposed) throw new Error("serveChannel: server disposed");
17436
+ const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
17437
+ if (owner == null) throw err_nice_transport.fromId("not_found", { actionId: target instanceof RuntimeCoordinate ? target.stringId : "push-target-connection" });
17438
+ return owner.pushToClient(runtime, target, request, pushOptions);
17439
+ };
17440
+ const broadcast = (makeRequest, broadcastOptions) => {
17441
+ if (disposed) throw new Error("serveChannel: server disposed");
17442
+ if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead");
17443
+ acceptors[0].broadcast(makeRequest, {
17444
+ runtime,
17445
+ ...broadcastOptions
17446
+ });
17447
+ };
17448
+ const makeConnectionContext = (connection, _request, isConnectionLive, execution) => ({
17449
+ ...execution,
17450
+ get connection() {
17451
+ return connection != null && isConnectionLive() ? connection : null;
17452
+ },
17453
+ get state() {
17454
+ return connection != null && isConnectionLive() && connections != null ? connections.get(connection) : null;
17455
+ },
17456
+ setState(value) {
17457
+ if (connection == null || !isConnectionLive()) throw err_nice_action.fromId("connection_required", { operation: "set connection state" });
17458
+ if (connections != null) connections.set(connection, value);
17459
+ },
17460
+ clearState() {
17461
+ if (connection == null || !isConnectionLive()) throw err_nice_action.fromId("connection_required", { operation: "clear connection state" });
17462
+ if (connections != null) connections.clearApp(connection);
17463
+ },
17464
+ broadcast(makeRequest, contextOptions) {
17465
+ broadcast(makeRequest, {
17466
+ except: contextOptions?.exceptSelf && isConnectionLive() ? connection ?? null : null,
17467
+ where: contextOptions?.where,
17468
+ timeout: contextOptions?.timeout,
17469
+ onError: contextOptions?.onError
17470
+ });
17471
+ },
17472
+ pushBack(pushRequest, pushOptions) {
17473
+ if (connection == null || !isConnectionLive()) throw err_nice_action.fromId("connection_required", { operation: "push back to the client" });
17474
+ return pushToClient(connection, pushRequest, pushOptions);
17475
+ }
16932
17476
  });
16933
- };
16934
- const makeConnectionContext = (connection, request) => ({
16935
- connection: connection ?? null,
16936
- origin: request.context.originClient,
16937
- reliability: request.context.reliability,
16938
- get state() {
16939
- return connection != null && connections != null ? connections.get(connection) : null;
16940
- },
16941
- setState(value) {
16942
- if (connection != null && connections != null) connections.set(connection, value);
16943
- },
16944
- clearState() {
16945
- if (connection != null && connections != null) connections.clearApp(connection);
16946
- },
16947
- broadcast(makeRequest, contextOptions) {
16948
- broadcast(makeRequest, {
16949
- except: contextOptions?.exceptSelf ? connection ?? null : null,
16950
- where: contextOptions?.where,
16951
- timeout: contextOptions?.timeout,
16952
- onError: contextOptions?.onError
17477
+ if (options.channelCases != null) installedHandlers.push(acceptors[0].forConnectionDomainCasesMulti(channel.toAcceptorDomains, options.channelCases, makeConnectionContext));
17478
+ let releaseRuntimeHandlers;
17479
+ try {
17480
+ releaseRuntimeHandlers = runtime._installHandlers(installedHandlers);
17481
+ } catch (error) {
17482
+ for (const carrier of duplexCarriers) carrier._dispose?.();
17483
+ for (const acceptor of acceptors) acceptor.dispose();
17484
+ throw error;
17485
+ }
17486
+ const exchangeSecurity = exchangeSecure && secure != null ? {
17487
+ link: secure.link,
17488
+ verifyKeyResolver: secure.verifyKeyResolver,
17489
+ localCoordinate: runtime.coordinate.toJsonObject(),
17490
+ dictionaryVersion: resolveChannel != null ? (hello) => resolveChannel(hello.channels)?.dictionaryVersion ?? null : channel.dictionaryVersion,
17491
+ securityLevel
17492
+ } : void 0;
17493
+ const defaultIsUpgrade = (request) => request.headers.get("Upgrade") === "websocket";
17494
+ const upgraders = [];
17495
+ for (const carrier of duplexCarriers) {
17496
+ if (carrier.upgrade == null) continue;
17497
+ upgraders.push({
17498
+ isUpgrade: carrier.isUpgrade ?? defaultIsUpgrade,
17499
+ upgrade: carrier.upgrade
16953
17500
  });
16954
- },
16955
- pushBack(pushRequest, pushOptions) {
16956
- if (connection == null) throw new Error("serveChannel: connection context has no live socket to push back to (HTTP-exchange path)");
16957
- return pushToClient(connection, pushRequest, pushOptions);
16958
17501
  }
16959
- });
16960
- if (options.channelCases != null) runtime.addHandlers([acceptors[0].forConnectionDomainCasesMulti(channel.toAcceptorDomains, options.channelCases, makeConnectionContext)]);
16961
- const exchangeSecurity = exchangeSecure && secure != null ? {
16962
- link: secure.link,
16963
- verifyKeyResolver: secure.verifyKeyResolver,
16964
- localCoordinate: runtime.coordinate.toJsonObject(),
16965
- dictionaryVersion: resolveChannel != null ? (hello) => resolveChannel(hello.channels)?.dictionaryVersion ?? null : channel.dictionaryVersion,
16966
- securityLevel
16967
- } : void 0;
16968
- const defaultIsUpgrade = (request) => request.headers.get("Upgrade") === "websocket";
16969
- const upgraders = [];
16970
- for (const carrier of duplexCarriers) {
16971
- if (carrier.upgrade == null) continue;
16972
- upgraders.push({
16973
- isUpgrade: carrier.isUpgrade ?? defaultIsUpgrade,
16974
- upgrade: carrier.upgrade
17502
+ const activeFetch = createActionFetchHandler(runtime, {
17503
+ cors: exchangeCarrier?.cors,
17504
+ onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
17505
+ isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
17506
+ isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
17507
+ security: exchangeSecurity,
17508
+ useErrorStatus: exchangeCarrier?.useErrorStatus,
17509
+ logger: options.logger,
17510
+ transportLabel: exchangeCarrier?.carrierLabel
16975
17511
  });
17512
+ const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
17513
+ status: 503,
17514
+ headers: { "cache-control": "no-store" }
17515
+ })) : activeFetch(request);
17516
+ const dispose = () => {
17517
+ if (disposed) return;
17518
+ disposed = true;
17519
+ for (const carrier of duplexCarriers) carrier._dispose?.();
17520
+ for (const acceptor of acceptors) acceptor.dispose();
17521
+ releaseRuntimeHandlers();
17522
+ if (ownsRuntime) runtime.dispose();
17523
+ };
17524
+ return {
17525
+ runtime,
17526
+ acceptors,
17527
+ fetch,
17528
+ receive,
17529
+ drop,
17530
+ dispose,
17531
+ pushToClient,
17532
+ broadcast,
17533
+ connections
17534
+ };
17535
+ } catch (error) {
17536
+ for (const carrier of options.carriers ?? []) if (!isExchangeAcceptorCarrier(carrier)) carrier._dispose?.();
17537
+ if (ownsRuntime) runtime.dispose();
17538
+ throw error;
16976
17539
  }
16977
- const activeFetch = createActionFetchHandler(runtime, {
16978
- cors: exchangeCarrier?.cors,
16979
- onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
16980
- isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
16981
- isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
16982
- security: exchangeSecurity,
16983
- useErrorStatus: exchangeCarrier?.useErrorStatus,
16984
- logger: options.logger,
16985
- transportLabel: exchangeCarrier?.carrierLabel
16986
- });
16987
- const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
16988
- status: 503,
16989
- headers: { "cache-control": "no-store" }
16990
- })) : activeFetch(request);
16991
- const dispose = () => {
16992
- if (disposed) return;
16993
- disposed = true;
16994
- for (const carrier of duplexCarriers) carrier._dispose?.();
16995
- for (const acceptor of acceptors) acceptor.dispose();
16996
- };
16997
- return {
16998
- acceptors,
16999
- fetch,
17000
- receive,
17001
- drop,
17002
- dispose,
17003
- pushToClient,
17004
- broadcast,
17005
- connections
17006
- };
17007
- }
17008
- //#endregion
17009
- //#region ../nice-action/src/ActionRuntime/Transport/Carrier/adaptWireCarrierSource.ts
17010
- /**
17011
- * The E2 bridge (shared-base-connect plan, Phase 2): wire's carrier sources are generalized over
17012
- * an opaque dial context, and nice-action's domain concept for it is the whole per-dispatch
17013
- * routing params — the action being sent decides the URL/cache key (e.g. the pixel demo keys its
17014
- * socket by the action's game id). These adapters wrap a wire source instantiated with
17015
- * `TDial = TTransportRouteParams` back into the action-shaped sources the transport
17016
- * factory (and hand-written test carriers) already speak, so consumer code compiles unchanged.
17017
- */
17018
- function toActionDialParams(input) {
17019
- return {
17020
- localClient: input.localClient,
17021
- externalClient: input.externalClient,
17022
- dialContext: input
17023
- };
17024
- }
17025
- function adaptWireDuplexCarrierSource(source) {
17026
- const { getCacheKey, getRouteInfo } = source;
17027
- return {
17028
- carrierLabel: source.carrierLabel,
17029
- open: (input) => source.open(toActionDialParams(input)),
17030
- getCacheKey: getCacheKey == null ? void 0 : (input) => getCacheKey(toActionDialParams(input)),
17031
- getRouteInfo: getRouteInfo == null ? void 0 : (input) => getRouteInfo(toActionDialParams(input))
17032
- };
17033
17540
  }
17034
17541
  err_nice_transport.createChildDomain({
17035
17542
  domain: "err_nice_transport_ws",
@@ -17040,44 +17547,31 @@ err_nice_transport.createChildDomain({
17040
17547
  }
17041
17548
  });
17042
17549
  //#endregion
17043
- //#region ../nice-action/src/ActionRuntime/Transport/Carrier/duplex/ws/wsAcceptorCarrier.ts
17044
- /**
17045
- * A WebSocket {@link IDuplexAcceptorCarrier}: the accept-in dual of {@link wsCarrier}. It describes how to
17046
- * write frames back to a live socket, how to upgrade an inbound request into one, and (optionally) how to
17047
- * persist bindings across hibernation. Hand it to `serveChannel`'s `carriers` list — the secure session,
17048
- * codec, and crypto identity are supplied centrally there, so this only carries the WS-specific surface.
17049
- */
17050
- function wsAcceptorCarrier(options) {
17051
- return {
17052
- ...createDuplexCarrierLifecycle(options.inboundLimits),
17053
- shape: "duplex",
17054
- carrierLabel: options.carrierLabel ?? "ws",
17055
- secure: options.secure,
17056
- send: options.send,
17057
- upgrade: options.upgrade,
17058
- isUpgrade: options.isUpgrade ?? ((request) => request.headers.get("Upgrade") === "websocket"),
17059
- attachmentStore: options.attachmentStore
17060
- };
17061
- }
17062
- //#endregion
17063
17550
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/duplex/ws/wsCarrier.ts
17064
17551
  /**
17065
17552
  * A WebSocket {@link IDuplexCarrierSource}: the action instantiation of wire's `wsCarrier`
17066
- * (shared-base-connect plan, Phase 2 / E2) — the dial context is the per-action routing params,
17553
+ * — the dial context is the per-action routing params,
17067
17554
  * so `createRequest` still derives the socket URL per action exactly as before. Pass it as a
17068
17555
  * `carrier` to `connectChannel`.
17069
17556
  *
17070
- * `createRequest` may return `null` for "no valid endpoint right now" (resilience-surface §6) —
17557
+ * `createRequest` may return `null` for "no valid endpoint right now" —
17071
17558
  * the keep-alive redial then PARKS instead of dialing garbage, so a dynamic-endpoint teardown
17072
17559
  * (`_activeMatchId = undefined`) needs no careful ordering against `releaseLink()`.
17073
17560
  */
17074
- function wsCarrier(createRequest, options = {}) {
17075
- const { getTransportCacheKey, getRouteInfo, createWebSocket } = options;
17076
- return adaptWireDuplexCarrierSource(wsCarrier$1((params) => createRequest(params.dialContext), {
17077
- getCacheKey: getTransportCacheKey == null ? void 0 : (params) => getTransportCacheKey(params.dialContext),
17078
- getRouteInfo: getRouteInfo == null ? void 0 : (params) => getRouteInfo(params.dialContext),
17079
- createWebSocket
17080
- }));
17561
+ function wsCarrier(request, options = {}) {
17562
+ if (options.getCacheKey != null && options.getTransportCacheKey != null) throw err_nice_action.fromId("conflicting_connect_options", { detail: "wsCarrier: pass only `getCacheKey`; `getTransportCacheKey` is deprecated" });
17563
+ const getCacheKey = options.getCacheKey ?? options.getTransportCacheKey;
17564
+ const getRouteInfo = options.getRouteInfo;
17565
+ return {
17566
+ ...wsCarrier$1(typeof request === "string" ? request : (params) => request(params.dialContext), {
17567
+ secure: options.secure,
17568
+ getCacheKey: getCacheKey == null ? void 0 : (params) => getCacheKey(params.dialContext),
17569
+ getRouteInfo: getRouteInfo == null ? void 0 : (params) => getRouteInfo(params.dialContext),
17570
+ createWebSocket: options.createWebSocket
17571
+ }),
17572
+ available: options.available,
17573
+ label: options.label
17574
+ };
17081
17575
  }
17082
17576
  //#endregion
17083
17577
  //#region ../nice-action/src/ActionRuntime/Transport/Carrier/exchange/http/httpAcceptorCarrier.ts
@@ -18825,7 +19319,7 @@ function update(store, updater, patchesCallback) {
18825
19319
  //#endregion
18826
19320
  //#region ../nice-realm/src/RealmDefinition/errors/err_realm.ts
18827
19321
  /**
18828
- * The realm base error domain (plan §4.4). Rejection frames carry `packError` output (a msgpack
19322
+ * The realm base error domain. Rejection frames carry `packError` output (a msgpack
18829
19323
  * map), never positional tuples — rejections are the rare path, so they stay fully descriptive
18830
19324
  * and hydratable. User realms define their own domains for rule/intent rejections; these are the
18831
19325
  * engine's own errors. (`protocol_unsupported` lives in `@nice-code/wire` — it is a link-level
@@ -18846,7 +19340,7 @@ const err_realm = err_nice.createChildDomain({
18846
19340
  message: ({ avatarType, expected }) => `Client type "${avatarType}" is not permitted here (expected: ${expected.join(", ")}).`,
18847
19341
  context: { required: true }
18848
19342
  }),
18849
- /** The connection's identity could not be resolved to a realm avatar (review A.7): the
19343
+ /** The connection's identity could not be resolved to a realm avatar: the
18850
19344
  * server's `resolveAvatar`/`avatarType` mapping returned nothing for this connection. */
18851
19345
  avatar_unresolved: err({
18852
19346
  message: ({ realmId }) => `This connection's identity could not be resolved to an avatar of realm "${realmId}" — the server's resolveAvatar returned undefined (or the attachment carries no coordinate).`,
@@ -18854,7 +19348,7 @@ const err_realm = err_nice.createChildDomain({
18854
19348
  }),
18855
19349
  /**
18856
19350
  * The connection's negotiated wire security level is below the realm's declared minimum
18857
- * (PLAN-security §5.2). Fail-closed at attach: the avatar never attaches, so no avatar data
19351
+ *. Fail-closed at attach: the avatar never attaches, so no avatar data
18858
19352
  * flows below the required level. Raise the connection's `securityLevel` (e.g. `encrypted`) to
18859
19353
  * attach — the realm requires it.
18860
19354
  */
@@ -18891,7 +19385,7 @@ const err_realm = err_nice.createChildDomain({
18891
19385
  }),
18892
19386
  /**
18893
19387
  * The optimistic frame expired / was rolled back before an authoritative answer arrived — an
18894
- * **unknown outcome**, NOT proof the server rejected it (DESYNC review app-contract §1). The
19388
+ * **unknown outcome**, NOT proof the server rejected it. The
18895
19389
  * write may have committed on the server while the ack was lost, or the link dropped mid-flight.
18896
19390
  * Do not blindly re-issue a non-idempotent **intent** on this error — re-read state (it
18897
19391
  * converges via the next replay/hydrate) and decide. A rules rejection, by contrast, is a
@@ -18901,7 +19395,7 @@ const err_realm = err_nice.createChildDomain({
18901
19395
  message: ({ basisVersion }) => `The optimistic frame (basis ${basisVersion}) expired before it could be confirmed — outcome unknown (it may have committed; re-read state rather than re-issuing a non-idempotent intent).`,
18902
19396
  context: { required: true }
18903
19397
  }),
18904
- /** The durable-write backlog cap (PLAN-FEATURE-COMPLETE §4): too many unconfirmed
19398
+ /** The durable-write backlog cap: too many unconfirmed
18905
19399
  * `durability: "reassert"` frames accumulated (a long outage). The app's cue to fall back to
18906
19400
  * its own source-of-truth re-sync instead of queueing more. */
18907
19401
  durable_backlog_overflow: err({
@@ -18920,7 +19414,7 @@ const err_realm = err_nice.createChildDomain({
18920
19414
  * frame was well-formed, the state simply moved out from under it. A predicted optimistic write
18921
19415
  * on this path rolls back; the app should re-read state (an assert-on-resume re-creates a
18922
19416
  * pruned own-entry) rather than re-issue blindly. Additive since 0.46 — pre-0.46 servers send
18923
- * `frame_invalid` for this case. (REVIEW-frame-invalid-issue §5.8.)
19417
+ * `frame_invalid` for this case.
18924
19418
  */
18925
19419
  write_target_missing: err({
18926
19420
  message: ({ path }) => `The write to "${path}" could not be applied — its parent no longer exists (a pruned entry or a transient region reset since the write's basis). Re-read state instead of re-issuing.`,
@@ -19058,7 +19552,7 @@ function validateValue(node, value) {
19058
19552
  //#endregion
19059
19553
  //#region ../nice-realm/src/RealmWire/keyDict.ts
19060
19554
  /**
19061
- * Dynamic record-key interning (plan §7 / proposal §7.9): record keys are arbitrary strings
19555
+ * Dynamic record-key interning: record keys are arbitrary strings
19062
19556
  * (nanoids, user ids); after their first appearance they travel as small ints. The server owns id
19063
19557
  * assignment (eager, on first committed write touching the key) and sends each connection the
19064
19558
  * `keyDict` delta entries it hasn't seen before any frame that uses them; clients only ever
@@ -19105,7 +19599,7 @@ var RealmKeyDict = class {
19105
19599
  //#endregion
19106
19600
  //#region ../nice-realm/src/RealmWire/realmFrame.types.ts
19107
19601
  /**
19108
- * The realm wire protocol (plan §7): every frame is a msgpack fixarray `[kind, slot, …]` riding
19602
+ * The realm wire protocol: every frame is a msgpack fixarray `[kind, slot, …]` riding
19109
19603
  * the wire frame-protocol port at prefix `0x01` (M1 seam). The **slot** is a client-assigned small
19110
19604
  * int established by `hello`, so several realms — or several instances — share one peer link with
19111
19605
  * a one-byte discriminator per frame.
@@ -19125,7 +19619,7 @@ const REALM_FRAME_KIND = {
19125
19619
  keyDict: 7,
19126
19620
  detach: 8,
19127
19621
  /**
19128
- * Client→server capability advertisement (PLAN-REALM-MESSAGE-OVERLOAD Phase 1). Sent right after
19622
+ * Client→server capability advertisement. Sent right after
19129
19623
  * every `hello` (fresh attach, reconnect, probe) so a hibernation-woken server — which lost the
19130
19624
  * per-session feature state — re-learns them for free. An old server decodes an unknown kind →
19131
19625
  * drops it → never emits the features it names; a new server with a client that never sends this
@@ -19160,7 +19654,7 @@ const REALM_DETACH_REASON_REHELLO = "rehello";
19160
19654
  //#endregion
19161
19655
  //#region ../nice-realm/src/RealmWire/realmFrameCodec.ts
19162
19656
  /**
19163
- * The realm frame codec (plan §7 / M3): encode side builds each frame's msgpack fixarray; decode
19657
+ * The realm frame codec: encode side builds each frame's msgpack fixarray; decode
19164
19658
  * side strictly validates shape and rejects with a typed `err_realm.frame_invalid` — garbage bytes
19165
19659
  * never throw-through as raw msgpackr/TypeErrors into the engines (the fuzz gate).
19166
19660
  */
@@ -19460,7 +19954,7 @@ function decodeRealmFrame(payload) {
19460
19954
  //#endregion
19461
19955
  //#region ../nice-realm/src/RealmWire/unsafeKey.ts
19462
19956
  /**
19463
- * Prototype-pollution deny-list for dynamic record keys (PLAN-security Phase 5 / §4). Wire segments
19957
+ * Prototype-pollution deny-list for dynamic record keys. Wire segments
19464
19958
  * become object keys in the state tree — on server apply and on client/replica projection. Three of
19465
19959
  * them are never legitimate `t.id()` record keys and are actively dangerous as object keys:
19466
19960
  *
@@ -19502,7 +19996,7 @@ function valueHasUnsafeKey(value) {
19502
19996
  //#endregion
19503
19997
  //#region ../nice-realm/src/RealmWire/wirePatch.ts
19504
19998
  /**
19505
- * Immer patches ↔ realm wire ops (plan §7). Wire ops always use **name-space string paths**
19999
+ * Immer patches ↔ realm wire ops. Wire ops always use **name-space string paths**
19506
20000
  * tokenized through the realm's token map; immer patches on realm state only ever contain string
19507
20001
  * segments *except* inside arrays — and arrays are leaf-replace-only on the wire (proposal §7.8),
19508
20002
  * so {@link canonicalizeStatePatches} lifts any array-interior patch to a whole-array `replace`
@@ -19582,7 +20076,7 @@ function canonicalizeStatePatches(patches, stateAfter, schemaRoot) {
19582
20076
  }
19583
20077
  /**
19584
20078
  * Conflate an ORDERED run of authoritative patch ops to the shortest final-state-equivalent run
19585
- * (PLAN-REALM-MESSAGE-OVERLOAD Phase 3). Used for replay: a reconnect inside the log window merges
20079
+ *. Used for replay: a reconnect inside the log window merges
19586
20080
  * every missed version's ops, which for a 60 Hz cursor is ~1000 dead intermediate positions in one
19587
20081
  * frame. Server→client ops are absolute-value ops (`add`/`replace` carry the whole subtree; `remove`
19588
20082
  * deletes it), so a later op at path `P` makes every earlier op AT `P` OR UNDER `P` redundant — the
@@ -19647,7 +20141,7 @@ function wireOpsToNamePatches(ops, tokens, resolveKey) {
19647
20141
  //#endregion
19648
20142
  //#region ../nice-realm/src/RealmClient/assertRealmSecurity.ts
19649
20143
  /**
19650
- * The client-side security floor (PLAN-security Phase 4 / §3b). The server's attach gate stops
20144
+ * The client-side security floor. The server's attach gate stops
19651
20145
  * *routing* an under-secured avatar — it does NOT stop this client from *sending*. So only this
19652
20146
  * local check keeps avatar identity/state from leaving the device as app-layer plaintext when a
19653
20147
  * realm marked `security: "encrypted"` is connected over an `authenticated` link (a misconfigured
@@ -19656,7 +20150,7 @@ function wireOpsToNamePatches(ops, tokens, resolveKey) {
19656
20150
  *
19657
20151
  * Shared by {@link connectRealm} and {@link connectRealmReplica} so the two connect paths can't
19658
20152
  * drift — the replica is the highest-value leak (an "everything" view of the realm) and a wholly
19659
- * separate code path (review §4).
20153
+ * separate code path.
19660
20154
  */
19661
20155
  /** Map the realm-local policy level to the wire enum for ranking (no `as`, per the code guide). */
19662
20156
  function realmLevelToWire(level) {
@@ -19695,7 +20189,7 @@ function computeRealmSecurityShortfall(adapter, realm, connectOverride) {
19695
20189
  //#endregion
19696
20190
  //#region ../nice-realm/src/RealmClient/diffProjected.ts
19697
20191
  /**
19698
- * Structural diff between two projections (review C.2): the generic version of what imperative
20192
+ * Structural diff between two projections: the generic version of what imperative
19699
20193
  * renderers used to hand-roll per consumer (the pixel demo's 40-line identity-gated record
19700
20194
  * diff). Immer's structural sharing makes it cheap: an unchanged subtree keeps its reference
19701
20195
  * across `applyPatches`/rebase, so `prev === next` prunes it in O(1) — the walk only descends
@@ -19760,12 +20254,12 @@ function evalAlterCond(cond, context, serverExtras) {
19760
20254
  }
19761
20255
  /** The slicer's signature-group key — view rules may not read `instanceId` (see module doc). */
19762
20256
  function viewSignatureKey(avatar) {
19763
- return `${avatar.type}${avatar.persistentId}`;
20257
+ return `${avatar.type}\0${avatar.persistentId}`;
19764
20258
  }
19765
20259
  //#endregion
19766
20260
  //#region ../nice-realm/src/RealmServer/expandWrite.ts
19767
20261
  /**
19768
- * Subtree-write expansion (plan §6.1, locked semantics): an object-valued patch — including a
20262
+ * Subtree-write expansion: an object-valued patch — including a
19769
20263
  * whole record-entry `add`/`remove` — expands to **every leaf path it covers**, and the write
19770
20264
  * passes only if every covered leaf's own most-specific rule passes. Creation is just the first
19771
20265
  * write; deletion is a `remove` through the same gate; rules never need "create" clauses.
@@ -19821,7 +20315,7 @@ function expandWriteToLeaves(options) {
19821
20315
  //#endregion
19822
20316
  //#region ../nice-realm/src/RealmClient/predict.ts
19823
20317
  /**
19824
- * Client-side write prediction (plan §6.1 step 2): the same expansion + rule pipeline the server
20318
+ * Client-side write prediction: the same expansion + rule pipeline the server
19825
20319
  * runs, minus everything server-only — `r.serverChecked` parts auto-pass (that is exactly the
19826
20320
  * slice of optimism that can later roll back), `prev`/`state` come from the writer's projected
19827
20321
  * view. A NiceError here rejects the write in the same tick, before anything renders.
@@ -19905,7 +20399,7 @@ function getAtPath$4(state, path) {
19905
20399
  * throw `path doesn't resolve` on the child patch, far from the cause. Fixed containers are
19906
20400
  * structural (the schema ships to every client), so synthesizing an empty shell reveals nothing.
19907
20401
  *
19908
- * It deliberately does NOT synthesize a missing **dynamic record entry** (DESYNC F5): a missing
20402
+ * It deliberately does NOT synthesize a missing **dynamic record entry**: a missing
19909
20403
  * entry means a missed `add <entry> = {…}`, and fabricating a `{}` shell would produce a silent
19910
20404
  * partial entry (missing the add's fields) that persists until the next reconnect. There, the
19911
20405
  * throw is the right outcome — the Phase-3 inbound wrap turns it into a resync that re-fetches the
@@ -20037,17 +20531,17 @@ function provesSyncHealth(frame) {
20037
20531
  }
20038
20532
  const DEFAULT_PENDING_EXPIRY_MS = 1e4;
20039
20533
  const DEFAULT_STALE_PROBE_AFTER_MS = 25e3;
20040
- /** How long a probe may go unanswered before the link is presumed dead (DESYNC F6 / 8a). */
20534
+ /** How long a probe may go unanswered before the link is presumed dead. */
20041
20535
  const DEFAULT_PROBE_REPLY_TIMEOUT_MS = 1e4;
20042
20536
  /**
20043
- * Attach a realm client to a connection (plan §9). The store starts empty and fills on hydrate;
20537
+ * Attach a realm client to a connection. The store starts empty and fills on hydrate;
20044
20538
  * `realm.update()` is the blessed write API (LWW absolute-set contract — read-modify-write
20045
- * belongs in an intent, plan §6.1).
20539
+ * belongs in an intent, the protocol contract).
20046
20540
  */
20047
20541
  function connectRealm(realm, options) {
20048
20542
  const coordinate = options.connection.coordinate;
20049
20543
  const persistentId = options.avatar.persistentId ?? coordinate?.perId;
20050
- if (persistentId == null) throw new Error("connectRealm: no avatar identity — the connection carries no persistent id. Give it one where you open the connection (identity: coord.specify({ perId })), or pass avatar.persistentId explicitly.");
20544
+ if (persistentId == null) throw new Error("connectRealm: no avatar identity — the connection carries no persistent id. Give it one where you open the connection (identity: coord.withPersistentId(id)), or pass avatar.persistentId explicitly.");
20051
20545
  const avatar = {
20052
20546
  type: options.avatar.type,
20053
20547
  persistentId,
@@ -20064,9 +20558,9 @@ function connectRealm(realm, options) {
20064
20558
  const pendingListeners = /* @__PURE__ */ new Set();
20065
20559
  let confirmed = {};
20066
20560
  let confirmedVersion = -1;
20067
- /** The log epoch `confirmedVersion` belongs to (review B.3) — echoed in every hello. */
20561
+ /** The log epoch `confirmedVersion` belongs to — echoed in every hello. */
20068
20562
  let serverEpoch;
20069
- /** Server-advertised ingress limits off the hydrate (review B.2) — drives flush splitting. */
20563
+ /** Server-advertised ingress limits off the hydrate — drives flush splitting. */
20070
20564
  let advertisedLimits;
20071
20565
  let identityWarned = false;
20072
20566
  let status = "connecting";
@@ -20080,7 +20574,7 @@ function connectRealm(realm, options) {
20080
20574
  const warnTag = () => serverEpoch == null ? `[realm:${realm.id}]` : `[realm:${realm.id}#${serverEpoch.slice(0, 8)}]`;
20081
20575
  /** Status-transition listeners: `subscribeStatus` subscribers + the `whenLive` waiters (B.4). */
20082
20576
  const statusListeners = /* @__PURE__ */ new Set();
20083
- /** Latched on the first `live` and never reset (resilience-surface §4) — joining vs reconnecting. */
20577
+ /** Latched on the first `live` and never reset — joining vs reconnecting. */
20084
20578
  let hasBeenLive = false;
20085
20579
  const setStatus = (next) => {
20086
20580
  if (status === next) return;
@@ -20097,7 +20591,7 @@ function connectRealm(realm, options) {
20097
20591
  let projecting = false;
20098
20592
  let port;
20099
20593
  /**
20100
- * Staleness-probe clocks (review B.1).
20594
+ * Staleness-probe clocks.
20101
20595
  *
20102
20596
  * `lastSyncInboundAt` is deliberately a **sync-health** clock, not a liveness one: only a frame
20103
20597
  * carrying real server sync information stamps it (see {@link provesSyncHealth}). A `reject`
@@ -20105,16 +20599,16 @@ function connectRealm(realm, options) {
20105
20599
  * suppress the probe. That distinction matters because the two used to be one clock, and the
20106
20600
  * failure it allowed was self-sealing: a pathological reject loop is exactly the situation the
20107
20601
  * staleness probe exists to heal, and every reject in it pushed the probe further away
20108
- * (REVIEW F2).
20602
+ *.
20109
20603
  *
20110
20604
  * There is no separate *liveness* clock here because nothing at this layer needs one — liveness is
20111
- * the wire's job (`connectChannel({ linkKeepalive })`, which counts any inbound frame and drops a
20605
+ * the wire's job (`connectChannel({ heartbeat })`, which counts any inbound frame and drops a
20112
20606
  * silent link). The realm's probe is purely "am I still in sync?". If server-initiated liveness
20113
20607
  * ever lands and wants a pure inbound clock, it adds one then rather than re-merging these.
20114
20608
  */
20115
20609
  let lastSyncInboundAt = Date.now();
20116
20610
  let lastProbeAt = 0;
20117
- /** One-shot probe-reply deadline (DESYNC F6 / 8a) — armed after a probe, cleared by any inbound. */
20611
+ /** One-shot probe-reply deadline — armed after a probe, cleared by any inbound. */
20118
20612
  let probeDeadline;
20119
20613
  /** An attach/recovery hello is out and unanswered — non-continuous frames drop, never apply. */
20120
20614
  let helloInFlight = false;
@@ -20122,7 +20616,7 @@ function connectRealm(realm, options) {
20122
20616
  /** Suppress duplicate recovery hellos only while one is plausibly still being answered. */
20123
20617
  const HELLO_REPLY_GRACE_MS = 1e4;
20124
20618
  const warnedDiagnostics = /* @__PURE__ */ new Set();
20125
- /** `subscribeDiagnostics` listeners (devtools plan 4.2) — additive observers, multi-listener. */
20619
+ /** `subscribeDiagnostics` listeners — additive observers, multi-listener. */
20126
20620
  const diagnosticListeners = /* @__PURE__ */ new Set();
20127
20621
  const onDiagnostic = (event) => {
20128
20622
  devtools?.onDiagnostic?.(event);
@@ -20201,7 +20695,7 @@ function connectRealm(realm, options) {
20201
20695
  });
20202
20696
  };
20203
20697
  /**
20204
- * Declare lost-sync and heal via re-hello (DESYNC F2): the recovery hello is **probe-flavored**
20698
+ * Declare lost-sync and heal via re-hello: the recovery hello is **probe-flavored**
20205
20699
  * — no status flap, since on a live link the heal is one round-trip (the server replays exactly
20206
20700
  * the missed span from `confirmedVersion`, or full-hydrates when out of window / epoch
20207
20701
  * mismatch). Safe in every trigger scenario because `applyConfirmed` is immutable — a detected
@@ -20275,7 +20769,7 @@ function connectRealm(realm, options) {
20275
20769
  }
20276
20770
  }
20277
20771
  };
20278
- /** Backoff retry for a recovery whose ANSWER failed to apply (DESYNC F3): never a tight loop,
20772
+ /** Backoff retry for a recovery whose ANSWER failed to apply: never a tight loop,
20279
20773
  * never a silent give-up — each retry re-emits the `resync` diagnostic via `requestResync`. */
20280
20774
  let resyncAttempts = 0;
20281
20775
  let resyncTimer;
@@ -20300,7 +20794,7 @@ function connectRealm(realm, options) {
20300
20794
  const notifyPending = () => {
20301
20795
  for (const listener of pendingListeners) listener();
20302
20796
  };
20303
- /** Patch-feed listeners (review C.2) + the last projection they were told about. */
20797
+ /** Patch-feed listeners + the last projection they were told about. */
20304
20798
  const patchListeners = /* @__PURE__ */ new Set();
20305
20799
  let lastProjected = {};
20306
20800
  /**
@@ -20487,7 +20981,7 @@ function connectRealm(realm, options) {
20487
20981
  return part;
20488
20982
  };
20489
20983
  /**
20490
- * Split one over-limit write frame into consecutive ≤`limit` parts (review B.2): each part is
20984
+ * Split one over-limit write frame into consecutive ≤`limit` parts: each part is
20491
20985
  * atomic on the server; every settle handle rides the LAST part, so read-your-writes holds
20492
20986
  * (acks are ordered). The trade — a split flush loses whole-flush atomicity — is documented on
20493
20987
  * `update()`. Replaces `frame` in the pending queue in place, preserving projection order.
@@ -20761,7 +21255,7 @@ function connectRealm(realm, options) {
20761
21255
  return controller.handle;
20762
21256
  };
20763
21257
  /**
20764
- * `limits_exceeded` recovery (review B.2): a well-behaved client must survive a breach — even
21258
+ * `limits_exceeded` recovery: a well-behaved client must survive a breach — even
20765
21259
  * a mis-advertised limit — instead of settling the write as a fatal reject (and, ×10, being
20766
21260
  * forcibly detached). Frame-size breaches re-split against a halved local ceiling; a rate
20767
21261
  * breach resends after a backoff. Bounded by {@link MAX_LIMIT_RETRIES} and the frame's own
@@ -20979,14 +21473,14 @@ function connectRealm(realm, options) {
20979
21473
  }
20980
21474
  };
20981
21475
  /**
20982
- * The defensive inbound boundary (DESYNC F3): every inbound frame runs through `handleFrame`
21476
+ * The defensive inbound boundary: every inbound frame runs through `handleFrame`
20983
21477
  * inside this wrap. A decode/apply throw — an unknown interned key id (`detokenizePath`), a
20984
21478
  * patch that can't resolve its parent (`applyConfirmed`) — must NOT escape into the wire mux,
20985
21479
  * silently drop the frame, or (inside a batch) abort its siblings. On any failure we heal the
20986
21480
  * same way a version gap does: re-hello with backoff. `lastSyncInboundAt` is stamped only AFTER a
20987
21481
  * clean handling, so a throwing frame no longer fools the staleness probe into thinking the
20988
- * link is healthy (review F1.3) — and only for a frame that actually carries sync information
20989
- * ({@link provesSyncHealth}), so a reject cannot either (REVIEW F2).
21482
+ * link is healthy — and only for a frame that actually carries sync information
21483
+ * ({@link provesSyncHealth}), so a reject cannot either.
20990
21484
  */
20991
21485
  const onFrame = (frame, byteSize) => {
20992
21486
  devtools?.onFrame?.("in", REALM_FRAME_KIND_NAME[frame.kind] ?? String(frame.kind), byteSize ?? 0);
@@ -21011,7 +21505,7 @@ function connectRealm(realm, options) {
21011
21505
  }
21012
21506
  };
21013
21507
  /**
21014
- * The identity echo check (review A.4.2): the hydrate names the avatar the server resolved —
21508
+ * The identity echo check: the hydrate names the avatar the server resolved —
21015
21509
  * the one verdicts and view slicing run against. A disagreement with our own ref is the
21016
21510
  * silent-flicker bug class (prediction passes locally, the server rejects every time), so it
21017
21511
  * warns loudly, once per handle.
@@ -21021,7 +21515,7 @@ function connectRealm(realm, options) {
21021
21515
  if (type === avatar.type && persistentId === avatar.persistentId && instanceId === avatar.instanceId) return;
21022
21516
  if (identityWarned) return;
21023
21517
  identityWarned = true;
21024
- console.warn(`${warnTag()} identity mismatch — this client predicts as ${avatar.type}/${avatar.persistentId}/${avatar.instanceId} but the server resolved it as ${type}/${persistentId}/${instanceId} (review A.4.2). Prediction and view slicing run against DIFFERENT identities: owner-gated writes will pass locally and reject on the server. Fix the server's resolveAvatar/avatarType, or the avatar passed to connectRealm.`);
21518
+ console.warn(`${warnTag()} identity mismatch — this client predicts as ${avatar.type}/${avatar.persistentId}/${avatar.instanceId} but the server resolved it as ${type}/${persistentId}/${instanceId}. Prediction and view slicing run against DIFFERENT identities: owner-gated writes will pass locally and reject on the server. Fix the server's resolveAvatar/avatarType, or the avatar passed to connectRealm.`);
21025
21519
  };
21026
21520
  /**
21027
21521
  * The reassert lane (Phase 2 / Overshot Issue 2): ride a recovery hello with a re-own WRITE so a
@@ -21092,7 +21586,7 @@ function connectRealm(realm, options) {
21092
21586
  * - A **probe** hello (staleness probe, wake rehello, `write_target_missing` resync) keeps `live`
21093
21587
  * status (no HUD flap on a link that never dropped) and KEEPS the dict: it rides the same-or-woken
21094
21588
  * session where the server re-sends a delta before first use of any id and `RealmKeyDict.load`
21095
- * overwrites, so a reassigned id is corrected before it is ever resolved (DESYNC F4). It arms the
21589
+ * overwrites, so a reassigned id is corrected before it is ever resolved. It arms the
21096
21590
  * escalation deadline instead — no inbound within the window ⇒ the link is genuinely dead and
21097
21591
  * status flips to `connecting` truthfully (Phase 1.2).
21098
21592
  */
@@ -21297,11 +21791,11 @@ function connectRealm(realm, options) {
21297
21791
  realmId: realm.id,
21298
21792
  slot,
21299
21793
  avatar,
21300
- peer: options.connection.peerCoordinate?.envId
21794
+ peer: (options.connection.peer ?? options.connection.peerCoordinate)?.envId
21301
21795
  });
21302
21796
  return handle;
21303
21797
  }
21304
- /** Last write wins per exact path inside one coalesced frame (plan §9.1). */
21798
+ /** Last write wins per exact path inside one coalesced frame. */
21305
21799
  function dedupeByPath(patches) {
21306
21800
  const byPath = /* @__PURE__ */ new Map();
21307
21801
  for (const patch of patches) byPath.set(patch.path.join(" "), patch);
@@ -21324,7 +21818,7 @@ enablePatches();
21324
21818
  //#endregion
21325
21819
  //#region ../nice-realm/src/RealmClient/realmMuxClient.ts
21326
21820
  const managers = /* @__PURE__ */ new WeakMap();
21327
- /** Grace period before a released slot number may be recycled (DESYNC F7) — see `release()`. */
21821
+ /** Grace period before a released slot number may be recycled — see `release()`. */
21328
21822
  const SLOT_QUARANTINE_MS = 5e3;
21329
21823
  function managerFor(mux) {
21330
21824
  let manager = managers.get(mux);
@@ -21410,7 +21904,7 @@ function realmConnection(source) {
21410
21904
  const mux = isMux ? source : source.wireMux;
21411
21905
  if (mux == null) throw new Error("realmConnection: this link has no frame-protocol mux — connect it via connectChannel (which creates one per connection) or pass a WireProtocolMux directly.");
21412
21906
  const coordinate = isMux ? void 0 : source.localCoordinate;
21413
- const peerCoordinate = isMux ? void 0 : source.peerClient;
21907
+ const peer = isMux ? void 0 : "peer" in source ? source.peer : source.peerClient;
21414
21908
  const securityLevel = isMux ? void 0 : source.securityLevel;
21415
21909
  const requestReconnect = isMux ? void 0 : source.requestReconnect;
21416
21910
  const linkEventSource = isMux ? void 0 : source.addLinkEventListener?.bind(source);
@@ -21422,7 +21916,8 @@ function realmConnection(source) {
21422
21916
  return {
21423
21917
  slot,
21424
21918
  coordinate,
21425
- peerCoordinate,
21919
+ peer,
21920
+ peerCoordinate: peer,
21426
21921
  securityLevel,
21427
21922
  requestReconnect,
21428
21923
  subscribeLinkEvents: linkEventSource,
@@ -21533,7 +22028,7 @@ function assertRulePatternsMatchSchema(root, patterns) {
21533
22028
  }
21534
22029
  }
21535
22030
  /**
21536
- * Validate + parse a realm's `transient` region paths (PLAN-REALM-MESSAGE-OVERLOAD Phase 5). v1
22031
+ * Validate + parse a realm's `transient` region paths. v1
21537
22032
  * accepts only **concrete, wildcard-free** dot-paths, each naming a subtree root that exists in the
21538
22033
  * schema (`"presence"`, `"board.cursors"`). Wildcards (`$var`, `*`, `**`, `{a,b}`) are rejected —
21539
22034
  * snapshot-strip and the replay refresh are a trivial root walk, not a pattern projection (that is a
@@ -21689,7 +22184,7 @@ var RealmRuleTrie = class {
21689
22184
  //#endregion
21690
22185
  //#region ../nice-realm/src/RealmDefinition/Schema/schemaHash.ts
21691
22186
  /**
21692
- * The realm schema hash (plan §4.1/§7.1-of-proposal): SHA-256 over a canonical serialization of
22187
+ * The realm schema hash: SHA-256 over a canonical serialization of
21693
22188
  * everything both sides must agree on for the wire to be meaningful — realm id, state shape
21694
22189
  * (sorted), client-type names, intent names + input shapes, and rule path patterns. It rides the
21695
22190
  * realm `hello` and hard-fails a mismatch (`err_realm.schema_mismatch`): silent token skew on a
@@ -21809,7 +22304,7 @@ var RealmTokenMap = class {
21809
22304
  }
21810
22305
  /**
21811
22306
  * Name path → wire path (object keys → ints; record keys pass through as strings, or as
21812
- * interned ids when `internKey` resolves one — plan §7.9 key interning).
22307
+ * interned ids when `internKey` resolves one — the protocol contract key interning).
21813
22308
  */
21814
22309
  tokenizePath(path, internKey) {
21815
22310
  const out = [];
@@ -21927,7 +22422,7 @@ function union(...args) {
21927
22422
  };
21928
22423
  }
21929
22424
  /**
21930
- * The realm schema builder — `t.*` (plan §4.1). One `defineRealm` block uses these to declare the
22425
+ * The realm schema builder — `t.*`. One `defineRealm` block uses these to declare the
21931
22426
  * state shape; from that single declaration the library derives the TS types, the token map, the
21932
22427
  * schema hash, and (M4) the server-side value validator.
21933
22428
  */
@@ -22007,7 +22502,7 @@ const t = {
22007
22502
  };
22008
22503
  },
22009
22504
  /**
22010
- * Declare the server-only context TYPE (plan §5). The value is injected at
22505
+ * Declare the server-only context TYPE. The value is injected at
22011
22506
  * `createRealmServerEngine(realm, { ctx })` time — nothing here exists in client bundles, and
22012
22507
  * nothing secret may be closed over in the definition module.
22013
22508
  */
@@ -22266,7 +22761,7 @@ function pruneNode(ctx, node, value, path) {
22266
22761
  anyVisible: true
22267
22762
  } : OMIT;
22268
22763
  }
22269
- /** The avatar's sliced view of the whole state — the hydrate payload (plan §8.1). */
22764
+ /** The avatar's sliced view of the whole state — the hydrate payload. */
22270
22765
  function sliceStateForAvatar(ctx, state) {
22271
22766
  const out = {};
22272
22767
  for (const [key, node] of Object.entries(ctx.schemaRoot)) out[key] = pruneNode(ctx, node, state[key], [key]).value ?? {};
@@ -22354,7 +22849,7 @@ function clientKey(avatar) {
22354
22849
  return `${avatar.type} ${avatar.persistentId}`;
22355
22850
  }
22356
22851
  /**
22357
- * Mint a log epoch (review B.3): a random id identifying one history of one realm instance.
22852
+ * Mint a log epoch: a random id identifying one history of one realm instance.
22358
22853
  * Uniqueness only needs to hold across *rebuilds of the same realm* (wiped storage, re-created
22359
22854
  * DO, migration) — collision means a stale avatar silently replays a foreign diff, so time +
22360
22855
  * randomness is plenty. Platform-clean on purpose (no `crypto` dependency).
@@ -22373,7 +22868,7 @@ var RealmServerEngine = class {
22373
22868
  _hasBounds;
22374
22869
  _version = 0;
22375
22870
  _mutating = false;
22376
- /** The log epoch (review B.3): identifies this history — replay requires an exact match. */
22871
+ /** The log epoch: identifies this history — replay requires an exact match. */
22377
22872
  _epoch;
22378
22873
  _log;
22379
22874
  _logWindow;
@@ -22411,10 +22906,10 @@ var RealmServerEngine = class {
22411
22906
  */
22412
22907
  _pendingAcks = [];
22413
22908
  /**
22414
- * Replay/duplicate high-water per connection **key** (PLAN-security §5.2b) — the highest
22909
+ * Replay/duplicate high-water per connection **key** — the highest
22415
22910
  * `clientSeq` accepted for processing on a `connKey`. Kept **outside** the `IEngineConnection`
22416
22911
  * record on purpose: a same-avatar re-hello swaps the conn record in place (`attach()`'s
22417
- * reattach path, DESYNC F3 — it no longer detaches at all), so a per-record counter would reset
22912
+ * reattach path, the reconnect contract — it no longer detaches at all), so a per-record counter would reset
22418
22913
  * to `-1` and a replayed `hello` could reopen the window (Fact B). This map survives the
22419
22914
  * re-attach trivially; `detachConnection` clears it on a *real* close. Phase 3b persists this
22420
22915
  * across a hibernation wake (Fact C).
@@ -22473,7 +22968,7 @@ var RealmServerEngine = class {
22473
22968
  get instanceId() {
22474
22969
  return this._instanceId;
22475
22970
  }
22476
- /** The log epoch (review B.3) — minted at genesis/migrate, persisted by the platform host. */
22971
+ /** The log epoch — minted at genesis/migrate, persisted by the platform host. */
22477
22972
  get epoch() {
22478
22973
  return this._epoch;
22479
22974
  }
@@ -22492,7 +22987,7 @@ var RealmServerEngine = class {
22492
22987
  * Calling it for a `connKey` that is already attached with the **same avatar** is a
22493
22988
  * **re-attach** (staleness probe / wake rehello): the connection record is swapped in place —
22494
22989
  * fresh `sentKeyIds`/`features`, preserved rate bucket, migrated window acks — and the avatar
22495
- * lifecycle hooks do NOT fire (DESYNC F3: the avatar never left). A different avatar on the
22990
+ * lifecycle hooks do NOT fire. A different avatar on the
22496
22991
  * same `connKey` first runs the old avatar's full detach bookkeeping.
22497
22992
  */
22498
22993
  attach(connKey, options) {
@@ -22599,7 +23094,7 @@ var RealmServerEngine = class {
22599
23094
  * per socket — so this is pure cleanup, not correctness). `preserveReplayHighWater` is retained
22600
23095
  * for compatibility but no longer has an internal caller: a same-realm re-hello no longer
22601
23096
  * detaches at all — `attach()` swaps the connection record in place without firing the avatar
22602
- * lifecycle (DESYNC F3), and the high-water survives trivially.
23097
+ * lifecycle, and the high-water survives trivially.
22603
23098
  */
22604
23099
  detachConnection(connKey, reason = "detached", notifyPeer = false, preserveReplayHighWater = false, bypassGrace = false) {
22605
23100
  const conn = this._connections.get(connKey);
@@ -22619,7 +23114,7 @@ var RealmServerEngine = class {
22619
23114
  this._deferOrFireDetach(conn.avatar, reason, bypassGrace);
22620
23115
  } else this._avatarConnCounts.set(ck, count - 1);
22621
23116
  }
22622
- /** Forced detach / revocation (plan §8.3): drop every connection of a persistent avatar. */
23117
+ /** Forced detach / revocation: drop every connection of a persistent avatar. */
22623
23118
  detachAvatar(persistentId, reason = "revoked") {
22624
23119
  for (const conn of [...this._connections.values()]) if (conn.avatar.persistentId === persistentId) this.detachConnection(conn.key, reason, true, false, true);
22625
23120
  for (const [ck, pending] of [...this._pendingDetaches]) {
@@ -22632,7 +23127,7 @@ var RealmServerEngine = class {
22632
23127
  /**
22633
23128
  * Park the per-avatar detach for the grace window (or fire it now with no/ bypassed grace) —
22634
23129
  * the one funnel every last-connection departure goes through, `reportAvatarLost` included.
22635
- * Dispatch stays microtask-deferred (review B.5) so the hook may freely `engine.update()`.
23130
+ * Dispatch stays microtask-deferred so the hook may freely `engine.update()`.
22636
23131
  */
22637
23132
  _deferOrFireDetach(avatar, reason, bypassGrace) {
22638
23133
  if (!bypassGrace && this._detachGraceMs > 0) {
@@ -22730,7 +23225,7 @@ var RealmServerEngine = class {
22730
23225
  return this._connections.size;
22731
23226
  }
22732
23227
  /**
22733
- * The engine's traffic totals since construction (devtools plan §5.1): ingress frames/bytes,
23228
+ * The engine's traffic totals since construction: ingress frames/bytes,
22734
23229
  * egress **messages** (the per-message billing unit) vs frames (pre-coalescing) and bytes.
22735
23230
  * `egressCoalesceRatio` is the batch-envelope + broadcast-tick win made measurable — frames
22736
23231
  * folded per WS message. Plain data; hosts expose it however they like (a dev-only debug
@@ -22774,7 +23269,7 @@ var RealmServerEngine = class {
22774
23269
  }
22775
23270
  /**
22776
23271
  * The egress features a connection advertised via `clientCaps`
22777
- * (PLAN-REALM-MESSAGE-OVERLOAD Phase 1), or `undefined` when the connKey is not attached. Phase 2
23272
+ *, or `undefined` when the connKey is not attached. Phase 2
22778
23273
  * consumes `REALM_FEATURE.batch` here to gate the `batch` envelope; exposed for hosts/tests.
22779
23274
  */
22780
23275
  connectionFeatures(connKey) {
@@ -22811,9 +23306,9 @@ var RealmServerEngine = class {
22811
23306
  }
22812
23307
  /**
22813
23308
  * Mutate authoritative state from server code (`r.serverOnly` paths — game ticks, fulfilment;
22814
- * plan §8.2). Flows through the same version/log/slice tail, so server writes broadcast
23309
+ * the protocol contract). Flows through the same version/log/slice tail, so server writes broadcast
22815
23310
  * identically. Throws when called re-entrantly from an intent `apply` or a rule (single-writer
22816
- * invariant, plan §8.3).
23311
+ * invariant, the protocol contract).
22817
23312
  */
22818
23313
  update(fn) {
22819
23314
  this._guardReentrancy();
@@ -23278,7 +23773,7 @@ var RealmServerEngine = class {
23278
23773
  return false;
23279
23774
  }
23280
23775
  /**
23281
- * The replay/duplicate high-water gate (PLAN-security §5.2b, Facts A/B). Returns `false` — caller
23776
+ * The replay/duplicate high-water gate. Returns `false` — caller
23282
23777
  * must stop — when `clientSeq` is at or below the connection's high-water: the frame is either a
23283
23778
  * replay (a captured frame re-injected into the framing layer) or a benign ack-lost resend, which
23284
23779
  * by seq alone are indistinguishable and both safe to treat as already-processed. It is settled
@@ -23300,7 +23795,7 @@ var RealmServerEngine = class {
23300
23795
  return true;
23301
23796
  }
23302
23797
  /**
23303
- * Advance the connection's replay high-water and persist it (PLAN-security §5.2b Fact C). Persist
23798
+ * Advance the connection's replay high-water and persist it. Persist
23304
23799
  * runs per accepted frame so the durable value never lags an arbitrary hibernation point (a
23305
23800
  * lagging value would reopen the wake-replay window). Cost: one host-side upsert per accepted
23306
23801
  * `write`/`intent` — see the host's `persistSeqHighWater`, which may batch if it proves hot.
@@ -23339,7 +23834,7 @@ var RealmServerEngine = class {
23339
23834
  /**
23340
23835
  * Send a rejection to one connection. The wire carries **only** the error's public
23341
23836
  * `toJsonObject()` (ids, user-provided error context, message, stack) — never the realm's
23342
- * `serverContext` (`ctx`), which the engine never places on an error (PLAN-security Phase 6
23837
+ * `serverContext` (`ctx`), which the engine never places on an error (the protocol contract
23343
23838
  * secret-scrub, verified). Discipline this implies for realm authors: a rule/intent error's
23344
23839
  * **context and message are wire-visible**, so they must not embed server secrets (`ctx` values,
23345
23840
  * internal ids) — the same rule as the client bundle. Documented in the security guide (Phase 8).
@@ -23450,14 +23945,14 @@ function pathsOverlap(a, b) {
23450
23945
  for (let i = 0; i < len; i++) if (a[i] !== b[i]) return false;
23451
23946
  return true;
23452
23947
  }
23453
- /** Factory with full inference from the realm definition (plan §8.2). */
23948
+ /** Factory with full inference from the realm definition. */
23454
23949
  function createRealmServerEngine(realm, options) {
23455
23950
  return new RealmServerEngine(realm, options);
23456
23951
  }
23457
23952
  //#endregion
23458
23953
  //#region ../nice-realm/src/RealmServer/realmAcceptorProtocol.ts
23459
23954
  function createRealmAcceptor(options) {
23460
- if (options.levelFor == null && Object.values(options.realms).some((hosted) => hosted.minSecurity != null)) console.warn("[realm] a hosted realm declares `minSecurity` but createRealmAcceptor received no `levelFor` — the security minimum is NOT enforced (only the coarse wire gate, which blocks `none`, applies). Wire a `levelFor` (serveRealmDurableObject does this for you).");
23955
+ for (const [realmId, hosted] of Object.entries(options.realms)) if (hosted.resolveAvatar == null === (hosted.avatarType == null)) throw new Error(`createRealmAcceptor: realm "${realmId}" requires exactly one of \`resolveAvatar\` or \`avatarType\``);
23461
23956
  const connStates = /* @__PURE__ */ new WeakMap();
23462
23957
  let connCounter = 0;
23463
23958
  const stateFor = (connection) => {
@@ -23476,7 +23971,11 @@ function createRealmAcceptor(options) {
23476
23971
  return {
23477
23972
  id: "realm",
23478
23973
  prefixByte: WIRE_PROTOCOL_PREFIX.realm,
23479
- onFrame(connection, payload, send) {
23974
+ onFrame(connection, payload, send, suppliedContext) {
23975
+ const context = suppliedContext ?? {
23976
+ client: void 0,
23977
+ level: options.levelFor?.(connection) ?? "none"
23978
+ };
23480
23979
  let frame;
23481
23980
  try {
23482
23981
  frame = decodeRealmFrame(payload);
@@ -23494,7 +23993,11 @@ function createRealmAcceptor(options) {
23494
23993
  }));
23495
23994
  return;
23496
23995
  }
23497
- const avatar = hosted.resolveAvatar(connection);
23996
+ const avatar = hosted.resolveAvatar?.(connection, context) ?? (hosted.avatarType != null && context.client?.perId != null ? {
23997
+ type: hosted.avatarType,
23998
+ persistentId: context.client.perId,
23999
+ instanceId: context.client.insId ?? "default"
24000
+ } : void 0);
23498
24001
  if (avatar == null) {
23499
24002
  send(encodeReject({
23500
24003
  slot: frame.slot,
@@ -23503,8 +24006,8 @@ function createRealmAcceptor(options) {
23503
24006
  }));
23504
24007
  return;
23505
24008
  }
23506
- if (hosted.minSecurity != null && options.levelFor != null) {
23507
- const actual = options.levelFor(connection);
24009
+ if (hosted.minSecurity != null) {
24010
+ const actual = context.level;
23508
24011
  if (!securityLevelMeets(actual, hosted.minSecurity)) {
23509
24012
  send(encodeReject({
23510
24013
  slot: frame.slot,
@@ -23854,7 +24357,7 @@ var CommanderDaemonBootError = class extends Error {
23854
24357
  */
23855
24358
  async function replaceSkewedDaemon(paths, skewed) {
23856
24359
  const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v6${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
23857
- let liveIds = [];
24360
+ let liveIds;
23858
24361
  try {
23859
24362
  liveIds = (await openProcessLedger({
23860
24363
  dir: paths.stateDir,
@@ -24098,11 +24601,17 @@ function checkEnvReport(value) {
24098
24601
  warnings
24099
24602
  };
24100
24603
  }
24101
- function checkIds(value) {
24604
+ function checkStop(value) {
24102
24605
  const record = asRecord(value);
24103
24606
  if (record == null) return "expected an object";
24104
24607
  const ids = asIdList(record["ids"]);
24105
- return ids == null ? "ids: expected an array of process ids" : { ids };
24608
+ if (ids == null) return "ids: expected an array of process ids";
24609
+ const withDependencies = record["withDependencies"];
24610
+ if (withDependencies != null && typeof withDependencies !== "boolean") return "withDependencies: expected a boolean";
24611
+ return withDependencies === true ? {
24612
+ ids,
24613
+ withDependencies
24614
+ } : { ids };
24106
24615
  }
24107
24616
  function checkRunSuite(value) {
24108
24617
  const record = asRecord(value);
@@ -24243,7 +24752,7 @@ const commanderControlDomain = createActionRootDomain({ domain: "commander" }).c
24243
24752
  actions: {
24244
24753
  ports: actionSchema().input({ schema: handSchema(checkPortsInput) }).output({ schema: handSchema(checkPortsReport) }),
24245
24754
  start: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
24246
- stop: actionSchema().input({ schema: handSchema(checkIds) }).output({ schema: handSchema(checkReport) }),
24755
+ stop: actionSchema().input({ schema: handSchema(checkStop) }).output({ schema: handSchema(checkReport) }),
24247
24756
  restart: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
24248
24757
  runSuite: actionSchema().input({ schema: handSchema(checkRunSuite) }).output({ schema: handSchema(checkRunSuiteReport) }),
24249
24758
  saveFilter: actionSchema().input({ schema: handSchema(checkSaveFilter) }).output({ schema: handSchema(checkOk) }),
@@ -24351,11 +24860,11 @@ async function connectDaemon(handle) {
24351
24860
  ephemeralIdentity: true,
24352
24861
  securityLevel: "authenticated",
24353
24862
  defaultTimeout: COMMANDER_CONTROL_TIMEOUT_MS,
24354
- keepLinkAlive: false,
24863
+ reconnect: false,
24355
24864
  onLinkEvent: (event) => {
24356
24865
  if (process.env["NICE_COMMANDER_DEBUG"] != null) process.stderr.write(`[link] ${JSON.stringify(event)}\n`);
24357
24866
  },
24358
- transports: [{ carrier: wsCarrier(() => ({ url: `ws://127.0.0.1:${record.port}${COMMANDER_WS_PATH}` }), { createWebSocket: (url) => {
24867
+ carriers: [wsCarrier(() => ({ url: `ws://127.0.0.1:${record.port}${COMMANDER_WS_PATH}` }), { createWebSocket: (url) => {
24359
24868
  if (process.env["NICE_COMMANDER_DEBUG"] != null) process.stderr.write(`[ws] dialing ${url}\n`);
24360
24869
  const socket = new WebSocket$1(url, [`${COMMANDER_TICKET_PROTOCOL_PREFIX}${ticket}`]);
24361
24870
  if (process.env["NICE_COMMANDER_DEBUG"] != null) {
@@ -24364,7 +24873,7 @@ async function connectDaemon(handle) {
24364
24873
  socket.on("close", (code) => process.stderr.write(`[ws] close ${code}\n`));
24365
24874
  }
24366
24875
  return socket;
24367
- } }) }]
24876
+ } })]
24368
24877
  });
24369
24878
  const realm = connectRealm(commanderStatusRealm, {
24370
24879
  onDiagnostic: (event) => {
@@ -24737,7 +25246,7 @@ async function listeners(port) {
24737
25246
  } catch (error) {
24738
25247
  const e = error;
24739
25248
  if (Number(e.code) === 1 && !e.stderr?.trim()) return parseLsof(e.stdout ?? "");
24740
- throw new Error(`Cannot inspect TCP ${port}: ${e.code === "ENOENT" ? "install lsof and retry" : e.message}`);
25249
+ throw new Error(`Cannot inspect TCP ${port}: ${e.code === "ENOENT" ? "install lsof and retry" : e.message}`, { cause: error });
24741
25250
  }
24742
25251
  }
24743
25252
  async function localAddresses(host) {
@@ -26421,7 +26930,7 @@ async function withTimeout(ctx, run) {
26421
26930
  async function main() {
26422
26931
  const argv = process.argv.slice(2);
26423
26932
  if (argv[0] === "daemon") {
26424
- const { runCommanderDaemon } = await import("./main-DrNJc_xN.mjs");
26933
+ const { runCommanderDaemon } = await import("./main-DCr__iZh.mjs");
26425
26934
  return runCommanderDaemon(argv.slice(1));
26426
26935
  }
26427
26936
  const parsed = parseCliArgs(argv);
@@ -26466,6 +26975,6 @@ main().then((code) => {
26466
26975
  process.exitCode = EXIT.failure;
26467
26976
  });
26468
26977
  //#endregion
26469
- export { ActionRuntime as A, withDependencies as B, resolveCommanderDataDir as C, wsAcceptorCarrier as D, httpAcceptorCarrier as E, envVarViews as F, writeInstanceRecord as G, readInstanceRecord as H, overrideFingerprint as I, hashCanonical as L, createMemoryStorageAdapter_json as M, validateCommanderConfig as N, serveChannel as O, effectiveEnv as P, loadCommanderConfigFile as R, ensureStateDir as S, createRealmServerEngine as T, recordDaemonAlive as U, savedFilterId as V, removeInstanceRecord as W, COMMANDER_WS_PATH as _, parseLogsClientMessage as a, commanderPackageVersion as b, countOverrides as c, commanderControlDomain as d, COMMANDER_BOOTSTRAP_PATH as f, COMMANDER_TICKET_PROTOCOL_PREFIX as g, COMMANDER_TICKET_PATH as h, runTaskPool as i, RuntimeCoordinate as j, createDefaultServeLogger as k, readEnvOverrides as l, COMMANDER_LOGS_PATH as m, readSavedFilters as n, createPortInspector as o, COMMANDER_HEALTH_PATH as p, writeSavedFilters as r, applyEnvMutation as s, mutateSavedFilters as t, commanderChannel as u, commanderStatusRealm as v, createRealmAcceptor as w, commanderStatePaths as x, commanderRuntimeError as y, orderByDependency as z };
26978
+ export { createMemoryStorageAdapter_json as A, withDependencies as B, resolveCommanderDataDir as C, serveChannel as D, httpAcceptorCarrier as E, overrideFingerprint as F, writeInstanceRecord as G, readInstanceRecord as H, hashCanonical as I, loadCommanderConfigFile as L, validateCommanderConfig as M, effectiveEnv as N, createDefaultServeLogger as O, envVarViews as P, orderByDependency as R, ensureStateDir as S, createRealmServerEngine as T, recordDaemonAlive as U, savedFilterId as V, removeInstanceRecord as W, COMMANDER_WS_PATH as _, parseLogsClientMessage as a, commanderPackageVersion as b, countOverrides as c, commanderControlDomain as d, COMMANDER_BOOTSTRAP_PATH as f, COMMANDER_TICKET_PROTOCOL_PREFIX as g, COMMANDER_TICKET_PATH as h, runTaskPool as i, wsAcceptorCarrier as j, RuntimeCoordinate as k, readEnvOverrides as l, COMMANDER_LOGS_PATH as m, readSavedFilters as n, createPortInspector as o, COMMANDER_HEALTH_PATH as p, writeSavedFilters as r, applyEnvMutation as s, mutateSavedFilters as t, commanderChannel as u, commanderStatusRealm as v, createRealmAcceptor as w, commanderStatePaths as x, commanderRuntimeError as y, stopSetWithDependencies as z };
26470
26979
 
26471
26980
  //# sourceMappingURL=cli.mjs.map