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