{"version":3,"file":"createHibernatableWsServerAdapter-C-xM8r1d.mjs","names":["ConnectionTransportManager","WireConnectionTransportManager","ConnectionTransportManager","ETransportShape","reliableStreamId","ETransportShape","TransportConnection","WireTransportConnection","TransportConnection","ETransportShape","ETransportShape","TransportConnection","ETransportShape","ETransportShape"],"sources":["../src/ActionDefinition/Action/ActionBase.ts","../src/ActionDefinition/Action/Payload/ActionPayload.ts","../src/utils/hashPayloadData.ts","../src/ActionDefinition/Action/Payload/ActionPayload.types.ts","../src/ActionDefinition/Action/Payload/ActionPayload_Progress.ts","../src/ActionDefinition/Action/Payload/ActionPayload_Result.ts","../src/ActionDefinition/Action/Payload/ActionPayload_Request.ts","../src/ActionDefinition/Action/RunningAction.ts","../src/errors/err_nice_action.ts","../src/utils/isAction_Base_JsonObject.ts","../src/utils/isActionPayload_Result_JsonObject.ts","../src/ActionDefinition/Schema/ActionSchema.ts","../src/utils/getAssumedRuntimeEnvironment.ts","../src/utils/isActionPayload_Progress_JsonObject.ts","../src/utils/isActionPayload_Request_JsonObject.ts","../src/utils/isActionPayload_Any_JsonObject.ts","../src/ActionRuntime/HandlerCallStack.ts","../src/ActionRuntime/Handler/PeerLink/Connector/err_nice_external_client.ts","../src/ActionRuntime/Transport/err_nice_transport.ts","../src/ActionRuntime/Transport/ConnectionTransportManager.ts","../src/ActionRuntime/ActionDomainManager.ts","../src/ActionRuntime/Routing/ActionRouter.ts","../src/ActionRuntime/Handler/ActionHandler.ts","../src/ActionRuntime/Handler/PeerLink/PeerLink.ts","../src/ActionRuntime/Handler/PeerLink/Connector/ReliableOutbox.ts","../src/ActionRuntime/Handler/PeerLink/Connector/ChannelConnector.ts","../src/ActionRuntime/ActionRuntime.ts","../src/ActionRuntime/Handler/Local/ActionLocalHandler.ts","../src/utils/decodeActionFrame.ts","../src/ActionRuntime/Channel/serveLogger.ts","../src/ActionRuntime/Handler/PeerLink/Acceptor/ChannelAcceptor.ts","../src/ActionRuntime/Handler/PeerLink/Acceptor/createSecureChannelAcceptor.ts","../src/ActionRuntime/Transport/codec/actionWireCodec.ts","../src/ActionRuntime/Transport/codec/createBinaryWireSessionFactory.ts","../src/ActionRuntime/Transport/Transport.ts","../src/ActionRuntime/Transport/SecureSession/establishExchangeSession.ts","../src/ActionRuntime/Transport/TransportConnection.ts","../src/ActionRuntime/Transport/Exchange/ExchangeConnection.ts","../src/ActionRuntime/Transport/Exchange/ExchangeTransport.ts","../src/ActionRuntime/Transport/helpers/createUnsetTransportResolvers.ts","../src/ActionRuntime/Transport/SecureSession/establishLinkSession.ts","../src/ActionRuntime/Transport/Link/LinkConnection.ts","../src/ActionRuntime/Transport/Link/LinkTransport.ts","../src/ActionRuntime/Transport/SecureSession/exchangeAcceptor.ts","../src/ActionRuntime/Handler/PeerLink/Acceptor/createActionFetchHandler.ts","../src/ActionRuntime/Handler/PeerLink/Acceptor/Hibernation/ConnectionStateStore.ts","../src/ActionRuntime/Handler/PeerLink/Acceptor/Hibernation/createHibernatableWsServerAdapter.ts"],"sourcesContent":["import type { ActionDomain } from \"../Domain/ActionDomain\";\nimport type { IActionDomain } from \"../Domain/ActionDomain.types\";\nimport type { EActionForm, IActionBase, IActionBase_JsonObject } from \"./ActionBase.types\";\n\nexport abstract class ActionBase<\n  FORM extends EActionForm,\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> implements IActionBase<FORM, DOM, ID>\n{\n  readonly domain: DOM[\"domain\"];\n  readonly allDomains: DOM[\"allDomains\"];\n  readonly schema: DOM[\"actionSchema\"][ID];\n\n  constructor(\n    readonly form: FORM,\n    readonly _domain: ActionDomain<DOM>,\n    readonly id: ID,\n  ) {\n    this.domain = _domain.domain;\n    this.allDomains = _domain.allDomains;\n    this.schema = _domain.actionSchema[id];\n  }\n\n  protected toJsonObject(): IActionBase_JsonObject<FORM, DOM, ID> {\n    return {\n      form: this.form,\n      domain: this.domain,\n      allDomains: this.allDomains,\n      id: this.id,\n    };\n  }\n\n  protected toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n}\n","import type { IActionDomain } from \"../../Domain/ActionDomain.types\";\nimport { ActionBase } from \"../ActionBase\";\nimport { EActionForm } from \"../ActionBase.types\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport type {\n  EActionPayloadType,\n  IActionPayload_Base,\n  IActionPayload_Base_JsonObject,\n  IActionPayload_Data_Base,\n} from \"./ActionPayload.types\";\n\nexport abstract class ActionPayload<\n    DT extends EActionPayloadType,\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n  >\n  extends ActionBase<EActionForm.data, DOM, ID>\n  implements IActionPayload_Base<DT, DOM, ID>\n{\n  readonly form: EActionForm.data = EActionForm.data;\n  readonly type: DT;\n  readonly context: ActionContext<DOM, ID>;\n  readonly time: number;\n\n  protected constructor(context: ActionContext<DOM, ID>, type: DT, data: IActionPayload_Data_Base) {\n    super(EActionForm.data, context._domain, context.id);\n    this.context = context;\n    this.type = type;\n    this.time = data.time;\n  }\n\n  protected toBaseJsonObject(): IActionPayload_Base_JsonObject<DT, DOM, ID> {\n    return {\n      ...super.toJsonObject(),\n      type: this.type,\n      context: this.context.toContextDataJsonObject(),\n      time: this.time,\n    };\n  }\n\n  abstract toJsonObject(): IActionPayload_Base_JsonObject<DT, DOM, ID>;\n}\n","function stableStringify(value: unknown): string {\n  if (value === null || value === undefined) return String(value);\n  if (typeof value !== \"object\") return JSON.stringify(value) ?? \"undefined\";\n  if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n  const keys = Object.keys(value as object).sort();\n  return (\n    \"{\" +\n    keys\n      .map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`)\n      .join(\",\") +\n    \"}\"\n  );\n}\n\nfunction fnv1a32(str: string): string {\n  let hash = 2166136261;\n  for (let i = 0; i < str.length; i++) {\n    hash = ((hash ^ str.charCodeAt(i)) * 16777619) >>> 0;\n  }\n  return hash.toString(16).padStart(8, \"0\");\n}\n\n/**\n * Produces a deterministic 8-char hex hash of any JSON-serializable value.\n * Useful for grouping/comparing action inputs, outputs, and progress payloads.\n */\nexport function hashPayloadData(data: unknown): string {\n  return fnv1a32(stableStringify(data));\n}\n","import type { INiceErrorJsonObject, NiceError } from \"@nice-code/error\";\nimport type { TInferActionError } from \"../../..\";\nimport type {\n  IActionHandler_Local_Json,\n  IActionHandler_Peer_Json,\n} from \"../../../ActionRuntime/Handler/ActionHandler.types\";\nimport type {\n  ETransportShape,\n  ITransportRouteInfo,\n} from \"../../../ActionRuntime/Transport/Transport.types\";\nimport type {\n  IActionDomain,\n  TInferInputFromSchema,\n  TInferOutputFromSchema,\n} from \"../../Domain/ActionDomain.types\";\nimport type { EActionForm, IActionBase, IActionBase_JsonObject } from \"../ActionBase.types\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport type { IActionContext_Data_JsonObject } from \"../Context/ActionContext.types\";\nimport type { ActionPayload_Progress } from \"./ActionPayload_Progress\";\nimport type { ActionPayload_Request } from \"./ActionPayload_Request\";\nimport type { ActionPayload_Result } from \"./ActionPayload_Result\";\n\nexport enum EActionPayloadType {\n  request = \"request\",\n  progress = \"progress\",\n  result = \"result\",\n  stream = \"stream\",\n  push = \"push\",\n}\n\nexport interface IActionPayload_Data_Base {\n  time: number;\n}\n\nexport interface IActionPayload_Base<\n  DT extends EActionPayloadType,\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string,\n> extends IActionBase<EActionForm.data, DOM, ID>,\n    IActionPayload_Data_Base {\n  readonly type: DT;\n  readonly context: ActionContext<DOM, ID>;\n}\n\nexport type IActionRouteItemHandler =\n  | IActionHandler_Local_Json\n  | (IActionHandler_Peer_Json & {\n      transShape: ETransportShape;\n      transOrd: number;\n      transInfo?: ITransportRouteInfo;\n    });\n\n/**\n *  [                        ]\n *  [  ACTION PAYLOAD TYPES  ]\n *  [                        ]\n */\n\n/**\n *\n *  [ RESULT ]\n *\n */\n\n/**\n * The outcome of an action.\n *\n * - `ok: true` — the action produced `output`.\n * - `ok: false; expected: true` — the action failed with one of the errors it\n *   declared via `.throws()`; `error` is narrowed to that declared union.\n * - `ok: false; expected: false` — any other failure (a `NiceError` from a domain\n *   the action didn't declare, or a wrapped foreign throw). Inspect\n *   `error.isUnhandled` to tell those two apart.\n *\n * Structurally a superset of `nice-error`'s `TNiceResult`, so `niceTry` composes.\n */\nexport type TActionResultOutcome<OUT, DECLARED extends NiceError<any, any>> =\n  | { ok: true; output: OUT }\n  | { ok: false; expected: true; error: DECLARED }\n  | { ok: false; expected: false; error: NiceError<any, any> };\n\n/**\n * Wire form of {@link TActionResultOutcome}: the `error` is the serialized\n * `INiceErrorJsonObject` (never a live `NiceError` instance), so the frame is plain\n * data for any transport — `JSON.stringify` *and* binary codecs (msgpackr) alike.\n * `expected` is carried for inspection but is re-derived against the receiver's own\n * schema on hydrate, never trusted from the wire.\n */\nexport type TActionResultOutcome_JsonObject<OUT_SERDE> =\n  | { ok: true; output: OUT_SERDE }\n  | { ok: false; expected: boolean; error: INiceErrorJsonObject };\n\nexport interface IActionPayload_Result<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string,\n> extends IActionPayload_Base<EActionPayloadType.result, DOM, ID> {\n  readonly result: TActionResultOutcome<\n    TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"],\n    TInferActionError<DOM[\"actionSchema\"][ID]>\n  >;\n}\n\n/**\n *\n *  [ PROGRESS ]\n *\n */\n\nexport enum EActionProgressType {\n  none = \"none\",\n  percentage = \"percentage\",\n  custom = \"custom\",\n}\n\nexport interface IActionProgress_None {\n  type: EActionProgressType.none;\n}\n\nexport interface IActionProgress_Percentage {\n  type: EActionProgressType.percentage;\n  progress: number; // value between 0 and 100\n  message?: string; // optional message describing the progress\n}\n\nexport interface IActionProgress_Custom {\n  type: EActionProgressType.custom;\n  data: any; // custom data for the progress\n}\n\nexport type TActionProgress =\n  | IActionProgress_None\n  | IActionProgress_Percentage\n  | IActionProgress_Custom;\n\nexport interface IActionPayload_Progress<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string,\n> extends IActionPayload_Base<EActionPayloadType.progress, DOM, ID> {\n  readonly progress: TActionProgress;\n}\n\n/**\n *\n *  [                   ]\n *  [  Wire JSON types  ]\n *  [                   ]\n *\n */\n\nexport interface IActionPayload_Base_JsonObject<\n  DT extends EActionPayloadType,\n  DOM extends IActionDomain = IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends IActionBase_JsonObject<EActionForm.data, DOM, ID> {\n  type: DT;\n  context: IActionContext_Data_JsonObject;\n  time: number;\n}\n\nexport interface IActionPayload_Request_JsonObject<\n  DOM extends IActionDomain = IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends IActionPayload_Base_JsonObject<EActionPayloadType.request, DOM, ID> {\n  type: EActionPayloadType.request;\n  input: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"SerdeInput\"];\n  inputHash: string;\n}\n\nexport interface IActionPayload_Progress_JsonObject<\n  DOM extends IActionDomain = IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends IActionPayload_Base_JsonObject<EActionPayloadType.progress, DOM, ID> {\n  type: EActionPayloadType.progress;\n  progress: TActionProgress;\n}\n\nexport interface IActionPayload_Result_JsonObject<\n  DOM extends IActionDomain = IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends IActionPayload_Base_JsonObject<EActionPayloadType.result, DOM, ID> {\n  type: EActionPayloadType.result;\n  result: TActionResultOutcome_JsonObject<\n    TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"SerdeOutput\"]\n  >;\n  outputHash: string;\n}\n\n/**\n *\n *  [                  ]\n *  [  COMBINED TYPES  ]\n *  [                  ]\n *\n */\n\nexport type TActionPayload_Any_Instance<\n  DOM extends IActionDomain = IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> =\n  | ActionPayload_Request<DOM, ID>\n  | ActionPayload_Result<DOM, ID>\n  | ActionPayload_Progress<DOM, ID>;\n\nexport type TActionPayload_Any_JsonObject<\n  DOM extends IActionDomain = IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> =\n  | IActionPayload_Request_JsonObject<DOM, ID>\n  | IActionPayload_Progress_JsonObject<DOM, ID>\n  | IActionPayload_Result_JsonObject<DOM, ID>;\n","import type { IActionDomain } from \"../../Domain/ActionDomain.types\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport { ActionPayload } from \"./ActionPayload\";\nimport type {\n  IActionPayload_Data_Base,\n  IActionPayload_Progress,\n  IActionPayload_Progress_JsonObject,\n  TActionProgress,\n} from \"./ActionPayload.types\";\nimport { EActionPayloadType } from \"./ActionPayload.types\";\nimport { ActionPayload_Request } from \"./ActionPayload_Request\";\n\nexport class ActionPayload_Progress<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n  >\n  extends ActionPayload<EActionPayloadType.progress, DOM, ID>\n  implements IActionPayload_Progress<DOM, ID>\n{\n  readonly progress: TActionProgress;\n\n  constructor(\n    params: { context: ActionContext<DOM, ID> } | ActionPayload_Request<DOM, ID>,\n    progress: TActionProgress,\n    data: IActionPayload_Data_Base,\n  ) {\n    super(params.context, EActionPayloadType.progress, data);\n    this.progress = progress;\n  }\n\n  toJsonObject(): IActionPayload_Progress_JsonObject<DOM, ID> {\n    return {\n      ...this.toBaseJsonObject(),\n      progress: this.progress,\n    };\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  toHttpResponse(): Response {\n    return new Response(this.toJsonString(), {\n      status: 200,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  }\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport { hashPayloadData } from \"../../../utils/hashPayloadData\";\nimport type { IActionDomain, TInferOutputFromSchema } from \"../../Domain/ActionDomain.types\";\nimport type { TInferActionError } from \"../../Schema/ActionSchema\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport { ActionPayload } from \"./ActionPayload\";\nimport type { IActionPayload_Data_Base, TActionResultOutcome } from \"./ActionPayload.types\";\nimport { EActionPayloadType, type IActionPayload_Result_JsonObject } from \"./ActionPayload.types\";\nimport { ActionPayload_Request } from \"./ActionPayload_Request\";\n\nexport class ActionPayload_Result<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends ActionPayload<EActionPayloadType.result, DOM, ID> {\n  readonly result: TActionResultOutcome<\n    TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"],\n    TInferActionError<DOM[\"actionSchema\"][ID]>\n  >;\n  readonly outputHash: string;\n\n  constructor(\n    params: { context: ActionContext<DOM, ID> } | ActionPayload_Request<DOM, ID>,\n    // Raw outcome — `expected` is derived here (against this side's own schema) so it\n    // is always type-sound, never trusted from the wire.\n    result:\n      | { ok: true; output: TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"] }\n      | { ok: false; error: NiceError<any, any> },\n    data: IActionPayload_Data_Base,\n  ) {\n    super(params.context, EActionPayloadType.result, data);\n\n    if (result.ok) {\n      this.result = result;\n      this.outputHash = hashPayloadData(this.context.schema.serializeOutput(result.output));\n    } else {\n      const expected = this.context.schema.isExpectedError(result.error);\n      this.result = expected\n        ? {\n            ok: false,\n            expected: true,\n            error: result.error as TInferActionError<DOM[\"actionSchema\"][ID]>,\n          }\n        : { ok: false, expected: false, error: result.error };\n      this.outputHash = hashPayloadData(result.error.message);\n    }\n  }\n\n  toJsonObject(): IActionPayload_Result_JsonObject<DOM, ID> {\n    // Serialize the error to its JSON-object form here — never let a live `NiceError`\n    // instance reach the wire. `JSON.stringify` would call its `toJSON()`, but binary\n    // codecs (msgpackr) serialize the instance via their built-in Error extension into\n    // a tuple that `castNiceError` can't rehydrate. Emitting the plain object keeps the\n    // frame transport-agnostic.\n    const wireResult = this.result.ok\n      ? { ok: true as const, output: this.context.schema.serializeOutput(this.result.output) }\n      : {\n          ok: false as const,\n          expected: this.result.expected,\n          error: this.result.error.toJsonObject(),\n        };\n    return {\n      ...this.toBaseJsonObject(),\n      result: wireResult,\n      outputHash: this.outputHash,\n    };\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  toHttpResponse({ useErrorStatus = true }: { useErrorStatus?: boolean } = {}): Response {\n    return new Response(this.toJsonString(), {\n      status: this.result.ok ? 200 : useErrorStatus ? this.result.error.httpStatusCode : 500,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n  }\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport type { IExecuteActionOptions } from \"../../../ActionRuntime/Handler/ActionHandler.types\";\nimport { hashPayloadData } from \"../../../utils/hashPayloadData\";\nimport type {\n  IActionDomain,\n  TInferInputFromSchema,\n  TInferOutputFromSchema,\n} from \"../../Domain/ActionDomain.types\";\nimport type { ActionContext } from \"../Context/ActionContext\";\nimport type { RunningAction } from \"../RunningAction\";\nimport { ActionPayload } from \"./ActionPayload\";\nimport type { IActionPayload_Data_Base, TActionProgress } from \"./ActionPayload.types\";\nimport { EActionPayloadType, type IActionPayload_Request_JsonObject } from \"./ActionPayload.types\";\nimport { ActionPayload_Progress } from \"./ActionPayload_Progress\";\nimport { ActionPayload_Result } from \"./ActionPayload_Result\";\n\nexport class ActionPayload_Request<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> extends ActionPayload<EActionPayloadType.request, DOM, ID> {\n  readonly input: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"];\n  readonly inputHash: string;\n  _callSite?: string;\n\n  constructor(\n    params: { context: ActionContext<DOM, ID> },\n    input: TInferInputFromSchema<DOM[\"actionSchema\"][ID]>[\"Input\"],\n    data: IActionPayload_Data_Base,\n  ) {\n    super(params.context, EActionPayloadType.request, data);\n    this.input = input;\n    this.inputHash = hashPayloadData(this.context.schema.serializeInput(input));\n  }\n\n  successResult(\n    ...args: [TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]] extends [never]\n      ? [] | [output: TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]]\n      : [output: TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]]\n  ): ActionPayload_Result<DOM, ID> {\n    const output = args[0];\n    const finalOutput = this.context.schema.validateOutput(output, {\n      domain: this.domain,\n      actionId: this.id,\n    });\n    return new ActionPayload_Result(this, { ok: true, output: finalOutput }, { time: Date.now() });\n  }\n\n  /**\n   * Build a failed result from any `NiceError`. The result's `expected` flag is\n   * derived from the action's `.throws()` declarations during construction, so\n   * declared errors surface as `expected: true` (typed) and everything else as\n   * `expected: false`.\n   */\n  errorResult(err: NiceError<any, any>): ActionPayload_Result<DOM, ID> {\n    return new ActionPayload_Result(this, { ok: false, error: err }, { time: Date.now() });\n  }\n\n  progress(progress: TActionProgress): ActionPayload_Progress<DOM, ID> {\n    return new ActionPayload_Progress(this, progress, { time: Date.now() });\n  }\n\n  toJsonObject(): IActionPayload_Request_JsonObject<DOM, ID> {\n    return {\n      ...super.toBaseJsonObject(),\n      input: this.context.schema.serializeInput(this.input),\n      inputHash: this.inputHash,\n    };\n  }\n\n  toJsonString(): string {\n    return JSON.stringify(this.toJsonObject());\n  }\n\n  async runToOutput(\n    options?: IExecuteActionOptions<DOM, ID>,\n  ): Promise<TInferOutputFromSchema<DOM[\"actionSchema\"][ID]>[\"Output\"]> {\n    const running = await this.run(options);\n    const result = await running.waitForResultPayload();\n    if (result.result.ok) return result.result.output;\n    throw result.result.error;\n  }\n\n  async runToResultPayload(\n    options?: IExecuteActionOptions<DOM, ID>,\n  ): Promise<ActionPayload_Result<DOM, ID>> {\n    const value = await this.run(options);\n    return value.waitForResultPayload();\n  }\n\n  /**\n   * Run and resolve to the bare result outcome (`{ ok } | { ok:false; expected; error }`)\n   * — the ergonomic way to handle expected vs unexpected errors without throwing.\n   */\n  async runToResult(\n    options?: IExecuteActionOptions<DOM, ID>,\n  ): Promise<ActionPayload_Result<DOM, ID>[\"result\"]> {\n    return (await this.runToResultPayload(options)).result;\n  }\n\n  async run(options?: IExecuteActionOptions<DOM, ID>): Promise<RunningAction<DOM, ID>> {\n    if (this._callSite == null) {\n      this._callSite = new Error().stack;\n    }\n    return this._domain.runAction(this, options);\n  }\n}\n","import type { ActionDomain } from \"../..\";\nimport type { IActionDomain } from \"../Domain/ActionDomain.types\";\nimport type { EReliabilityTier } from \"../Schema/ActionSchema\";\nimport type { ActionContext } from \"./Context/ActionContext\";\nimport { type IActionPayload_Result_JsonObject } from \"./Payload/ActionPayload.types\";\nimport type { ActionPayload_Progress } from \"./Payload/ActionPayload_Progress\";\nimport type { ActionPayload_Result } from \"./Payload/ActionPayload_Result\";\nimport {\n  ERunningActionFinishedType,\n  ERunningActionUpdateType,\n  type IRunningActionState,\n  type IRunningActionState_ConstructorParams,\n  type IRunningActionUserMethods,\n  type TRunningActionUpdate,\n  type TRunningActionUpdateListener,\n} from \"./RunningAction.types\";\n\n/** Reliable-delivery facts an observer (devtools) can show for a reliable action, stamped by the connector. */\nexport interface IRunningActionReliability {\n  /** The reliability tier this action opted into (`session` / `persisted`). */\n  tier: EReliabilityTier;\n  /** This frame's per-stream sequence number (the sender's outbox seq). */\n  seq?: number;\n  /** The `streamKey` this send rode on (E3), when the stream is keyed. */\n  streamKey?: string;\n  /**\n   * Set `true` when the peer's cumulative ack covered this frame — the sender-side proof of delivery.\n   * Stamped by the connector when its outbox prunes the send (a reply's piggyback or a standalone `rack`).\n   * Flipping it emits an {@link ERunningActionUpdateType.reliability} update; `waitForAck()` awaits it.\n   */\n  acked?: boolean;\n}\n\nexport class RunningAction<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string = keyof DOM[\"actionSchema\"] & string,\n> implements IRunningActionUserMethods<DOM, ID>\n{\n  protected _state: IRunningActionState<DOM, ID>;\n\n  /**\n   * Reliability facts for a `.reliable()` action (tier + this frame's seq), stamped by the connector when it\n   * assigns the outbox seq. `undefined` for a best-effort action. Read by devtools to surface a reliable chip;\n   * the cumulative `ack` / `redelivered` are receiver-side facts (see the server serve-logger), not the\n   * sender's to report.\n   */\n  reliability?: IRunningActionReliability;\n\n  readonly context: ActionContext<DOM, ID>;\n  readonly cuid: string;\n  readonly id: ID;\n  readonly _domain: ActionDomain<DOM>;\n  readonly domain: DOM[\"domain\"];\n  readonly allDomains: DOM[\"allDomains\"];\n  readonly parentCuid?: string;\n  readonly callSite?: string;\n\n  private readonly _resultPayloadPromise: Promise<ActionPayload_Result<DOM, ID>>;\n  private _resolveResult!: (response: ActionPayload_Result<DOM, ID>) => void;\n  private _rejectResult!: (reason?: unknown) => void;\n\n  private _isAborted = false;\n\n  private readonly _updates: TRunningActionUpdate<DOM, ID>[] = [];\n\n  private readonly _updateListeners: TRunningActionUpdateListener<DOM, ID>[] = [];\n\n  /**\n   * Delivery-settlement state for {@link waitForAck}, recorded even when nobody is waiting so a late\n   * `waitForAck()` still settles correctly. The promise itself is created lazily on first call —\n   * otherwise every abandoned reliable send would raise unhandled-rejection noise for the callers\n   * (the overwhelming majority) that never ask.\n   */\n  private _ackOutcome?: { ok: true } | { ok: false; reason: unknown };\n  private _ackPromise?: Promise<void>;\n  private _resolveAck?: () => void;\n  private _rejectAck?: (reason?: unknown) => void;\n\n  constructor(initialState: IRunningActionState_ConstructorParams<DOM, ID>) {\n    this.context = initialState.context;\n    this.cuid = initialState.context.cuid;\n    this.id = initialState.context.id;\n    this.domain = initialState.context.domain;\n    this.allDomains = initialState.context.allDomains;\n    this._domain = initialState.context._domain;\n    this.parentCuid = initialState.parentCuid;\n    this.callSite = initialState.callSite;\n\n    this._resultPayloadPromise = new Promise<ActionPayload_Result<DOM, ID>>((resolve, reject) => {\n      this._resolveResult = resolve;\n      this._rejectResult = reject;\n    });\n    // Prevent unhandled rejection when this RunningAction is aborted/failed but\n    // waitForResultPayload() is never called (e.g. error-path in _runAction).\n    this._resultPayloadPromise.catch(() => {});\n\n    this._state = {\n      request: initialState.request,\n      progress: initialState.progress ?? [],\n      result: initialState.result,\n    };\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.started,\n      runningAction: this,\n      time: Date.now(),\n    });\n  }\n\n  get state(): IRunningActionState<DOM, ID> {\n    return this._state;\n  }\n\n  /** Whether this action has reached a terminal state (resolved, aborted, or failed) — no more updates. */\n  get isSettled(): boolean {\n    return this._state.result != null || this._isAborted;\n  }\n\n  /**\n   * Whether this action was aborted (deadline, overflow, or an explicit abort) — as opposed to having\n   * completed successfully. A reliable **reply-less** action completes *on send* (so it's `isSettled`), yet\n   * the outbox must keep delivering it in the background until the peer acks; only an *abort* should stop\n   * those resends. Resend/resync gating uses this, not {@link isSettled}.\n   */\n  get isAborted(): boolean {\n    return this._isAborted;\n  }\n\n  /** Stamp this action's reliability facts (tier + seq) — the connector calls it when it assigns the seq. */\n  _setReliability(reliability: IRunningActionReliability): void {\n    this.reliability = reliability;\n  }\n\n  /**\n   * Await this send's **delivery settlement** — the sender-side proof of what became of the frame,\n   * distinct from the action's own promise (a reply-less reliable action resolves *on send* while\n   * delivery continues in the background; this is how you await that delivery):\n   *\n   * - **Reliable action** — resolves when the peer's cumulative ack covers this frame; rejects with the\n   *   abandon reason when the frame is dropped undelivered (delivery deadline, explicit `abort()`, a\n   *   newer frame's cumulative sweep, or a `closeReliableStream`).\n   * - **Best-effort action** — there is no ack concept, so it mirrors the action itself: resolves when\n   *   the action settles successfully (for fire-and-forget: on send), rejects when it aborts/fails.\n   *   Callers compose without branching on the tier.\n   *\n   * Note the at-least-once caveat: a *rejected* `waitForAck` means the sender stopped trying, not that\n   * the frame provably never arrived (the ack itself may have been lost).\n   */\n  waitForAck(): Promise<void> {\n    if (this._ackPromise == null) {\n      this._ackPromise = new Promise<void>((resolve, reject) => {\n        this._resolveAck = resolve;\n        this._rejectAck = reject;\n      });\n      // Same guard as the result promise: a caller may request the promise and then not await it.\n      this._ackPromise.catch(() => {});\n      // Settled before anyone asked — replay the recorded outcome into the fresh promise.\n      const outcome = this._ackOutcome;\n      if (outcome != null) {\n        if (outcome.ok) this._resolveAck?.();\n        else this._rejectAck?.(outcome.reason);\n      }\n    }\n    return this._ackPromise;\n  }\n\n  /** Record a delivery-settlement outcome (first one wins) and settle {@link waitForAck} if it exists. */\n  private _settleAck(outcome: { ok: true } | { ok: false; reason: unknown }): boolean {\n    if (this._ackOutcome != null) return false;\n    this._ackOutcome = outcome;\n    if (outcome.ok) this._resolveAck?.();\n    else this._rejectAck?.(outcome.reason);\n    return true;\n  }\n\n  /**\n   * The peer's cumulative ack covered this frame — the connector calls it when its outbox prunes the\n   * send. Stamps `reliability.acked` and emits a {@link ERunningActionUpdateType.reliability} update so\n   * observers (devtools) refresh, then settles {@link waitForAck}.\n   */\n  _notifyAcked(): void {\n    if (this.reliability != null && this.reliability.acked !== true) {\n      this.reliability.acked = true;\n      this._sendUpdate({\n        type: ERunningActionUpdateType.reliability,\n        runningAction: this,\n        time: Date.now(),\n      });\n    }\n    this._settleAck({ ok: true });\n  }\n\n  /**\n   * This frame was dropped undelivered (deadline / abort / sweep / stream close) — the connector calls\n   * it from the outbox's drop hook. Rejects {@link waitForAck} with the abandon reason.\n   */\n  _notifyAckAbandoned(reason: unknown): void {\n    this._settleAck({ ok: false, reason });\n  }\n\n  abort(reason?: unknown): void {\n    this._abort(reason);\n  }\n\n  addUpdateListeners(listeners: TRunningActionUpdateListener<DOM, ID>[]): () => void {\n    this._updateListeners.push(...listeners);\n    // Emit all past events to the new listeners\n    for (const event of this._updates) {\n      for (const listener of listeners) {\n        listener(event);\n      }\n    }\n    return () => {\n      for (const listener of listeners) {\n        const i = this._updateListeners.indexOf(listener);\n        if (i !== -1) this._updateListeners.splice(i, 1);\n      }\n    };\n  }\n\n  async *iterateUpdates(): AsyncIterable<TRunningActionUpdate<DOM, ID>> {\n    const queue: TRunningActionUpdate<DOM, ID>[] = [];\n    let resolveWaiter: (() => void) | null = null;\n\n    const unsubscribe = this.addUpdateListeners([\n      (event) => {\n        queue.push(event);\n        // Wake up the while-loop if it's currently paused waiting for an event\n        if (resolveWaiter) {\n          resolveWaiter();\n          resolveWaiter = null;\n        }\n      },\n    ]);\n\n    try {\n      while (true) {\n        if (queue.length === 0) {\n          await new Promise<void>((resolve) => {\n            resolveWaiter = resolve;\n          });\n        }\n\n        const event = queue.shift()!;\n        yield event;\n\n        // Safely terminate the generator when the action concludes\n        if (event.type === ERunningActionUpdateType.finished) {\n          break;\n        }\n      }\n    } finally {\n      unsubscribe();\n    }\n  }\n\n  _sendUpdate(update: TRunningActionUpdate<DOM, ID>): void {\n    this._updates.push(update);\n    for (const listener of this._updateListeners) listener(update);\n  }\n\n  _completeWithResult(result: ActionPayload_Result<DOM, ID>): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n\n    this._state = {\n      request: this._state.request,\n      progress: this._state.progress,\n      result: result,\n    };\n\n    this._resolveResult(result);\n    this._sendUpdate({\n      type: ERunningActionUpdateType.finished,\n      finishType: ERunningActionFinishedType.success,\n      runningAction: this,\n      time: Date.now(),\n      response: result,\n    });\n\n    // Best-effort settlement mirror: with no ack concept, `waitForAck` follows the action itself. A\n    // *reliable* action's settlement is owned by the outbox hooks instead (a reply-less one completes\n    // on send while its delivery is still pending — success here must not imply delivery).\n    if (this.reliability == null) this._settleAck({ ok: true });\n\n    return true;\n  }\n\n  _abort(reason?: unknown): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n    this._isAborted = true;\n    this._rejectResult(reason);\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.finished,\n      finishType: ERunningActionFinishedType.aborted,\n      runningAction: this,\n      time: Date.now(),\n      reason,\n    });\n\n    // Best-effort mirror (see _completeWithResult). A reliable action's abort settles delivery through\n    // the outbox's drop hook (abandon-and-skip) with the same reason.\n    if (this.reliability == null) this._settleAck({ ok: false, reason });\n\n    return true;\n  }\n\n  _failWithError(error: unknown): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n    this._isAborted = true;\n    this._rejectResult(error);\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.finished,\n      finishType: ERunningActionFinishedType.failed,\n      runningAction: this,\n      time: Date.now(),\n      error,\n    } as any);\n\n    // Best-effort mirror (see _completeWithResult).\n    if (this.reliability == null) this._settleAck({ ok: false, reason: error });\n\n    return true;\n  }\n\n  _updateProgress(progress: ActionPayload_Progress<DOM, ID>): void {\n    if (this._state.result != null || this._isAborted) return;\n    this._state.progress.push(progress);\n\n    this._sendUpdate({\n      type: ERunningActionUpdateType.progress,\n      runningAction: this,\n      time: Date.now(),\n      progress: progress.progress,\n    });\n  }\n\n  waitForResultPayload(): Promise<ActionPayload_Result<DOM, ID>> {\n    return this._resultPayloadPromise;\n  }\n\n  _resolveFromJson(resultJson: IActionPayload_Result_JsonObject<DOM, ID>): boolean {\n    if (this._state.result != null || this._isAborted) return false;\n    const result = this._domain.hydrateResultPayload(resultJson);\n    return this._completeWithResult(result as unknown as ActionPayload_Result<DOM, ID>);\n  }\n}\n","import { err, err_nice } from \"@nice-code/error\";\nimport type { RuntimeCoordinate, TRuntimeCoordinateStringId } from \"@nice-code/wire\";\nimport { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { IActionRuntimeManagerContext } from \"../ActionRuntime/ActionRuntime.types\";\n\nexport enum EErrId_NiceAction {\n  not_implemented = \"not_implemented\",\n  action_id_not_in_domain = \"action_id_not_in_domain\",\n  domain_already_exists_in_hierarchy = \"domain_already_exists_in_hierarchy\",\n  domain_name_collision = \"domain_name_collision\",\n  domain_no_handler = \"domain_no_handler\",\n  hydration_domain_mismatch = \"hydration_domain_mismatch\",\n  hydration_action_state_mismatch = \"hydration_action_state_mismatch\",\n  hydration_action_id_not_found = \"hydration_action_id_not_found\",\n  no_action_execution_handler = \"no_action_execution_handler\",\n  wire_action_not_payload = \"wire_action_not_payload\",\n  wire_not_action_data = \"wire_not_action_data\",\n  client_runtime_already_registered = \"client_runtime_already_registered\",\n  client_runtime_not_registered = \"client_runtime_not_registered\",\n  runtime_reset = \"runtime_reset\",\n  no_client_runtimes_registered = \"no_client_runtimes_registered\",\n  action_input_validation_failed = \"action_input_validation_failed\",\n  action_input_validation_promise = \"action_input_validation_promise\",\n  action_output_validation_failed = \"action_output_validation_failed\",\n  action_output_validation_promise = \"action_output_validation_promise\",\n}\n\nexport const err_nice_action = err_nice.createChildDomain({\n  domain: \"err_nice_action\",\n  defaultHttpStatusCode: 500,\n  schema: {\n    [EErrId_NiceAction.not_implemented]: err<{ label: string }>({\n      message: ({ label }) => `The \"${label}\" functionality is not implemented yet.`,\n    }),\n    [EErrId_NiceAction.action_id_not_in_domain]: err<{ domain: string; actionId: string }>({\n      message: ({ actionId, domain }) =>\n        `Action with id \"${actionId}\" does not exist in domain \"${domain}\".`,\n    }),\n    [EErrId_NiceAction.domain_already_exists_in_hierarchy]: err<{\n      domain: string;\n      allParentDomains: string[];\n      parentDomain: string;\n    }>({\n      message: ({ domain, allParentDomains, parentDomain }) =>\n        `Domain \"${domain}\" already exists in the hierarchy under the parent \"${parentDomain}\". All parent domains [\"${allParentDomains.join(\", \")}\"]`,\n    }),\n    [EErrId_NiceAction.domain_name_collision]: err<{\n      domain: string;\n      existingParentDomains: string[];\n      incomingParentDomains: string[];\n    }>({\n      message: ({ domain, existingParentDomains, incomingParentDomains }) =>\n        `Two different domain definitions named \"${domain}\" were registered on one runtime router (existing under [${existingParentDomains.join(\" > \")}], incoming under [${incomingParentDomains.join(\" > \")}]). Wire routing is by name only, so the later registration would silently shadow the earlier one — give the domains distinct names, or register the same instance.`,\n    }),\n    [EErrId_NiceAction.domain_no_handler]: err<{ domain: string }>({\n      message: ({ domain }) => `Domain \"${domain}\" has no action handler registered.`,\n    }),\n    [EErrId_NiceAction.hydration_domain_mismatch]: err<{\n      expected: string;\n      received: string;\n    }>({\n      message: ({ expected, received }) =>\n        `Cannot hydrate action: domain mismatch. Expected \"${expected}\", got \"${received}\".`,\n    }),\n    [EErrId_NiceAction.hydration_action_state_mismatch]: err<{\n      expected: string;\n      received: string;\n    }>({\n      message: ({ expected, received }) =>\n        `Cannot hydrate action: action state type mismatch. Expected \"${expected}\", got \"${received}\".`,\n    }),\n    [EErrId_NiceAction.hydration_action_id_not_found]: err<{\n      domain: string;\n      actionId: string;\n    }>({\n      message: ({ domain, actionId }) =>\n        `Cannot hydrate action: id \"${actionId}\" does not exist in domain \"${domain}\".`,\n    }),\n    [EErrId_NiceAction.no_action_execution_handler]: err<{\n      domain: string;\n      actionId: string;\n      specifiedClient?: RuntimeCoordinate;\n    }>({\n      message: ({ domain, actionId, specifiedClient }) =>\n        `${specifiedClient ? ` The targeted client runtime [${specifiedClient.stringId}] has no` : \"No\"} action handler registered for \"${actionId}\" in domain \"${domain}\".`,\n    }),\n    [EErrId_NiceAction.wire_action_not_payload]: err<{\n      domain: string;\n      actionId: string;\n      actionState: string | undefined;\n    }>({\n      message: ({ domain, actionId, actionState }) =>\n        `Cannot handle wire for action \"${actionId}\" in domain \"${domain}\": expected action form of \"${EActionForm.data}\" and type of \"${EActionPayloadType.request}\", \"${EActionPayloadType.progress}\" or \"${EActionPayloadType.result}\", got \"${actionState}\".`,\n    }),\n    [EErrId_NiceAction.wire_not_action_data]: err({\n      message: () =>\n        `Cannot handle wire for action: expected an object with a \"domain\" property of type string, a \"form\" property of \"${EActionForm.data}\" and a \"type\" property of \"${EActionPayloadType.request}\", \"${EActionPayloadType.progress}\" or \"${EActionPayloadType.result}\".`,\n    }),\n    [EErrId_NiceAction.runtime_reset]: err({\n      message: () => `Runtime has been reset.`,\n    }),\n    [EErrId_NiceAction.client_runtime_already_registered]: err<{\n      context?: IActionRuntimeManagerContext;\n      client: RuntimeCoordinate;\n    }>({\n      message: ({ context, client }) =>\n        `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.`,\n    }),\n    [EErrId_NiceAction.client_runtime_not_registered]: err<{\n      context?: IActionRuntimeManagerContext;\n      clientStringId: TRuntimeCoordinateStringId;\n    }>({\n      message: ({ context, clientStringId }) =>\n        `No runtime registered${context?.domain ? ` on domain \"${context.domain}\"` : \"\"} for client [${clientStringId}].`,\n    }),\n    [EErrId_NiceAction.no_client_runtimes_registered]: err<{\n      context?: IActionRuntimeManagerContext;\n    }>({\n      message: ({ context }) =>\n        `No runtimes registered${context?.domain ? ` on domain \"${context.domain}\"` : \"\"}. Add handlers to a runtime via runtime.addHandlers([handler]) before executing actions.`,\n    }),\n    [EErrId_NiceAction.action_input_validation_failed]: err<{\n      domain: string;\n      actionId: string;\n      validationMessage: string;\n    }>({\n      message: ({ domain, actionId, validationMessage }) =>\n        `Input validation failed for action \"${actionId}\" in domain \"${domain}\":\\n${validationMessage}`,\n      httpStatusCode: 400,\n    }),\n    [EErrId_NiceAction.action_input_validation_promise]: err<{\n      domain: string;\n      actionId: string;\n    }>({\n      message: ({ domain, actionId }) =>\n        `Input validation for action \"${actionId}\" in domain \"${domain}\" returned a promise, which is not supported.`,\n      httpStatusCode: 400,\n    }),\n    [EErrId_NiceAction.action_output_validation_failed]: err<{\n      domain: string;\n      actionId: string;\n      validationMessage: string;\n    }>({\n      message: ({ domain, actionId, validationMessage }) =>\n        `Output validation failed for action \"${actionId}\" in domain \"${domain}\":\\n${validationMessage}`,\n      httpStatusCode: 500,\n    }),\n    [EErrId_NiceAction.action_output_validation_promise]: err<{\n      domain: string;\n      actionId: string;\n    }>({\n      message: ({ domain, actionId }) =>\n        `Output validation for action \"${actionId}\" in domain \"${domain}\" returned a promise, which is not supported.`,\n      httpStatusCode: 500,\n    }),\n  },\n});\n","import type { IActionBase_JsonObject } from \"../ActionDefinition/Action/ActionBase.types\";\n\nexport const isAction_Base_JsonObject = (obj: unknown): obj is IActionBase_JsonObject => {\n  return (\n    typeof obj === \"object\" &&\n    obj !== null &&\n    typeof (obj as any).domain === \"string\" &&\n    typeof (obj as any).id === \"string\" &&\n    typeof (obj as any).form === \"string\"\n  );\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionPayload_Result_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isActionPayload_Result_JsonObject = (\n  obj: unknown,\n): obj is IActionPayload_Result_JsonObject => {\n  return (\n    isAction_Base_JsonObject(obj) &&\n    (obj as any).result != null &&\n    (obj as any).form === EActionForm.data &&\n    (obj as any).type === EActionPayloadType.result\n  );\n};\n","import { extractMessageFromStandardSchema } from \"@nice-code/common-errors\";\nimport {\n  type INiceErrorDomainProps,\n  type InferNiceError,\n  type NiceError,\n  type NiceErrorDomain,\n} from \"@nice-code/error\";\nimport type { err_cast_not_nice } from \"@nice-code/error/internal\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport type {\n  IActionErrorDeclaration,\n  TActionSchemaOptions,\n  TInferDeclaredErrors,\n  TTransportedValue,\n} from \"./ActionSchema.types\";\n\n/**\n * What a sender should expect back from an action — declared on its schema so both ends agree without\n * any wire flag (each derives the mode from the shared `domain:id`).\n *\n * - `payload` — a typed output (the action has `.output(...)`); the sender awaits it.\n * - `ack` — an empty success confirming receipt (no output); the sender may await it to know the\n *   receiver handled it (or to surface an error). This is the default for an action with no output.\n * - `none` — fire-and-forget: the receiver sends no reply and the sender doesn't wait. The sender's\n *   running action completes as soon as the frame is on the wire (no pending reply, no timeout).\n */\nexport enum EActionResponseMode {\n  payload = \"payload\",\n  ack = \"ack\",\n  none = \"none\",\n}\n\n/**\n * The delivery guarantee for an action, declared on its schema so both ends agree without a wire flag\n * (each derives the tier from the shared `domain:id`, exactly like {@link EActionResponseMode}). Opt-in;\n * the default is `none` (today's best-effort transport, unchanged).\n *\n * - `none` — best-effort (default). A dropped frame is lost; a reconnect does not replay it.\n * - `session` — ordered, at-least-once, dedup-by-seq **within a resumable session**; the client resends\n *   unacked frames on reconnect. Across a session reset (server eviction/restart) it degrades to\n *   at-least-once *with possible redelivery*, so a reliable handler **must be idempotent**.\n * - `persisted` — as `session`, but the server's dedup high-water is persisted (e.g. DO storage), so dedup\n *   and gap-free catch-up survive eviction too. Backed by the `ReliableLog` primitive.\n *\n * Orthogonal to {@link EActionResponseMode}: the reliability ack is a transport concern (it rides a\n * dedicated envelope slot), separate from the action's application-level reply. A reliable action with no\n * natural reply still gets a standalone transport ack.\n */\nexport enum EReliabilityTier {\n  none = \"none\",\n  session = \"session\",\n  persisted = \"persisted\",\n}\n\nexport class ActionSchema<\n  INPUT extends TTransportedValue<any, any> = never,\n  OUTPUT extends TTransportedValue<any, any> = never,\n  ERRORS extends readonly IActionErrorDeclaration<any, any>[] = readonly [],\n> {\n  private _errorDeclarations: IActionErrorDeclaration[] = [];\n  private inputOptions: TActionSchemaOptions<any, any> | undefined;\n  private outputOptions: TActionSchemaOptions<any, any> | undefined;\n  private _responseMode: EActionResponseMode | undefined;\n  private _reliabilityTier: EReliabilityTier = EReliabilityTier.none;\n\n  get inputSchema(): StandardSchemaV1 | undefined {\n    return this.inputOptions?.schema;\n  }\n\n  get outputSchema(): StandardSchemaV1 | undefined {\n    return this.outputOptions?.schema;\n  }\n\n  /**\n   * The response contract for this action. Defaults are inferred — `payload` when an output schema is\n   * declared, otherwise `ack` — and made explicit by {@link ack} / {@link fireAndForget}.\n   */\n  get responseMode(): EActionResponseMode {\n    if (this._responseMode != null) return this._responseMode;\n    return this.outputOptions != null ? EActionResponseMode.payload : EActionResponseMode.ack;\n  }\n\n  /**\n   * Mark this action as expecting only an acknowledgment (an empty success). Mostly for clarity — an\n   * output-less action already acks by default — but it documents intent and reads as the deliberate\n   * counterpart to {@link fireAndForget}.\n   */\n  ack(): this {\n    this._responseMode = EActionResponseMode.ack;\n    return this;\n  }\n\n  /**\n   * Mark this action as fire-and-forget: the receiver sends no reply, and the sender's running action\n   * completes the moment the frame is sent (no awaited reply, no timeout). Ideal for high-frequency\n   * server→client pushes (presence, ticks) where an ack would only add wire chatter.\n   */\n  fireAndForget(): this {\n    this._responseMode = EActionResponseMode.none;\n    return this;\n  }\n\n  /**\n   * The reliability tier for this action (see {@link EReliabilityTier}). Both ends read it from the\n   * shared schema, so no wire flag says \"this is reliable\" — the sender/receiver derive it from the\n   * `domain:id`. Defaults to {@link EReliabilityTier.none} (best-effort).\n   */\n  get reliabilityTier(): EReliabilityTier {\n    return this._reliabilityTier;\n  }\n\n  /**\n   * Opt this action into ordered, at-least-once delivery with resend-on-reconnect (see\n   * {@link EReliabilityTier}). Pass `{ persist: true }` for the persisted tier whose dedup survives\n   * server eviction. The `persist` flag is the *only* knob — reliability is deliberately un-parameterized\n   * (no priorities/TTL/exactly-once-effect); those stay in app land.\n   *\n   * At-least-once means a reliable handler can see a redelivered frame after a session reset, so it\n   * **must be idempotent**. The dedup-by-seq runtime makes that a non-issue within a live session.\n   */\n  reliable(options?: { persist?: boolean }): this {\n    this._reliabilityTier =\n      options?.persist === true ? EReliabilityTier.persisted : EReliabilityTier.session;\n    return this;\n  }\n\n  /**\n   * Declare the input schema (JSON-native or with explicit SERDE type param).\n   * For non-JSON-native inputs, prefer the 3-argument form below to avoid\n   * needing explicit type parameters.\n   *\n   * The schema runs at `request()` AND again on the receiving runtime before the handler executes,\n   * so it must accept its own validated output. Plain validators always do; a `transform` whose\n   * output fails its own input schema will reject valid requests on arrival — type conversion\n   * belongs in the SERDE pack/unpack arguments, not in schema transforms.\n   */\n  input<VS extends StandardSchemaV1 = StandardSchemaV1, SERDE_IN = any>(\n    options: TActionSchemaOptions<VS, SERDE_IN>,\n  ): ActionSchema<TTransportedValue<StandardSchemaV1.InferInput<VS>, SERDE_IN>, OUTPUT, ERRORS> {\n    this.inputOptions = options;\n    return this;\n  }\n\n  /**\n   * Declare the output schema (JSON-native or with explicit SERDE type param).\n   * For non-JSON-native outputs, prefer the 3-argument form below to avoid\n   * needing explicit type parameters.\n   */\n  output<VS extends StandardSchemaV1 = StandardSchemaV1, SERDE_OUT = any>(\n    options: TActionSchemaOptions<VS, SERDE_OUT>,\n  ): ActionSchema<INPUT, TTransportedValue<StandardSchemaV1.InferInput<VS>, SERDE_OUT>, ERRORS> {\n    this.outputOptions = options;\n    return this;\n  }\n\n  /**\n   * Declare that this action may throw any error from `domain`.\n   * `TInferActionError` will include `NiceError<DEF, keyof schema>` in its union.\n   */\n  throws<ERR_DEF extends INiceErrorDomainProps>(\n    domain: NiceErrorDomain<ERR_DEF>,\n  ): ActionSchema<\n    INPUT,\n    OUTPUT,\n    readonly [...ERRORS, IActionErrorDeclaration<ERR_DEF, keyof ERR_DEF[\"schema\"] & string>]\n  >;\n\n  /**\n   * Declare that this action may throw only the listed `ids` from `domain`.\n   * `TInferActionError` will include `NiceError<DEF, IDS[number]>` narrowed to those IDs.\n   */\n  throws<\n    ERR_DEF extends INiceErrorDomainProps,\n    IDS extends ReadonlyArray<keyof ERR_DEF[\"schema\"] & string>,\n  >(\n    domain: NiceErrorDomain<ERR_DEF>,\n    ids: IDS,\n  ): ActionSchema<\n    INPUT,\n    OUTPUT,\n    readonly [...ERRORS, IActionErrorDeclaration<ERR_DEF, IDS[number] & string>]\n  >;\n\n  throws(domain: NiceErrorDomain<any>, ids?: ReadonlyArray<string>): ActionSchema<any, any, any> {\n    this._errorDeclarations.push({ _domain: domain, _ids: ids });\n    return this;\n  }\n\n  /**\n   * Runtime counterpart of {@link TInferActionError}: `true` when `error` is one of\n   * the errors this action declared via `.throws()` (exact domain + id match). A\n   * wrapped foreign throw (`err_cast_not_nice`) is never declared, so it returns\n   * `false` automatically. Drives the `expected` flag on the action result.\n   */\n  isExpectedError(error: NiceError<any, any>): boolean {\n    return this._errorDeclarations.some(\n      (d) => d._domain.isExact(error) && (d._ids == null || d._ids.some((id) => error.hasId(id))),\n    );\n  }\n\n  /**\n   * Serialize raw input to a JSON-serializable form.\n   * Uses the schema's serialization.serialize if defined; otherwise the input\n   * is already JSON-native and is returned as-is.\n   */\n  serializeInput(rawInput: INPUT[0]): INPUT[1] {\n    if (this.inputOptions?.serialization) {\n      return this.inputOptions.serialization.serialize(rawInput);\n    }\n    return rawInput;\n  }\n\n  /**\n   * Deserialize a JSON value back into the raw input type.\n   * Uses serialization.deserialize if defined; otherwise the value is cast\n   * directly (it's already in the correct shape).\n   */\n  deserializeInput(serialized: INPUT[1]): INPUT[0] {\n    if (this.inputOptions?.serialization) {\n      return this.inputOptions.serialization.deserialize(serialized);\n    }\n    return serialized as INPUT[0];\n  }\n\n  /**\n   * Validate raw input against the schema defined via `.input({ schema })`.\n   * Throws `action_input_validation_failed` if validation fails.\n   * Returns the validated (and possibly coerced) value on success.\n   * If no input schema was declared, the value is passed through as-is.\n   */\n  validateInput(value: unknown, meta: { domain: string; actionId: string }): INPUT[0] {\n    if (this.inputOptions?.schema == null) {\n      return value as INPUT[0];\n    }\n    const result = this.inputOptions.schema[\"~standard\"].validate(value);\n\n    if (result instanceof Promise) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_input_validation_promise, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n      });\n    }\n\n    if (result.issues != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_input_validation_failed, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n        validationMessage: extractMessageFromStandardSchema(result),\n      });\n    }\n\n    return result.value as INPUT[0];\n  }\n\n  validateOutput(value: unknown, meta: { domain: string; actionId: string }): OUTPUT[0] {\n    if (this.outputOptions?.schema == null) {\n      return value as OUTPUT[0];\n    }\n    const result = this.outputOptions.schema[\"~standard\"].validate(value);\n\n    if (result instanceof Promise) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_output_validation_promise, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n      });\n    }\n\n    if (result.issues != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.action_output_validation_failed, {\n        domain: meta.domain,\n        actionId: meta.actionId,\n        validationMessage: extractMessageFromStandardSchema(result),\n      });\n    }\n\n    return result.value as OUTPUT[0];\n  }\n\n  /**\n   * Serialize raw output to a JSON-serializable form.\n   */\n  serializeOutput(rawOutput: OUTPUT[0]): OUTPUT[1] {\n    if (this.outputOptions?.serialization) {\n      return this.outputOptions.serialization.serialize(rawOutput);\n    }\n    return rawOutput as OUTPUT[1];\n  }\n\n  /**\n   * Deserialize a JSON value back into the raw output type.\n   */\n  deserializeOutput(serialized: OUTPUT[1]): OUTPUT[0] {\n    if (this.outputOptions?.serialization) {\n      return this.outputOptions.serialization.deserialize(serialized);\n    }\n    return serialized as OUTPUT[0];\n  }\n}\n\n// ---------------------------------------------------------------------------\n// TInferActionError — lives here (not in .types) to avoid circular imports\n// ---------------------------------------------------------------------------\n\n/**\n * The union of `NiceError`s an action **declares** via `.throws()` — i.e. its\n * \"expected\" errors. An action with no `.throws()` declares none (`never`). The\n * generic / unhandled failures an action can also produce are intentionally *not*\n * here; they surface through the `expected: false` branch of the result outcome.\n */\nexport type TInferActionError<SCH> =\n  SCH extends ActionSchema<any, any, infer DECLS>\n    ? DECLS extends readonly IActionErrorDeclaration[]\n      ? TInferDeclaredErrors<DECLS>\n      : never\n    : never;\n\n/**\n * The error type for the **throw / catch** surface (`runToOutput`, react-query) —\n * the action's declared errors *plus* the generic `err_cast_not_nice` fallback,\n * since a thrown error may be one we never accounted for. (On the non-throwing\n * `runToResult` path you instead get the typed `expected` discriminant.)\n */\nexport type TActionThrownError<SCH> =\n  | TInferActionError<SCH>\n  | InferNiceError<typeof err_cast_not_nice>;\n\nexport const actionSchema = (): ActionSchema => {\n  return new ActionSchema();\n};\n","import { runtime } from \"std-env\";\nimport type { IRuntimeMeta } from \"../ActionRuntime/ActionRuntime.types\";\n\nexport const getAssumedRuntimeInfo = (): IRuntimeMeta => {\n  return {\n    assumed: true,\n    runtimeName: runtime,\n  };\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionPayload_Progress_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isActionPayload_Progress_JsonObject = (\n  obj: unknown,\n): obj is IActionPayload_Progress_JsonObject => {\n  return (\n    isAction_Base_JsonObject(obj) &&\n    \"progress\" in (obj as any) &&\n    (obj as any).form === EActionForm.data &&\n    (obj as any).type === EActionPayloadType.progress\n  );\n};\n","import { EActionForm } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionPayload_Request_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isAction_Base_JsonObject } from \"./isAction_Base_JsonObject\";\n\nexport const isActionPayload_Request_JsonObject = (\n  obj: unknown,\n): obj is IActionPayload_Request_JsonObject => {\n  // `input` is deliberately NOT required (review A.7): a no-input action's bare `request()`\n  // serializes with no input field (JSON drops `undefined`), and requiring the key made the\n  // plain-JSON path silently ignore the whole request. The `type`/`form` discriminants identify\n  // a request on their own; a genuinely missing-but-required input now reaches the schema\n  // validation downstream and rejects loudly as a typed error instead of vanishing.\n  return (\n    isAction_Base_JsonObject(obj) &&\n    (obj as any).form === EActionForm.data &&\n    (obj as any).type === EActionPayloadType.request\n  );\n};\n","import type { TActionPayload_Any_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isActionPayload_Progress_JsonObject } from \"./isActionPayload_Progress_JsonObject\";\nimport { isActionPayload_Request_JsonObject } from \"./isActionPayload_Request_JsonObject\";\nimport { isActionPayload_Result_JsonObject } from \"./isActionPayload_Result_JsonObject\";\n\nexport function isActionPayload_Any_JsonObject(obj: unknown): obj is TActionPayload_Any_JsonObject {\n  return (\n    isActionPayload_Request_JsonObject(obj) ||\n    isActionPayload_Result_JsonObject(obj) ||\n    isActionPayload_Progress_JsonObject(obj)\n  );\n}\n","// Module-level stack tracking which local handler is currently in its synchronous execution phase.\n// Child actions dispatched synchronously from inside a handler capture the top of this stack\n// as their parentCuid. The stack is push/popped around each handler's synchronous phase only.\nconst _stack: string[] = [];\n\nexport function pushHandlerCuid(cuid: string): void {\n  _stack.push(cuid);\n}\n\nexport function popHandlerCuid(): void {\n  _stack.pop();\n}\n\nexport function peekHandlerCuid(): string | undefined {\n  return _stack[_stack.length - 1];\n}\n","import { err_nice_action } from \"../../../../errors/err_nice_action\";\n\nexport const err_nice_external_client = err_nice_action.createChildDomain({\n  domain: \"err_nice_external_client\",\n  schema: {},\n});\n","import { err } from \"@nice-code/error\";\nimport type { EWireConnectFailureKind } from \"@nice-code/wire\";\nimport { err_nice_external_client } from \"../Handler/PeerLink/Connector/err_nice_external_client\";\nimport type { ETransportShape } from \"./Transport.types\";\n\nexport enum EErrId_NiceTransport {\n  timeout = \"timeout\",\n  not_found = \"not_found\",\n  unsupported = \"unsupported\",\n  initialization_failed = \"initialization_failed\",\n  send_failed = \"send_failed\",\n  invalid_action_response = \"invalid_action_response\",\n  reliable_outbox_overflow = \"reliable_outbox_overflow\",\n  reliable_delivery_abandoned = \"reliable_delivery_abandoned\",\n  reliable_stream_closed = \"reliable_stream_closed\",\n}\n\nexport const err_nice_transport = err_nice_external_client.createChildDomain({\n  domain: \"err_nice_transport\",\n  schema: {\n    [EErrId_NiceTransport.timeout]: err<{ timeout: number }>({\n      message: ({ timeout }) => `ActionConnect transport timed out after ${timeout}ms.`,\n    }),\n    [EErrId_NiceTransport.not_found]: err<{\n      actionId: string;\n    }>({\n      message: ({ actionId }) => `No connected transport found for action \"${actionId}\".`,\n    }),\n    [EErrId_NiceTransport.unsupported]: err<{ transportShapes: ETransportShape[] }>({\n      message: ({ transportShapes }) =>\n        `${transportShapes.length} Transport(s) [${transportShapes.join(\", \")}] found but returned \"unsupported\" status.`,\n    }),\n    [EErrId_NiceTransport.initialization_failed]: err<{\n      actionId: string;\n      /** The most relevant underlying failure (e.g. a rejected handshake) — surfaced in the message. */\n      cause?: string;\n      /**\n       * The endpoint the failing transport actually dialed (meteor-connect-bridge feedback W2).\n       * One line that makes the error self-locating instead of \"some transport, somewhere\".\n       */\n      endpoint?: string;\n      /**\n       * Answered-wrongly vs unreachable vs rejected, typed (feedback W3) — branch on this rather\n       * than matching the message, which is exactly the brittleness consumers had to write:\n       *\n       * ```ts\n       * if (\n       *   err_nice_transport.isExact(e) &&\n       *   e.hasId(\"initialization_failed\") &&\n       *   e.getContext(\"initialization_failed\").kind ===\n       *     EWireConnectFailureKind.endpoint_unreachable\n       * ) { ... }\n       * ```\n       */\n      kind?: EWireConnectFailureKind;\n    }>({\n      message: ({ actionId, cause, endpoint }) => {\n        const head = `Could not connect any transport for action \"${actionId}\"${\n          endpoint != null ? ` against ${endpoint}` : \"\"\n        }`;\n        if (cause == null) return `${head} (all transports failed to initialize).`;\n        // A typed cause already ends in a full stop; appending ours would read as \"…\"..\"\n        return `${head}: ${cause}${cause.endsWith(\".\") ? \"\" : \".\"}`;\n      },\n    }),\n    [EErrId_NiceTransport.send_failed]: err<{\n      actionState: string;\n      actionId: string;\n      httpStatusCode?: number;\n      message?: string;\n    }>({\n      message: ({ actionId, httpStatusCode, message }) =>\n        `Failed to send action \"${actionId}\" [${httpStatusCode ?? \"Unknown status\"}]: ${message ?? \"Unknown error\"}.`,\n      httpStatusCode: ({ httpStatusCode }) => httpStatusCode ?? 500,\n    }),\n    [EErrId_NiceTransport.invalid_action_response]: err<{\n      actionId: string;\n    }>({\n      message: ({ actionId }) => `Invalid action response JSON structure for action \"${actionId}\"`,\n    }),\n    [EErrId_NiceTransport.reliable_outbox_overflow]: err<{\n      actionId: string;\n      streamId: string;\n      maxUnacked: number;\n    }>({\n      message: ({ actionId, maxUnacked }) =>\n        `Reliable outbox for action \"${actionId}\" exceeded its unacked window (${maxUnacked}) — the peer is not acknowledging. Send rejected to bound memory.`,\n    }),\n    [EErrId_NiceTransport.reliable_delivery_abandoned]: err<{\n      actionId: string;\n      streamId: string;\n      timeout: number;\n    }>({\n      message: ({ actionId, timeout }) =>\n        `Reliable action \"${actionId}\" was abandoned: not acknowledged within its ${timeout}ms delivery deadline (or swept with an aborted earlier frame on its stream). The stream skips past it and continues.`,\n    }),\n    [EErrId_NiceTransport.reliable_stream_closed]: err<{\n      actionId: string;\n      streamId: string;\n    }>({\n      message: ({ actionId, streamId }) =>\n        `Reliable action \"${actionId}\" was abandoned because its stream (\"${streamId}\") was closed (closeReliableStream) while the send was still unacknowledged.`,\n    }),\n  },\n});\n","import { ConnectionTransportManager as WireConnectionTransportManager } from \"@nice-code/wire\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"./err_nice_transport\";\nimport type {\n  IActionTransportReadyData_Methods,\n  TTransportCache,\n  TTransportRouteParams,\n} from \"./Transport.types\";\nimport type { TransportConnection } from \"./TransportConnection\";\n\n/**\n * Preference-ordered transport selection for action dispatch — wire's generic\n * `ConnectionTransportManager` (shared-base-connect plan, Phase 2) pinned to the action routing\n * params + methods, with the selection failures expressed in action's own `err_nice_transport`\n * vocabulary (the exact errors thrown before the move). An actionless dial\n * (`ChannelConnector.connect()`, review A.1) reports as `\"connect()\"` in the failure messages.\n */\nexport class ConnectionTransportManager extends WireConnectionTransportManager<\n  TTransportRouteParams,\n  IActionTransportReadyData_Methods,\n  TransportConnection\n> {\n  constructor(cache: TTransportCache) {\n    super(cache, {\n      unsupported: (transportShapes) =>\n        err_nice_transport.fromId(EErrId_NiceTransport.unsupported, { transportShapes }),\n      notFound: (input) =>\n        err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n          actionId: input.action == null ? \"connect()\" : input.action.id,\n        }),\n      initializationFailed: (input, failure) =>\n        err_nice_transport\n          .fromId(EErrId_NiceTransport.initialization_failed, {\n            actionId: input.action == null ? \"connect()\" : input.action.id,\n            cause: failure.cause,\n            endpoint: failure.endpoint,\n            kind: failure.kind,\n          })\n          .withOriginError(failure.origin),\n    });\n  }\n}\n","import type {\n  TAction_Any_JsonObject,\n  TNarrowActionJsonTypeToActionInstanceType,\n} from \"../ActionDefinition/Action/Action.combined.types\";\nimport type { INiceActionIdAndDomain } from \"../ActionDefinition/Action/ActionBase.types\";\nimport type { ActionDomain } from \"../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../errors/err_nice_action\";\n\nexport class ActionDomainManager {\n  private _domains: Map<string, ActionDomain<any>> = new Map();\n\n  addDomain(domain: ActionDomain<any>): void {\n    const existing = this._domains.get(domain.domain);\n    // Re-registering the SAME instance is routine (router overloads, merges) and stays silent.\n    // A different instance under the same wire name would silently shadow the earlier one —\n    // routing keys are name-only — so it fails here, at setup, instead of misrouting in production.\n    if (existing === domain) return;\n    if (existing != null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.domain_name_collision, {\n        domain: domain.domain,\n        existingParentDomains: existing.allDomains,\n        incomingParentDomains: domain.allDomains,\n      });\n    }\n    this._domains.set(domain.domain, domain);\n  }\n\n  getDomains(): ActionDomain<any>[] {\n    return [...this._domains.values()];\n  }\n\n  verifyIsActionJson(action: INiceActionIdAndDomain<any>): void {\n    if (typeof action.domain !== \"string\" || typeof action.id !== \"string\") {\n      throw err_nice_action.fromId(EErrId_NiceAction.wire_not_action_data);\n    }\n  }\n\n  getActionDomain<DOM extends IActionDomain, ACT extends INiceActionIdAndDomain<DOM>>(\n    action: ACT,\n  ): ActionDomain<DOM> | undefined {\n    this.verifyIsActionJson(action);\n    const domain = this._domains.get(action.domain) as ActionDomain<DOM>;\n\n    if (!domain) {\n      return undefined;\n    }\n\n    return domain;\n  }\n\n  getActionDomainOrThrow<DOM extends IActionDomain, ACT extends INiceActionIdAndDomain<DOM>>(\n    action: ACT,\n  ): ActionDomain<DOM> {\n    this.verifyIsActionJson(action);\n    const domain = this._domains.get(action.domain) as ActionDomain<DOM>;\n\n    if (!domain) {\n      throw err_nice_action.fromId(EErrId_NiceAction.domain_no_handler, {\n        domain: action.domain,\n      });\n    }\n\n    return domain;\n  }\n\n  hydrateActionPayload<\n    D extends IActionDomain,\n    ID extends keyof D[\"actionSchema\"] & string,\n    A extends TAction_Any_JsonObject<D, ID>,\n  >(actionJson: A): TNarrowActionJsonTypeToActionInstanceType<D, A, ID> {\n    const domain = this.getActionDomainOrThrow(actionJson) as ActionDomain<D>;\n    return domain.hydrateAnyAction(actionJson);\n  }\n}\n","import type { INiceActionIdAndDomain } from \"../../ActionDefinition/Action/ActionBase.types\";\nimport type { ActionCore } from \"../../ActionDefinition/Action/Core/ActionCore\";\nimport type { ActionDomain } from \"../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../errors/err_nice_action\";\nimport { ActionDomainManager } from \"../ActionDomainManager\";\nimport type { IHandleActionOptions } from \"../Handler/ActionHandler.types\";\nimport {\n  EActionRouterContextType,\n  type IActionRouterContext,\n  type TMatchHandlerKey,\n} from \"./ActionRouter.types\";\n\nexport class ActionRouter<DATA> {\n  readonly domainManager = new ActionDomainManager();\n  private actionRouteData = new Map<TMatchHandlerKey, DATA[]>();\n  private _context: IActionRouterContext;\n\n  constructor(context: IActionRouterContext) {\n    this._context = context;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Merge / copy\n  // ---------------------------------------------------------------------------\n\n  /** Copy all routes from another router into this one, replacing any overlapping keys. */\n  mergeRouter(actionRouter: ActionRouter<DATA>): void {\n    for (const domain of actionRouter.getDomains()) {\n      this.domainManager.addDomain(domain);\n    }\n    for (const [matchKey, routeDataEntries] of actionRouter.actionRouteData.entries()) {\n      this.actionRouteData.set(matchKey, [...routeDataEntries]);\n    }\n  }\n\n  addDomainsFromOther(actionRouter: ActionRouter<DATA>): void {\n    for (const domain of actionRouter.getDomains()) {\n      this.domainManager.addDomain(domain);\n    }\n  }\n\n  // ---------------------------------------------------------------------------\n  // Lookup\n  // ---------------------------------------------------------------------------\n\n  /** All FNs registered for an action, ID-specific entries first then domain wildcard. */\n  getRouteDataEntriesForAction(action: { domain: string; id: string }): DATA[] {\n    const idKey: TMatchHandlerKey = `dom[${action.domain}]id[${action.id}]`;\n    const domKey: TMatchHandlerKey = `dom[${action.domain}]id[_]`;\n    return [\n      ...(this.actionRouteData.get(idKey) ?? []),\n      ...(this.actionRouteData.get(domKey) ?? []),\n    ];\n  }\n\n  /** First FN registered for an action (ID-specific beats domain wildcard). */\n  getRouteDataForAction(action: INiceActionIdAndDomain): DATA | undefined {\n    return this.getRouteDataEntriesForAction(action)[0];\n  }\n\n  private throwNoHandlerForAction(\n    action: INiceActionIdAndDomain,\n    context: IHandleActionOptions,\n  ): never {\n    if (this._context.contextType === EActionRouterContextType.handler_route) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n        domain: action.domain,\n        actionId: action.id,\n        specifiedClient: context.targetLocalRuntime?.coordinate,\n      });\n    }\n\n    if (this._context.contextType === EActionRouterContextType.runtime_to_handler) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n        domain: action.domain,\n        actionId: action.id,\n        specifiedClient: this._context.runtime.coordinate,\n      });\n    }\n    throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n      domain: action.domain,\n      actionId: action.id,\n    });\n  }\n\n  getRouteDataEntriesForActionOrThrow(\n    action: INiceActionIdAndDomain,\n    context: IHandleActionOptions,\n  ): DATA[] {\n    const entries = this.getRouteDataEntriesForAction(action);\n\n    if (entries.length === 0) {\n      this.throwNoHandlerForAction(action, context);\n    }\n\n    return entries;\n  }\n\n  getRouteDataForActionOrThrow(\n    action: INiceActionIdAndDomain,\n    context: IHandleActionOptions,\n  ): DATA {\n    const routeData = this.getRouteDataForAction(action);\n\n    if (!routeData) {\n      this.throwNoHandlerForAction(action, context);\n    }\n\n    return routeData;\n  }\n\n  /** All FNs stored under an exact match key. */\n  getForKey(key: TMatchHandlerKey): readonly DATA[] {\n    return this.actionRouteData.get(key) ?? [];\n  }\n\n  /** Every match key that has at least one registered FN. */\n  getRegisteredKeys(): TMatchHandlerKey[] {\n    return [...this.actionRouteData.keys()];\n  }\n\n  getDomains(): ActionDomain[] {\n    return this.domainManager.getDomains();\n  }\n\n  // ---------------------------------------------------------------------------\n  // Registration — for* (replace) and add* (accumulate)\n  // ---------------------------------------------------------------------------\n\n  /** Register a handler for all actions in a domain, replacing any existing one. */\n  forDomain<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>, routeData: DATA): this {\n    this.domainManager.addDomain(domain);\n    this.actionRouteData.set(`dom[${domain.domain}]id[_]`, [routeData]);\n    return this;\n  }\n\n  forAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    action: ActionCore<ACT_DOM, ID>,\n    routeData: DATA,\n  ): this {\n    return this.forActionId(action._domain, action.id, routeData);\n  }\n\n  /** Register a handler for a specific action, replacing any existing one. */\n  forActionId<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    domain: ActionDomain<ACT_DOM>,\n    id: ID,\n    routeData: DATA,\n  ): this {\n    this.domainManager.addDomain(domain);\n    this.actionRouteData.set(`dom[${domain.domain}]id[${id}]`, [routeData]);\n    return this;\n  }\n\n  /** Register one handler for several action IDs, replacing any existing ones. */\n  forActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(domain: ActionDomain<ACT_DOM>, ids: IDS, routeData: DATA): this {\n    this.domainManager.addDomain(domain);\n    for (const id of ids) {\n      this.forActionId(domain, id, routeData);\n    }\n    return this;\n  }\n\n  /** Register per-action handlers from a cases map, replacing any existing ones. */\n  forDomainActionCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: { [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: DATA },\n  ): this {\n    this.domainManager.addDomain(domain);\n    for (const id of Object.keys(cases) as Array<keyof FOR_DOM[\"actionSchema\"] & string>) {\n      const routeData = cases[id];\n      if (routeData != null) {\n        this.actionRouteData.set(`dom[${domain.domain}]id[${id}]`, [routeData]);\n      }\n    }\n    return this;\n  }\n\n  /** Append a handler for all actions in a domain (accumulates alongside existing). */\n  addForDomain<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    routeData: DATA,\n  ): this {\n    this.domainManager.addDomain(domain);\n    this._push(`dom[${domain.domain}]id[_]`, routeData);\n    return this;\n  }\n\n  /** Append a handler for a specific action (accumulates alongside existing). */\n  addForAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    domain: ActionDomain<ACT_DOM>,\n    id: ID,\n    routeData: DATA,\n  ): this {\n    this.domainManager.addDomain(domain);\n    this._push(`dom[${domain.domain}]id[${id}]`, routeData);\n    return this;\n  }\n\n  /** Append one handler for several action IDs (accumulates alongside existing). */\n  addForActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(domain: ActionDomain<ACT_DOM>, ids: IDS, routeData: DATA): this {\n    this.domainManager.addDomain(domain);\n    for (const id of ids) {\n      this.addForAction(domain, id, routeData);\n    }\n    return this;\n  }\n\n  /** Append per-action handlers from a cases map (accumulates alongside existing). */\n  addForDomainActionCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: { [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: DATA },\n  ): this {\n    this.domainManager.addDomain(domain);\n    for (const id of Object.keys(cases) as Array<keyof FOR_DOM[\"actionSchema\"] & string>) {\n      const routeData = cases[id];\n      if (routeData != null) {\n        this._push(`dom[${domain.domain}]id[${id}]`, routeData);\n      }\n    }\n    return this;\n  }\n\n  /** Append a handler directly by its raw match key (used when the key is known ahead of time). */\n  addForKey(key: TMatchHandlerKey, routeData: DATA): this {\n    this._push(key, routeData);\n    return this;\n  }\n\n  private _push(key: TMatchHandlerKey, routeData: DATA): void {\n    const existing = this.actionRouteData.get(key);\n    if (existing != null) {\n      existing.push(routeData);\n    } else {\n      this.actionRouteData.set(key, [routeData]);\n    }\n  }\n}\n","import { nanoid } from \"nanoid\";\nimport type { IActionRouteItemHandler } from \"../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionPayload_Request } from \"../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport type { RunningAction } from \"../../ActionDefinition/Action/RunningAction\";\nimport type { IActionDomain } from \"../../ActionDefinition/Domain/ActionDomain.types\";\nimport { ActionRouter } from \"../Routing/ActionRouter\";\nimport type {\n  EActionHandlerType,\n  IActionHandler_Base,\n  IHandleActionOptions,\n  TActionHandler_Json,\n} from \"./ActionHandler.types\";\n\nexport abstract class ActionHandler<T extends EActionHandlerType>\n  implements IActionHandler_Base<T>\n{\n  abstract readonly handlerType: T;\n  readonly cuid: string;\n  abstract readonly actionRouter: ActionRouter<any>;\n\n  constructor() {\n    this.cuid = nanoid();\n  }\n\n  getActionRouter() {\n    return this.actionRouter;\n  }\n\n  abstract handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>>;\n\n  abstract toJsonObject(): TActionHandler_Json;\n\n  abstract toHandlerRouteItem(...args: any[]): IActionRouteItemHandler;\n}\n","import type { RuntimeCoordinate } from \"@nice-code/wire\";\nimport type { ActionCore } from \"../../../ActionDefinition/Action/Core/ActionCore\";\nimport type {\n  TActionPayload_Any_Instance,\n  TActionPayload_Any_JsonObject,\n} from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain.types\";\nimport type { ActionRuntime } from \"../../ActionRuntime\";\nimport { ActionRouter } from \"../../Routing/ActionRouter\";\nimport { EActionRouterContextType } from \"../../Routing/ActionRouter.types\";\nimport { ActionHandler } from \"../ActionHandler\";\nimport { EActionHandlerType, type IActionHandler_Peer } from \"../ActionHandler.types\";\n\n/**\n * Shared base for every handler that routes a domain set to/from *another runtime* (a \"peer\") — the\n * unified peer-link concept. Both specializations extend this as siblings, differing only in *who\n * establishes the connection*, which is a transport trait, not a routing one:\n *\n * - {@link ChannelConnector} — **dial-out**: this runtime opens connection(s) to one peer\n *   over a transport stack (with caching + fallback). The classic \"client → backend\" link.\n * - {@link ChannelAcceptor} — **accept-in**: connections are accepted from many peers and fed in\n *   via `receive()`; it keeps a per-connection registry and can push to any of them.\n *\n * To the runtime there is no \"client\" vs \"server\" — both are peer-link handlers (`handlerType =\n * external`) keyed to a peer coordinate, chosen by the return-path dispatch via {@link sendReturnPayload}.\n */\nexport abstract class PeerLink\n  extends ActionHandler<EActionHandlerType.peer>\n  implements IActionHandler_Peer\n{\n  /** The peer runtime this handler links to (an env-only coordinate for an accept-in handler). */\n  readonly peerClient: RuntimeCoordinate;\n  readonly handlerType = EActionHandlerType.peer;\n\n  /**\n   * Whether this link can deliver an *unsolicited* frame to the peer (a result/progress pushed back on\n   * the return path, or a `broadcast`). A duplex carrier (WebSocket/WebRTC/…) can; an exchange-only\n   * carrier (HTTP) cannot — its reply must ride the response to its own request. The runtime's\n   * return-path dispatch ({@link ActionRuntime.getReturnHandlerForOrigin}) skips handlers that can't\n   * push, so an exchange-only handler is never asked to deliver one.\n   */\n  abstract readonly canPush: boolean;\n\n  readonly actionRouter: ActionRouter<true> = new ActionRouter({\n    contextType: EActionRouterContextType.handler_route,\n    handler: this,\n  });\n\n  /** Listeners installed by the runtime (`resolveIncomingActionPayload`) for inbound peer frames. */\n  private readonly _incomingActionDataListeners: ((\n    json: TActionPayload_Any_JsonObject<any, any>,\n  ) => void)[] = [];\n\n  constructor(peerCoordinate: RuntimeCoordinate) {\n    super();\n    this.peerClient = peerCoordinate;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Routing — which domains/actions travel to this peer (shared by both specializations)\n  // ---------------------------------------------------------------------------\n\n  forDomain<FOR_DOM extends IActionDomain>(domain: ActionDomain<FOR_DOM>): this {\n    this.actionRouter.forDomain(domain, true);\n    return this;\n  }\n\n  forAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    action: ActionCore<ACT_DOM, ID>,\n  ): this {\n    this.actionRouter.forAction(action, true);\n    return this;\n  }\n\n  forActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(domain: ActionDomain<ACT_DOM>, ids: IDS): this {\n    this.actionRouter.forActionIds(domain, ids, true);\n    return this;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Runtime binding — inbound peer frames\n  // ---------------------------------------------------------------------------\n\n  _setIncomingActionDataListener(\n    listener: (json: TActionPayload_Any_JsonObject<any, any>) => void,\n  ): void {\n    this._incomingActionDataListeners.push(listener);\n  }\n\n  /** Hand a decoded inbound frame to the runtime (called by each specialization's receive path). */\n  protected _emitIncoming(json: TActionPayload_Any_JsonObject<any, any>): void {\n    for (const listener of this._incomingActionDataListeners) listener(json);\n  }\n\n  /**\n   * Dispatch a result/progress payload back to the action's origin peer over this link. The runtime's\n   * return-path dispatch calls it on whichever peer-link handler best reaches `originClient`. Returns\n   * `true` if it was sent, `false` if no channel was available.\n   */\n  abstract sendReturnPayload(\n    payload: TActionPayload_Any_Instance<any, any>,\n    config: { targetLocalRuntime: ActionRuntime },\n  ): Promise<boolean>;\n\n  /**\n   * Whether this handler currently holds a *live* connection bound to `origin`. The runtime's return-path\n   * dispatch ({@link ActionRuntime.getReturnHandlerForOrigin}) prefers a handler that owns the origin's\n   * connection over a mere coordinate match, so with several duplex acceptors a result/push routes back\n   * over the carrier the client connected on. Defaults to `false`; an acceptor overrides it from its\n   * connection registry.\n   */\n  ownsLiveConnectionFor(_origin: RuntimeCoordinate): boolean {\n    return false;\n  }\n\n  /** Release any long-lived connections this handler owns (a teardown). No-op by default. */\n  clearTransportCache(): void {}\n}\n","import { reliableStreamId } from \"@nice-code/wire\";\nimport type { IFrameReliability } from \"../../../Transport/Transport.types\";\n\nexport { reliableStreamId };\n\n/**\n * Client-side send bookkeeping for the `.reliable()` tier — the ordered, at-least-once outbox that lets a\n * reliable stream survive a dropped frame or a reconnect. It is **pure**: it assigns per-stream sequence\n * numbers, remembers unacked sends, prunes them on a cumulative ack, and hands back what to resend. The\n * actual dispatch (acquiring a transport, packing the frame) is the {@link ChannelConnector}'s job — this\n * component never touches the network, which keeps it exhaustively unit-testable.\n *\n * ## Stream identity (locked decision #1)\n * A reliable stream is keyed `(peerCoordinate + actionRoute)`. That id is *local* — it's reconstructed on\n * each side from the connection (peer) and the frame's route, so it never travels on the wire. Only the\n * per-frame `seq` (and the reply's cumulative `ack`) ride the envelope.\n *\n * ## Guarantee & contract\n * Ordered + dedup within a resumable session; at-least-once across a session reset (so handlers must be\n * idempotent). `seq` is 0-based and monotonic per stream. `ack` is the highest **contiguous** seq the\n * server has stored; the client prunes every unacked send `<= ack` and resends everything `> ack`.\n */\n\n/** One unacked send held until its `seq` is acknowledged (or dropped as undeliverable). */\nexport interface IOutboxEntry {\n  seq: number;\n  /** When the send was prepared (ms epoch) — drives the `oldestUnackedAgeMs` pressure stat. */\n  preparedAt: number;\n  reliability: IFrameReliability;\n  /** Re-dispatch this exact frame (same `seq`) over a freshly-ready transport. Idempotent server-side. */\n  dispatch: () => void;\n  /**\n   * Called when the entry is **dropped without delivery** by {@link ReliableOutbox.dropThrough} (its\n   * action aborted / its delivery deadline expired / an earlier frame's drop swept it). The connector\n   * uses it to abort the entry's still-pending action, so abandoning a stream's head fails the swept\n   * frames loudly instead of leaving them to time out one by one.\n   */\n  onDrop?: (reason: unknown) => void;\n  /** Called when the entry is pruned by an **ack** — the sender-side proof this frame was delivered. */\n  onAck?: () => void;\n}\n\n/** The per-send lifecycle hooks a caller may attach at {@link ReliableOutbox.prepare}. */\nexport interface IReliablePrepareHooks {\n  onDrop?: (reason: unknown) => void;\n  onAck?: () => void;\n}\n\ninterface IReliableStreamState {\n  /** Next seq to hand out. */\n  nextSeq: number;\n  /** Highest contiguous seq the peer has acknowledged; `-1` = nothing acked yet. */\n  ackedSeq: number;\n  /** seq → unacked entry, insertion-ordered (so resend is naturally in seq order). */\n  unacked: Map<number, IOutboxEntry>;\n}\n\nexport interface IReliableOutboxOptions {\n  /**\n   * Max unacked sends held per stream before the outbox refuses new ones. Guards against a permanently\n   * dead peer growing memory unbounded (review point 7). Default 1024.\n   */\n  maxUnackedPerStream?: number;\n  /** Called once when a stream first overflows `maxUnackedPerStream`, with the offending stream id. */\n  onOverflow?: (streamId: string) => void;\n}\n\nconst DEFAULT_MAX_UNACKED = 1024;\n\n/** The seq/reliability a {@link ChannelConnector} stamps on a reliable frame, plus whether to proceed. */\nexport interface IReliablePrepared {\n  reliability: IFrameReliability;\n}\n\nexport class ReliableOutbox {\n  private readonly _streams = new Map<string, IReliableStreamState>();\n  private readonly _overflowed = new Set<string>();\n  private readonly _maxUnacked: number;\n  private readonly _onOverflow?: (streamId: string) => void;\n\n  constructor(options?: IReliableOutboxOptions) {\n    this._maxUnacked = options?.maxUnackedPerStream ?? DEFAULT_MAX_UNACKED;\n    this._onOverflow = options?.onOverflow;\n  }\n\n  /** The per-stream unacked cap (for surfacing in an overflow error). */\n  get maxUnackedPerStream(): number {\n    return this._maxUnacked;\n  }\n\n  private _stream(streamId: string): IReliableStreamState {\n    let state = this._streams.get(streamId);\n    if (state == null) {\n      state = { nextSeq: 0, ackedSeq: -1, unacked: new Map() };\n      this._streams.set(streamId, state);\n    }\n    return state;\n  }\n\n  /**\n   * Assign the next `seq` for a stream and remember the send until it's acked. Returns `null` when the\n   * stream is over its unacked window — the caller should fail the action with an overflow error rather\n   * than grow memory. `dispatch` is stored so the outbox can resend the exact frame on reconnect.\n   */\n  prepare(\n    streamId: string,\n    dispatch: () => void,\n    streamKey?: string,\n    hooks?: IReliablePrepareHooks,\n  ): IReliablePrepared | null {\n    const state = this._stream(streamId);\n    if (state.unacked.size >= this._maxUnacked) {\n      if (!this._overflowed.has(streamId)) {\n        this._overflowed.add(streamId);\n        this._onOverflow?.(streamId);\n      }\n      return null;\n    }\n\n    const seq = state.nextSeq++;\n    // `streamKey` (E3) rides the reliability object so the wire carries it and a re-sync (which mutates\n    // `seq` in place) preserves the key. Omitted when absent, keeping the default single-stream shape.\n    const reliability: IFrameReliability =\n      streamKey == null ? { streamId, seq } : { streamId, seq, streamKey };\n    state.unacked.set(seq, {\n      seq,\n      preparedAt: Date.now(),\n      reliability,\n      dispatch,\n      onDrop: hooks?.onDrop,\n      onAck: hooks?.onAck,\n    });\n    return { reliability };\n  }\n\n  /**\n   * Apply a cumulative ack for a stream: advance the high-water and drop every unacked send `<= ackSeq`.\n   * Returns the pruned entries (so the caller can settle per-send bookkeeping, e.g. clear delivery\n   * deadlines keyed by `entry.reliability`). A stale/duplicate ack (`<= ackedSeq`) is a no-op. Clears the\n   * overflow latch once the window drains.\n   */\n  ack(streamId: string, ackSeq: number): IOutboxEntry[] {\n    const state = this._streams.get(streamId);\n    if (state == null || ackSeq <= state.ackedSeq) return [];\n\n    state.ackedSeq = ackSeq;\n    const pruned: IOutboxEntry[] = [];\n    for (const entry of state.unacked.values()) {\n      if (entry.seq <= ackSeq) pruned.push(entry);\n    }\n    for (const entry of pruned) state.unacked.delete(entry.seq);\n\n    if (state.unacked.size < this._maxUnacked) this._overflowed.delete(streamId);\n    for (const entry of pruned) entry.onAck?.();\n    return pruned;\n  }\n\n  /**\n   * Abandon delivery of every still-unacked send `<= seq` on a stream — the undeliverable-frame escape\n   * hatch. Called when a reliable action **aborts** (deadline / explicit) while its frame is still\n   * unacked: the frame will never legitimately resend (the dispatch guard skips aborted actions), so\n   * leaving it would wedge the stream on a permanent seq gap. Dropping is **cumulative** (like an ack):\n   * every older unacked frame goes with it — they could no longer be delivered in order anyway — and each\n   * dropped entry's `onDrop` runs so its action fails loudly *now* rather than timing out serially.\n   *\n   * The caller then tells the receiver via an `rskip` control frame to advance past the abandoned seqs,\n   * so the stream **continues** (later frames deliver in order) instead of stalling. Advances `ackedSeq`\n   * (abandoned = settled) so a stale in-flight ack can't resurrect confusion, and clears the overflow\n   * latch as the window drains. Returns the dropped entries; empty when nothing `<= seq` was pending.\n   */\n  dropThrough(streamId: string, seq: number, reason: unknown): IOutboxEntry[] {\n    const state = this._streams.get(streamId);\n    if (state == null) return [];\n\n    const dropped: IOutboxEntry[] = [];\n    for (const entry of state.unacked.values()) {\n      if (entry.seq <= seq) dropped.push(entry);\n    }\n    for (const entry of dropped) state.unacked.delete(entry.seq);\n    if (seq > state.ackedSeq) state.ackedSeq = seq;\n    if (state.unacked.size < this._maxUnacked) this._overflowed.delete(streamId);\n\n    for (const entry of dropped) entry.onDrop?.(reason);\n    return dropped;\n  }\n\n  /** The unacked entries for one stream, in ascending seq order (Map preserves insertion = seq order). */\n  pending(streamId: string): IOutboxEntry[] {\n    return [...(this._streams.get(streamId)?.unacked.values() ?? [])];\n  }\n\n  /** Unacked count for one stream — the cheap read `pending().length` would allocate for. */\n  pendingCount(streamId: string): number {\n    return this._streams.get(streamId)?.unacked.size ?? 0;\n  }\n\n  /**\n   * `preparedAt` of the oldest unacked send on a stream (`undefined` when drained/unknown). Entries are\n   * insertion-ordered ascending by seq, so the first is the oldest — no scan.\n   */\n  oldestPreparedAt(streamId: string): number | undefined {\n    const state = this._streams.get(streamId);\n    if (state == null) return undefined;\n    for (const entry of state.unacked.values()) return entry.preparedAt;\n    return undefined;\n  }\n\n  /**\n   * The highest seq ever assigned on a stream (`nextSeq - 1`), or `undefined` for a stream this outbox\n   * has never prepared a send on. `closeReliableStream` abandons *through* this seq — covering every\n   * unacked send — without the caller holding any handle.\n   */\n  highestSeq(streamId: string): number | undefined {\n    const state = this._streams.get(streamId);\n    if (state == null || state.nextSeq === 0) return undefined;\n    return state.nextSeq - 1;\n  }\n\n  /** Every unacked entry across all streams, grouped per stream in seq order — the reconnect flush set. */\n  allPending(): IOutboxEntry[] {\n    const out: IOutboxEntry[] = [];\n    for (const state of this._streams.values()) out.push(...state.unacked.values());\n    return out;\n  }\n\n  /** Re-dispatch all unacked sends (call after a transport (re)connects). */\n  resendAll(): void {\n    for (const entry of this.allPending()) entry.dispatch();\n  }\n\n  /**\n   * Re-sync a stream after the receiver reset (an `rsync` control frame from an evicted/restarted server that\n   * lost its in-memory high-water): renumber the still-unacked entries from seq 0 — **mutating each entry's\n   * `reliability.seq` in place** so its stored dispatch closure resends the frame with the new seq — reset the\n   * ack high-water, then resend them in order. The fresh receiver then delivers the in-flight tail from 0\n   * instead of stalling on an unfillable gap. No-op when nothing is unacked or the stream is unknown;\n   * renumbering an already-0-based stream is harmless (idempotent), so a duplicate `rsync` is safe.\n   */\n  resync(streamId: string): void {\n    const state = this._streams.get(streamId);\n    if (state == null || state.unacked.size === 0) return;\n\n    const entries = [...state.unacked.values()]; // Map preserves insertion = ascending seq order\n    const renumbered = new Map<number, IOutboxEntry>();\n    entries.forEach((entry, index) => {\n      entry.seq = index;\n      entry.reliability.seq = index;\n      renumbered.set(index, entry);\n    });\n    state.unacked = renumbered;\n    state.ackedSeq = -1;\n    state.nextSeq = entries.length;\n\n    for (const entry of renumbered.values()) entry.dispatch();\n  }\n\n  /** Total unacked sends held (across streams) — for tests / diagnostics. */\n  get size(): number {\n    let n = 0;\n    for (const state of this._streams.values()) n += state.unacked.size;\n    return n;\n  }\n}\n","import type { IControlMessage_ReliableClose, IControlMessage_ReliableSkip } from \"@nice-code/wire\";\nimport {\n  DEFAULT_TRANSPORT_TIMEOUT,\n  WireClient,\n  warnReliableDeliveryAbandonedOnce,\n} from \"@nice-code/wire\";\nimport type { IActionRouteItem } from \"../../../../ActionDefinition/Action/Context/ActionContext.types\";\nimport type {\n  IActionRouteItemHandler,\n  TActionPayload_Any_Instance,\n} from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EActionPayloadType } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionPayload_Request } from \"../../../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { RunningAction } from \"../../../../ActionDefinition/Action/RunningAction\";\nimport { ERunningActionUpdateType } from \"../../../../ActionDefinition/Action/RunningAction.types\";\nimport type { IActionDomain } from \"../../../../ActionDefinition/Domain/ActionDomain.types\";\nimport {\n  EActionResponseMode,\n  EReliabilityTier,\n} from \"../../../../ActionDefinition/Schema/ActionSchema\";\nimport { ActionRuntime } from \"../../../ActionRuntime\";\nimport { peekHandlerCuid } from \"../../../HandlerCallStack\";\nimport { ConnectionTransportManager } from \"../../../Transport/ConnectionTransportManager\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../../../Transport/err_nice_transport\";\nimport {\n  ETransportShape,\n  type IActionTransportReadyData_Methods,\n  type IFrameReliability,\n  type ITransportMethod_SendActionData_Input,\n  type ITransportRouteActionParams,\n  type TTransportRouteParams,\n} from \"../../../Transport/Transport.types\";\nimport type { TransportConnection } from \"../../../Transport/TransportConnection\";\nimport type { IActionHandler_Peer_Json, IHandleActionOptions } from \"../../ActionHandler.types\";\nimport { PeerLink } from \"../../PeerLink/PeerLink\";\nimport type {\n  IChannelConnectorConfig,\n  IReliableStreamPressure,\n  TLinkEvent,\n  TReliableStreamEvent,\n} from \"./ChannelConnector.types\";\nimport { ReliableOutbox, reliableStreamId } from \"./ReliableOutbox\";\n\n/**\n * Overall deadline for a reliable action, after which it aborts if still unacked. Reliability retries\n * across reconnects, but it must not retry *forever* — an unreachable peer has to surface as a failure\n * rather than a silent hang. Generous by default (tolerates a long reconnect) and overridable per\n * connector. (At-least-once + a deadline means a timed-out reliable action *may* still have been\n * delivered — the ack was simply lost; documented in the reliability contract.)\n */\nconst DEFAULT_RELIABLE_ACTION_TIMEOUT = 60_000;\n/** Backoff between retries when a reliable action can't acquire a transport at all (initial connect fails). */\nconst RELIABLE_CONNECT_RETRY_MS = 1_000;\n\n/**\n * Dial-out peer link: this runtime opens connection(s) to one peer over a transport stack (cached, with\n * preference-ordered fallback). The classic \"client → backend\" handler — but to the runtime it's just a\n * {@link PeerLink} like the accept-in server one.\n *\n * The connection **lifecycle** — dial, keep-alive redial ladder, link events, park, teardown — lives on\n * the {@link WireClient} this handler holds ({@link _wire}); the handler keeps only the action *lane*:\n * routing, the reliable outbox, return-path dispatch, and delegates every lifecycle verb to the client\n * (so `connectChannel` and a realm-only `createWireClient` are one connection implementation).\n */\nexport class ChannelConnector extends PeerLink {\n  private _defaultTimeout: number;\n  private _reliableTimeout: number;\n  /**\n   * The wire connection this handler binds the action lane onto — it owns the transport cache,\n   * preference-ordered selection, the mux, and the whole connection **lifecycle** (dial, keep-alive\n   * redial, link events, park, teardown). The handler delegates every connection-level verb +\n   * property to it; `createWireClient` wraps the same class for a realm-only app.\n   */\n  private readonly _wire: WireClient<\n    TTransportRouteParams,\n    IActionTransportReadyData_Methods,\n    TransportConnection\n  >;\n\n  // ── Connection surface (delegated to `_wire`) — the `IRealmWireLink` seam + the chaos verb ──\n  /** Whether any transport can push (duplex) — a realm reads it. */\n  get canPush() {\n    return this._wire.canPush;\n  }\n  /** The local coordinate this connection dials out from — a realm defaults its identity from it. */\n  get localCoordinate() {\n    return this._wire.localCoordinate;\n  }\n  /**\n   * The negotiated wire security level this connection's frame protocols (a realm) ride at — a realm\n   * client reads it via `realmConnection(connector)` and refuses to send below its required minimum.\n   */\n  get securityLevel() {\n    return this._wire.securityLevel;\n  }\n  /**\n   * The frame-protocol mux riding this connection's link — protocol modules (a realm client)\n   * register here. Register protocols *before* {@link connect} / the first dispatch so the handshake\n   * advertises them.\n   */\n  get wireMux() {\n    return this._wire.wireMux;\n  }\n  /**\n   * The re-dial hook a realm client rides (DESYNC F6 / Phase 8a — the `IRealmWireLink` seam):\n   * `realmConnection(connector)` hands it to the engine as `requestReconnect`, invoked on an\n   * unanswered staleness probe.\n   */\n  get requestReconnect() {\n    return this._wire.requestReconnect;\n  }\n  /**\n   * Chaos/QA surface — `connector.debug.dropLink(...)` forces the outages\n   * page-level interception can't (never for production control flow). Delegated to the connection.\n   */\n  get debug() {\n    return this._wire.debug;\n  }\n\n  /** Client-side send bookkeeping for `.reliable()` actions (seq/ack/resend). Inert until one is used. */\n  private readonly _outbox = new ReliableOutbox();\n  /** Transports we've already attached a resend-on-disconnect listener to (attach once per connection). */\n  private readonly _resendHooked = new WeakSet<IActionTransportReadyData_Methods>();\n  /**\n   * Per-send **delivery deadline** timers, keyed by each unacked send's reliability object (stable across\n   * a re-sync, which renumbers `seq` by mutating that same object in place). Armed at `prepare`, cleared\n   * when the send is **acked** (not when its action settles — a reply-less action settles on send while\n   * its delivery is still pending). On expiry the frame is abandoned: its action aborts if still pending,\n   * and the stream skips past it (see {@link _abandonReliableThrough}), so delivery is *bounded* for\n   * reply-carrying and reply-less sends alike.\n   */\n  private readonly _deliveryDeadlines = new WeakMap<\n    IFrameReliability,\n    ReturnType<typeof setTimeout>\n  >();\n  /**\n   * The highest-abandoned-seq `rskip` per stream, kept (and re-flushed on every fresh connection) until\n   * the peer's ack passes it — so a skip lost to a drop mid-send still lands, and the receiver never\n   * waits forever on a seq the outbox abandoned. Cleared on an `rsync` (a fresh receiver has no gap to\n   * skip; stale pre-reset seqs must not be replayed against the renumbered stream).\n   */\n  private readonly _streamSkips = new Map<string, IControlMessage_ReliableSkip>();\n  /**\n   * Pending `rclose` per closed stream, kept until sent once on a live control channel (then dropped —\n   * `rclose` is a loss-tolerant memory reclaim, unlike an `rskip` it needs no ack retirement: delivery\n   * was already settled by the close's retained `rskip`, and a receiver that misses it self-heals).\n   */\n  private readonly _streamCloses = new Map<string, IControlMessage_ReliableClose>();\n  /** Most recent live methods able to carry control frames — the immediate path for an `rskip`. */\n  private _controlMethods?: IActionTransportReadyData_Methods;\n  /** Stream-level reliable-delivery observers (see {@link TReliableStreamEvent}). */\n  private readonly _reliableEventListeners = new Set<(event: TReliableStreamEvent) => void>();\n\n  constructor({\n    runtimeCoordinate: peerSpecifier,\n    transports,\n    defaultTimeout,\n    reliableActionTimeout,\n    wireMux,\n    localCoordinate,\n    securityLevel,\n    keepLinkAlive,\n  }: IChannelConnectorConfig) {\n    super(peerSpecifier);\n\n    this._defaultTimeout = defaultTimeout ?? DEFAULT_TRANSPORT_TIMEOUT;\n    this._reliableTimeout = reliableActionTimeout ?? DEFAULT_RELIABLE_ACTION_TIMEOUT;\n    this._wire = new WireClient({\n      createManager: (cache) => new ConnectionTransportManager(cache),\n      mux: wireMux,\n      peer: this.peerClient,\n      localCoordinate,\n      securityLevel,\n      canPush: transports.some((transport) => transport.type === ETransportShape.duplex),\n      keepLinkAlive,\n      // The action lane's route params ARE a valid actionless dial input (action/reliability optional).\n      buildConnectInput: (pair) => pair,\n      // Preserve the dispatch-driven default: fall back to the ambient runtime's coordinate.\n      defaultLocalCoordinate: () => ActionRuntime.getDefault().coordinate,\n    });\n\n    for (const transport of transports) {\n      const connection = transport._createConnection({\n        resolvers: {\n          onIncomingActionDataJson: (json, reliability) => {\n            // A reliable reply carries the peer's cumulative high-water — prune the outbox for that stream\n            // so acked sends stop being resent. Keyed by (peer + route [+ streamKey]), matching how the\n            // request stamped it. No-op for a best-effort frame.\n            if (reliability?.ack != null) {\n              this._applyAck(\n                reliableStreamId(this.peerClient, json.domain, json.id, reliability.streamKey),\n                reliability.ack,\n              );\n            }\n            this._emitIncoming(json);\n          },\n          onControlMessage: (message) => {\n            // Rebuild the (possibly keyed) stream id from the route + optional streamKey the frame carries.\n            const streamId = reliableStreamId(\n              this.peerClient,\n              message.domain,\n              message.id,\n              message.k,\n            );\n            if (message.$c === \"rack\") {\n              // A standalone reliability ack (no action reply to piggyback on — a reply-less stream, a keyed\n              // stream, or a duplicate the server suppressed). Prune the outbox, settling each acked send.\n              this._applyAck(streamId, message.ack);\n            } else if (message.$c === \"rsync\") {\n              // The server lost its state mid-stream (session-tier eviction/restart) and asked us to re-sync:\n              // renumber our still-unacked frames from 0 and resend, so the in-flight tail continues in order\n              // on the fresh receiver instead of stalling. Any pending skip is stale against the fresh\n              // receiver (its seqs predate the renumber — replaying it would swallow live renumbered\n              // frames), and there is no gap to skip on a state-less stream: drop it first.\n              this._streamSkips.delete(streamId);\n              this._outbox.resync(streamId);\n            }\n          },\n        },\n      });\n      connection.definition = transport;\n      this._wire.addTransport(connection);\n    }\n  }\n\n  // ── Connection lifecycle (delegated to `_wire`) ─────────────────────────────\n  /**\n   * Establish the connection without dispatching an action — so a realm-only\n   * (actionless) client can exist. Idempotent; resolves when the handshake completes, rejects (and\n   * arms/parks the keep-alive ladder) when the transport chain is exhausted. `targetLocalRuntime`\n   * overrides the dial identity; otherwise the connection's configured coordinate, else the ambient\n   * runtime's default — preserving the pre-descent behaviour.\n   *\n   * **Do not fire-and-forget the returned promise** — it is where handshake failures surface,\n   * including `identity_pin_mismatch` (branch on it with `err.hasId(\"identity_pin_mismatch\")`; see\n   * `err_wire_connect`).\n   */\n  async connect(config?: { targetLocalRuntime?: ActionRuntime }): Promise<void> {\n    await this._wire.connect({ localCoordinate: config?.targetLocalRuntime?.coordinate });\n  }\n\n  /**\n   * Tear down the (possibly half-open) duplex link and immediately re-dial it (DESYNC F6 / Phase\n   * 8b) — surfaced to a realm client as `requestReconnect`, called by the staleness-probe\n   * escalation. **Awaitable** — resolves when the fresh link's handshake completes.\n   */\n  reconnectLink(): Promise<void> {\n    return this._wire.reconnectLink();\n  }\n\n  /**\n   * Permanently stop this connector: cancel any pending auto-redial and drop the connection cache\n   * (keep-alive never re-dials again — an explicit, final teardown, distinct from\n   * {@link clearTransportCache}).\n   */\n  dispose(): void {\n    this._wire.dispose();\n  }\n\n  // ---------------------------------------------------------------------------\n  // Action handling\n  // ---------------------------------------------------------------------------\n\n  async handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>> {\n    const localRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();\n    const localClient = localRuntime.coordinate;\n\n    const incomingTimeout = config?.timeout ?? this._defaultTimeout;\n\n    // Capture parent + call site synchronously — once we await the transport the call stack is gone.\n    const parentCuid = peekHandlerCuid();\n    const callSite = action._callSite ?? new Error().stack;\n\n    const routeParams: ITransportRouteActionParams = {\n      action,\n      localClient,\n      externalClient: this.peerClient,\n    };\n\n    // Record the route hop up-front, labelled with the highest-priority transport, so the action shows\n    // its (expected) destination — the runtime + e.g. \"ws → backend\" — the moment it appears, instead\n    // of an \"unknown\" hop while the transport is still connecting. `_dispatchWhenTransportReady`\n    // corrects it once `getReadyTransport` picks the real winner (which can differ if the preferred\n    // transport is unavailable and a fallback serves the action).\n    const preferredTransport = this._wire.getPreferredTransport();\n    const routeItem: IActionRouteItem | undefined =\n      preferredTransport != null\n        ? {\n            runtime: localClient,\n            handler: this.toHandlerRouteItem(preferredTransport, routeParams),\n            time: Date.now(),\n          }\n        : undefined;\n    if (routeItem != null) action.context.addRouteItem(routeItem);\n\n    // Create + register the RunningAction up-front, before acquiring the transport. Acquiring it can\n    // take real time (opening a WebSocket + running its handshake on the first action), and that wait\n    // is part of the action's running lifecycle — not a precondition for the action to exist. Creating\n    // it now means observers (devtools, the dispatching domain's listeners) see the action the moment\n    // it's initiated and watch it move through \"connecting → sent → finished\", instead of it only\n    // popping into existence — already mid-flight or done — once the socket is ready.\n    const runningAction = new RunningAction<DOM, ID>({\n      context: action.context,\n      request: action,\n      parentCuid,\n      callSite,\n    });\n    localRuntime.registerRunningAction(runningAction);\n\n    // Reliable tier: assign the stream's next seq and remember this send in the outbox before dispatch,\n    // so a drop/reconnect can resend it. `routeParams.reliability` is then stamped onto every (re)send of\n    // this exact frame. Overflow (peer not acking) aborts the action rather than growing memory.\n    if (action.schema.reliabilityTier !== EReliabilityTier.none) {\n      // An optional per-request `streamKey` (E3) scopes an independent ordered stream of this action\n      // (e.g. one per room id); absent → the single default stream, byte-identical to today.\n      const streamKey = config?.streamKey;\n      const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);\n      const prepared = this._outbox.prepare(\n        streamId,\n        () => {\n          // Stop resending only once the action is **aborted** (deadline / overflow / explicit abort) — not\n          // merely settled. A reply-less reliable action completes *on send* (isSettled), but the outbox must\n          // keep delivering it in the background until the peer acks (which prunes it here); gating on\n          // isSettled would silently skip resending a lost fire-and-forget frame.\n          if (runningAction.isAborted) return;\n          void this._dispatchWhenTransportReady(\n            runningAction,\n            routeParams,\n            routeItem,\n            incomingTimeout,\n          );\n        },\n        streamKey,\n        {\n          // Swept by an older frame's abandonment (or a stream close): settle the delivery promise, then\n          // fail the action loudly *now* (its frame was dropped with the head it was ordered behind)\n          // instead of riding out its own deadline undeliverable.\n          onDrop: (reason) => {\n            runningAction._notifyAckAbandoned(reason);\n            void runningAction._abort(reason);\n          },\n          // Acked = the sender-side proof of delivery — stamps the devtools chip (E7), emits the\n          // `reliability` update, and resolves `waitForAck()`.\n          onAck: () => runningAction._notifyAcked(),\n        },\n      );\n      if (prepared == null) {\n        this._emitReliableEvent(\n          streamKey == null\n            ? { type: \"overflow\", domain: action.domain, actionId: action.id }\n            : { type: \"overflow\", domain: action.domain, actionId: action.id, streamKey },\n        );\n        runningAction._abort(\n          err_nice_transport.fromId(EErrId_NiceTransport.reliable_outbox_overflow, {\n            actionId: action.id,\n            streamId,\n            maxUnacked: this._outbox.maxUnackedPerStream,\n          }),\n        );\n        return runningAction;\n      }\n      routeParams.reliability = prepared.reliability;\n      // Surface the tier + this frame's seq/streamKey on the RunningAction so observers (devtools) can\n      // show a reliable chip. The cumulative ack/redelivered are receiver-side facts (the server\n      // serve-logger + the handler's `context.reliability`), not ours.\n      runningAction._setReliability({\n        tier: action.schema.reliabilityTier,\n        seq: prepared.reliability.seq,\n        streamKey,\n      });\n      // Per-send delivery deadline: reliability retries across reconnects, but delivery must stay\n      // *bounded* — for a reply-carrying send (abort the pending action) and a reply-less one (already\n      // settled on send) alike. Cleared when the peer acks the frame, not when the action settles.\n      this._armDeliveryDeadline(streamId, prepared.reliability, runningAction);\n      // Any abort while the frame is unacked — the deadline above, an explicit `.abort()`, a transport\n      // failure — means the frame will never legitimately resend (the dispatch guard skips aborted\n      // actions). Left in place it would wedge the stream on a permanent seq gap; instead **abandon** it\n      // (and anything older still unacked) and tell the receiver to skip past, so the stream continues.\n      const abandonOnAbort = runningAction.addUpdateListeners([\n        (update) => {\n          if (update.type !== ERunningActionUpdateType.finished) return;\n          abandonOnAbort();\n          if (runningAction.isAborted) {\n            this._abandonReliableThrough(\n              streamId,\n              prepared.reliability,\n              action.domain,\n              action.id,\n              streamKey,\n            );\n          }\n        },\n      ]);\n    }\n\n    // Resolve the transport and dispatch in the background so the RunningAction can be returned (and\n    // observed) immediately. Any failure along the way aborts the action, surfacing through its result\n    // and in the devtools just as a synchronous send failure would.\n    void this._dispatchWhenTransportReady(runningAction, routeParams, routeItem, incomingTimeout);\n\n    return runningAction;\n  }\n\n  private async _dispatchWhenTransportReady<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    runningAction: RunningAction<DOM, ID>,\n    routeParams: ITransportRouteActionParams,\n    routeItem: IActionRouteItem | undefined,\n    incomingTimeout: number,\n  ): Promise<void> {\n    const action = routeParams.action;\n    try {\n      const { methods, transport } = await this._wire.getReadyTransport(routeParams);\n\n      // Establishment bookkeeping (keep-alive re-enable, backoff reset, `link_up`) already ran\n      // inside `_wire.getReadyTransport` above — a dispatch that brings a link up counts exactly\n      // like an explicit `connect()`. The lane only adds its own resend-on-disconnect hook below.\n\n      // First dispatch over a *fresh* connection: arm a resend of all still-unacked reliable frames if it\n      // drops (deferred a tick so the dropped connection's cache slot is evicted first, letting the resend\n      // acquire a fresh connection rather than the dead one) — and flush the other direction too: resend\n      // whatever is still unacked *now* (frames orphaned while no connection existed) plus any pending\n      // stream skips, so recovery is an invariant of acquiring a new transport, not only a side effect of\n      // losing the old one.\n      if (methods.addOnDisconnectListener != null && !this._resendHooked.has(methods)) {\n        this._resendHooked.add(methods);\n        methods.addOnDisconnectListener(() => {\n          if (this._outbox.size > 0) setTimeout(() => this._outbox.resendAll(), 0);\n        });\n        if (methods.sendControlData != null) this._controlMethods = methods;\n        if (this._outbox.size > 0) setTimeout(() => this._outbox.resendAll(), 0);\n      }\n\n      // Correct the hop to the transport that actually serves the action (the preferred one may have\n      // been unavailable). Mutated in place so the action wire and the devtools \"finished\" view reflect\n      // the real route.\n      const handlerRouteItem = this.toHandlerRouteItem(transport, routeParams);\n      if (routeItem != null) {\n        routeItem.handler = handlerRouteItem;\n        routeItem.time = Date.now();\n      } else {\n        action.context.addRouteItem({\n          runtime: routeParams.localClient,\n          handler: handlerRouteItem,\n          time: Date.now(),\n        });\n      }\n\n      const sendInput: ITransportMethod_SendActionData_Input = {\n        ...routeParams,\n        runningAction,\n        timeout: incomingTimeout,\n      };\n\n      if (action.type === EActionPayloadType.request && methods.updateRunConfig != null) {\n        const runConfig = methods.updateRunConfig(sendInput);\n        sendInput.timeout = runConfig?.timeout ?? incomingTimeout;\n      }\n\n      methods.sendActionData(sendInput);\n\n      // Flush any pending stream skips *after* the action frame: on a fresh connection the first request\n      // is what binds the client identity server-side, and a control frame arriving before any request\n      // couldn't be resolved to its client (it would be dropped). Frames are processed in order, and\n      // `skipTo` drains anything the request buffered behind the abandoned gap — so after-works, before\n      // doesn't.\n      if (this._streamSkips.size > 0) this._flushStreamSkips();\n\n      // Fire-and-forget: no reply correlates back, so resolve the running action on send instead of\n      // leaving it pending until it times out. This holds for a *reliable* fire-and-forget too — its\n      // delivery is guaranteed transparently by the outbox (resend on reconnect, prune on the standalone\n      // ack) in the background, so the caller still sees fire-and-forget completion on send.\n      if (\n        action.type === EActionPayloadType.request &&\n        action.schema.responseMode === EActionResponseMode.none\n      ) {\n        runningAction._completeWithResult(\n          (action as ActionPayload_Request<any, any>).successResult(undefined),\n        );\n      }\n    } catch (err) {\n      // A best-effort action aborts on any dispatch failure. A reliable action instead **retries**: a\n      // live connection would resend on disconnect, but a connect failure (initial *or* at resend time)\n      // has no live connection to hook — so schedule a backoff retry. Gated on `isAborted`, not\n      // `isSettled`: a reply-less reliable action is settled the moment it completes-on-send, yet its\n      // delivery must keep retrying until the peer acks (same rationale as the outbox resend guard).\n      // The per-entry delivery deadline is the upper bound that eventually drops it if the peer stays\n      // unreachable.\n      if (action.type === EActionPayloadType.request && routeParams.reliability != null) {\n        if (!runningAction.isAborted) {\n          setTimeout(() => {\n            if (runningAction.isAborted) return;\n            void this._dispatchWhenTransportReady(\n              runningAction,\n              routeParams,\n              routeItem,\n              incomingTimeout,\n            );\n          }, RELIABLE_CONNECT_RETRY_MS);\n        }\n        return;\n      }\n      runningAction._abort(err);\n    }\n  }\n\n  /**\n   * Apply a cumulative ack for a stream: prune the outbox, clear each acked send's delivery deadline, and\n   * retire a pending `rskip` once the ack passes it (proof the skip — or the frames it covered — landed).\n   * The single funnel for both ack paths (reply piggyback + standalone `rack` control frame).\n   */\n  private _applyAck(streamId: string, ack: number): void {\n    for (const entry of this._outbox.ack(streamId, ack)) {\n      const deadline = this._deliveryDeadlines.get(entry.reliability);\n      if (deadline != null) {\n        clearTimeout(deadline);\n        this._deliveryDeadlines.delete(entry.reliability);\n      }\n    }\n    const skip = this._streamSkips.get(streamId);\n    if (skip != null && ack >= skip.seq) this._streamSkips.delete(streamId);\n  }\n\n  /**\n   * Arm one reliable send's **delivery deadline**: if the peer hasn't acked the frame within\n   * {@link _reliableTimeout}, the frame is abandoned — the action aborts if still pending (its abort\n   * listener then runs the abandonment), while an already-settled reply-less action abandons directly\n   * (with a one-time route warning, since its caller was already told \"success on send\"). This is what\n   * turns \"retry across reconnects\" from a potential infinite hang into a bounded, eventually-failing\n   * operation for an unreachable peer — for *every* reliable send, reply-less included. Cleared by\n   * {@link _applyAck} when the frame is acked.\n   */\n  private _armDeliveryDeadline(\n    streamId: string,\n    reliability: IFrameReliability,\n    runningAction: RunningAction<any, any>,\n  ): void {\n    const timer = setTimeout(() => {\n      const aborted = runningAction._abort(\n        err_nice_transport.fromId(EErrId_NiceTransport.reliable_delivery_abandoned, {\n          actionId: runningAction.state.request.id,\n          streamId,\n          timeout: this._reliableTimeout,\n        }),\n      );\n      if (!aborted) {\n        // Reply-less (settled-on-send) — the abort listener won't fire, abandon here and warn once.\n        const request = runningAction.state.request;\n        warnReliableDeliveryAbandonedOnce(request.domain, request.id);\n        this._abandonReliableThrough(\n          streamId,\n          reliability,\n          request.domain,\n          request.id,\n          reliability.streamKey,\n        );\n      }\n    }, this._reliableTimeout);\n    this._deliveryDeadlines.set(reliability, timer);\n  }\n\n  /**\n   * Abandon a reliable send that will never deliver (its action aborted / its delivery deadline expired):\n   * drop it — and, cumulatively, every older still-unacked send on its stream (they could no longer be\n   * delivered in order; each fails loudly via its `onDrop`) — then record + send an `rskip` so the\n   * receiver advances past the abandoned seqs and the stream **continues** instead of wedging on a\n   * permanent gap. The skip is kept (and re-flushed on each fresh connection) until an ack passes it, so\n   * a drop can't lose it. Idempotent: a second call for the same (or an older) seq drops nothing.\n   */\n  private _abandonReliableThrough(\n    streamId: string,\n    reliability: IFrameReliability,\n    domain: string,\n    actionId: string,\n    streamKey?: string,\n    /** Overrides the default deadline-abandon reason (e.g. a `closeReliableStream`'s close reason). */\n    reasonOverride?: unknown,\n  ): void {\n    const seq = reliability.seq;\n    if (seq == null) return;\n\n    const reason =\n      reasonOverride ??\n      err_nice_transport.fromId(EErrId_NiceTransport.reliable_delivery_abandoned, {\n        actionId,\n        streamId,\n        timeout: this._reliableTimeout,\n      });\n    const dropped = this._outbox.dropThrough(streamId, seq, reason);\n    for (const entry of dropped) {\n      const deadline = this._deliveryDeadlines.get(entry.reliability);\n      if (deadline != null) {\n        clearTimeout(deadline);\n        this._deliveryDeadlines.delete(entry.reliability);\n      }\n    }\n    // Surface the abandoned range to stream-level observers: entries are in ascending seq order, so the\n    // range is `[first dropped, seq]` (the sweep is cumulative — it may cover several sends).\n    if (dropped.length > 0) {\n      this._emitReliableEvent({\n        type: \"abandoned\",\n        domain,\n        actionId,\n        ...(streamKey == null ? {} : { streamKey }),\n        fromSeq: dropped[0].seq,\n        toSeq: seq,\n        reason,\n      });\n    }\n    if (dropped.length === 0 && (this._streamSkips.get(streamId)?.seq ?? -1) >= seq) return;\n\n    const previous = this._streamSkips.get(streamId);\n    if (previous == null || seq > previous.seq) {\n      this._streamSkips.set(\n        streamId,\n        streamKey == null\n          ? { $c: \"rskip\", domain, id: actionId, seq }\n          : { $c: \"rskip\", domain, id: actionId, seq, k: streamKey },\n      );\n    }\n    this._flushStreamSkips();\n  }\n\n  /**\n   * Send every pending `rskip` over the last live control-capable connection (kept until acked past),\n   * then every pending `rclose` (dropped after one successful send — loss-tolerant reclaim).\n   */\n  private _flushStreamSkips(): void {\n    const methods = this._controlMethods;\n    if (methods?.sendControlData == null) return;\n    for (const skip of this._streamSkips.values()) {\n      methods.sendControlData(skip);\n    }\n    for (const [streamId, close] of this._streamCloses) {\n      methods.sendControlData(close);\n      this._streamCloses.delete(streamId);\n    }\n  }\n\n  /**\n   * Observe stream-level reliable-delivery events — the handle-less settlement surface: `abandoned`\n   * (frames `fromSeq..toSeq` dropped undelivered; the stream skipped past them) and `overflow` (a send\n   * rejected at the unacked-window cap). Complements the per-send `RunningAction.waitForAck()`, which\n   * requires holding the handle. Returns an unsubscribe. Wired by `connectChannel({ onReliableEvent })`.\n   */\n  addReliableEventListener(listener: (event: TReliableStreamEvent) => void): () => void {\n    this._reliableEventListeners.add(listener);\n    return () => {\n      this._reliableEventListeners.delete(listener);\n    };\n  }\n\n  private _emitReliableEvent(event: TReliableStreamEvent): void {\n    for (const listener of this._reliableEventListeners) {\n      try {\n        listener(event);\n      } catch (err) {\n        console.error(\"[reliable] onReliableEvent listener threw\", err);\n      }\n    }\n  }\n\n  /**\n   * Observe transport link-state: `link_down`, `redial_scheduled`\n   * (attempt + delay — truthful \"retrying in N s\" UX), `link_up` (with `downForMs`). Returns an\n   * unsubscribe. Wired by `connectChannel({ onLinkEvent })`; see {@link TLinkEvent} for the\n   * contract (a healthy heal is silent at the realm's sync layer — this is where it's visible).\n   */\n  addLinkEventListener(listener: (event: TLinkEvent) => void): () => void {\n    return this._wire.addLinkEventListener(listener);\n  }\n\n  /**\n   * Close one logical reliable stream **for good** — the teardown verb for a stream whose real-world\n   * subject is over (a finished game run, a departed room): abandon every still-unacked send on it\n   * (each pending action aborts loudly with `reliable_stream_closed`; already-settled fire-and-forget\n   * sends stop resending), tell the receiver to skip past them (retained `rskip` — survives drops), and\n   * release both sides' stream state (an `rclose` reclaim frame; on a keyed stream it also frees the\n   * key's `maxKeyedStreamsPerClient` slot).\n   *\n   * **Synchronous on the sender's state**: after it returns, nothing from this stream can resend — so\n   * calling it at teardown *before* changing dial state (e.g. switching the active run whose URL a\n   * multiplexed-peer transport derives) closes the cross-instance redelivery window entirely.\n   *\n   * The local seq counter is deliberately **kept** (a tiny tombstone): a reused key continues the seq\n   * space, so a receiver that missed the `rclose` (dead-socket race) can never mistake new sends for\n   * duplicates — and against a receiver that *did* forget, the first new send self-heals through the\n   * normal mid-stream re-sync. Closing a stream this connection never sent on is a no-op.\n   */\n  closeReliableStream(action: { domain: string; id: string }, streamKey?: string): void {\n    const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);\n    const highest = this._outbox.highestSeq(streamId);\n    if (highest == null) return;\n\n    const reason = err_nice_transport.fromId(EErrId_NiceTransport.reliable_stream_closed, {\n      actionId: action.id,\n      streamId,\n    });\n    // Abandon the whole unacked tail (fails swept actions with the close reason, clears deadlines,\n    // emits the `abandoned` event, queues + flushes the retained rskip).\n    this._abandonReliableThrough(\n      streamId,\n      { streamId, seq: highest, streamKey },\n      action.domain,\n      action.id,\n      streamKey,\n      reason,\n    );\n    // Queue the receiver-side reclaim; sent with the skip flush (dropped after one successful send).\n    this._streamCloses.set(\n      streamId,\n      streamKey == null\n        ? { $c: \"rclose\", domain: action.domain, id: action.id }\n        : { $c: \"rclose\", domain: action.domain, id: action.id, k: streamKey },\n    );\n    this._flushStreamSkips();\n  }\n\n  /** Total unacked reliable sends held across every stream of this connection. */\n  reliablePending(): number;\n  /** One stream's pressure stats — see {@link IReliableStreamPressure}. */\n  reliablePending(\n    action: { domain: string; id: string },\n    streamKey?: string,\n  ): IReliableStreamPressure;\n  reliablePending(\n    action?: { domain: string; id: string },\n    streamKey?: string,\n  ): number | IReliableStreamPressure {\n    if (action == null) return this._outbox.size;\n    const streamId = reliableStreamId(this.peerClient, action.domain, action.id, streamKey);\n    const oldest = this._outbox.oldestPreparedAt(streamId);\n    return {\n      unackedCount: this._outbox.pendingCount(streamId),\n      oldestUnackedAgeMs: oldest == null ? undefined : Date.now() - oldest,\n      maxUnackedPerStream: this._outbox.maxUnackedPerStream,\n    };\n  }\n\n  /**\n   * Dispatch a result or progress payload directly back to the external client via the best\n   * available bidirectional transport (WebSocket / Custom). Used for return-path routing when the\n   * local runtime recognises that it has a direct channel to the action's originClient.\n   *\n   * Returns `true` if the payload was sent, `false` if no suitable transport was available.\n   */\n  async sendReturnPayload(\n    payload: TActionPayload_Any_Instance<any, any>,\n    config: { targetLocalRuntime: ActionRuntime },\n  ): Promise<boolean> {\n    const localClient = config.targetLocalRuntime.coordinate;\n    try {\n      const { methods } = await this._wire.getReadyTransport({\n        action: payload,\n        localClient,\n        externalClient: this.peerClient,\n      });\n      if (methods.sendReturnData == null) return false;\n      methods.sendReturnData(payload, { localClient, externalClient: this.peerClient });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  toJsonObject(): IActionHandler_Peer_Json {\n    return {\n      type: this.handlerType,\n      client: this.peerClient,\n    };\n  }\n\n  toHandlerRouteItem(\n    transport: TransportConnection,\n    input: ITransportRouteActionParams,\n  ): IActionRouteItemHandler {\n    return {\n      type: this.handlerType,\n      client: this.peerClient,\n      transOrd: transport.transOrd,\n      transShape: transport.type,\n      transInfo: transport.getRouteInfo(input),\n    };\n  }\n\n  /**\n   * Stop the keep-alive auto-redial and release the current link — the intention-revealing\n   * teardown counterpart of `keepLinkAlive`. Call this when a session is\n   * over (leaving a match, logging out): the link closes and stays closed until the next explicit\n   * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the connector is reusable.\n   *\n   * For dynamic-endpoint carriers, pair with a `createRequest` that returns `null` once its dial\n   * context is torn down — then even a mis-ordered teardown can't dial a garbage endpoint (the\n   * redial loop parks on `dial_unavailable`).\n   */\n  releaseLink(): void {\n    this._wire.releaseLink();\n  }\n\n  clearTransportCache(): void {\n    this._wire.clearTransportCache();\n  }\n}\n\nexport const createChannelConnector = (config: IChannelConnectorConfig) => {\n  return new ChannelConnector(config);\n};\n","import { castNiceError } from \"@nice-code/error\";\nimport {\n  type IRuntimeCoordinateSpecifics,\n  RuntimeCoordinate,\n  UNSET_RUNTIME_ENV_ID,\n} from \"@nice-code/wire\";\nimport { nanoid } from \"nanoid\";\nimport type { ActionCore } from \"../ActionDefinition/Action/Core/ActionCore\";\nimport type { TActionPayload_Any_Instance } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport {\n  EActionPayloadType,\n  type TActionPayload_Any_JsonObject,\n} from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { ActionPayload_Request } from \"../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { RunningAction } from \"../ActionDefinition/Action/RunningAction\";\nimport {\n  ERunningActionFinishedType,\n  ERunningActionUpdateType,\n} from \"../ActionDefinition/Action/RunningAction.types\";\nimport type { ActionDomain } from \"../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../ActionDefinition/Domain/ActionDomain.types\";\nimport { EActionResponseMode, EReliabilityTier } from \"../ActionDefinition/Schema/ActionSchema\";\nimport { EErrId_NiceAction, err_nice_action } from \"../errors/err_nice_action\";\nimport { getAssumedRuntimeInfo } from \"../utils/getAssumedRuntimeEnvironment\";\nimport { isActionPayload_Any_JsonObject } from \"../utils/isActionPayload_Any_JsonObject\";\nimport type { IRuntimeMeta, TActionRuntimeHandler } from \"./ActionRuntime.types\";\nimport {\n  EActionHandlerType,\n  type IHandleActionOptions,\n  type TActionHandler,\n} from \"./Handler/ActionHandler.types\";\nimport { ChannelConnector } from \"./Handler/PeerLink/Connector/ChannelConnector\";\nimport type { PeerLink } from \"./Handler/PeerLink/PeerLink\";\nimport { ActionRouter } from \"./Routing/ActionRouter\";\nimport { EActionRouterContextType } from \"./Routing/ActionRouter.types\";\nimport type { Transport } from \"./Transport/Transport\";\n\nexport class ActionRuntime {\n  private _coordinate: RuntimeCoordinate;\n  readonly timeCreated: number;\n  readonly runtimeInfo: IRuntimeMeta = getAssumedRuntimeInfo();\n  private readonly actionRouter: ActionRouter<TActionRuntimeHandler>;\n  private readonly _pendingRunningActions: Map<string, RunningAction<any, any>> = new Map();\n  private readonly _registeredPeerHandlers: PeerLink[] = [];\n  private _applied = false;\n\n  static getDefault(): ActionRuntime {\n    return getDefaultActionRuntime();\n  }\n\n  constructor(coordinate: RuntimeCoordinate) {\n    // A fresh-per-boot `insId` when unset — load-bearing for reliable delivery, not just labelling:\n    // reliable streams are keyed by the full coordinate, so a rebooted runtime must present a *new*\n    // stream identity (its outbox restarts at seq 0; against a receiver's retained high-water for the\n    // old identity those frames would be silently swallowed as duplicates). See the epoch contract on\n    // `IRuntimeCoordinateSpecifics.insId`.\n    this._coordinate = coordinate.specifyIfUnset({\n      insId: nanoid(14),\n    });\n    this.timeCreated = Date.now();\n\n    this.actionRouter = new ActionRouter({\n      contextType: EActionRouterContextType.runtime_to_handler,\n      runtime: this,\n    });\n  }\n\n  get coordinate(): RuntimeCoordinate {\n    return this._coordinate;\n  }\n\n  specifyRuntimeCoordinate(specifics: IRuntimeCoordinateSpecifics & { envId?: string }): void {\n    if (specifics.envId != null && this._coordinate.envId !== specifics.envId) {\n      throw err_nice_action.fromId(EErrId_NiceAction.not_implemented, {\n        label: `updating RuntimeCoordinate with a different \"envId\" (\"${this._coordinate.envId}\" → \"${specifics.envId}\")`,\n      });\n    }\n\n    this._coordinate = this._coordinate.specify(specifics);\n    this.apply();\n  }\n\n  registerRunningAction(ra: RunningAction<any, any>): void {\n    this._pendingRunningActions.set(ra.cuid, ra);\n    ra.addUpdateListeners([\n      (update) => {\n        if (update.type === ERunningActionUpdateType.finished) {\n          this._pendingRunningActions.delete(ra.cuid);\n        }\n      },\n    ]);\n  }\n\n  resolveIncomingActionPayload(json: TActionPayload_Any_JsonObject<any, any>): void {\n    if (json.type === EActionPayloadType.request) {\n      this.handleActionPayloadWire(json).catch((err) => {\n        console.error(\n          `[ActionRuntime] Incoming action [${json.domain}:${json.id}:${json.form}:${json.type}] unhandled:`,\n          err,\n        );\n      });\n      return;\n    }\n    this._pendingRunningActions.get(json.context.cuid)?._resolveFromJson(json as any);\n  }\n\n  /**\n   * Handle an incoming action wire (e.g. from a transport layer), route it to\n   * the correct handler, and return the response. The most specific handler\n   * match is chosen (action-ID-specific beats domain-wildcard).\n   */\n  async handleActionPayloadWire<\n    D extends IActionDomain,\n    ID extends keyof D[\"actionSchema\"] & string,\n  >(wire: TActionPayload_Any_JsonObject<D, ID>): Promise<RunningAction<D, ID>>;\n  async handleActionPayloadWire(wire: unknown): Promise<RunningAction<any, any>>;\n  async handleActionPayloadWire(wire: unknown): Promise<RunningAction<any, any>> {\n    let action: TActionPayload_Any_Instance<any, any> | undefined;\n\n    if (isActionPayload_Any_JsonObject(wire)) {\n      const domain = this.actionRouter.domainManager.getActionDomainOrThrow(wire);\n      action = domain.hydrateAnyAction(wire) as TActionPayload_Any_Instance<any, any>;\n    }\n\n    if (action == null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.wire_not_action_data);\n    }\n\n    return this.handleActionPayload(action);\n  }\n\n  /**\n   * The declared {@link EActionResponseMode} for a wire frame's action, looked up from its registered\n   * domain — `undefined` if the route isn't registered. Lets a transport decide, without executing the\n   * action, whether a reply will come back (so e.g. the reliable acceptor knows whether an ack must ride a\n   * standalone control frame vs. piggyback a reply).\n   */\n  responseModeForWire(wire: TActionPayload_Any_JsonObject<any>): EActionResponseMode | undefined {\n    try {\n      const domain = this.actionRouter.domainManager.getActionDomainOrThrow(wire);\n      return domain.actionSchema[wire.id]?.responseMode;\n    } catch {\n      return undefined;\n    }\n  }\n\n  /**\n   * The declared {@link EReliabilityTier} for a wire frame's action, looked up from its registered domain —\n   * `undefined` if the route isn't registered. Lets the reliable acceptor route a `persisted` stream through\n   * its persisted store (vs. the in-memory inbox for the `session` tier) without any wire flag: the tier is\n   * derived from the shared `domain:id`, exactly as the connector derives it to opt a send into the outbox.\n   */\n  reliabilityTierForWire(wire: TActionPayload_Any_JsonObject<any>): EReliabilityTier | undefined {\n    return this.reliabilityTierForRoute(wire.domain, wire.id);\n  }\n\n  /**\n   * {@link reliabilityTierForWire} by bare `domain:id` route — for callers holding only a route, e.g. the\n   * reliable acceptor resolving which receive store an `rskip` control message (no action payload) applies to.\n   */\n  reliabilityTierForRoute(domain: string, id: string): EReliabilityTier | undefined {\n    try {\n      const actionDomain = this.actionRouter.domainManager.getActionDomainOrThrow({ domain, id });\n      return actionDomain.actionSchema[id]?.reliabilityTier;\n    } catch {\n      return undefined;\n    }\n  }\n\n  async handleActionPayload<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: TActionPayload_Any_Instance<DOM, ID>,\n    options?: Omit<IHandleActionOptions, \"targetLocalRuntime\">,\n  ): Promise<RunningAction<DOM, ID>> {\n    if (action.type === EActionPayloadType.request) {\n      // This is the inbound entrypoint (server receiving a wire, or a bidirectional\n      // transport pushing an action to this client). Unlike the local-dispatch path\n      // (`runAction`), the handler doesn't attach the domain's action observers, so\n      // wire them on here — otherwise inbound actions never surface in devtools.\n      const observers = action.context._domain._collectActionObservers();\n\n      let handlerForAction: TActionHandler;\n      try {\n        handlerForAction = this.getHandlerForActionOrThrow(action, options);\n      } catch (err) {\n        const runningAction = new RunningAction<DOM, ID>({\n          context: action.context,\n          request: action,\n        });\n        runningAction.addUpdateListeners(observers);\n        runningAction._completeWithResult(action.errorResult(castNiceError(err)));\n        return runningAction;\n      }\n\n      // A request created locally has already passed ActionCore.request() validation, but a request\n      // hydrated from JSON/msgpack came from an untrusted peer and hydration intentionally only restores\n      // its wire shape. Validate again at the universal execution boundary before application code can\n      // observe `input`. Besides rejecting hostile frames, this makes adjacent-version schema drift a\n      // deterministic action result instead of allowing a handler to throw a foreign/native error while\n      // dereferencing a newly required field.\n      let validatedAction: ActionPayload_Request<DOM, ID>;\n      try {\n        validatedAction = new ActionPayload_Request(\n          { context: action.context },\n          action.context.validateInput(action.input),\n          { time: action.time },\n        );\n        validatedAction._callSite = action._callSite;\n      } catch (err) {\n        const runningAction = new RunningAction<DOM, ID>({\n          context: action.context,\n          request: action,\n        });\n        runningAction.addUpdateListeners(observers);\n        runningAction._completeWithResult(action.errorResult(castNiceError(err)));\n        this._trySetupReturnDispatch(runningAction);\n        return runningAction;\n      }\n\n      const runningAction = await handlerForAction.handleActionRequest(validatedAction, {\n        ...options,\n        targetLocalRuntime: this,\n      });\n      runningAction.addUpdateListeners(observers);\n      this._trySetupReturnDispatch(runningAction);\n      return runningAction;\n    }\n\n    throw err_nice_action.fromId(EErrId_NiceAction.not_implemented, {\n      label: `Handling incoming action payloads of type \"${action.type}\"`,\n    });\n  }\n\n  /**\n   * @internal\n   *\n   * Return the first handler registered for the given action, or `undefined`\n   * if none has been registered (action-ID-specific beats domain-wildcard).\n   */\n  _getHandlerForAction<ACT extends TActionPayload_Any_Instance<any, any>>(\n    action: ACT,\n    options?: Omit<IHandleActionOptions, \"targetLocalRuntime\">,\n  ): TActionHandler | undefined {\n    const handlers = this.actionRouter.getRouteDataEntriesForAction(action);\n    const targetPeer = options?.targetPeer;\n\n    const possibleHandlers = handlers.filter((handler) => {\n      if (handler.handlerType === EActionHandlerType.peer) {\n        if (targetPeer && !targetPeer.isSameFor(handler.peerClient).id) {\n          return false;\n        }\n\n        return true;\n      }\n\n      if (targetPeer != null) {\n        return false;\n      }\n\n      if (action.type === EActionPayloadType.request) {\n        return true;\n      }\n\n      return false;\n    });\n\n    if (possibleHandlers.length === 0) {\n      return undefined;\n    }\n\n    const scoringPeer = targetPeer ?? RuntimeCoordinate.unknown;\n\n    let handlerScore = -1;\n    let handler: TActionHandler | undefined;\n\n    for (const possibleHandler of possibleHandlers) {\n      // A local handler always wins over any external one: registering a local handler for an action\n      // means \"execute it here\" (the \"handle locally if you can, else forward\" pattern, and the path\n      // by which an inbound push on a bidirectional domain is handled rather than re-forwarded). This\n      // is independent of registration order — otherwise an external `forDomain` registered first could\n      // shadow a local handler for the same action.\n      if (possibleHandler.handlerType === EActionHandlerType.local) {\n        return possibleHandler;\n      }\n\n      if (possibleHandler.handlerType === EActionHandlerType.peer) {\n        const score = scoringPeer.similarityLevel(possibleHandler.peerClient);\n        if (score > handlerScore) {\n          handlerScore = score;\n          handler = possibleHandler;\n        }\n      }\n    }\n\n    return handler;\n  }\n\n  getHandlerForActionOrThrow<ACT extends TActionPayload_Any_Instance<any, any>>(\n    action: ACT,\n    options?: Omit<IHandleActionOptions, \"localRuntime\">,\n  ): TActionHandler {\n    const handler = this._getHandlerForAction(action, options);\n\n    if (handler == null) {\n      throw err_nice_action.fromId(EErrId_NiceAction.no_action_execution_handler, {\n        actionId: action.id,\n        domain: action.domain,\n        specifiedClient: options?.targetPeer,\n      });\n    }\n\n    return handler;\n  }\n\n  /**\n   * Register one or more handlers. Each handler's own `actionRouter` defines\n   * which domains/actions it handles — those routing keys are mirrored into\n   * this runtime's router so the same action can be served by multiple handlers.\n   * Duplicate registrations (same handler cuid for the same key) are skipped.\n   */\n  addHandlers(handlers: TActionRuntimeHandler[]): this {\n    for (const handler of handlers) {\n      if (handler.handlerType === EActionHandlerType.peer) {\n        handler._setIncomingActionDataListener((json) => this.resolveIncomingActionPayload(json));\n        this._registeredPeerHandlers.push(handler);\n      }\n\n      const handlerRouter = handler.getActionRouter();\n      this.actionRouter.addDomainsFromOther(handlerRouter);\n\n      if (this._applied) {\n        this.apply();\n      }\n\n      for (const key of handlerRouter.getRegisteredKeys()) {\n        const alreadyRegistered = this.actionRouter\n          .getForKey(key)\n          .some((h) => h.cuid === handler.cuid);\n        if (!alreadyRegistered) {\n          this.actionRouter.addForKey(key, handler);\n        }\n      }\n    }\n\n    return this;\n  }\n\n  /**\n   * @internal Low-level primitive — the public way to open a connection is `connectChannel`, which\n   * derives routing from a channel and binds the crypto identity for you. This stays as the raw building\n   * block it sits on (it restates domain lists by hand) and is not part of the supported surface.\n   *\n   * Declare an external \"backend client\" in one call: build an\n   * {@link ChannelConnector} for `externalCoordinate` carrying the given\n   * `transports`, route the listed `domains`/`actions` to it, register it (plus any\n   * `localHandlers` — e.g. server→client push handlers that share the same channel)\n   * on this runtime, and `apply()`. Returns the external handler so the caller can\n   * later `clearTransportCache()` it.\n   */\n  connectTo(\n    externalCoordinate: RuntimeCoordinate,\n    options: {\n      transports: Transport[];\n      domains?: ActionDomain<any>[];\n      actions?: ActionCore<any, any>[];\n      localHandlers?: TActionRuntimeHandler[];\n      defaultTimeout?: number;\n      reliableActionTimeout?: number;\n      wireMux?: import(\"@nice-code/wire\").WireProtocolMux;\n      /** The negotiated security level frame protocols ride at (PLAN-security Phase 4.1). */\n      securityLevel?: import(\"@nice-code/wire\").ESecurityLevel;\n      /** Auto-redial a protocol-carrying (realm) duplex link on drop (DESYNC F6 / Phase 8b). */\n      keepLinkAlive?: boolean;\n    },\n  ): ChannelConnector {\n    const handler = new ChannelConnector({\n      runtimeCoordinate: externalCoordinate,\n      transports: options.transports,\n      defaultTimeout: options.defaultTimeout,\n      reliableActionTimeout: options.reliableActionTimeout,\n      wireMux: options.wireMux,\n      localCoordinate: this.coordinate,\n      securityLevel: options.securityLevel,\n      keepLinkAlive: options.keepLinkAlive,\n    });\n\n    for (const domain of options.domains ?? []) {\n      handler.forDomain(domain);\n    }\n    for (const action of options.actions ?? []) {\n      handler.forAction(action);\n    }\n\n    this.addHandlers([handler, ...(options.localHandlers ?? [])]);\n    this.apply();\n\n    return handler;\n  }\n\n  private applyRuntimeForDomain(domain: ActionDomain<any>): void {\n    const rootDomain = domain.rootDomain;\n    if (!rootDomain._hasRuntime(this)) {\n      rootDomain._registerRuntime(this);\n    }\n  }\n\n  /**\n   * Register this runtime with all root domains covered by its currently-added handlers,\n   * making it eligible to execute actions dispatched from those domains.\n   * After apply() is called, any subsequent addHandlers() calls also auto-register.\n   */\n  apply(): this {\n    this._applied = true;\n    for (const domain of this.actionRouter.getDomains()) {\n      this.applyRuntimeForDomain(domain);\n    }\n    return this;\n  }\n\n  /**\n   * Find the best registered external handler that can reach `originClient` directly.\n   * Used to locate the return-path channel for dispatching results back to the action origin.\n   * Returns `undefined` if no handler matches (score > 0 required, i.e. at least id must match).\n   *\n   * A handler that currently holds the origin's *live* connection always wins, regardless of its\n   * coordinate score — owning the live socket bound to the origin's exact coordinate (set from the\n   * handshake) is a strictly more precise match than any env-level `peerClient` score. This lets one\n   * server accept clients of *several* envs over a single acceptor (a multi-role Durable Object): the\n   * result/push routes back over the carrier the client actually connected on even when the handler's\n   * `clientEnv` is unset or names a different env. Only when no handler owns a live connection do we fall\n   * back to the plain best-coordinate-score pick (the offline-return and connector-only cases).\n   */\n  getReturnHandlerForOrigin(originClient: RuntimeCoordinate): PeerLink | undefined {\n    if (originClient.envId === UNSET_RUNTIME_ENV_ID) return undefined;\n\n    let bestScore = -1;\n    let bestHandler: PeerLink | undefined;\n    let bestOwnedScore = -1;\n    let bestOwnedHandler: PeerLink | undefined;\n\n    for (const handler of this._registeredPeerHandlers) {\n      // Only a push-capable (duplex) link can deliver an unsolicited result back; an exchange-only\n      // (HTTP) handler returns its reply inline on the request, so skip it as a return-path candidate.\n      if (!handler.canPush) continue;\n      const score = originClient.similarityLevel(handler.peerClient);\n      if (score > bestScore) {\n        bestScore = score;\n        bestHandler = handler;\n      }\n      // Track the owning handler regardless of score; among several owners the higher score breaks the\n      // tie (first-registered on an all-equal tie, since `>` keeps the earlier one).\n      if (handler.ownsLiveConnectionFor(originClient) && score > bestOwnedScore) {\n        bestOwnedScore = score;\n        bestOwnedHandler = handler;\n      }\n    }\n\n    if (bestOwnedHandler != null) return bestOwnedHandler;\n    return bestScore > 0 ? bestHandler : undefined;\n  }\n\n  resetRuntime(): void {\n    for (const ra of this._pendingRunningActions.values()) {\n      ra._abort(err_nice_action.fromId(EErrId_NiceAction.runtime_reset));\n    }\n\n    for (const handler of this._registeredPeerHandlers) {\n      handler.clearTransportCache();\n    }\n  }\n\n  private _trySetupReturnDispatch(runningAction: RunningAction<any, any>): void {\n    // Fire-and-forget actions get no reply — the sender never waits for one. Skip the return path\n    // entirely (the inbound push was handled locally; that's the whole contract).\n    if (runningAction.context.schema.responseMode === EActionResponseMode.none) {\n      return;\n    }\n\n    const originClient = runningAction.context.originClient;\n\n    if (\n      originClient.envId === UNSET_RUNTIME_ENV_ID ||\n      originClient.isSameFor(this._coordinate).id\n    ) {\n      return;\n    }\n\n    runningAction.addUpdateListeners([\n      (update) => {\n        if (\n          update.type === ERunningActionUpdateType.finished &&\n          update.finishType === ERunningActionFinishedType.success\n        ) {\n          const returnHandler = this.getReturnHandlerForOrigin(originClient);\n          returnHandler\n            ?.sendReturnPayload(update.response, { targetLocalRuntime: this })\n            .catch(() => {});\n        }\n      },\n    ]);\n  }\n}\n\nconst runtimeState: {\n  defaultLocalRuntime?: ActionRuntime;\n  assumedRuntimeInfo?: IRuntimeMeta;\n} = {\n  defaultLocalRuntime: undefined,\n  assumedRuntimeInfo: undefined,\n};\n\nfunction getDefaultActionRuntime(): ActionRuntime {\n  if (runtimeState.assumedRuntimeInfo == null) {\n    runtimeState.assumedRuntimeInfo = getAssumedRuntimeInfo();\n  }\n\n  if (runtimeState.defaultLocalRuntime == null) {\n    runtimeState.defaultLocalRuntime = new ActionRuntime(\n      RuntimeCoordinate.unknown.specify({\n        perId: `${runtimeState.assumedRuntimeInfo?.runtimeName ?? \"unknown\"}-runtime`,\n      }),\n    );\n  }\n\n  return runtimeState.defaultLocalRuntime;\n}\n","import { niceTryAsync } from \"@nice-code/error\";\nimport type { ActionCore } from \"../../../ActionDefinition/Action/Core/ActionCore\";\nimport type { IActionRouteItemHandler } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { ActionPayload_Request } from \"../../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { ActionPayload_Result } from \"../../../ActionDefinition/Action/Payload/ActionPayload_Result\";\nimport { RunningAction } from \"../../../ActionDefinition/Action/RunningAction\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain.types\";\nimport { EErrId_NiceAction, err_nice_action } from \"../../../errors/err_nice_action\";\nimport { isActionPayload_Result_JsonObject } from \"../../../utils/isActionPayload_Result_JsonObject\";\nimport { ActionRuntime } from \"../../ActionRuntime\";\nimport { peekHandlerCuid, popHandlerCuid, pushHandlerCuid } from \"../../HandlerCallStack\";\nimport { ActionRouter } from \"../../Routing/ActionRouter\";\nimport { EActionRouterContextType } from \"../../Routing/ActionRouter.types\";\nimport { ActionHandler } from \"../ActionHandler\";\nimport {\n  EActionHandlerType,\n  type IActionHandler_Local,\n  type IActionHandler_Local_Json,\n  type IHandleActionOptions,\n} from \"../ActionHandler.types\";\nimport type { THandleActionExecutionFn } from \"./ActionLocalHandler.types\";\n\nexport class ActionLocalHandler\n  extends ActionHandler<EActionHandlerType.local>\n  implements IActionHandler_Local\n{\n  readonly handlerType = EActionHandlerType.local;\n  readonly actionRouter: ActionRouter<THandleActionExecutionFn<any, any>> = new ActionRouter({\n    contextType: EActionRouterContextType.handler_route,\n    handler: this,\n  });\n\n  constructor() {\n    super();\n  }\n\n  /**\n   * Register a handler for all actions in a domain.\n   * Receives the full primed action — use `matchAction()` to narrow to a specific action id.\n   * Useful for forwarding all domain actions to a remote endpoint.\n   * Lower priority than `forAction`.\n   */\n  forDomain<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    handler: THandleActionExecutionFn<FOR_DOM>,\n  ): this {\n    this.actionRouter.forDomain(domain, handler);\n    return this;\n  }\n\n  /**\n   * Register a handler for a base action instance. Takes priority over domain-wide handlers.\n   * Receives the full primed action with narrowed input type.\n   * Useful for handling specific actions locally while forwarding the rest of the domain. For example, a local \"ping\" action that checks connectivity without needing a round trip.\n   */\n  forAction<ACT_DOM extends IActionDomain, ID extends keyof ACT_DOM[\"actionSchema\"] & string>(\n    action: ActionCore<ACT_DOM, ID>,\n    handler: THandleActionExecutionFn<ACT_DOM, ID>,\n  ): this {\n    this.actionRouter.forAction(action, handler);\n    return this;\n  }\n\n  /**\n   * Register a handler for multiple action IDs (first-match-wins among cases).\n   * Receives the full primed action narrowed to the union of those IDs.\n   * Use `act.coreAction.id` to branch on which action was dispatched.\n   */\n  forActionIds<\n    ACT_DOM extends IActionDomain,\n    IDS extends ReadonlyArray<keyof ACT_DOM[\"actionSchema\"] & string>,\n  >(\n    domain: ActionDomain<ACT_DOM>,\n    ids: IDS,\n    handler: THandleActionExecutionFn<ACT_DOM, IDS[number]>,\n  ): this {\n    this.actionRouter.forActionIds(domain, ids, handler);\n    return this;\n  }\n\n  /**\n   * Register per-action handlers for a domain using a single map, without needing\n   * separate `forAction` calls. Unregistered action IDs are unaffected.\n   *\n   * @example\n   * ```ts\n   * handler.forDomainActionCases(userDomain, {\n   *   getUser:    (primed) => db.getUser(primed.input.userId),\n   *   deleteUser: (primed) => db.deleteUser(primed.input.userId),\n   * });\n   * ```\n   */\n  forDomainActionCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: {\n      [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: THandleActionExecutionFn<FOR_DOM, ID>;\n    },\n  ): this {\n    this.actionRouter.forDomainActionCases(domain, cases);\n    return this;\n  }\n\n  async handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>> {\n    const targetLocalRuntime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();\n\n    const handler = this.actionRouter.getRouteDataForActionOrThrow(action, {\n      targetLocalRuntime,\n    });\n\n    action.context.addRouteItem({\n      runtime: targetLocalRuntime.coordinate,\n      handler: this.toHandlerRouteItem(),\n      time: Date.now(),\n    });\n\n    const runningAction = new RunningAction<DOM, ID>({\n      context: action.context,\n      request: action,\n      parentCuid: peekHandlerCuid(),\n      callSite: action._callSite ?? new Error().stack,\n    });\n    // `_handleRunningAction` funnels every outcome (handler throw, output-validation\n    // throw, foreign throw) into a deterministic result via `niceTryAsync` — it never\n    // rejects, so there is no error ladder here.\n    void this._handleRunningAction(handler, runningAction);\n    return runningAction;\n  }\n\n  private async _handleRunningAction(\n    handler: THandleActionExecutionFn<any, any>,\n    runningAction: RunningAction<any, any>,\n  ) {\n    const state = runningAction.state;\n\n    if (state.result != null) {\n      return;\n    }\n\n    // Yield before pushing so that sibling actions dispatched in the same synchronous\n    // frame have already read their parentCuid (which they do synchronously in\n    // handleActionRequest) before we mutate the stack. Without this, a concurrent\n    // sibling's peek would see our cuid and incorrectly treat us as its parent.\n    // Truly nested child actions (dispatched from inside the handler body below) still\n    // see our cuid correctly because the push happens before we call handler().\n    await Promise.resolve();\n\n    pushHandlerCuid(runningAction.cuid);\n    try {\n      // Everything that can fail — the handler itself and result normalization\n      // (output validation, payload hydration) — runs inside the funnel so any\n      // throw becomes a `{ ok: false }` result rather than an unhandled rejection.\n      const ran = await niceTryAsync(async (): Promise<ActionPayload_Result<any, any>> => {\n        const rawResult = await handler(state.request);\n\n        if (rawResult instanceof ActionPayload_Result) {\n          return rawResult;\n        }\n        if (rawResult != null && isActionPayload_Result_JsonObject(rawResult)) {\n          const domain = this.actionRouter.domainManager.getActionDomainOrThrow(state.request);\n          return domain.hydrateResultPayload(rawResult);\n        }\n        return state.request.successResult(rawResult);\n      });\n\n      const result = ran.ok ? ran.output : state.request.errorResult(ran.error);\n      runningAction._completeWithResult(result);\n    } finally {\n      popHandlerCuid();\n    }\n  }\n\n  async handlePayloadWireOrThrow(\n    wire: unknown,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<any, any>> {\n    const hydratedAction = this.actionRouter.domainManager.hydrateActionPayload(wire as any);\n\n    if (!(hydratedAction instanceof ActionPayload_Request)) {\n      throw err_nice_action.fromId(EErrId_NiceAction.wire_action_not_payload, {\n        domain: hydratedAction.domain,\n        actionId: hydratedAction.id,\n        actionState: (hydratedAction as any).type ?? (hydratedAction as any).form,\n      });\n    }\n\n    return await this.handleActionRequest(hydratedAction, config);\n  }\n\n  toJsonObject(): IActionHandler_Local_Json {\n    return {\n      type: this.handlerType,\n    };\n  }\n\n  toHandlerRouteItem(): IActionRouteItemHandler {\n    return {\n      type: this.handlerType,\n    };\n  }\n}\n\nexport const createLocalHandler = () => {\n  return new ActionLocalHandler();\n};\n","import type { TActionPayload_Any_JsonObject } from \"../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isActionPayload_Any_JsonObject } from \"./isActionPayload_Any_JsonObject\";\n\n/**\n * Minimal codec shape needed to turn an incoming channel frame back into action wire JSON. Matches\n * the `formatMessage` object the WebSocket transport (and `createBinaryWireAdapter`) provide.\n */\nexport interface IActionFrameDecoder {\n  incoming?: (\n    frame: string | ArrayBuffer | Uint8Array | Blob,\n  ) => TActionPayload_Any_JsonObject<any, any> | undefined;\n}\n\n/**\n * Decode a single inbound channel frame (text or binary) into validated action wire JSON, or\n * `undefined` if it isn't a recognisable action payload.\n *\n * Shared by the WebSocket transport's message listener and the server-side `ChannelAcceptor` so\n * both decode identically: a binary `decoder.incoming` (e.g. msgpackr) takes precedence, and plain\n * text frames fall back to JSON — keeping binary and JSON clients interoperable on one channel.\n */\nexport function decodeActionFrame(\n  frame: string | ArrayBuffer | Uint8Array,\n  decoder?: IActionFrameDecoder,\n): TActionPayload_Any_JsonObject<any, any> | undefined {\n  const decoded =\n    decoder?.incoming?.(frame) ??\n    (typeof frame === \"string\" ? parseJsonActionFrame(frame) : undefined);\n\n  return decoded != null && isActionPayload_Any_JsonObject(decoded) ? decoded : undefined;\n}\n\nfunction parseJsonActionFrame(\n  message: string,\n): TActionPayload_Any_JsonObject<any, any> | undefined {\n  try {\n    const json = JSON.parse(message);\n    return isActionPayload_Any_JsonObject(json) ? json : undefined;\n  } catch {\n    return undefined;\n  }\n}\n","import type { ESecurityLevel } from \"@nice-code/wire\";\nimport { RuntimeCoordinate } from \"@nice-code/wire\";\nimport type { IActionPayload_Request_JsonObject } from \"../../ActionDefinition/Action/Payload/ActionPayload.types\";\n\n/**\n * What the server knows about an inbound action request when it accepts it — handed to a logger *before*\n * the action executes. Deliberately carries only routing-level facts (which action, over which transport,\n * from whom) plus the raw {@link input}; a logger decides for itself whether to surface the input (the\n * default logger hides it unless told otherwise, since inputs can hold sensitive data).\n */\nexport interface IActionServeRequestInfo {\n  /** The carrier that received the request — its short kind label, e.g. `\"http\"`, `\"ws\"`, `\"webrtc\"`. */\n  transport: string;\n  /** Domain-qualified action id, e.g. `\"demo_basic/greet\"` (the {@link domain} + {@link action}). */\n  actionId: string;\n  /** The action's own (unqualified) id, e.g. `\"greet\"`. */\n  action: string;\n  /** The domain the action belongs to, e.g. `\"demo_basic\"`. */\n  domain: string;\n  /** The originating client runtime coordinate (its `stringId`) — who sent the request. */\n  origin: string;\n  /** The security level the request arrived under (`none` for a plain endpoint), when known. */\n  securityLevel?: ESecurityLevel;\n  /** The action's input — always provided; a logger shows it only if configured to (default: hidden). */\n  input: unknown;\n  /**\n   * The encoded request frame's size in bytes, as the serving path decoded it — **pre-decryption**, so\n   * this is the action payload's own cost, not the billed carrier frame. (For true wire bytes across\n   * every lane, use `serveChannel({ wireTap })`.) Absent where the path never sees an encoded frame.\n   */\n  bytes?: number;\n  /**\n   * Reliable-delivery metadata, present only when the request arrived on a `.reliable()` stream: the frame's\n   * per-stream sequence number, the cumulative high-water acked back to the client, and whether it was a\n   * **redelivered** duplicate (a resend the server already had). Absent for best-effort requests.\n   */\n  reliability?: IActionServeReliabilityInfo;\n}\n\n/** The reliable-stream facts a logger can surface for a `.reliable()` request. See {@link IActionServeRequestInfo.reliability}. */\nexport interface IActionServeReliabilityInfo {\n  seq?: number;\n  ack?: number;\n  redelivered?: boolean;\n}\n\n/**\n * How an action request was served — handed to the reporter that {@link IActionServeLogger.onRequest}\n * returns, once the action has finished and its result has been handed back to the client.\n */\nexport interface IActionServeResultInfo {\n  /** Whether the action succeeded. */\n  ok: boolean;\n  /** How the result went back to the client — typically the receiving transport (`\"http\"`, `\"ws\"`, …). */\n  returnedVia: string;\n  /** Wall-clock milliseconds from the request being received to its result being returned. */\n  durationMs: number;\n  /**\n   * The encoded result frame's size in bytes, pre-encryption — the mirror of\n   * {@link IActionServeRequestInfo.bytes}. Absent where the path never encodes a frame.\n   */\n  bytes?: number;\n  /** When {@link ok} is `false`: the failure's error id (when present) and message. */\n  error?: { id?: string; message: string };\n}\n\n/** Called once with the outcome by the reporter {@link IActionServeLogger.onRequest} returns. */\nexport type TActionServeResultReporter = (result: IActionServeResultInfo) => void;\n\n/**\n * A pluggable server-side logger for {@link serveChannel}. {@link onRequest} is called when the server\n * accepts an inbound action request (before it executes) and returns a reporter the server then calls with\n * the outcome — so one logger call spans the whole request→response, letting an implementation pair the two\n * lines (and time the gap) however it likes.\n *\n * Pass an instance as `serveChannel(..., { logger })`. Use {@link createDefaultServeLogger} for a ready-made\n * console logger, or implement this interface to forward to your own logging stack (pino, a metrics sink, …).\n */\nexport interface IActionServeLogger {\n  /**\n   * Observe an accepted inbound request. Return a reporter the server invokes once the action has been\n   * served with its outcome + how it was returned. Returning `undefined` skips the result line for this one\n   * request (e.g. to sample, or to ignore a noisy action).\n   */\n  onRequest(info: IActionServeRequestInfo): TActionServeResultReporter | undefined;\n}\n\n/** Build the {@link IActionServeRequestInfo} for an inbound request wire, shared by every serving path. */\nexport function actionServeRequestInfo(\n  wire: IActionPayload_Request_JsonObject,\n  meta: {\n    transport: string;\n    securityLevel?: ESecurityLevel;\n    origin?: string;\n    reliability?: IActionServeReliabilityInfo;\n    bytes?: number;\n  },\n): IActionServeRequestInfo {\n  // The bound (authenticated) origin is passed when the path knows it; otherwise fall back to the wire's\n  // self-asserted coordinate so a plain endpoint still names its caller.\n  const origin =\n    meta.origin ??\n    (wire.context.originClient != null\n      ? new RuntimeCoordinate(wire.context.originClient).stringId\n      : \"unknown\");\n  return {\n    transport: meta.transport,\n    domain: wire.domain,\n    action: wire.id,\n    actionId: `${wire.domain}/${wire.id}`,\n    origin,\n    securityLevel: meta.securityLevel,\n    input: wire.input,\n    bytes: meta.bytes,\n    reliability: meta.reliability,\n  };\n}\n\n/**\n * Reduce a result's failure error to the flat `{ id?, message }` a logger shows. Typed against the minimal\n * structural shape of a `NiceError` so {@link serveLogger} stays free of an `@nice-code/error` import.\n */\nexport function serveResultErrorInfo(error: {\n  def?: { domain?: string };\n  ids?: readonly string[];\n  cleanMessage?: string;\n  message: string;\n}): { id?: string; message: string } {\n  const domain = error.def?.domain;\n  const ids = error.ids != null && error.ids.length > 0 ? error.ids.join(\",\") : undefined;\n  const id = domain != null && ids != null ? `${domain}/${ids}` : (ids ?? domain);\n  return { id, message: error.cleanMessage ?? error.message };\n}\n\n/** Options for {@link createDefaultServeLogger}. */\nexport interface IDefaultServeLoggerOptions {\n  /** Where each line is written. Defaults to the global `console`. */\n  sink?: Pick<Console, \"log\" | \"error\">;\n  /** Tag prefixed to every line so server logs are greppable. Defaults to `\"[nice-action]\"`. */\n  tag?: string;\n  /**\n   * Include the action input on the request line. Off by default — inputs can carry sensitive data, so\n   * opt in only when you want it (this is the \"unless configured that way\" switch).\n   */\n  logInputs?: boolean;\n  /** Show the negotiated security level (`[encrypted]`, …) on the request line. Defaults to `true`. */\n  showSecurityLevel?: boolean;\n}\n\n/**\n * A ready-made {@link IActionServeLogger} that prints one line when a request arrives and one when it has\n * been served, to `console` (or any `sink` you pass). Drop it straight into `serveChannel` so a \"host and\n * forget\" backend gets request/response feedback with no extra wiring:\n * ```ts\n * serveChannel(runtime, channel, { storage, carriers, logger: createDefaultServeLogger() });\n * // → [nice-action] ▶ demo_basic/greet  via http  from envId[web_app]…  [encrypted]\n * // ← [nice-action] ✓ demo_basic/greet  ok  via http  12ms\n * ```\n * Inputs are hidden by default (`logInputs: true` to include them).\n */\nexport function createDefaultServeLogger(\n  options: IDefaultServeLoggerOptions = {},\n): IActionServeLogger {\n  const sink = options.sink ?? console;\n  const tag = options.tag ?? \"[nice-action]\";\n  const showSecurity = options.showSecurityLevel ?? true;\n\n  return {\n    onRequest(info) {\n      const request = [tag, \"▶\", info.actionId, `via ${info.transport}`, `from ${info.origin}`];\n      if (info.bytes != null) request.push(`${info.bytes}B`);\n      if (showSecurity && info.securityLevel != null) request.push(`[${info.securityLevel}]`);\n      if (info.reliability != null) {\n        const { seq, ack, redelivered } = info.reliability;\n        request.push(\n          `reliable seq=${seq ?? \"-\"} ack=${ack ?? \"-\"}${redelivered ? \" (redelivered)\" : \"\"}`,\n        );\n      }\n      if (options.logInputs) request.push(`input=${safeJson(info.input)}`);\n      sink.log(request.join(\"  \"));\n\n      return (result) => {\n        const line = [\n          tag,\n          result.ok ? \"✓\" : \"✗\",\n          info.actionId,\n          result.ok ? \"ok\" : \"FAIL\",\n          `via ${result.returnedVia}`,\n          `${result.durationMs}ms`,\n        ];\n        if (result.bytes != null) line.push(`${result.bytes}B`);\n        if (!result.ok && result.error != null) {\n          const prefix = result.error.id != null ? `${result.error.id}: ` : \"\";\n          line.push(`— ${prefix}${result.error.message}`);\n        }\n        (result.ok ? sink.log : sink.error)(line.join(\"  \"));\n      };\n    },\n  };\n}\n\nfunction safeJson(value: unknown): string {\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n","import type { ClientCryptoKeyLink } from \"@nice-code/util\";\nimport {\n  DEFAULT_TRANSPORT_TIMEOUT,\n  decodeControlFrame,\n  ESecurityLevel,\n  encodeControlFrame,\n  type IClientVerifyKeyResolver,\n  type IReliableReceiver,\n  type IRuntimeCoordinate,\n  type IWireAcceptorProtocol,\n  type IWireConnectionBinding,\n  ReliableInbox,\n  RuntimeCoordinate,\n  reliableStreamId,\n  type TControlMessage,\n  type TFrame,\n  type TServerDictionaryVersionResolver,\n  UNSET_RUNTIME_ENV_ID,\n  WireAcceptor,\n  warnReliablePushUnsupportedOnce,\n  wireFrameByteSize,\n} from \"@nice-code/wire\";\nimport type { TDistributeActionPayload_Request } from \"../../../../ActionDefinition/Action/Action.combined.types\";\nimport type { IActionRouteItemHandler } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport {\n  EActionPayloadType,\n  type TActionPayload_Any_Instance,\n  type TActionPayload_Any_JsonObject,\n} from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionPayload_Request } from \"../../../../ActionDefinition/Action/Payload/ActionPayload_Request\";\nimport { RunningAction } from \"../../../../ActionDefinition/Action/RunningAction\";\nimport { ERunningActionUpdateType } from \"../../../../ActionDefinition/Action/RunningAction.types\";\nimport type { ActionDomain } from \"../../../../ActionDefinition/Domain/ActionDomain\";\nimport type { IActionDomain } from \"../../../../ActionDefinition/Domain/ActionDomain.types\";\nimport {\n  EActionResponseMode,\n  EReliabilityTier,\n} from \"../../../../ActionDefinition/Schema/ActionSchema\";\nimport { decodeActionFrame } from \"../../../../utils/decodeActionFrame\";\nimport { ActionRuntime } from \"../../../ActionRuntime\";\nimport {\n  actionServeRequestInfo,\n  type IActionServeLogger,\n  type IActionServeReliabilityInfo,\n  serveResultErrorInfo,\n  type TActionServeResultReporter,\n} from \"../../../Channel/serveLogger\";\nimport { peekHandlerCuid } from \"../../../HandlerCallStack\";\nimport type { IActionWireFormat } from \"../../../Transport/codec/actionWireCodec\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../../../Transport/err_nice_transport\";\nimport { ETransportShape, type IFrameReliability } from \"../../../Transport/Transport.types\";\nimport type { IActionHandler_Peer_Json, IHandleActionOptions } from \"../../ActionHandler.types\";\nimport { ActionLocalHandler } from \"../../Local/ActionLocalHandler\";\nimport type { THandleActionExecutionFn } from \"../../Local/ActionLocalHandler.types\";\nimport { PeerLink } from \"../../PeerLink/PeerLink\";\n\n/** The codec shape `ChannelAcceptor` uses to pack/unpack frames — same as the Link transport's. */\nexport type TActionChannelFormatMessage = IActionWireFormat;\n\n/** How a connection encodes its frames, remembered so we answer each client in its own dialect. */\nexport type TActionConnectionEncoding = \"json\" | \"binary\";\n\n/**\n * A connection's restorable identity — since plan Phase 4 this is wire's versioned\n * {@link IWireConnectionBinding} (`v: 1`; client coordinate + secure-session state + advertised\n * protocol ids owned by wire, with the lane's own facts in the opaque `lane` slot — see\n * {@link IAcceptorLaneBindingState}). Persisted attachments from before the versioned schema are\n * ignored on rehydrate (the socket is treated as fresh).\n */\nexport type IAcceptorConnectionBinding = IWireConnectionBinding;\n\n/**\n * The action lane's slot on the wire binding (E4): what this handler persists per connection\n * beyond the wire-owned identity — the frame encoding and the negotiated channel tags, so a\n * hibernation-woken acceptor answers each client in its dialect and rebuilds its codec.\n */\nexport interface IAcceptorLaneBindingState {\n  encoding: TActionConnectionEncoding;\n  /**\n   * The channel tags the connection negotiated (`hello.channels`), persisted so a multi-channel\n   * acceptor rebuilds the right per-connection codec on wake. Absent for a single-channel acceptor.\n   */\n  channelTags?: readonly string[];\n}\n\n/** Validate + read a rehydrated binding's opaque lane slot back into the lane's shape. */\nfunction readLaneBindingState(lane: unknown): IAcceptorLaneBindingState | undefined {\n  if (typeof lane !== \"object\" || lane == null || !(\"encoding\" in lane)) return undefined;\n  const channelTags =\n    \"channelTags\" in lane && Array.isArray(lane.channelTags) ? lane.channelTags : undefined;\n  return { encoding: lane.encoding === \"json\" ? \"json\" : \"binary\", channelTags };\n}\n\n/**\n * An acceptor-side frame protocol (M1 multiplex seam, realm plan §3) — since plan Phase 4 this is\n * wire's {@link IWireAcceptorProtocol}: the server half of a protocol riding the same connections\n * as action frames. Register via {@link ChannelAcceptor.registerFrameProtocol} (or the underlying\n * `WireAcceptor` directly); the wire acceptor dispatches reserved-prefix frames (`0x01`–`0x0F`)\n * per connection, advertises `proto:<id>` in its handshake welcome, gates traffic on the\n * connection's security level (review A.6 — set `allowPlain` for a deliberately plain endpoint),\n * and fires attach/detach around the connection lifecycle (including hibernation resume).\n */\nexport type IAcceptorFrameProtocol<TConn> = IWireAcceptorProtocol<TConn>;\n\n/**\n * Server-side secure-channel config. When set, each connection negotiates a level from\n * {@link securityLevel}: an `authenticated`/`encrypted` client must complete the handshake (and is then\n * bound to its *authenticated* coordinate) before any action frame is accepted. A `none` client (only\n * when `none` is in the allowed set) is accepted as-is with a self-asserted identity. For the\n * `encrypted` level the codec source should be a session factory (`createFormatMessage`).\n */\nexport interface IAcceptorSecurity {\n  /**\n   * Accepted level(s). A single level is strict; an array is a negotiable allowed set — the server\n   * adopts whichever level each client requests (e.g. `[none, authenticated, encrypted]` serves all\n   * three over one endpoint).\n   */\n  securityLevel: ESecurityLevel | readonly ESecurityLevel[];\n  /** This server's crypto identity (verify + exchange key pairs, optionally persisted). */\n  link: ClientCryptoKeyLink;\n  /** This server's coordinate — its identity to clients during the handshake. */\n  localCoordinate: IRuntimeCoordinate;\n  /** Wire dictionary version — a fixed string (single channel), or a resolver composing it from the\n   * `hello.channels` tags (multi-channel). The handshake rejects on a mismatch / unknown channel. */\n  dictionaryVersion: string | TServerDictionaryVersionResolver;\n  /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n}\n\ninterface IChannelAcceptorBaseOptions<TConn> {\n  /**\n   * Coordinate of the *connecting clients* (typically env-only, e.g. `RuntimeCoordinate.env(\"web_app\")`),\n   * scored against an action's `originClient` to pick this handler when *no* handler holds the client's\n   * live connection (the offline-return fallback). A handler that currently owns the live socket always\n   * wins regardless, so this is optional: omit it for a multi-role server that accepts several client envs\n   * over one acceptor — it then defaults to `RuntimeCoordinate.unknown` (scores 0 against every client).\n   */\n  clientEnv?: RuntimeCoordinate;\n  /** Write an encoded frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */\n  send: (connection: TConn, frame: string | Uint8Array | ArrayBuffer) => void;\n  /**\n   * The runtime this handler belongs to. When set, {@link ChannelAcceptor.broadcast} can be called\n   * without threading a runtime through each call. Optional — `pushToClient` still takes one explicitly.\n   */\n  runtime?: ActionRuntime;\n  /** Timeout (ms) applied to server-initiated actions awaiting a client response. */\n  defaultTimeout?: number;\n  /**\n   * Called once when a connection is first bound to a client identity. Use it to persist the binding\n   * for transports that can resume after eviction — e.g. a Durable Object's hibernatable WebSocket:\n   * `(ws, binding) => ws.serializeAttachment(binding)` — then replay it via {@link ChannelAcceptor.rehydrate}\n   * when the channel comes back.\n   */\n  onConnectionBound?: (connection: TConn, binding: IAcceptorConnectionBinding) => void;\n  /**\n   * Enable the authenticated (optionally encrypted) handshake. When omitted, connections are trusted\n   * as-is (identity self-asserted) — fine for dev / trusted networks.\n   */\n  security?: IAcceptorSecurity;\n  /** Optional server-side logger — called per inbound action request with its served outcome. */\n  logger?: IActionServeLogger;\n  /**\n   * The server's wire-observation seam — the mirror of `connectChannel({ wireTap })`. Every frame\n   * crossing a carrier is reported with its true wire byte size (post-encryption) and its lane\n   * (`handshake` / `keepalive` / `action` / a protocol id such as `realm`), tagged with the bound\n   * client as `linkId`. Sizes only, never payload contents.\n   */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (e.g. `\"ws\"`). */\n  transportLabel?: string;\n  /**\n   * Persisted receive store for the **persisted** reliability tier (`.reliable({ persist: true })`). When set,\n   * a frame whose action declares the `persisted` tier is deduped through this store (e.g. a `ReliableLog` over\n   * a Durable Object's SQL) instead of the in-memory inbox — so its high-water survives eviction and a\n   * replayed stream dedups rather than redelivering. Omit it and persisted-tier streams degrade gracefully to\n   * the in-memory (session) behavior. `session`-tier streams always use the in-memory inbox.\n   *\n   * On the high-level serve surface this is the `reliableStore` option (`serveChannel` /\n   * `serveDurableObject`) — one store, two entry points; both names describe the same\n   * `IReliableReceiver`.\n   */\n  persistedReceiver?: IReliableReceiver<TActionPayload_Any_JsonObject<any>>;\n  /**\n   * Max distinct **keyed** (`streamKey`, E3) reliable streams tracked per bound client (default 256).\n   * Every keyed frame mints receiver state named by a client-chosen string, so without a cap one client\n   * could allocate unbounded server-side stream state; past the cap a new key's frames are served\n   * best-effort (delivered, but no ordering/dedup state is created) with a one-time warning.\n   */\n  maxKeyedStreamsPerClient?: number;\n}\n\n/**\n * Multi-channel codec selection: resolve a connection's advertised channel tags (`hello.channels`) into the\n * codec factory it should use, so one acceptor can serve several channels and pick each connection's codec\n * from the subset it connected. Returns `undefined` only for an unknown/unserved set (the handshake already\n * rejects those); given no tags it returns the default (single/combined) channel's factory.\n */\nexport type TAcceptorResolveCodec = (\n  tags: readonly string[] | undefined,\n) => (() => TActionChannelFormatMessage) | undefined;\n\n/**\n * Provide exactly one codec source:\n * - `formatMessage` — a single shared codec for every connection (stateless, e.g. `createBinaryWireAdapter`).\n * - `createFormatMessage` — a per-connection factory for stateful codecs (e.g.\n *   `createBinaryWireSessionFactory`, whose sessions hold correlation + identity state). Required for the\n *   leanest binary wire; the handler creates and caches one codec per connection.\n */\nexport type IChannelAcceptorOptions<TConn> = IChannelAcceptorBaseOptions<TConn> &\n  (\n    | {\n        formatMessage: TActionChannelFormatMessage;\n        createFormatMessage?: never;\n        resolveCodec?: never;\n      }\n    | {\n        createFormatMessage: () => TActionChannelFormatMessage;\n        formatMessage?: never;\n        resolveCodec?: never;\n      }\n    | { resolveCodec: TAcceptorResolveCodec; formatMessage?: never; createFormatMessage?: never }\n  );\n\n/**\n * A connection-aware execution case (see {@link ChannelAcceptor.forConnectionDomainCases}). It receives\n * the primed request plus a per-invocation `context` — whatever the wiring's context mapper produces from\n * the originating connection. The low-level handler passes the raw connection (`TConn | undefined`); the\n * higher-level `serveChannel` enriches it into an `IConnectionContext` (state + broadcast + pushBack). A\n * case may return the action's raw output, a result payload, or nothing (auto-wrapped as an empty\n * success) — exactly like a local handler case.\n */\nexport type TAcceptorCaseFn<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string,\n  TCtx,\n> = (\n  action: TDistributeActionPayload_Request<DOM, ID>,\n  context: TCtx,\n) => ReturnType<THandleActionExecutionFn<DOM, ID>> | void;\n\n/**\n * The connection-aware case the bare {@link ChannelAcceptor} serves: its `context` is the originating\n * client's live connection (resolved from the request's `originClient`, `undefined` if the socket is\n * gone). It's {@link TAcceptorCaseFn} fixed to `TConn | undefined` — the un-enriched shape used by\n * {@link ChannelAcceptor.forConnectionDomainCases} and `acceptChannelConnections`.\n */\nexport type TAcceptorConnectionCaseFn<\n  DOM extends IActionDomain,\n  ID extends keyof DOM[\"actionSchema\"] & string,\n  TConn,\n> = TAcceptorCaseFn<DOM, ID, TConn | undefined>;\n\n/**\n * Server-side handler for backends that accept many client connections over a single open channel\n * (WebSockets, Durable Objects, …). It is transport-agnostic: you feed it inbound frames with\n * {@link receive} and tell it how to write outbound frames via the `send` option.\n *\n * Since plan Phase 4 this class is the **action lane** over a wire-owned {@link WireAcceptor}\n * (reachable as {@link wireAcceptor}): the backbone — handshake accept + secure sessions, security\n * levels, the client-identity registry, frame-protocol registration/dispatch/lifecycle, versioned\n * binding persistence + rehydrate, and keepalive — lives in wire; this handler keeps the action\n * half — codec negotiation, reliable receive (inbox/dedup/acks), request execution routing, and\n * the results/pushes going back out.\n *\n * Add it alongside your local execution handler:\n * ```ts\n * const serverHandler = createChannelAcceptor({ clientEnv, formatMessage, send: (ws, f) => ws.send(f) });\n * runtime.addHandlers([localHandler, serverHandler]);\n * // per inbound message (e.g. a Durable Object's webSocketMessage):\n * serverHandler.receive(ws, message);\n * ```\n *\n * Inbound requests route to your local handler; the runtime's return dispatch then calls this\n * handler back (it is an external handler keyed to `clientEnv`) to send the result to the originating\n * connection. It registers an empty action router, so it is never chosen to *execute* an inbound\n * request — only to ferry results/pushes back out.\n */\nexport class ChannelAcceptor<TConn = unknown> extends PeerLink {\n  /** Accept-in over a live (duplex) connection registry — it pushes results/broadcasts to bound sockets. */\n  readonly canPush = true;\n\n  /** The wire-owned acceptor backbone this lane composes on (plan Phase 4). */\n  readonly wireAcceptor: WireAcceptor<TConn>;\n\n  private readonly _formatMessage?: TActionChannelFormatMessage;\n  private readonly _createFormatMessage?: () => TActionChannelFormatMessage;\n  private readonly _resolveCodec?: TAcceptorResolveCodec;\n  private readonly _runtime?: ActionRuntime;\n  private readonly _serverTimeout: number;\n\n  // Per-connection lane registries: encoding + codec + negotiated channel tags (census §6).\n  private readonly _connEncoding = new Map<TConn, TActionConnectionEncoding>();\n  private readonly _codecByConn = new Map<TConn, TActionChannelFormatMessage>();\n  /** The channel tags each connection negotiated — drives its `resolveCodec` selection. */\n  private readonly _connTags = new Map<TConn, readonly string[] | undefined>();\n\n  // Server-side receive bookkeeping for `.reliable()` streams (dedup + ordered dispatch + high-water for\n  // acks). Keyed by (bound client + route). Inert until a frame carries a reliability seq.\n  private readonly _inbox = new ReliableInbox<TActionPayload_Any_JsonObject<any>>();\n\n  // Persisted receive store for the `persisted` tier (set when `persistedReceiver` is provided). Persisted-tier\n  // streams dedup through this instead of `_inbox`, so their high-water survives eviction.\n  private readonly _persistedReceiver?: IReliableReceiver<TActionPayload_Any_JsonObject<any>>;\n\n  // The streamKey of each dispatched **keyed reply-carrying** reliable request, by its (per-delivery)\n  // cuid — consumed by `_sendPayload` so the reply's piggyback slot carries `{ack, streamKey}` and keyed\n  // acks stay atomic with their replies (exactly like unkeyed ones). Entries are deleted when the reply\n  // goes out; a time sweep bounds the rare never-replied leftovers.\n  private readonly _replyStreamKeys = new Map<string, { streamKey: string; time: number }>();\n\n  // Distinct keyed (E3) stream ids admitted per bound client + the clients already warned for exceeding\n  // the cap. Keys are client-chosen strings, so this is the allocation bound on receiver stream state.\n  private readonly _keyedStreamsByClient = new Map<string, Set<string>>();\n  private readonly _keyedCapWarned = new Set<string>();\n  private readonly _maxKeyedStreams: number;\n\n  // Streams for which a session-reset re-sync has been requested (and warned). Latches the `rsync` *send*\n  // — one request per reset, not one per frame — so a burst of stale-numbered frames (a reconnect's\n  // resendAll) doesn't trigger a client re-sync (a full-window renumber + resend) per frame. Cleared when\n  // the stream recovers (a fresh in-order frame arrives) so a future reset re-syncs afresh, and on\n  // connection drop (the rsync may have died with the socket; the reconnect's stale frames must be able\n  // to request it again).\n  private readonly _resyncRequested = new Set<string>();\n\n  // Optional request/response logging. `_pendingReports` correlates an inbound request to its returned\n  // result by the action's `cuid`, so one log line can span the whole serve (and time the gap).\n  private readonly _logger?: IActionServeLogger;\n  private readonly _transportLabel: string;\n  private readonly _pendingReports = new Map<\n    string,\n    { report: TActionServeResultReporter; startedAt: number }\n  >();\n\n  constructor(options: IChannelAcceptorOptions<TConn>) {\n    super(options.clientEnv ?? RuntimeCoordinate.unknown);\n    this._formatMessage = options.formatMessage;\n    this._createFormatMessage = options.createFormatMessage;\n    this._resolveCodec = options.resolveCodec;\n    this._runtime = options.runtime;\n    this._serverTimeout = options.defaultTimeout ?? DEFAULT_TRANSPORT_TIMEOUT;\n    this._logger = options.logger;\n    this._transportLabel = options.transportLabel ?? \"ws\";\n    this._persistedReceiver = options.persistedReceiver;\n    this._maxKeyedStreams = options.maxKeyedStreamsPerClient ?? 256;\n\n    // The wire backbone, with this handler wired in as its lane (E5): every unprefixed frame — the\n    // lane's namespace — routes to `_onLaneFrame`, the lane supplies the handshake's version\n    // payload (`dictionaryVersion`, plan Phase 5 — wire's security config keeps only the neutral\n    // core), and the lane's per-connection facts (encoding + channel tags) ride the binding's\n    // opaque `lane` slot.\n    const security = options.security;\n    this.wireAcceptor = new WireAcceptor<TConn>({\n      send: options.send,\n      tap: options.wireTap,\n      security:\n        security == null\n          ? undefined\n          : {\n              securityLevel: security.securityLevel,\n              link: security.link,\n              localCoordinate: security.localCoordinate,\n              verifyKeyResolver: security.verifyKeyResolver,\n            },\n      onConnectionBound: options.onConnectionBound,\n      lane: {\n        dictionaryVersion: security?.dictionaryVersion,\n        onFrame: (connection, frame, level) => this._onLaneFrame(connection, frame, level),\n        onAuthenticated: (connection, auth) => {\n          // Binary is the secure channel's encoding; remember the negotiated channel subset so\n          // `_codecFor` composes the matching codec.\n          this._connEncoding.set(connection, \"binary\");\n          this._connTags.set(connection, auth.channelTags);\n        },\n        bindingState: (connection) => this._laneBindingState(connection),\n        restoreBindingState: (connection, lane) => {\n          const state = readLaneBindingState(lane);\n          if (state == null) return;\n          this._connEncoding.set(connection, state.encoding);\n          this._connTags.set(connection, state.channelTags);\n        },\n        onDrop: (connection, client) => this._onConnectionDropped(connection, client),\n      },\n    });\n  }\n\n  /** The lane's opaque binding slot for a connection — persisted by the wire acceptor. */\n  private _laneBindingState(connection: TConn): IAcceptorLaneBindingState {\n    return {\n      encoding: this._connEncoding.get(connection) ?? \"binary\",\n      channelTags: this._connTags.get(connection),\n    };\n  }\n\n  /**\n   * Admit (or refuse) a **keyed** reliable stream for a client — the allocation bound on receiver stream\n   * state, since keys are client-chosen strings. Past the cap the caller serves the frame best-effort\n   * (delivered, no state) and this warns once per client.\n   */\n  private _admitKeyedStream(client: RuntimeCoordinate, streamId: string): boolean {\n    let admitted = this._keyedStreamsByClient.get(client.stringId);\n    if (admitted == null) {\n      admitted = new Set();\n      this._keyedStreamsByClient.set(client.stringId, admitted);\n    }\n    if (admitted.has(streamId)) return true;\n    if (admitted.size >= this._maxKeyedStreams) {\n      if (!this._keyedCapWarned.has(client.stringId)) {\n        this._keyedCapWarned.add(client.stringId);\n        console.warn(\n          `[reliable] client \"${client.stringId}\" exceeded maxKeyedStreamsPerClient ` +\n            `(${this._maxKeyedStreams}) — further keyed reliable streams from it are served best-effort ` +\n            \"(no ordering/dedup state). Raise the option if this is legitimate fan-out.\",\n        );\n      }\n      return false;\n    }\n    admitted.add(streamId);\n    return true;\n  }\n\n  /**\n   * Log an inbound request (basic action/transport/origin facts) before it executes, stashing the returned\n   * reporter by `cuid` so {@link _reportServed} can pair it with the result. Only requests are logged;\n   * result/progress frames replying to *our* pushes are not.\n   */\n  private _logRequestIn(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n    securityLevel: ESecurityLevel,\n    reliability?: IActionServeReliabilityInfo,\n    bytes?: number,\n  ): void {\n    if (this._logger == null || wire.type !== EActionPayloadType.request) return;\n    const report = this._logger.onRequest(\n      actionServeRequestInfo(wire, {\n        transport: this._transportLabel,\n        securityLevel,\n        origin: this.wireAcceptor.clientForConnection(connection)?.stringId,\n        reliability,\n        bytes,\n      }),\n    );\n    // Only stash the reporter when a result will actually come back to pair with it — a reply-less\n    // (fire-and-forget) request never produces one, so its entry would sit in the map forever (and\n    // reply-less reliable streams are the highest-volume path).\n    if (report != null && this._runtime?.responseModeForWire(wire) !== EActionResponseMode.none) {\n      this._pendingReports.set(wire.context.cuid, { report, startedAt: Date.now() });\n    }\n  }\n\n  /** Report a served result back to the reporter stashed by {@link _logRequestIn} (no-op if none/not a result). */\n  private _reportServed(payload: TActionPayload_Any_Instance<any, any>, bytes?: number): void {\n    if (payload.type !== EActionPayloadType.result) return;\n    const entry = this._pendingReports.get(payload.context.cuid);\n    if (entry == null) return;\n    this._pendingReports.delete(payload.context.cuid);\n    const durationMs = Date.now() - entry.startedAt;\n    const outcome = payload.result;\n    entry.report(\n      outcome.ok\n        ? { ok: true, returnedVia: this._transportLabel, durationMs, bytes }\n        : {\n            ok: false,\n            returnedVia: this._transportLabel,\n            durationMs,\n            bytes,\n            error: serveResultErrorInfo(outcome.error),\n          },\n    );\n  }\n\n  /**\n   * The codec for a connection: a per-connection session (cached) when a factory was provided, else\n   * the single shared `formatMessage`.\n   */\n  private _codecFor(connection: TConn): TActionChannelFormatMessage {\n    // Multi-channel: the per-connection codec is composed from the tags the connection negotiated. Cached\n    // once resolved (a session codec holds correlation state, so it must be the same instance per socket).\n    if (this._resolveCodec != null) {\n      let codec = this._codecByConn.get(connection);\n      if (codec == null) {\n        const factory = this._resolveCodec(this._connTags.get(connection));\n        if (factory != null) {\n          codec = factory();\n          this._codecByConn.set(connection, codec);\n          return codec;\n        }\n      } else {\n        return codec;\n      }\n    }\n    if (this._createFormatMessage != null) {\n      let codec = this._codecByConn.get(connection);\n      if (codec == null) {\n        codec = this._createFormatMessage();\n        this._codecByConn.set(connection, codec);\n      }\n      return codec;\n    }\n    if (this._formatMessage != null) return this._formatMessage;\n    throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n      actionId:\n        \"server-handler-codec (provide formatMessage, createFormatMessage, or resolveCodec)\",\n    });\n  }\n\n  /**\n   * Register (or replace) the connection-bound persistence callback after construction. Used by\n   * lifecycle helpers like {@link createHibernatableWsServerAdapter} so persistence and replay are\n   * owned by one place instead of being split across the constructor options.\n   */\n  setOnConnectionBound(\n    onConnectionBound: (connection: TConn, binding: IAcceptorConnectionBinding) => void,\n  ): void {\n    this.wireAcceptor.setOnConnectionBound(onConnectionBound);\n  }\n\n  /**\n   * Register a frame protocol (M1 multiplex seam) on the wire acceptor: every connection can then\n   * exchange the protocol's prefixed frames beside action frames (subject to the wire security\n   * gate, review A.6). Register before serving; protocols are advertised in the handshake welcome.\n   */\n  registerFrameProtocol(protocol: IAcceptorFrameProtocol<TConn>): void {\n    this.wireAcceptor.registerProtocol(protocol);\n  }\n\n  /**\n   * Feed one inbound frame from a connection into the wire acceptor. Prefixed protocol frames and\n   * the handshake/keepalive are handled there; everything else — the lane's namespace — comes back\n   * through {@link _onLaneFrame} to be decoded, identity-bound, and routed (requests execute\n   * locally; results/progress resolve pending server-initiated actions).\n   */\n  receive(connection: TConn, frame: string | ArrayBuffer | Uint8Array): void {\n    this.wireAcceptor.receive(connection, frame);\n  }\n\n  /** One inbound lane frame (already decrypted), with the connection's negotiated level. */\n  private _onLaneFrame(connection: TConn, frame: TFrame, level: ESecurityLevel): void {\n    // Sender-originated control frames (`rskip`, …) ride beside action frames — a cheap first-byte\n    // peek short-circuits action frames, mirroring the connector's receive path.\n    const control = decodeControlFrame(frame);\n    if (control != null) {\n      this._onControlMessage(connection, control);\n      return;\n    }\n\n    const codec = this._codecFor(connection);\n    const wire = decodeActionFrame(frame, codec);\n    if (wire == null) return;\n\n    if (level === ESecurityLevel.none) {\n      // Plain path: identity is self-asserted; remember the dialect the client speaks.\n      const encoding: TActionConnectionEncoding = typeof frame === \"string\" ? \"json\" : \"binary\";\n      this._connEncoding.set(connection, encoding);\n      if (wire.type === EActionPayloadType.request) {\n        this._resolveRequestIdentity(connection, wire);\n      }\n    } else if (wire.type === EActionPayloadType.request) {\n      // The connection is bound to an *authenticated* coordinate — always use it, never the wire's\n      // self-asserted originClient.\n      const bound = this.wireAcceptor.clientForConnection(connection);\n      if (bound != null) wire.context.originClient = bound.toJsonObject();\n    }\n\n    this._dispatchInbound(connection, wire, codec, frame, level);\n  }\n\n  /**\n   * Route a decoded inbound frame to the runtime. A best-effort frame is logged + emitted as before. A\n   * **reliable** request (its frame carries a `seq`) goes through the {@link ReliableInbox}: it's\n   * dispatched only in contiguous order (out-of-order frames buffer), duplicates are suppressed, and a\n   * duplicate/gap sends a standalone ack so the client's outbox drains. `frame` is the raw (decrypted)\n   * encoded bytes the codec re-reads for the reliability slot.\n   */\n  private _dispatchInbound(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n    codec: TActionChannelFormatMessage,\n    frame: string | ArrayBuffer | Uint8Array,\n    level: ESecurityLevel,\n  ): void {\n    const reliability =\n      wire.type === EActionPayloadType.request ? codec.incomingReliability?.(frame) : undefined;\n    // The decoded frame's own size (the action payload's cost), for `IActionServeRequestInfo.bytes`.\n    // True billed carrier bytes are a different measurement — see `serveChannel({ wireTap })`.\n    const bytes = this._logger != null ? wireFrameByteSize(frame) : undefined;\n\n    if (reliability?.seq != null) {\n      this._dispatchReliableRequest(\n        connection,\n        wire,\n        reliability.seq,\n        level,\n        reliability.streamKey,\n        bytes,\n      );\n      return;\n    }\n\n    this._logRequestIn(connection, wire, level, undefined, bytes);\n    this._emitIncoming(wire);\n  }\n\n  /** Ordered/dedup dispatch of one reliable request via the inbox (see {@link _dispatchInbound}). */\n  private _dispatchReliableRequest(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n    seq: number,\n    level: ESecurityLevel,\n    streamKey?: string,\n    bytes?: number,\n  ): void {\n    const client = this.wireAcceptor.clientForConnection(connection);\n    // No bound identity → can't key the stream; fall back to a plain dispatch (best-effort).\n    if (client == null) {\n      this._logRequestIn(connection, wire, level, undefined, bytes);\n      this._emitIncoming(wire);\n      return;\n    }\n\n    const streamId = reliableStreamId(client, wire.domain, wire.id, streamKey);\n    // Keyed streams are capped per client (keys are client-chosen strings — an allocation lever): past\n    // the cap the frame is served best-effort rather than minting more receiver state.\n    if (streamKey != null && !this._admitKeyedStream(client, streamId)) {\n      this._logRequestIn(connection, wire, level, undefined, bytes);\n      this._emitIncoming(wire);\n      return;\n    }\n    // Persisted-tier streams dedup through the persisted store (high-water survives eviction); every other\n    // reliable stream uses the in-memory inbox. The tier is derived from the shared `domain:id`, no wire flag.\n    const receiver = this._receiverForWire(wire);\n    const { deliver, duplicate, needsResync } = receiver.receive(streamId, seq, wire);\n\n    // Session-tier reset (a mid-stream frame on a receiver with no state): ask the client to re-sync rather\n    // than buffer an unfillable gap. Nothing is delivered/buffered; the client renumbers its unacked frames\n    // from 0 and resends, which then arrives on a clean stream. The request (and its warn) is latched per\n    // reset: a burst of stale frames — a reconnect's whole resendAll — triggers exactly one `rsync`, not a\n    // client-side full-window renumber + resend per frame.\n    if (needsResync) {\n      if (!this._resyncRequested.has(streamId)) {\n        this._resyncRequested.add(streamId);\n        this._sendControl(\n          connection,\n          streamKey == null\n            ? { $c: \"rsync\", domain: wire.domain, id: wire.id }\n            : { $c: \"rsync\", domain: wire.domain, id: wire.id, k: streamKey },\n        );\n        console.warn(\n          `[reliable] stream reset detected for \"${wire.domain}:${wire.id}\" (received seq ${seq} with no ` +\n            \"prior state) — requesting client re-sync of its in-flight frames. Use the persisted tier \" +\n            \"(.reliable({ persist: true })) to also survive eviction without a re-sync.\",\n        );\n      }\n      return;\n    }\n    // Stream is progressing normally again — clear the reset latch so a future reset re-syncs afresh.\n    this._resyncRequested.delete(streamId);\n\n    const ack = receiver.contiguousSeq(streamId);\n    // Reliability facts for the logger, tagged onto the frame that was actually received this call (`seq`);\n    // any buffered frames it drains are logged without a seq, since they were received on an earlier call.\n    const receivedReliability: IActionServeReliabilityInfo = { seq, ack, redelivered: duplicate };\n\n    // A reply-less (fire-and-forget) reliable stream sends no handler reply, so its ack has nothing to\n    // piggyback on — it rides a standalone control frame instead. That lets us **truly dedup**: a\n    // duplicate yields an empty `deliver` and is simply not re-dispatched (the handler never sees a\n    // resent frame), and we still re-ack the high-water so the client's outbox drains on reconnect.\n    if (this._runtime?.responseModeForWire(wire) === EActionResponseMode.none) {\n      this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey);\n      this._sendControl(\n        connection,\n        streamKey == null\n          ? { $c: \"rack\", domain: wire.domain, id: wire.id, ack }\n          : { $c: \"rack\", domain: wire.domain, id: wire.id, ack, k: streamKey },\n      );\n      return;\n    }\n\n    // Reply-carrying: the ack rides the handler's reply (piggyback) — for a **keyed** (E3) stream too:\n    // each dispatched frame's (per-delivery) cuid is mapped to its streamKey so `_sendPayload` builds the\n    // keyed stream id and the reply's slot carries `{ack, streamKey}`. Piggybacking (rather than an\n    // immediate standalone `rack`) keeps ack ↔ reply **atomic**: if the server dies before replying, the\n    // frame is still unacked, so the client resends and the idempotent handler regenerates the reply.\n    if (streamKey != null) {\n      this._stashReplyStreamKey(wire.context.cuid, streamKey);\n      for (const delivered of deliver) {\n        if (delivered !== wire) this._stashReplyStreamKey(delivered.context.cuid, streamKey);\n      }\n    }\n\n    // A duplicate (a reconnect resend) is re-dispatched to the idempotent handler so its reply — carrying\n    // the output the client may still be waiting for — regenerates with a fresh ack. Ordering is still\n    // guaranteed (out-of-order frames buffer; the handler never sees frames out of order). The handler\n    // can see it *is* a re-run (`redelivered: true`) via the local context stamp — e.g. to return a\n    // memoized reply instead of re-running an expensive body.\n    if (duplicate) {\n      this._stampHandledReliability(wire, seq, streamKey, true);\n      this._logRequestIn(connection, wire, level, receivedReliability, bytes);\n      this._emitIncoming(wire);\n      return;\n    }\n\n    // In-order (possibly draining a buffered contiguous run); a gap yields an empty `deliver` — the frame\n    // is buffered and the client's ordered resend delivers the filler that releases it.\n    this._emitReliableDelivered(connection, deliver, level, receivedReliability, streamKey, bytes);\n  }\n\n  /**\n   * Stamp the receiver-side reliability facts onto a delivered frame's **local** context (the\n   * `originClient`-overwrite pattern) so the executing handler reads them as `action.context.reliability`\n   * — the free idempotency key. Local-only: `toJsonObject()` never writes the field, so a reply built off\n   * this context is byte-identical with and without the stamp.\n   */\n  private _stampHandledReliability(\n    wire: TActionPayload_Any_JsonObject<any>,\n    seq: number,\n    streamKey: string | undefined,\n    redelivered: boolean,\n  ): void {\n    // `redelivered` can only be true on the reply-carrying re-run path — reply-less duplicates are\n    // suppressed before dispatch, so a reply-less handler correctly never sees it.\n    wire.context.reliability =\n      streamKey == null ? { seq, redelivered } : { seq, streamKey, redelivered };\n  }\n\n  /**\n   * Log + emit each frame the receiver decided to deliver in this receive. Only the **first** (the frame\n   * actually received this call) carries the reliability facts for the *logger*; drained buffered frames\n   * were logged/seq'd on their own earlier arrivals, so they log without a (stale) seq. Every delivered\n   * frame is stamped with its **own** seq for the executing handler, though — delivered frames are a\n   * contiguous run ending at the new high-water (`ack`), so frame `i` carries `ack - (length - 1 - i)`.\n   */\n  private _emitReliableDelivered(\n    connection: TConn,\n    deliver: TActionPayload_Any_JsonObject<any>[],\n    level: ESecurityLevel,\n    receivedReliability: IActionServeReliabilityInfo,\n    streamKey?: string,\n    bytes?: number,\n  ): void {\n    const ack = receivedReliability.ack;\n    deliver.forEach((delivered, index) => {\n      if (ack != null) {\n        this._stampHandledReliability(\n          delivered,\n          ack - (deliver.length - 1 - index),\n          streamKey,\n          false,\n        );\n      }\n      // `deliver` may drain frames buffered by an earlier gap, whose encoded sizes are long gone.\n      // Only the frame that just arrived carries `bytes` (the same one that carries the reliability\n      // facts) — the rest report none rather than a borrowed, wrong number.\n      this._logRequestIn(\n        connection,\n        delivered,\n        level,\n        index === 0 ? receivedReliability : undefined,\n        index === 0 ? bytes : undefined,\n      );\n      this._emitIncoming(delivered);\n    });\n  }\n\n  /**\n   * The receive store a reliable frame's stream is served by: the persisted {@link _persistedReceiver} for a\n   * `persisted`-tier action (when one is configured), else the in-memory {@link _inbox}. A persisted action with\n   * no configured store degrades to the inbox (session-tier behavior) rather than failing.\n   */\n  private _receiverForWire(\n    wire: TActionPayload_Any_JsonObject<any>,\n  ): IReliableReceiver<TActionPayload_Any_JsonObject<any>> {\n    return this._receiverForRoute(wire.domain, wire.id);\n  }\n\n  /** {@link _receiverForWire} by bare route — for control messages, which carry no action payload. */\n  private _receiverForRoute(\n    domain: string,\n    id: string,\n  ): IReliableReceiver<TActionPayload_Any_JsonObject<any>> {\n    if (\n      this._persistedReceiver != null &&\n      this._runtime?.reliabilityTierForRoute(domain, id) === EReliabilityTier.persisted\n    ) {\n      return this._persistedReceiver;\n    }\n    return this._inbox;\n  }\n\n  /**\n   * A sender-originated transport control message arrived on a connection. `rskip` and `rclose` are the\n   * meaningful ones server-side (`rack`/`rsync` flow the other way — a decoded one here is simply\n   * ignored). `rskip`: the client's outbox **abandoned** every undelivered frame `<= seq` of the stream\n   * (their actions aborted / delivery deadlines expired), so advance the stream past the abandoned seqs\n   * and deliver whatever was buffered behind the gap — the stream continues instead of wedging on frames\n   * that will never arrive; the new high-water is re-acked so the client can retire the skip. `rclose`:\n   * the client closed the stream for good — release its receiver state (a pure reclaim).\n   */\n  private _onControlMessage(connection: TConn, message: TControlMessage): void {\n    // A sender closed a stream for good (`closeReliableStream`) — release every bit of receiver state\n    // named by it: the tracking store's high-water + frames, the re-sync latch, and (for a keyed stream)\n    // its slot in the keyed-stream quota, so closed keys stop counting against `maxKeyedStreamsPerClient`.\n    // Loss-tolerant by design (see the `rclose` doc): delivery was already settled by the sender's\n    // retained `rskip`, so this is purely a reclaim.\n    if (message.$c === \"rclose\") {\n      const client = this.wireAcceptor.clientForConnection(connection);\n      if (client == null) return;\n      const streamId = reliableStreamId(client, message.domain, message.id, message.k);\n      this._receiverForRoute(message.domain, message.id).forgetStream?.(streamId);\n      // A persisted-tier stream may have degraded to the inbox (no store configured) — clear both.\n      this._inbox.forget(streamId);\n      this._resyncRequested.delete(streamId);\n      if (message.k != null) {\n        this._keyedStreamsByClient.get(client.stringId)?.delete(streamId);\n      }\n      return;\n    }\n\n    if (message.$c !== \"rskip\") return;\n    const client = this.wireAcceptor.clientForConnection(connection);\n    if (client == null) return;\n\n    const streamId = reliableStreamId(client, message.domain, message.id, message.k);\n    // The keyed-stream cap applies here too — a skip for an inadmissible key must not mint state.\n    if (message.k != null && !this._admitKeyedStream(client, streamId)) return;\n    const receiver = this._receiverForRoute(message.domain, message.id);\n    const { deliver, ack } = receiver.skipTo(streamId, message.seq);\n    // The stream is live again from the skip point — a future genuine reset should warn/re-sync afresh.\n    this._resyncRequested.delete(streamId);\n\n    this._emitReliableDelivered(connection, deliver, this.wireAcceptor.levelFor(connection), {\n      ack,\n    });\n    this._sendControl(\n      connection,\n      message.k == null\n        ? { $c: \"rack\", domain: message.domain, id: message.id, ack }\n        : { $c: \"rack\", domain: message.domain, id: message.id, ack, k: message.k },\n    );\n  }\n\n  /** How long a stashed reply streamKey survives without its reply being sent (sweep bound). */\n  private static readonly _REPLY_STREAMKEY_TTL_MS = 5 * 60_000;\n\n  /** Remember a dispatched keyed reply-carrying request's streamKey until its reply goes out. */\n  private _stashReplyStreamKey(cuid: string, streamKey: string): void {\n    const now = Date.now();\n    // Insertion-ordered + inserted in time order, so sweep from the front until the first live entry.\n    for (const [key, entry] of this._replyStreamKeys) {\n      if (now - entry.time <= ChannelAcceptor._REPLY_STREAMKEY_TTL_MS) break;\n      this._replyStreamKeys.delete(key);\n    }\n    this._replyStreamKeys.set(cuid, { streamKey, time: now });\n  }\n\n  /** Encode + send a transport {@link TControlMessage} to a connection (through its secure session if any). */\n  private _sendControl(connection: TConn, message: TControlMessage): void {\n    this.wireAcceptor.sendTo(connection, encodeControlFrame(message));\n  }\n\n  /**\n   * Ensure an inbound request carries the client's identity and that this connection is bound to it,\n   * so its result can be routed back. A session codec omits `originClient` after the first request, so\n   * when it's missing we restore it from the (possibly rehydrated) binding instead. (Plain mode only;\n   * secure mode binds the authenticated coordinate at handshake time.)\n   */\n  private _resolveRequestIdentity(\n    connection: TConn,\n    wire: TActionPayload_Any_JsonObject<any>,\n  ): void {\n    const wireOrigin = wire.context.originClient;\n\n    if (wireOrigin != null && wireOrigin.envId !== UNSET_RUNTIME_ENV_ID) {\n      // Bind (and, when the identity is new, persist) through the wire acceptor — the encoding set\n      // just before this call rides the binding's lane slot.\n      this.wireAcceptor.bindPlainConnection(connection, new RuntimeCoordinate(wireOrigin));\n      return;\n    }\n\n    // Identity dropped by the session — restore it from the binding so return routing still works.\n    const bound = this.wireAcceptor.clientForConnection(connection);\n    if (bound != null) wire.context.originClient = bound.toJsonObject();\n  }\n\n  /**\n   * Restore a connection→client binding without an inbound frame — for transports that resume after\n   * eviction. Pair it with the {@link IChannelAcceptorOptions.onConnectionBound} hook: persist\n   * the binding there, then replay each live connection here when the channel comes back (e.g. a\n   * Durable Object iterating `ctx.getWebSockets()` as it wakes from hibernation). A binding persisted\n   * before the versioned (`v: 1`) schema is ignored — the socket is treated as fresh.\n   */\n  rehydrate(connection: TConn, binding: IAcceptorConnectionBinding): void {\n    this.wireAcceptor.rehydrate(connection, binding);\n  }\n\n  toJsonObject(): IActionHandler_Peer_Json {\n    return {\n      type: this.handlerType,\n      client: this.peerClient,\n    };\n  }\n\n  override toHandlerRouteItem(): IActionRouteItemHandler {\n    return {\n      type: this.handlerType,\n      client: this.peerClient,\n      transShape: ETransportShape.duplex,\n      transOrd: 0,\n    };\n  }\n\n  /** Forget a connection (call on socket close) so stale entries don't misroute later results. */\n  drop(connection: TConn): void {\n    this.wireAcceptor.drop(connection);\n  }\n\n  /** Permanently quiesce this acceptor and detach every live/rehydrated connection. */\n  dispose(): void {\n    this.wireAcceptor.dispose();\n  }\n\n  /** Lane cleanup when the wire acceptor drops a connection (fired with the bound client, if any). */\n  private _onConnectionDropped(connection: TConn, client: RuntimeCoordinate | undefined): void {\n    // Un-latch any pending re-sync requests for this client's streams: the `rsync` may have died with the\n    // socket, and the reconnect's stale frames must be able to trigger a fresh one (the latch alone would\n    // otherwise deadlock recovery). The inbox state itself is deliberately kept — reconnect dedup needs it.\n    if (client != null) {\n      const prefix = `${client.stringId}::`;\n      for (const streamId of this._resyncRequested) {\n        if (streamId.startsWith(prefix)) this._resyncRequested.delete(streamId);\n      }\n    }\n    this._connEncoding.delete(connection);\n    this._codecByConn.delete(connection);\n    this._connTags.delete(connection);\n  }\n\n  /** Live connection for a client coordinate, if currently registered. */\n  getConnectionForClient(client: RuntimeCoordinate): TConn | undefined {\n    return this.wireAcceptor.connectionForClient(client.stringId);\n  }\n\n  /** This acceptor owns the origin's return path when it currently holds a live connection bound to it. */\n  override ownsLiveConnectionFor(origin: RuntimeCoordinate): boolean {\n    return this.wireAcceptor.ownsLiveConnectionFor(origin.stringId);\n  }\n\n  /** Whether this acceptor currently tracks `connection` — used to pick the owning handler among several. */\n  hasConnection(connection: TConn): boolean {\n    return this.wireAcceptor.hasConnection(connection);\n  }\n\n  /**\n   * Send (and optionally await) a server-initiated action to a specific connected client. Pass the\n   * connection token directly (e.g. the `ws`) or a client `RuntimeCoordinate` to look one up.\n   */\n  pushToClient<DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    runtime: ActionRuntime,\n    target: TConn | RuntimeCoordinate,\n    request: ActionPayload_Request<DOM, ID>,\n    options?: { timeout?: number },\n  ): RunningAction<DOM, ID> {\n    const connection = this._resolveConnection(target);\n    return this._dispatch(runtime, connection, request, options?.timeout);\n  }\n\n  /**\n   * Build a local handler whose cases are connection-aware: each case receives the primed request and\n   * the originating client's live connection (resolved from `originClient`), so handlers don't repeat\n   * the `getConnectionForClient(action.context.originClient)` lookup. Cases may return raw output or\n   * nothing, just like {@link ActionLocalHandler.forDomainActionCases}. Add the returned handler to the\n   * runtime alongside this server handler:\n   * ```ts\n   * runtime.addHandlers([serverHandler.forConnectionDomainCases(domain, { … }), serverHandler]);\n   * ```\n   */\n  forConnectionDomainCases<FOR_DOM extends IActionDomain>(\n    domain: ActionDomain<FOR_DOM>,\n    cases: {\n      [ID in keyof FOR_DOM[\"actionSchema\"] & string]?: TAcceptorConnectionCaseFn<\n        FOR_DOM,\n        ID,\n        TConn\n      >;\n    },\n  ): ActionLocalHandler {\n    // Default context = the raw connection (or undefined when the socket is gone). The cast bridges the\n    // per-id mapped case map to the merged `any`-keyed map the multi form iterates (a known TS variance\n    // limitation on the contravariant action param — same bridge `acceptChannelConnections` uses).\n    return this.forConnectionDomainCasesMulti(\n      [domain],\n      cases as Record<string, TAcceptorConnectionCaseFn<any, any, TConn> | undefined>,\n      (connection) => connection,\n    );\n  }\n\n  /**\n   * Like {@link forConnectionDomainCases} but spanning several domains with one merged case map — used\n   * by channel-derived wiring (`acceptChannelConnections` / `serveChannel`) where the channel's\n   * `toAcceptor` domains are served together. Each domain takes only the cases whose ids it owns, so a\n   * single map can cover several domains and unrelated ids are ignored.\n   *\n   * `mapContext` turns the resolved connection into whatever the case's second argument should be: the\n   * raw connection for the low-level helper, or an enriched `IConnectionContext` for `serveChannel`. It's\n   * called once per inbound action, after the originating connection is resolved.\n   */\n  forConnectionDomainCasesMulti<TCtx>(\n    domains: readonly ActionDomain<any>[],\n    cases: Record<string, TAcceptorCaseFn<any, any, TCtx> | undefined>,\n    mapContext: (connection: TConn | undefined, request: ActionPayload_Request<any, any>) => TCtx,\n  ): ActionLocalHandler {\n    const handler = new ActionLocalHandler();\n\n    for (const domain of domains) {\n      const ownedIds = new Set(Object.keys(domain.actionsMap()));\n      const wrapped: Record<string, THandleActionExecutionFn<any, any>> = {};\n\n      for (const id in cases) {\n        if (!ownedIds.has(id)) continue;\n        const caseFn = cases[id];\n        if (caseFn == null) continue;\n        wrapped[id] = (request) => {\n          const connection = this.getConnectionForClient(request.context.originClient);\n          return caseFn(request, mapContext(connection, request));\n        };\n      }\n\n      handler.forDomainActionCases(domain, wrapped);\n    }\n\n    return handler;\n  }\n\n  /**\n   * Fan a server-initiated request out to every currently-bound connection. A fresh request is built\n   * per connection (each push mutates its own action context) and dispatched fire-and-forget. Pass\n   * `except` to skip the originating socket and `where` to filter by connection (e.g. read its\n   * attachment for a role). Iterating bound connections (rather than every accepted socket) skips\n   * sockets that are still mid-handshake and so can't yet receive a frame.\n   */\n  broadcast<DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    makeRequest: () => ActionPayload_Request<DOM, ID>,\n    options?: {\n      runtime?: ActionRuntime;\n      except?: TConn | null;\n      where?: (connection: TConn) => boolean;\n      timeout?: number;\n      onError?: (error: unknown, connection: TConn) => void;\n    },\n  ): void {\n    const runtime = options?.runtime ?? this._runtime;\n    if (runtime == null) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n        actionId: \"server-handler-runtime (construct with `runtime` or pass `options.runtime`)\",\n      });\n    }\n\n    for (const connection of this.wireAcceptor.connections()) {\n      if (options?.except != null && connection === options.except) continue;\n      if (options?.where != null && !options.where(connection)) continue;\n      try {\n        this.pushToClient(runtime, connection, makeRequest(), { timeout: options?.timeout });\n      } catch (error) {\n        if (options?.onError != null) options.onError(error, connection);\n        else console.error(\"[ws-server] broadcast push failed\", error);\n      }\n    }\n  }\n\n  override async sendReturnPayload(\n    payload: TActionPayload_Any_Instance<any, any>,\n    config: { targetLocalRuntime: ActionRuntime },\n  ): Promise<boolean> {\n    const connection = this.wireAcceptor.connectionForClient(payload.context.originClient.stringId);\n    if (connection == null) return false;\n    const bytes = this._sendPayload(connection, payload, config.targetLocalRuntime.coordinate);\n    this._reportServed(payload, bytes);\n    return true;\n  }\n\n  override async handleActionRequest<\n    DOM extends IActionDomain,\n    ID extends keyof DOM[\"actionSchema\"] & string,\n  >(\n    action: ActionPayload_Request<DOM, ID>,\n    config?: IHandleActionOptions,\n  ): Promise<RunningAction<DOM, ID>> {\n    const runtime = config?.targetLocalRuntime ?? ActionRuntime.getDefault();\n    const connection = this._resolveSingleConnection();\n    return this._dispatch(runtime, connection, action, config?.timeout);\n  }\n\n  private _dispatch<DOM extends IActionDomain, ID extends keyof DOM[\"actionSchema\"] & string>(\n    runtime: ActionRuntime,\n    connection: TConn,\n    action: ActionPayload_Request<DOM, ID>,\n    timeout?: number,\n  ): RunningAction<DOM, ID> {\n    const timeoutMs = timeout ?? this._serverTimeout;\n\n    // Reliability is connector→acceptor only: a server-initiated push of a reliable-declared action is\n    // best-effort (no outbox/seq/resend). Warn once per route so the direction downgrade is visible.\n    if (action.schema.reliabilityTier !== EReliabilityTier.none) {\n      warnReliablePushUnsupportedOnce(action.domain, action.id);\n    }\n\n    // The client must be able to route its result back to *us*, so the origin is this backend.\n    action.context._setOriginClient(runtime.coordinate);\n    action.context.addRouteItem({\n      runtime: runtime.coordinate,\n      handler: this.toHandlerRouteItem(),\n      time: Date.now(),\n    });\n\n    const runningAction = new RunningAction<DOM, ID>({\n      context: action.context,\n      request: action,\n      parentCuid: peekHandlerCuid(),\n      callSite: action._callSite,\n    });\n    runtime.registerRunningAction(runningAction);\n\n    // Fire-and-forget: no reply will come, so don't park a pending action behind a timeout. Send the\n    // frame and complete immediately as success — the running action still surfaces in devtools, it just\n    // resolves on send rather than on a (never-arriving) reply.\n    if (action.schema.responseMode === EActionResponseMode.none) {\n      try {\n        this._sendPayload(connection, action, runtime.coordinate);\n        runningAction._completeWithResult(\n          (action as ActionPayload_Request<any, any>).successResult(undefined),\n        );\n      } catch (err) {\n        runningAction._abort(err);\n      }\n      return runningAction;\n    }\n\n    const timeoutId = setTimeout(() => {\n      runningAction._abort(\n        err_nice_transport.fromId(EErrId_NiceTransport.timeout, { timeout: timeoutMs }),\n      );\n    }, timeoutMs);\n    runningAction.addUpdateListeners([\n      (update) => {\n        if (update.type === ERunningActionUpdateType.finished) clearTimeout(timeoutId);\n      },\n    ]);\n\n    try {\n      this._sendPayload(connection, action, runtime.coordinate);\n    } catch (err) {\n      runningAction._abort(err);\n    }\n\n    return runningAction;\n  }\n\n  /** Encode + send one payload; returns the encoded frame's size so a logger can report it. */\n  private _sendPayload(\n    connection: TConn,\n    payload: TActionPayload_Any_Instance<any, any>,\n    localClient: RuntimeCoordinate,\n    reliability?: IFrameReliability,\n  ): number {\n    const encoding = this._connEncoding.get(connection) ?? \"binary\";\n\n    // Piggyback the cumulative ack onto a reply for a tracked reliable stream (unless the caller passed\n    // an explicit one, e.g. a standalone ack). Keyed by (origin client + route [+ the streamKey stashed\n    // for this reply's cuid]), matching the inbox. The JSON encoding can't carry the reliability slot, so\n    // reliable delivery rides the binary codec only.\n    let rel = reliability;\n    if (rel == null && payload.type === EActionPayloadType.result) {\n      const stashedKey = this._replyStreamKeys.get(payload.context.cuid);\n      if (stashedKey != null) this._replyStreamKeys.delete(payload.context.cuid);\n      const streamKey = stashedKey?.streamKey;\n      const streamId = reliableStreamId(\n        payload.context.originClient,\n        payload.domain,\n        payload.id,\n        streamKey,\n      );\n      // Whichever store tracks the stream owns its high-water (persisted store checked first).\n      const receiver = this._persistedReceiver?.hasStream(streamId)\n        ? this._persistedReceiver\n        : this._inbox.hasStream(streamId)\n          ? this._inbox\n          : undefined;\n      if (receiver != null) {\n        const ack = receiver.contiguousSeq(streamId);\n        rel = streamKey == null ? { streamId, ack } : { streamId, ack, streamKey };\n      }\n    }\n\n    const frame =\n      encoding === \"json\"\n        ? JSON.stringify(payload.toJsonObject())\n        : this._codecFor(connection).outgoing({\n            action: payload,\n            localClient,\n            externalClient: this.peerClient,\n            reliability: rel,\n          });\n\n    // A secure connection's session encrypts (and orders) the frame; plain/authenticated connections (and\n    // connections with no secure session at all) send as-is — the wire acceptor owns that branch.\n    this.wireAcceptor.sendTo(connection, frame);\n    return wireFrameByteSize(frame);\n  }\n\n  private _resolveConnection(target: TConn | RuntimeCoordinate): TConn {\n    if (target instanceof RuntimeCoordinate) {\n      const connection = this.wireAcceptor.connectionForClient(target.stringId);\n      if (connection == null) {\n        throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n          actionId: target.stringId,\n        });\n      }\n      return connection;\n    }\n    return target;\n  }\n\n  private _resolveSingleConnection(): TConn {\n    if (this.wireAcceptor.connectionCount !== 1) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n        actionId:\n          \"server-handler-target (use pushToClient with an explicit connection or client coordinate)\",\n      });\n    }\n    const first = this.wireAcceptor.connections().next();\n    if (first.done === true) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.not_found, {\n        actionId: \"server-handler-target\",\n      });\n    }\n    return first.value;\n  }\n}\n\nexport const createChannelAcceptor = <TConn = unknown>(\n  options: IChannelAcceptorOptions<TConn>,\n): ChannelAcceptor<TConn> => {\n  return new ChannelAcceptor<TConn>(options);\n};\n","import { ClientCryptoKeyLink, type StorageAdapter } from \"@nice-code/util\";\nimport type { IReliableReceiver, RuntimeCoordinate } from \"@nice-code/wire\";\nimport {\n  createStorageTofuVerifyKeyResolver,\n  ESecurityLevel,\n  type IClientVerifyKeyResolver,\n} from \"@nice-code/wire\";\nimport type { TActionPayload_Any_JsonObject } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionRuntime } from \"../../../ActionRuntime\";\nimport type { IActionChannel } from \"../../../Channel/ActionChannel\";\nimport type { IActionServeLogger } from \"../../../Channel/serveLogger\";\nimport { ChannelAcceptor } from \"./ChannelAcceptor\";\n\n/** Default accepted set: negotiate per connection to whatever the client picks. */\nconst DEFAULT_SERVER_SECURITY_LEVELS = [\n  ESecurityLevel.none,\n  ESecurityLevel.authenticated,\n  ESecurityLevel.encrypted,\n] as const;\n\nexport interface ISecureChannelAcceptorOptions<TConn> {\n  /**\n   * The default channel identity (codec + dictionary version) — same one single-channel clients use, and\n   * the fallback a multi-channel acceptor composes against when a client advertises no tags.\n   */\n  channel: IActionChannel;\n  /**\n   * Multi-channel: resolve a connection's advertised channel tags (`hello.channels`) into the channel it\n   * should use (its codec + dictionary version), or `null` for an unknown/unserved set (the handshake then\n   * rejects). When set, this acceptor serves several channels and selects/composes per connection; when\n   * omitted it serves the single {@link channel}. Built by `serveChannel` from its channel registry.\n   */\n  resolveChannel?: (tags: readonly string[] | undefined) => IActionChannel | null;\n  /**\n   * Coordinate of the *connecting clients* (typically env-only, e.g. `RuntimeCoordinate.env(\"web_app\")`),\n   * used as the offline-return scoring fallback (a live connection always wins regardless). Optional —\n   * omit it for a multi-role server accepting several client envs over one acceptor.\n   */\n  clientEnv?: RuntimeCoordinate;\n  /** This server's runtime — its coordinate is the server identity presented in the handshake. */\n  runtime: ActionRuntime;\n  /**\n   * One backing store for the server's crypto identity *and* its trust-on-first-use verify-key pins.\n   * Their keys don't collide, so a single adapter is enough; back it with persistent storage (e.g. a\n   * Durable Object's storage) so identity and pins survive eviction.\n   */\n  storage: StorageAdapter;\n  /** Write an encoded frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */\n  send: (connection: TConn, frame: string | Uint8Array | ArrayBuffer) => void;\n  /**\n   * The server's crypto identity. Defaults to a fresh {@link ClientCryptoKeyLink} over `storage`.\n   * Pass an existing link to share one identity across several acceptors on the same server (e.g. a\n   * WebSocket acceptor and a secure-HTTP {@link createActionFetchHandler}), so they present the same\n   * verify/exchange keys — avoiding a divergent-key race when two fresh links initialize concurrently.\n   */\n  link?: ClientCryptoKeyLink;\n  /** Accepted level(s); defaults to negotiating any of none/authenticated/encrypted. */\n  securityLevel?: ESecurityLevel | readonly ESecurityLevel[];\n  /** Trust decision for a client's verify key; defaults to storage-backed TOFU over `storage`. */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n  /** Timeout (ms) applied to server-initiated actions awaiting a client response. */\n  defaultTimeout?: number;\n  /** Optional server-side logger — called per inbound action request with its served outcome. */\n  logger?: IActionServeLogger;\n  /** Server-side wire tap (see {@link IChannelAcceptorBaseOptions.wireTap}). */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (e.g. `\"ws\"`). */\n  transportLabel?: string;\n  /** Persisted receive store for the persisted reliability tier (see {@link IChannelAcceptorBaseOptions.persistedReceiver}). */\n  persistedReceiver?: IReliableReceiver<TActionPayload_Any_JsonObject<any>>;\n  /** Cap on distinct keyed (`streamKey`) reliable streams per client (see {@link IChannelAcceptorBaseOptions.maxKeyedStreamsPerClient}). */\n  maxKeyedStreamsPerClient?: number;\n}\n\n/**\n * Build an {@link ChannelAcceptor} for the secure binary channel with the boilerplate folded in:\n * it creates the {@link ClientCryptoKeyLink} and the storage-backed TOFU resolver from a single\n * `storage`, installs the channel's per-connection codec, and assembles the `security` block\n * from the runtime coordinate + channel version (accepting all three levels by default).\n *\n * For a hibernatable transport (e.g. a Durable Object), pair it with\n * {@link createHibernatableWsServerAdapter} to wire persistence + replay.\n */\nexport function createSecureChannelAcceptor<TConn = unknown>(\n  options: ISecureChannelAcceptorOptions<TConn>,\n): ChannelAcceptor<TConn> {\n  const link = options.link ?? new ClientCryptoKeyLink({ storageAdapter: options.storage });\n  const resolveChannel = options.resolveChannel;\n\n  const baseSecurity = {\n    securityLevel: options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS,\n    link,\n    localCoordinate: options.runtime.coordinate.toJsonObject(),\n    verifyKeyResolver:\n      options.verifyKeyResolver ?? createStorageTofuVerifyKeyResolver(options.storage),\n  };\n  const baseOptions = {\n    clientEnv: options.clientEnv,\n    send: options.send,\n    runtime: options.runtime,\n    defaultTimeout: options.defaultTimeout,\n    logger: options.logger,\n    wireTap: options.wireTap,\n    transportLabel: options.transportLabel,\n    persistedReceiver: options.persistedReceiver,\n    maxKeyedStreamsPerClient: options.maxKeyedStreamsPerClient,\n  };\n\n  // Multi-channel: codec + dictionary version are composed per connection from the advertised tags.\n  if (resolveChannel != null) {\n    return new ChannelAcceptor<TConn>({\n      ...baseOptions,\n      resolveCodec: (tags) => resolveChannel(tags)?.createCodec,\n      security: {\n        ...baseSecurity,\n        dictionaryVersion: (hello) => resolveChannel(hello.channels)?.dictionaryVersion ?? null,\n      },\n    });\n  }\n\n  // Single channel: one fixed codec + dictionary version (unchanged behaviour).\n  return new ChannelAcceptor<TConn>({\n    ...baseOptions,\n    createFormatMessage: options.channel.createCodec,\n    security: { ...baseSecurity, dictionaryVersion: options.channel.dictionaryVersion },\n  });\n}\n","import { EActionForm } from \"../../../ActionDefinition/Action/ActionBase.types\";\nimport type { IActionContext_Data_JsonObject } from \"../../../ActionDefinition/Action/Context/ActionContext.types\";\nimport {\n  EActionPayloadType,\n  type IActionPayload_Base_JsonObject,\n  type TActionPayload_Any_JsonObject,\n} from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { TPossibleDomainIdList } from \"../../../ActionDefinition/Domain/ActionDomain.types\";\nimport type { IFrameReliabilityWire, ITransportRouteActionParams } from \"../Transport.types\";\n\nexport type { IFrameReliabilityWire } from \"../Transport.types\";\n\n/**\n * Shared building blocks for the binary action codecs (the stateless {@link createBinaryWireAdapter} and\n * the per-connection `createBinaryWireSessionFactory`). Both map a `domain:id` route to a tiny integer\n * and reduce the verbose JSON wire to a positional tuple — they only differ in how much context they\n * carry per frame, so the dictionary + payload (de)assembly live here.\n */\n\n/**\n * The carrier-neutral codec a Link connection uses to (de)serialize action payloads on the wire — the\n * same shape every duplex carrier (WS/WebRTC/in-memory) shares.\n */\nexport interface IActionWireFormat {\n  /**\n   * Pack an outgoing action payload. Return a `string` for text frames (JSON) or a binary\n   * `Uint8Array`/`ArrayBuffer` for optimized binary frames (e.g. msgpackr).\n   */\n  outgoing: (input: ITransportRouteActionParams) => string | Uint8Array | ArrayBuffer;\n  /**\n   * Unpack an incoming frame back into the wire JSON object the runtime hydrates + validates. Return\n   * `undefined` to defer to the connection's built-in JSON parser — this is how binary adapters stay\n   * backward compatible with plain-JSON clients on the same socket.\n   */\n  incoming?: (\n    input: string | ArrayBuffer | Uint8Array | Blob,\n  ) => TActionPayload_Any_JsonObject<any, any> | undefined;\n  /**\n   * Unpack just the reliability integers off a frame (the optional trailing envelope slot), or\n   * `undefined` when the frame carries none (a best-effort frame). Separate from {@link incoming} so the\n   * best-effort decode path stays untouched; the receive-side reliability layer reads this alongside.\n   */\n  incomingReliability?: (\n    input: string | ArrayBuffer | Uint8Array | Blob,\n  ) => IFrameReliabilityWire | undefined;\n}\n\n/**\n * The single integer a reliable frame carries in its trailing envelope slot, chosen by direction:\n * a request carries its `seq`, any reply/progress carries the cumulative `ack`. Returns `undefined`\n * when there's nothing to stamp, so the codec keeps the frame at its best-effort length.\n */\nexport function encodeReliabilitySlot(\n  reliability: { seq?: number; ack?: number } | undefined,\n  payloadType: (typeof ReversePayloadType)[number],\n): number | undefined {\n  if (reliability == null) return undefined;\n  const value = payloadType === EActionPayloadType.request ? reliability.seq : reliability.ack;\n  return value == null ? undefined : value;\n}\n\n/**\n * Reconstruct the {@link IFrameReliabilityWire} from a decoded slot value, by payload direction — or\n * `undefined` when the slot isn't a well-formed reliability integer (a request's `seq` must be an integer\n * `>= 0`; a reply's cumulative `ack` an integer `>= -1`). The slot comes straight off the peer's wire, so\n * a malformed value from a buggy/hostile peer must degrade the frame to best-effort dispatch rather than\n * pollute stream state with a garbage seq.\n */\nexport function decodeReliabilitySlot(\n  value: unknown,\n  payloadType: (typeof ReversePayloadType)[number],\n): IFrameReliabilityWire | undefined {\n  const min = payloadType === EActionPayloadType.request ? 0 : -1;\n  if (typeof value !== \"number\" || !Number.isInteger(value) || value < min) return undefined;\n  return payloadType === EActionPayloadType.request ? { seq: value } : { ack: value };\n}\n\n/**\n * Tiny integer codes for the payload type, so the verbose `\"request\"`/`\"result\"`/`\"progress\"`\n * strings never hit the wire. The index in {@link ReversePayloadType} must line up with the value.\n */\nexport const PayloadTypeToInt: Record<\n  EActionPayloadType.request | EActionPayloadType.result | EActionPayloadType.progress,\n  number\n> = {\n  [EActionPayloadType.request]: 0,\n  [EActionPayloadType.result]: 1,\n  [EActionPayloadType.progress]: 2,\n};\nexport const ReversePayloadType = [\n  EActionPayloadType.request,\n  EActionPayloadType.result,\n  EActionPayloadType.progress,\n] as const;\n\nexport interface IActionRouteMeta {\n  domain: string;\n  id: string;\n  allDomains: TPossibleDomainIdList;\n}\n\nexport interface IActionRouteDictionary {\n  /** `domain:id` → wire integer. */\n  routeToInt: Map<string, number>;\n  /** wire integer → route metadata for reconstruction. */\n  intToRoute: IActionRouteMeta[];\n}\n\n/**\n * Build the positional `domain:id` ↔ integer dictionary. Both ends of a channel MUST build it from\n * the same domains in the same order — the mapping is positional, so a mismatch routes to the wrong\n * action. Add new transported domains to the end of the list.\n */\nexport function buildActionRouteDictionary(domains: ActionDomain<any>[]): IActionRouteDictionary {\n  const routeToInt = new Map<string, number>();\n  const intToRoute: IActionRouteMeta[] = [];\n\n  for (const dom of domains) {\n    for (const actionId of Object.keys(dom.actionSchema)) {\n      const routeKey = `${dom.domain}:${actionId}`;\n      if (routeToInt.has(routeKey)) continue;\n      routeToInt.set(routeKey, intToRoute.length);\n      intToRoute.push({ domain: dom.domain, id: actionId, allDomains: dom.allDomains });\n    }\n  }\n\n  return { routeToInt, intToRoute };\n}\n\n/** Pull the type-specific payload (`input` / `result` / `progress`) out of a wire JSON object. */\nexport function extractWirePayload(json: TActionPayload_Any_JsonObject<any, any>): unknown {\n  if (json.type === EActionPayloadType.request) return json.input;\n  if (json.type === EActionPayloadType.result) return json.result;\n  if (json.type === EActionPayloadType.progress) return json.progress;\n  return undefined;\n}\n\n/**\n * Reassemble a full wire JSON object from its decoded parts. `inputHash`/`outputHash` are emitted\n * empty — the hydration constructors recompute them — and the result still satisfies\n * `isActionPayload_Any_JsonObject` so it flows through validation like a JSON frame.\n */\nexport function assembleWireJson(\n  routeMeta: IActionRouteMeta,\n  payloadType: (typeof ReversePayloadType)[number],\n  time: number,\n  context: IActionContext_Data_JsonObject,\n  // Runtime-dynamic payload straight off the wire (msgpack/JSON) — Valibot validates it on hydrate.\n  payloadData: any,\n): TActionPayload_Any_JsonObject<any, any> {\n  const base: Omit<IActionPayload_Base_JsonObject<EActionPayloadType>, \"type\"> = {\n    form: EActionForm.data,\n    domain: routeMeta.domain,\n    id: routeMeta.id,\n    allDomains: routeMeta.allDomains,\n    time,\n    context,\n  };\n\n  if (payloadType === EActionPayloadType.request) {\n    return { ...base, type: EActionPayloadType.request, input: payloadData, inputHash: \"\" };\n  }\n  if (payloadType === EActionPayloadType.result) {\n    return { ...base, type: EActionPayloadType.result, result: payloadData, outputHash: \"\" };\n  }\n  return { ...base, type: EActionPayloadType.progress, progress: payloadData };\n}\n","import { type IRuntimeCoordinate, RuntimeCoordinate, UNSET_RUNTIME_ENV_ID } from \"@nice-code/wire\";\nimport { pack, unpack } from \"msgpackr\";\nimport { nanoid } from \"nanoid\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { ActionDomain } from \"../../../ActionDefinition/Domain/ActionDomain\";\nimport type { ITransportRouteActionParams } from \"../Transport.types\";\nimport {\n  assembleWireJson,\n  buildActionRouteDictionary,\n  decodeReliabilitySlot,\n  encodeReliabilitySlot,\n  extractWirePayload,\n  type IActionWireFormat,\n  type IFrameReliabilityWire,\n  PayloadTypeToInt,\n  ReversePayloadType,\n} from \"./actionWireCodec\";\n\n/**\n * Positional layout of the *session* binary envelope — the leanest frame. Compared to the stateless\n * adapter it replaces the 21-char `cuid` with a small per-connection integer and only carries\n * `originClient` on the very first request of each direction (the peer remembers it afterwards).\n *\n *   [ routeInt, typeInt, corrId, time, originClient?, payloadData ]\n */\nconst ENVELOPE = {\n  route: 0,\n  type: 1,\n  corr: 2,\n  time: 3,\n  originClient: 4,\n  payload: 5,\n  /** Optional trailing slot — present only on a reliable frame (see {@link encodeReliabilitySlot}). */\n  reliability: 6,\n  /** Optional streamKey slot (E3) — present only on a *keyed* reliable frame; makes the frame length 8. */\n  streamKey: 7,\n} as const;\n/**\n * Best-effort frame length. A reliable frame appends the seq/ack slot → {@link ENVELOPE_LENGTH_RELIABLE};\n * a *keyed* reliable frame appends one more (the streamKey) → {@link ENVELOPE_LENGTH_RELIABLE_KEYED}. The\n * distinct lengths are self-discriminating: a peer that predates a length rejects the frame wholesale\n * (never mis-decodes it), so keyless reliable frames stay byte-identical and an old peer drops a keyed one.\n */\nconst ENVELOPE_LENGTH = 6;\nconst ENVELOPE_LENGTH_RELIABLE = 7;\nconst ENVELOPE_LENGTH_RELIABLE_KEYED = 8;\n\n/**\n * How long a pending correlation entry is kept before it's swept. A correlation only matters until its\n * action resolves or times out, so anything older than the longest realistic action timeout can be\n * dropped — this bounds memory when requests time out or a connection dies mid-flight (their replies\n * would never arrive, leaving the entry orphaned). Generous default so live correlations are never\n * pruned (the default transport timeout is 10s).\n */\nconst DEFAULT_CORRELATION_TTL_MS = 5 * 60_000;\n\ntype TFormatMessage = IActionWireFormat;\n\ninterface IPendingCorrelation<V> {\n  value: V;\n  /** Insertion time (ms), used to expire orphaned entries. */\n  time: number;\n}\n\nexport interface IBinaryWireSessionOptions {\n  /** Override how long an unresolved correlation is retained before being swept (ms). */\n  correlationTtlMs?: number;\n}\n\nfunction isKnownIdentity(\n  coordinate: IRuntimeCoordinate | null | undefined,\n): coordinate is IRuntimeCoordinate {\n  return coordinate != null && coordinate.envId !== UNSET_RUNTIME_ENV_ID;\n}\n\n/**\n * Drop entries older than `ttlMs`. Maps keep insertion order and entries are inserted in time order,\n * so the oldest are first — stop sweeping at the first live entry.\n */\nfunction pruneExpired<K, V>(map: Map<K, IPendingCorrelation<V>>, now: number, ttlMs: number): void {\n  for (const [key, entry] of map) {\n    if (now - entry.time <= ttlMs) break;\n    map.delete(key);\n  }\n}\n\n/**\n * Builds a factory of *stateful, per-connection* codecs for {@link LinkTransport} /\n * `ChannelAcceptor` — the maximally compact binary wire. Call the returned factory once per live\n * connection (each socket on the client, each accepted connection on the server) so every channel\n * gets its own correlation + identity state.\n *\n * On top of everything {@link createBinaryWireAdapter} drops, a session also drops:\n * - **`cuid`** — replaced by a per-connection integer correlation id. The initiator maps it to its\n *   real cuid; the responder echoes it; each side reconstructs the cuid from its own map. Correlation\n *   only needs to be unique per socket, so a counter suffices.\n * - **`originClient` after the first request** — the first request each side sends carries its\n *   identity; the peer remembers it and injects it into later frames. Replies omit it entirely (a\n *   reply carries the initiator's own origin, which the initiator already knows).\n *\n * Both ends MUST build the factory from the same domains in the same order (positional dictionary).\n * Text frames still return `undefined` from `incoming`, so JSON clients remain interoperable.\n *\n * Hibernation note: after a server connection is evicted its session resets, so a still-connected\n * client (whose session persists) will keep omitting `originClient`. The server must therefore restore\n * the connection→client binding from its own store (see `ChannelAcceptor.rehydrate`) and\n * inject `originClient` from there — the session alone can't recover it.\n */\nexport function createBinaryWireSessionFactory(\n  domains: ActionDomain<any>[],\n  options?: IBinaryWireSessionOptions,\n): () => TFormatMessage {\n  const { routeToInt, intToRoute } = buildActionRouteDictionary(domains);\n  const unknownIdentity = RuntimeCoordinate.unknown.toJsonObject();\n  const ttlMs = options?.correlationTtlMs ?? DEFAULT_CORRELATION_TTL_MS;\n\n  return (): TFormatMessage => {\n    let outCounter = 0;\n    // Requests this side initiated: correlation id → our cuid (to resolve the eventual reply).\n    const corrToCuid = new Map<number, IPendingCorrelation<string>>();\n    // Requests this side is responding to: our (synthesized) cuid → the correlation id to echo back.\n    const cuidToCorr = new Map<string, IPendingCorrelation<number>>();\n    let selfIdentity: IRuntimeCoordinate | undefined;\n    let peerIdentity: IRuntimeCoordinate | undefined;\n\n    return {\n      outgoing: (input: ITransportRouteActionParams): Uint8Array => {\n        const json = input.action.toJsonObject();\n        const routeKey = `${json.domain}:${json.id}`;\n        const routeInt = routeToInt.get(routeKey);\n        if (routeInt == null) {\n          throw new Error(`[binary-wire] Cannot pack unregistered action route: ${routeKey}`);\n        }\n\n        const now = Date.now();\n        pruneExpired(corrToCuid, now, ttlMs);\n        pruneExpired(cuidToCorr, now, ttlMs);\n\n        let corr: number;\n        let wireIdentity: IRuntimeCoordinate | undefined;\n\n        if (json.type === EActionPayloadType.request) {\n          // Initiator: assign a fresh per-connection correlation id, remember our cuid for the reply.\n          corr = outCounter++;\n          corrToCuid.set(corr, { value: json.context.cuid, time: now });\n\n          // Send our identity only on the first request — the peer remembers it from then on.\n          if (selfIdentity == null && isKnownIdentity(json.context.originClient)) {\n            selfIdentity = json.context.originClient;\n            wireIdentity = json.context.originClient;\n          }\n        } else {\n          // Responder: echo the correlation id the request arrived with.\n          corr = cuidToCorr.get(json.context.cuid)?.value ?? -1;\n          if (json.type === EActionPayloadType.result) cuidToCorr.delete(json.context.cuid);\n        }\n\n        // A reliable frame appends the seq/ack slot; a keyed reliable frame appends the streamKey too; a\n        // best-effort frame stays at ENVELOPE_LENGTH, so its packed bytes are unchanged.\n        const reliabilitySlot = encodeReliabilitySlot(input.reliability, json.type);\n        const streamKey = input.reliability?.streamKey;\n        const length =\n          streamKey != null\n            ? ENVELOPE_LENGTH_RELIABLE_KEYED\n            : reliabilitySlot == null\n              ? ENVELOPE_LENGTH\n              : ENVELOPE_LENGTH_RELIABLE;\n        const envelope = new Array(length);\n        envelope[ENVELOPE.route] = routeInt;\n        envelope[ENVELOPE.type] = PayloadTypeToInt[json.type];\n        envelope[ENVELOPE.corr] = corr;\n        envelope[ENVELOPE.time] = json.time;\n        envelope[ENVELOPE.originClient] = wireIdentity; // undefined except the first request\n        envelope[ENVELOPE.payload] = extractWirePayload(json);\n        if (reliabilitySlot != null) envelope[ENVELOPE.reliability] = reliabilitySlot;\n        if (streamKey != null) envelope[ENVELOPE.streamKey] = streamKey;\n\n        return pack(envelope);\n      },\n\n      incoming: (frame: string | ArrayBuffer | Uint8Array | Blob) => {\n        let buffer: Uint8Array;\n        if (frame instanceof ArrayBuffer) {\n          buffer = new Uint8Array(frame);\n        } else if (frame instanceof Uint8Array) {\n          buffer = frame;\n        } else {\n          return undefined;\n        }\n\n        try {\n          const envelope = unpack(buffer);\n          if (!isSessionEnvelope(envelope)) return undefined;\n\n          const routeMeta = intToRoute[envelope[ENVELOPE.route]];\n          const payloadType = ReversePayloadType[envelope[ENVELOPE.type]];\n          if (routeMeta == null || payloadType == null) return undefined;\n\n          const now = Date.now();\n          pruneExpired(corrToCuid, now, ttlMs);\n          pruneExpired(cuidToCorr, now, ttlMs);\n\n          const corr: number = envelope[ENVELOPE.corr];\n          const time: number = envelope[ENVELOPE.time];\n          const wireIdentity: IRuntimeCoordinate | undefined = envelope[ENVELOPE.originClient];\n\n          let cuid: string;\n          let originClient: IRuntimeCoordinate;\n\n          if (payloadType === EActionPayloadType.request) {\n            // Incoming request: synthesize a local cuid, remember the correlation for our reply.\n            cuid = nanoid();\n            cuidToCorr.set(cuid, { value: corr, time: now });\n\n            if (isKnownIdentity(wireIdentity)) peerIdentity = wireIdentity;\n            originClient = peerIdentity ?? unknownIdentity;\n          } else {\n            // Incoming reply: map the correlation id back to the cuid of the request we initiated.\n            cuid = corrToCuid.get(corr)?.value ?? nanoid();\n            if (payloadType === EActionPayloadType.result) corrToCuid.delete(corr);\n            // A reply carries our own origin (the request originated on this side).\n            originClient = selfIdentity ?? unknownIdentity;\n          }\n\n          const context = { cuid, timeCreated: time, routing: [], originClient };\n          return assembleWireJson(\n            routeMeta,\n            payloadType,\n            time,\n            context,\n            envelope[ENVELOPE.payload],\n          );\n        } catch (e) {\n          console.error(\"[binary-wire] Failed to unpack binary action session frame\", e);\n          return undefined;\n        }\n      },\n\n      // A pure peek at the reliability slot — must NOT touch the correlation/identity state `incoming`\n      // maintains, so it unpacks independently and only reads the trailing integer.\n      incomingReliability: (frame): IFrameReliabilityWire | undefined => {\n        let buffer: Uint8Array;\n        if (frame instanceof ArrayBuffer) buffer = new Uint8Array(frame);\n        else if (frame instanceof Uint8Array) buffer = frame;\n        else return undefined;\n\n        try {\n          const envelope = unpack(buffer);\n          if (\n            !isSessionEnvelope(envelope) ||\n            (envelope.length !== ENVELOPE_LENGTH_RELIABLE &&\n              envelope.length !== ENVELOPE_LENGTH_RELIABLE_KEYED)\n          ) {\n            return undefined;\n          }\n          const payloadType = ReversePayloadType[envelope[ENVELOPE.type]];\n          if (payloadType == null) return undefined;\n          const wire = decodeReliabilitySlot(envelope[ENVELOPE.reliability], payloadType);\n          if (wire == null) return undefined;\n          if (envelope.length === ENVELOPE_LENGTH_RELIABLE_KEYED) {\n            // The streamKey slot comes off the peer's wire — a non-string (buggy/hostile peer) must not\n            // flow into stream ids / control frames, so the whole slot degrades to best-effort.\n            const streamKey = envelope[ENVELOPE.streamKey];\n            if (typeof streamKey !== \"string\") return undefined;\n            wire.streamKey = streamKey;\n          }\n          return wire;\n        } catch {\n          return undefined;\n        }\n      },\n    };\n  };\n}\n\n/** A decoded session frame is one of ours iff it's an array of best-effort or reliable length. */\n// msgpackr yields `any`; this matches the pre-existing `Array.isArray` narrowing the raw envelope indexing relied on.\nfunction isSessionEnvelope(envelope: unknown): envelope is any[] {\n  return (\n    Array.isArray(envelope) &&\n    (envelope.length === ENVELOPE_LENGTH ||\n      envelope.length === ENVELOPE_LENGTH_RELIABLE ||\n      envelope.length === ENVELOPE_LENGTH_RELIABLE_KEYED)\n  );\n}\n","import type { IActionTransportResolvers } from \"./Transport.types\";\nimport {\n  type ETransportShape,\n  type ITransportRouteInfo,\n  type TTransportRouteParams,\n} from \"./Transport.types\";\nimport type { TransportConnection } from \"./TransportConnection\";\n\n/**\n * Context handed to a {@link Transport} definition when a handler builds a live connection from it.\n * Only bidirectional transports (WebSocket / Custom) make use of `resolvers`.\n */\nexport interface ITransportConnectionContext {\n  resolvers?: IActionTransportResolvers;\n}\n\n/**\n * Reusable transport definition. Built by the internal `transport({ carrier, secure })` factory (which\n * `connectChannel` / `serveChannel` drive) and passed to a `ChannelConnector`. A single\n * definition can be shared across multiple handlers — each handler builds its own live\n * {@link TransportConnection} via {@link TransportConnection._createConnection}.\n */\nexport abstract class Transport<T extends ETransportShape = ETransportShape> {\n  abstract readonly type: T;\n\n  /** Internal: build a fresh, per-handler live connection from this definition. */\n  abstract _createConnection(ctx: ITransportConnectionContext): TransportConnection<T>;\n\n  /**\n   * Resolve human-readable info about how a specific action would be routed through this transport\n   * (e.g. the request URL/method, or the WebSocket endpoint). Surfaced in the action devtools.\n   */\n  abstract getRouteInfo(input: TTransportRouteParams): ITransportRouteInfo;\n}\n","import {\n  establishPlainExchangeSession,\n  establishSecureExchangeSession,\n  type IWireExchangeSession,\n} from \"@nice-code/wire\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { ERunningActionUpdateType } from \"../../../ActionDefinition/Action/RunningAction.types\";\nimport { isActionPayload_Result_JsonObject } from \"../../../utils/isActionPayload_Result_JsonObject\";\nimport type { IExchangeCarrier } from \"../Carrier/Carrier.types\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../err_nice_transport\";\nimport type {\n  IActionTransportReadyData_Methods,\n  ISecureClientConfig,\n  TSendActionDataMethod,\n  TUpdateActionRunConfig,\n} from \"../Transport.types\";\n\n/**\n * The action lane over wire's exchange session (shared-base-connect plan, Phase 6): wire's\n * `establishPlain/SecureExchangeSession` owns the envelope, the one-time handshake, and the\n * per-request token + crypto; what stays here is the lane — each action's wire rides one\n * exchange, and (for a request) the correlated reply completes the {@link RunningAction} inline\n * (there is no return path — the duplex counterpart is `establishLinkSession`). The lane\n * contributes its handshake payload (`dictionaryVersion`/`channelTags`) exactly as the duplex\n * lane's `handshakeConfig()` does; the exchange path is lane-only (no mux — plan D-11).\n */\nexport interface IExchangeSessionContext {\n  carrier: IExchangeCarrier;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** When present (and not `none`) the handshake runs at bring-up; absent ⇒ plain exchange. */\n  secure?: ISecureClientConfig;\n}\n\n/** Plain path (no handshake/token): every action rides a bare `act` envelope, plaintext both ways. */\nexport function finalizePlainExchangeMethods(\n  ctx: IExchangeSessionContext,\n): IActionTransportReadyData_Methods {\n  return buildExchangeMethods(ctx, establishPlainExchangeSession(ctx.carrier));\n}\n\n/** Secure path: run the handshake (two exchanges) once at bring-up, then reuse the token + crypto. */\nexport async function finalizeSecureExchangeMethods(\n  ctx: IExchangeSessionContext & { secure: ISecureClientConfig },\n): Promise<IActionTransportReadyData_Methods> {\n  const session = await establishSecureExchangeSession({\n    carrier: ctx.carrier,\n    secure: ctx.secure,\n    // The lane's handshake payload (E5) — the same fields the duplex lane supplies.\n    lane: { dictionaryVersion: ctx.secure.dictionaryVersion, channels: ctx.secure.channelTags },\n  });\n  return buildExchangeMethods(ctx, session);\n}\n\nfunction buildExchangeMethods(\n  ctx: IExchangeSessionContext,\n  session: IWireExchangeSession,\n): IActionTransportReadyData_Methods {\n  const sendActionData: TSendActionDataMethod = (inputs) => {\n    void runExchange(session, inputs).catch((err) => inputs.runningAction._abort(err));\n  };\n\n  return { sendActionData, updateRunConfig: ctx.updateRunConfig };\n}\n\nasync function runExchange(\n  session: IWireExchangeSession,\n  inputs: Parameters<TSendActionDataMethod>[0],\n): Promise<void> {\n  const { action, runningAction, timeout } = inputs;\n\n  const ac = new AbortController();\n  let timedOut = false;\n  const timeoutId = setTimeout(() => {\n    timedOut = true;\n    ac.abort();\n  }, timeout);\n  const unsubscribe = runningAction.addUpdateListeners([\n    (update) => {\n      if (update.type === ERunningActionUpdateType.finished) {\n        clearTimeout(timeoutId);\n        ac.abort();\n      }\n    },\n  ]);\n\n  try {\n    // Only a request awaits a reply (progress/result payloads aren't sent by a connector over exchange).\n    if (action.type !== EActionPayloadType.request) {\n      await session.send(action.toJsonObject(), { signal: ac.signal });\n      return;\n    }\n\n    const outcome = await session.exchange(action.toJsonObject(), { signal: ac.signal });\n    if (!outcome.ok && outcome.reason === \"peer_error\") {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.send_failed, {\n        actionState: action.type,\n        actionId: action.id,\n        message: outcome.message,\n      });\n    }\n    if (!outcome.ok || !isActionPayload_Result_JsonObject(outcome.wire)) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.invalid_action_response, {\n        actionId: action.id,\n      });\n    }\n\n    runningAction._completeWithResult(action._domain.hydrateResultPayload(outcome.wire));\n  } catch (err) {\n    if (timedOut) {\n      throw err_nice_transport.fromId(EErrId_NiceTransport.timeout, { timeout });\n    }\n    throw err;\n  } finally {\n    clearTimeout(timeoutId);\n    unsubscribe();\n  }\n}\n","import { TransportConnection as WireTransportConnection } from \"@nice-code/wire\";\nimport type {\n  ETransportShape,\n  IActionTransportDef,\n  IActionTransportInitialized,\n  IActionTransportReadyData_Base,\n  IActionTransportReadyData_Methods,\n  TTransportRouteParams,\n} from \"./Transport.types\";\n\n/**\n * Live, per-handler transport runtime built from a reusable {@link Transport} definition — the\n * action instantiation of wire's generic `TransportConnection` (shared-base-connect plan,\n * Phase 2): routing params pinned to {@link ITransportRouteActionParams} and the finalized\n * methods to {@link IActionTransportReadyData_Methods}. The machinery (status processing, cache\n * keys, async bring-up hooks) lives in wire; subclasses (`LinkConnection`, `ExchangeConnection`)\n * are unchanged. Construct these via `definition._createConnection(...)`, never directly.\n */\nexport abstract class TransportConnection<\n  T extends ETransportShape = ETransportShape,\n  RP extends TTransportRouteParams = TTransportRouteParams,\n  RD extends IActionTransportReadyData_Base = IActionTransportReadyData_Base,\n  I extends IActionTransportInitialized<RP, RD> = IActionTransportInitialized<RP, RD>,\n  DEF extends IActionTransportDef<T, I> = IActionTransportDef<T, I>,\n> extends WireTransportConnection<T, RP, RD, IActionTransportReadyData_Methods, I, DEF> {}\n","import { ESecurityLevel } from \"@nice-code/wire\";\nimport {\n  finalizePlainExchangeMethods,\n  finalizeSecureExchangeMethods,\n  type IExchangeSessionContext,\n} from \"../SecureSession/establishExchangeSession\";\nimport {\n  ETransportShape,\n  type IActionTransportReadyData_Methods,\n  type TTransportRouteParams,\n} from \"../Transport.types\";\nimport { TransportConnection } from \"../TransportConnection\";\nimport type {\n  IActionTransportDef_Exchange,\n  IActionTransportInitialized_Exchange,\n  IActionTransportReadyData_Exchange,\n} from \"./TransportExchange.types\";\n\n/**\n * Carrier-agnostic live connection for the exchange (request → single reply) shape — the HTTP\n * counterpart to {@link LinkConnection}. It owns only the bring-up (run the secure handshake on first\n * use); the request/reply lifecycle + crypto live in the shared `establishExchangeSession`.\n */\nexport class ExchangeConnection extends TransportConnection<\n  ETransportShape.exchange,\n  TTransportRouteParams,\n  IActionTransportReadyData_Exchange,\n  IActionTransportInitialized_Exchange,\n  IActionTransportDef_Exchange\n> {\n  constructor(def: Omit<IActionTransportDef_Exchange, \"type\">) {\n    super({ ...def, type: ETransportShape.exchange });\n  }\n\n  protected override _getCacheKey(input: TTransportRouteParams): string {\n    return this.initialized.getTransportCacheKey?.(input).join(\"\\x00\") ?? \"\";\n  }\n\n  // Only a secure exchange needs async bring-up (the handshake). A plain (`none`) exchange is usable the\n  // instant the carrier opens — finalized synchronously like HTTP today.\n  protected override _needsAsyncBringUp(data: IActionTransportReadyData_Exchange): boolean {\n    return data.secureChannel != null && data.secureChannel.securityLevel !== ESecurityLevel.none;\n  }\n\n  protected override _finalizeReady(\n    data: IActionTransportReadyData_Exchange,\n  ): IActionTransportReadyData_Methods | Promise<IActionTransportReadyData_Methods> {\n    const secure = data.secureChannel;\n    if (secure != null && secure.securityLevel !== ESecurityLevel.none) {\n      return finalizeSecureExchangeMethods({ ...this._sessionContext(data), secure });\n    }\n    return this._finalizeTransportMethods(data);\n  }\n\n  _finalizeTransportMethods(\n    data: IActionTransportReadyData_Exchange,\n  ): IActionTransportReadyData_Methods {\n    return finalizePlainExchangeMethods(this._sessionContext(data));\n  }\n\n  private _sessionContext(data: IActionTransportReadyData_Exchange): IExchangeSessionContext {\n    return {\n      carrier: data.carrier,\n      updateRunConfig: data.updateRunConfig,\n      secure: data.secureChannel,\n    };\n  }\n}\n","import {\n  err_wire_connect,\n  protocolsFromCaps,\n  type TWireTapFn,\n  type WireProtocolMux,\n  withExchangeTap,\n} from \"@nice-code/wire\";\nimport type { IExchangeCarrier } from \"../Carrier/Carrier.types\";\nimport { type ITransportConnectionContext, Transport } from \"../Transport\";\nimport {\n  ETransportShape,\n  ETransportStatus,\n  type ISecureClientConfig,\n  type ITransportRouteInfo,\n  type TTransportRouteParams,\n  type TUpdateActionRunConfig,\n} from \"../Transport.types\";\nimport { ExchangeConnection } from \"./ExchangeConnection\";\n\nexport interface IExchangeTransportOptions {\n  /** Open (or reuse) the exchange carrier for an action — e.g. `httpCarrier(...).open`. */\n  openCarrier: (input: TTransportRouteParams) => IExchangeCarrier;\n  /** Secure config; when set (and `securityLevel !== none`) the handshake runs once at bring-up. */\n  security?: ISecureClientConfig;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** Keys identifying a reusable session, so one carrier is shared across actions to the same peer. */\n  getTransportCacheKey?: (input: TTransportRouteParams) => string[];\n  /**\n   * Optional availability gate. When it returns `false`, the manager skips this transport for that action\n   * (reporting `unsupported`) and falls through to the next — without opening the carrier or computing its\n   * cache key. Re-evaluated per dispatch, so the transport can become available later with no reconnect.\n   */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Short label for the devtools chip (defaults to \"exchange\"). */\n  label?: string;\n  getRouteInfo?: (input: TTransportRouteParams) => ITransportRouteInfo;\n  /** The connection's frame-protocol mux, when one exists — consulted only by the D-11 guard. */\n  mux?: WireProtocolMux;\n  /**\n   * Whether *every* transport on this connection is exchange-shaped (computed by `connectChannel`).\n   * Prefixed protocols need a duplex transport (plan D-11) — on an exchange-only connection they\n   * could never speak, so bringing this transport up with protocols registered on {@link mux}\n   * throws `err_nice_wire_connect.protocol_on_exchange_only` instead of leaving them silently mute.\n   * A mixed chain (duplex preferred, exchange fallback) never sets this: there the protocols\n   * legitimately ride the duplex transport when it is up.\n   */\n  exchangeOnlyConnection?: boolean;\n  /** Wire-traffic observation (devtools) — request/reply envelope bytes under the `\"http\"` lane. */\n  wireTap?: TWireTapFn;\n}\n\n/**\n * A carrier-agnostic exchange (request → single reply) transport: it drives nice-action's secure session\n * over any {@link IExchangeCarrier} (HTTP being the one built-in). The duplex counterpart is\n * {@link LinkTransport}; this is the no-push half — its reply rides the response to its own request, so it\n * can't deliver an unsolicited frame (the runtime never picks it for the return path).\n */\nexport class ExchangeTransport extends Transport<ETransportShape.exchange> {\n  readonly type = ETransportShape.exchange;\n\n  constructor(private readonly options: IExchangeTransportOptions) {\n    super();\n  }\n\n  static create(options: IExchangeTransportOptions): ExchangeTransport {\n    return new ExchangeTransport(options);\n  }\n\n  _createConnection(_ctx: ITransportConnectionContext): ExchangeConnection {\n    const options = this.options;\n\n    return new ExchangeConnection({\n      initialize: () => ({\n        getTransportCacheKey: options.getTransportCacheKey,\n        isAvailable: options.available,\n        getTransport: (input) => {\n          assertProtocolsRideDuplex(options);\n          const carrier = options.openCarrier(input);\n          return {\n            status: ETransportStatus.ready,\n            readyData: {\n              carrier:\n                options.wireTap != null ? withExchangeTap(carrier, options.wireTap) : carrier,\n              secureChannel: options.security,\n              updateRunConfig: options.updateRunConfig,\n            },\n          };\n        },\n      }),\n    });\n  }\n\n  getRouteInfo(input: TTransportRouteParams): ITransportRouteInfo {\n    if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);\n    return {\n      carrierLabel: this.options.label ?? \"exchange\",\n      summary: this.options.label ?? \"exchange\",\n    };\n  }\n}\n\n/**\n * The D-11 guard: an exchange-only connection carries only the lane, so a registered prefixed\n * protocol is a configuration error surfaced clearly at bring-up (the first dispatch through this\n * transport) — after registration, which may legitimately happen later than `connectChannel`\n * (e.g. `realmConnection(connector)`), hence not at construction.\n */\nfunction assertProtocolsRideDuplex(options: IExchangeTransportOptions): void {\n  if (options.exchangeOnlyConnection !== true || options.mux == null) return;\n  for (const protocolId of protocolsFromCaps(options.mux.localCaps())) {\n    throw err_wire_connect.fromId(\"protocol_on_exchange_only\", { protocolId });\n  }\n}\n","import type { IActionTransportResolvers } from \"../Transport.types\";\n\nexport const createUnsetTransportResolvers = (\n  transportLabel: string,\n): IActionTransportResolvers => ({\n  onIncomingActionDataJson: (json) => {\n    console.warn(\n      `Received incoming action JSON [${json.domain}:${json.id}] on Transport [${transportLabel}] but no incoming data listener has been set.`,\n    );\n  },\n});\n","import type { NiceError } from \"@nice-code/error\";\nimport {\n  CAP_RELIABLE,\n  CAP_RELIABLE_STREAMKEY,\n  decodeControlFrame,\n  encodeControlFrame,\n  establishPlainDuplexSession,\n  establishSecureDuplexSession,\n  type IWireDuplexSession,\n  type IWireLaneEndpoint,\n  type IWireLaneProtocol,\n  type IWireLinkKeepalive,\n  type TFrame,\n  type TWireTapFn,\n  warnReliablePeerUnsupportedOnce,\n  warnReliableStreamKeyUnsupportedOnce,\n  warnReliableWireUnavailableOnce,\n} from \"@nice-code/wire\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport type { RunningAction } from \"../../../ActionDefinition/Action/RunningAction\";\nimport { ERunningActionUpdateType } from \"../../../ActionDefinition/Action/RunningAction.types\";\nimport { EReliabilityTier } from \"../../../ActionDefinition/Schema/ActionSchema\";\nimport { decodeActionFrame } from \"../../../utils/decodeActionFrame\";\nimport type { IDuplexCarrier } from \"../Carrier/Carrier.types\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../err_nice_transport\";\nimport type { TLinkFormatMessage } from \"../Link/TransportLink.types\";\nimport type {\n  IActionTransportReadyData_Methods,\n  IActionTransportResolvers,\n  ISecureClientConfig,\n  TSendActionDataMethod,\n  TUpdateActionRunConfig,\n} from \"../Transport.types\";\n\n/**\n * The action **lane tail** of a connector link session (shared-base-connect plan, Phase 2;\n * formalized as the wire lane protocol at Phase 5). The wire half — carrier attach, client\n * handshake, frame-crypto pipe, pre-ready buffering, mux bind, disconnect fan-out — lives in\n * `@nice-code/wire`'s `establish(Plain|Secure)DuplexSession`; what stays here is everything that\n * speaks *actions*: the codec (binary wire / JSON fallback), control-frame decode, reliability\n * warnings/stripping, per-send timeouts + the abort set, and the\n * {@link IActionTransportReadyData_Methods} surface `LinkConnection` exposes upward — packaged as\n * the {@link IWireLaneProtocol} implementation the session drives (E5: action owns the\n * unprefixed-frame namespace and supplies the handshake's `dictionaryVersion`/`channels`).\n */\nexport interface ILinkSessionContext {\n  channel: IDuplexCarrier;\n  resolvers: IActionTransportResolvers;\n  formatMessage?: TLinkFormatMessage;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** The error used to abort in-flight actions when the channel is closed/gone (carrier-specific). */\n  makeDisconnectError: (actionId: string) => NiceError;\n  /** Wire keepalive (8b.3) — half-open detection for this link's session; `undefined` = off. */\n  linkKeepalive?: IWireLinkKeepalive;\n  /** Wire-traffic observation (devtools) — reports every carrier frame's true bytes. */\n  wireTap?: TWireTapFn;\n}\n\n/**\n * The action lane as a wire lane endpoint: every unprefixed frame decodes here (control frame →\n * action frame), and a lost connection aborts the in-flight best-effort sends.\n */\nfunction connectorLaneEndpoint(\n  ctx: ILinkSessionContext,\n  abortSet: Set<RunningAction<any, any>>,\n): IWireLaneEndpoint {\n  return {\n    id: \"action\",\n    onLaneFrame: (frame) => handleLaneFrame(ctx, frame),\n    onDetach: () => abortInFlight(ctx, abortSet),\n  };\n}\n\n/** Plain path (no handshake): route every inbound frame to the runtime; send without crypto. */\nexport function finalizePlainLinkMethods(\n  ctx: ILinkSessionContext,\n): IActionTransportReadyData_Methods {\n  const abortSet = new Set<RunningAction<any, any>>();\n  const session = establishPlainDuplexSession({\n    channel: ctx.channel,\n    lane: connectorLaneEndpoint(ctx, abortSet),\n    keepalive: ctx.linkKeepalive,\n    tap: ctx.wireTap,\n  });\n  return buildSendMethods(ctx, session, abortSet);\n}\n\n/**\n * Secure path: the wire session runs the handshake (buffering frames that race ahead), then lane\n * frames flow here. The lane protocol supplies the handshake payload (E5 — `dictionaryVersion`/\n * `channelTags` come off the action channel via {@link ISecureClientConfig}, which is the lane's\n * own config surface; wire consumes only the neutral core). `remoteReliable`/`remoteStreamKey`\n * come off the negotiated caps.\n */\nexport async function finalizeSecureLinkMethods(\n  ctx: ILinkSessionContext & { secure: ISecureClientConfig },\n): Promise<IActionTransportReadyData_Methods> {\n  const abortSet = new Set<RunningAction<any, any>>();\n  const lane: IWireLaneProtocol = {\n    ...connectorLaneEndpoint(ctx, abortSet),\n    handshakeConfig: () => ({\n      dictionaryVersion: ctx.secure.dictionaryVersion,\n      channels: ctx.secure.channelTags,\n    }),\n  };\n  const session = await establishSecureDuplexSession({\n    channel: ctx.channel,\n    secure: ctx.secure,\n    lane,\n    mux: ctx.secure.mux,\n    keepalive: ctx.linkKeepalive,\n    tap: ctx.wireTap,\n  });\n\n  // `remoteReliable`/`remoteStreamKey` are known (true/false) for a secure connection: an old peer omits the\n  // cap, so a `.reliable()` (or keyed) send warns + degrades. The plain path can't negotiate caps → both\n  // `undefined` (no warn).\n  return buildSendMethods(\n    ctx,\n    session,\n    abortSet,\n    session.remoteCaps?.includes(CAP_RELIABLE) ?? false,\n    session.remoteCaps?.includes(CAP_RELIABLE_STREAMKEY) ?? false,\n  );\n}\n\nfunction buildSendMethods(\n  ctx: ILinkSessionContext,\n  session: IWireDuplexSession,\n  abortSet: Set<RunningAction<any, any>>,\n  /** Secure path only: whether the peer advertised reliable support. `undefined` = unknown (plain path). */\n  remoteReliable?: boolean,\n  /** Secure path only: whether the peer advertised streamkey (E3) support. `undefined` = unknown (plain). */\n  remoteStreamKey?: boolean,\n): IActionTransportReadyData_Methods {\n  const sendActionData: TSendActionDataMethod = (inputs) => {\n    const { action, runningAction, timeout } = inputs;\n\n    // A reliable request owns its own lifecycle in the connector's outbox: it must NOT be aborted when\n    // this connection drops (the outbox resends it on reconnect) and it does NOT use the normal\n    // per-send timeout (delivery is guaranteed by resend, bounded by the outbox window). Best-effort\n    // requests keep their existing abort-on-close + timeout behaviour, byte-for-byte unchanged.\n    const isReliableRequest =\n      action.type === EActionPayloadType.request &&\n      action.schema?.reliabilityTier != null &&\n      action.schema.reliabilityTier !== EReliabilityTier.none;\n\n    if (!session.isOpen()) {\n      if (action.type === EActionPayloadType.request && !isReliableRequest) {\n        runningAction._abort(ctx.makeDisconnectError(action.id));\n      }\n      return;\n    }\n\n    if (action.type === EActionPayloadType.request && !isReliableRequest) {\n      abortSet.add(runningAction);\n      const timeoutId = setTimeout(() => {\n        runningAction._abort(err_nice_transport.fromId(EErrId_NiceTransport.timeout, { timeout }));\n      }, timeout);\n      runningAction.addUpdateListeners([\n        (update) => {\n          if (update.type === ERunningActionUpdateType.finished) {\n            clearTimeout(timeoutId);\n            abortSet.delete(runningAction);\n          }\n        },\n      ]);\n    }\n\n    // A reliable frame carries a `reliability` slot the binary codec writes; with no codec the JSON fallback\n    // below drops it, silently degrading the frame to best-effort. Surface that once per route.\n    let sendInputs = inputs;\n    if (inputs.reliability != null) {\n      if (ctx.formatMessage == null) {\n        warnReliableWireUnavailableOnce(action.domain, action.id);\n      } else if (remoteReliable === false) {\n        // Secure peer that predates reliable support (no `reliable` cap in its welcome): its decoder only\n        // accepts the best-effort envelope length, so a frame carrying the slot would be rejected\n        // *wholesale* — not delivered at all. Strip the slot instead: the frame goes out genuinely\n        // best-effort (byte-identical to a non-reliable send) and is delivered; ordering/dedup/resend\n        // don't apply. Warn once so the version skew is visible. (The outbox still tracks the send — its\n        // delivery deadline eventually abandons it, since a slot-less frame is never acked.)\n        warnReliablePeerUnsupportedOnce(action.domain, action.id);\n        sendInputs = { ...inputs, reliability: undefined };\n      } else if (inputs.reliability.streamKey != null && remoteStreamKey === false) {\n        // Secure peer that supports reliability but not *keyed* streams (E3): a keyed frame is a distinct\n        // length it drops wholesale, so it won't be delivered. The key can NOT be safely stripped (that\n        // would merge independent seq spaces into the single default stream and corrupt its dedup), so\n        // this stays a clean non-delivery. Warn once so the version skew is visible.\n        warnReliableStreamKeyUnsupportedOnce(action.domain, action.id);\n      }\n    }\n\n    session.send(\n      ctx.formatMessage?.outgoing(sendInputs) ?? JSON.stringify(sendInputs.action.toJsonObject()),\n    );\n  };\n\n  return {\n    sendActionData,\n    // Sender-originated control frames (`rskip`, …) ride the same pipe as action frames, so on a secure\n    // connection they're encrypted + ordered with the stream they control.\n    sendControlData: (message) => {\n      if (!session.isOpen()) return;\n      session.send(encodeControlFrame(message));\n    },\n    updateRunConfig: ctx.updateRunConfig,\n    addOnDisconnectListener: (cb) => session.addOnDisconnectListener(cb),\n    disconnect: () => session.close(),\n    sendReturnData: (payload, clients) => {\n      const formatted =\n        clients != null ? ctx.formatMessage?.outgoing({ action: payload, ...clients }) : undefined;\n      session.send(formatted ?? JSON.stringify(payload.toJsonObject()));\n    },\n  };\n}\n\n/**\n * One inbound lane frame (already decrypted; the mux never saw it or didn't claim it): a control\n * frame or an action frame — the lane's whole receive vocabulary.\n */\nfunction handleLaneFrame(ctx: ILinkSessionContext, frame: TFrame): void {\n  // Peek for a transport control frame (reliability ack, …) before the action path — a cheap first-byte\n  // check short-circuits action frames, so best-effort decoding is unchanged.\n  const control = decodeControlFrame(frame);\n  if (control != null) {\n    ctx.resolvers.onControlMessage?.(control);\n    return;\n  }\n\n  const rawJson = decodeActionFrame(frame, ctx.formatMessage);\n  if (rawJson != null) {\n    // Surface the reliability integers (seq/ack) alongside the frame so the connector can prune its\n    // outbox and the acceptor can dedup. Only pass the second arg for an actual reliable frame — the\n    // best-effort receive call stays exactly one arg (unchanged contract).\n    const reliability = ctx.formatMessage?.incomingReliability?.(frame);\n    if (reliability != null) ctx.resolvers.onIncomingActionDataJson(rawJson, reliability);\n    else ctx.resolvers.onIncomingActionDataJson(rawJson);\n  }\n}\n\nfunction abortInFlight(ctx: ILinkSessionContext, abortSet: Set<RunningAction<any, any>>): void {\n  const error = ctx.makeDisconnectError(\"—\");\n  for (const ra of [...abortSet]) ra._abort(error);\n}\n","import type { NiceError } from \"@nice-code/error\";\nimport { ESecurityLevel } from \"@nice-code/wire\";\nimport { EErrId_NiceTransport, err_nice_transport } from \"../err_nice_transport\";\nimport { createUnsetTransportResolvers } from \"../helpers/createUnsetTransportResolvers\";\nimport {\n  finalizePlainLinkMethods,\n  finalizeSecureLinkMethods,\n  type ILinkSessionContext,\n} from \"../SecureSession/establishLinkSession\";\nimport {\n  ETransportShape,\n  type IActionTransportReadyData_Methods,\n  type IActionTransportResolvers,\n  type TTransportRouteParams,\n} from \"../Transport.types\";\nimport { TransportConnection } from \"../TransportConnection\";\nimport type {\n  IActionTransportDef_Link,\n  IActionTransportInitialized_Link,\n  IActionTransportReadyData_Link,\n} from \"./TransportLink.types\";\n\n/** Abort error for a closed link channel (carrier-neutral — the carrier itself isn't named). */\nfunction linkDisconnectError(actionId: string): NiceError {\n  return err_nice_transport.fromId(EErrId_NiceTransport.send_failed, {\n    actionId,\n    actionState: \"request\",\n    message: \"link channel disconnected\",\n  });\n}\n\n/**\n * Carrier-agnostic live connection. It owns only the *bring-up* (open the carrier, then run the secure\n * session); the session itself — handshake, frame crypto, codec, send/receive — lives in the shared\n * {@link finalizeSecureLinkMethods}/{@link finalizePlainLinkMethods}, so a WebSocket, a WebRTC data\n * channel, a Bluetooth characteristic, and an in-memory pipe all run the identical secure layer.\n */\nexport class LinkConnection extends TransportConnection<\n  ETransportShape.duplex,\n  TTransportRouteParams,\n  IActionTransportReadyData_Link,\n  IActionTransportInitialized_Link,\n  IActionTransportDef_Link\n> {\n  private resolvers: IActionTransportResolvers;\n\n  constructor(def: Omit<IActionTransportDef_Link, \"type\">, resolvers?: IActionTransportResolvers) {\n    super({ ...def, type: ETransportShape.duplex });\n    this.resolvers = resolvers ?? createUnsetTransportResolvers(\"link\");\n  }\n\n  protected override _getCacheKey(input: TTransportRouteParams): string {\n    return this.initialized.getTransportCacheKey?.(input).join(\"\\x00\") ?? \"\";\n  }\n\n  // A link is always brought up asynchronously: open the carrier (`channel.ready`), then run the\n  // handshake when secure. The base reports `initializing` and drives these hooks.\n  protected override _needsAsyncBringUp(): boolean {\n    return true;\n  }\n\n  protected override _awaitCarrierReady(data: IActionTransportReadyData_Link): Promise<void> {\n    return data.channel.ready;\n  }\n\n  protected override _finalizeReady(\n    data: IActionTransportReadyData_Link,\n  ): IActionTransportReadyData_Methods | Promise<IActionTransportReadyData_Methods> {\n    const secure = data.secureChannel;\n    if (secure != null && secure.securityLevel !== ESecurityLevel.none) {\n      return finalizeSecureLinkMethods({ ...this._sessionContext(data), secure });\n    }\n    return this._finalizeTransportMethods(data);\n  }\n\n  private _sessionContext(data: IActionTransportReadyData_Link): ILinkSessionContext {\n    return {\n      channel: data.channel,\n      resolvers: this.resolvers,\n      formatMessage: data.formatMessage,\n      updateRunConfig: data.updateRunConfig,\n      makeDisconnectError: linkDisconnectError,\n      linkKeepalive: data.linkKeepalive,\n      wireTap: data.wireTap,\n    };\n  }\n\n  // Public (not `protected`) so the binary-frame test can finalize a connection's methods directly.\n  _finalizeTransportMethods(\n    data: IActionTransportReadyData_Link,\n  ): IActionTransportReadyData_Methods {\n    return finalizePlainLinkMethods(this._sessionContext(data));\n  }\n}\n","import type { IDuplexCarrier } from \"../Carrier/Carrier.types\";\nimport { type ITransportConnectionContext, Transport } from \"../Transport\";\nimport {\n  ETransportShape,\n  ETransportStatus,\n  type ISecureClientConfig,\n  type ITransportRouteInfo,\n  type TTransportRouteParams,\n  type TUpdateActionRunConfig,\n} from \"../Transport.types\";\nimport { LinkConnection } from \"./LinkConnection\";\nimport type { TLinkFormatMessage } from \"./TransportLink.types\";\n\nexport interface ILinkTransportOptions {\n  /**\n   * Open (or reuse) the carrier for an action — a WebSocket adapter, a WebRTC data channel, a Bluetooth\n   * characteristic, an in-memory pipe, anything that satisfies {@link IDuplexCarrier}.\n   */\n  openChannel: (input: TTransportRouteParams) => IDuplexCarrier;\n  /** Shared codec for every channel (stateless). */\n  formatMessage?: TLinkFormatMessage;\n  /**\n   * Per-channel codec factory — called once per opened channel so stateful codecs (e.g. the binary\n   * session) get their own instance. Takes precedence over `formatMessage`.\n   */\n  createFormatMessage?: () => TLinkFormatMessage;\n  /** Secure-channel config; when set (and `securityLevel !== none`) the handshake runs on init. */\n  security?: ISecureClientConfig;\n  updateRunConfig?: TUpdateActionRunConfig;\n  /** Keys identifying a reusable channel, so one carrier is shared across actions to the same peer. */\n  getTransportCacheKey?: (input: TTransportRouteParams) => string[];\n  /**\n   * Optional availability gate. When it returns `false`, the manager skips this transport for that action\n   * (reporting `unsupported`) and falls through to the next — without opening the carrier or computing its\n   * cache key. Re-evaluated per dispatch, so the transport can become available later with no reconnect.\n   */\n  available?: (input: TTransportRouteParams) => boolean;\n  /** Short label for the devtools chip (defaults to \"link\"). */\n  label?: string;\n  getRouteInfo?: (input: TTransportRouteParams) => ITransportRouteInfo;\n  /**\n   * Wire keepalive (8b.3) resolver — a thunk so `connectChannel` can decide **at dial time**\n   * (protocols register on the mux after the connector is built; the auto-on default depends on\n   * them). Returns the concrete config, or `undefined` for off.\n   */\n  linkKeepalive?: () => import(\"@nice-code/wire\").IWireLinkKeepalive | undefined;\n  /** Wire-traffic observation (devtools) — threaded into every dial's session (survives redials). */\n  wireTap?: import(\"@nice-code/wire\").TWireTapFn;\n}\n\n/**\n * A carrier-agnostic transport: it drives nice-action's secure session + action routing over any\n * {@link IDuplexCarrier}. The WebSocket transport is the special case that opens a `WebSocket`;\n * this opens whatever `openChannel` returns, so the identical secure layer works over WebRTC, Bluetooth,\n * or an in-memory pipe. Reported with an overridable carrier label in the devtools (defaults to \"link\").\n */\nexport class LinkTransport extends Transport<ETransportShape.duplex> {\n  readonly type = ETransportShape.duplex;\n\n  constructor(private readonly options: ILinkTransportOptions) {\n    super();\n  }\n\n  static create(options: ILinkTransportOptions): LinkTransport {\n    return new LinkTransport(options);\n  }\n\n  _createConnection(ctx: ITransportConnectionContext): LinkConnection {\n    const options = this.options;\n\n    return new LinkConnection(\n      {\n        initialize: () => ({\n          getTransportCacheKey: options.getTransportCacheKey,\n          isAvailable: options.available,\n          getTransport: (input) => ({\n            status: ETransportStatus.ready,\n            readyData: {\n              channel: options.openChannel(input),\n              formatMessage: options.createFormatMessage?.() ?? options.formatMessage,\n              updateRunConfig: options.updateRunConfig,\n              secureChannel: options.security,\n              linkKeepalive: options.linkKeepalive?.(),\n              wireTap: options.wireTap,\n            },\n          }),\n        }),\n      },\n      ctx.resolvers,\n    );\n  }\n\n  getRouteInfo(input: TTransportRouteParams): ITransportRouteInfo {\n    if (this.options.getRouteInfo != null) return this.options.getRouteInfo(input);\n    return {\n      carrierLabel: this.options.label ?? \"link\",\n      summary: this.options.label ?? \"link\",\n    };\n  }\n}\n","import type { ClientCryptoKeyLink } from \"@nice-code/util\";\nimport type {\n  ESecurityLevel,\n  IClientVerifyKeyResolver,\n  IRuntimeCoordinate,\n  TServerDictionaryVersionResolver,\n} from \"@nice-code/wire\";\nimport {\n  type IWireExchangeLaneRequest,\n  type TWireExchangeLaneReply,\n  WireExchangeAcceptor,\n} from \"@nice-code/wire\";\nimport { EActionPayloadType } from \"../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { isActionPayload_Any_JsonObject } from \"../../../utils/isActionPayload_Any_JsonObject\";\nimport type { ActionRuntime } from \"../../ActionRuntime\";\nimport {\n  actionServeRequestInfo,\n  type IActionServeLogger,\n  serveResultErrorInfo,\n} from \"../../Channel/serveLogger\";\n\n/** Acceptor secure config for the exchange (HTTP) endpoint — same identity an `ChannelAcceptor` uses. */\nexport interface IExchangeAcceptorSecurity {\n  /** This acceptor's crypto identity (verify + exchange key pairs, optionally persisted). */\n  link: ClientCryptoKeyLink;\n  /** This acceptor's coordinate — its identity to clients during the handshake. */\n  localCoordinate: IRuntimeCoordinate;\n  /** Wire dictionary version — a fixed string (single channel), or a resolver composing it from the\n   * `hello.channels` tags (multi-channel). The handshake rejects on a mismatch / unknown channel. */\n  dictionaryVersion: string | TServerDictionaryVersionResolver;\n  /** Accepted level(s) — a single level is strict, an array is a negotiable allowed set. */\n  securityLevel: ESecurityLevel | readonly ESecurityLevel[];\n  /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */\n  verifyKeyResolver?: IClientVerifyKeyResolver;\n}\n\nexport interface IExchangeAcceptorConfig {\n  security: IExchangeAcceptorSecurity;\n  /** The runtime that executes an inbound action wire and produces its result. */\n  runtime: ActionRuntime;\n  /** Optional server-side logger — called per inbound action request with its outcome. */\n  logger?: IActionServeLogger;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (default `\"http\"`). */\n  transportLabel?: string;\n  /**\n   * How long a minted session ticket stays valid (ms). After it expires the client's next action is\n   * rejected and it must re-handshake. Defaults to 12h — long enough for an ordinary session's life,\n   * since a sealed ticket carries no server state to revoke before then. Keep it shorter for a more\n   * tightly time-boxed session.\n   */\n  sessionTtlMs?: number;\n}\n\n/**\n * The action lane over wire's {@link WireExchangeAcceptor} (shared-base-connect plan, Phase 6) —\n * the HTTP counterpart to `ChannelAcceptor` composing on `WireAcceptor`. Wire owns the exchange\n * mechanics: the envelope, the server handshake over the two `hs` POSTs, the sealed `hsc`/`t`\n * tokens that make the whole endpoint **stateless** across isolates, and the per-session frame\n * crypto. What stays here is the lane: validating the opened wire as an action payload, binding\n * the handshake-authenticated identity onto it (never the wire's self-asserted one), routing it\n * through the runtime, logging, and returning the result wire for the same response.\n *\n * The public config is unchanged by the split — `dictionaryVersion` remains on\n * {@link IExchangeAcceptorSecurity} (it is the lane's own handshake payload, E5); internally it\n * feeds wire's exchange lane while the neutral core feeds wire's security block, mirroring how\n * `ChannelAcceptor` splits its `IAcceptorSecurity`.\n */\nexport class ExchangeAcceptor {\n  private readonly _core: WireExchangeAcceptor;\n  private readonly _runtime: ActionRuntime;\n  private readonly _logger?: IActionServeLogger;\n  private readonly _transportLabel: string;\n\n  constructor(config: IExchangeAcceptorConfig) {\n    this._runtime = config.runtime;\n    this._logger = config.logger;\n    this._transportLabel = config.transportLabel ?? \"http\";\n    this._core = new WireExchangeAcceptor({\n      security: {\n        securityLevel: config.security.securityLevel,\n        link: config.security.link,\n        localCoordinate: config.security.localCoordinate,\n        verifyKeyResolver: config.security.verifyKeyResolver,\n      },\n      lane: {\n        dictionaryVersion: config.security.dictionaryVersion,\n        onExchange: (request) => this._onExchange(request),\n      },\n      sessionTtlMs: config.sessionTtlMs,\n    });\n  }\n\n  /** Process one POST body (an exchange envelope), returning the reply body to send back. */\n  handlePost(body: string): Promise<string> {\n    return this._core.handlePost(body);\n  }\n\n  /** Serve one opened `act` wire: validate → bind identity → log → run → return the result wire. */\n  private async _onExchange(request: IWireExchangeLaneRequest): Promise<TWireExchangeLaneReply> {\n    if (!isActionPayload_Any_JsonObject(request.wire)) {\n      return { ok: false, message: \"malformed action wire\" };\n    }\n    const wire = request.wire;\n    const client = request.client;\n\n    // Bind the *authenticated* identity (never the wire's self-asserted one) so the action runs as the\n    // handshake-verified client.\n    if (client != null && wire.type === EActionPayloadType.request) {\n      wire.context.originClient = client.toJsonObject();\n    }\n\n    // Log the request (basic action/transport/origin facts) before executing, and report the outcome once\n    // the result is back — the reply rides this same response, so it returned over the same transport.\n    const report =\n      this._logger != null && wire.type === EActionPayloadType.request\n        ? this._logger.onRequest(\n            actionServeRequestInfo(wire, {\n              transport: this._transportLabel,\n              securityLevel: request.securityLevel,\n              origin: client?.stringId,\n            }),\n          )\n        : undefined;\n    const startedAt = Date.now();\n\n    const running = await this._runtime.handleActionPayloadWire(wire);\n    const result = await running.waitForResultPayload();\n    const resultWire = result.toJsonObject();\n\n    if (report != null) {\n      const returnedVia = request.encrypted\n        ? `${this._transportLabel} (encrypted)`\n        : this._transportLabel;\n      report(\n        result.result.ok\n          ? { ok: true, returnedVia, durationMs: Date.now() - startedAt }\n          : {\n              ok: false,\n              returnedVia,\n              durationMs: Date.now() - startedAt,\n              error: serveResultErrorInfo(result.result.error),\n            },\n      );\n    }\n\n    return { ok: true, wire: resultWire };\n  }\n}\n","import { NiceError } from \"@nice-code/error\";\nimport { EActionPayloadType } from \"../../../../ActionDefinition/Action/Payload/ActionPayload.types\";\nimport { EErrId_NiceAction } from \"../../../../errors/err_nice_action\";\nimport { isActionPayload_Any_JsonObject } from \"../../../../utils/isActionPayload_Any_JsonObject\";\nimport type { ActionRuntime } from \"../../../ActionRuntime\";\nimport {\n  actionServeRequestInfo,\n  type IActionServeLogger,\n  serveResultErrorInfo,\n} from \"../../../Channel/serveLogger\";\nimport {\n  ExchangeAcceptor,\n  type IExchangeAcceptorSecurity,\n} from \"../../../Transport/SecureSession/exchangeAcceptor\";\n\n/** Permissive defaults — fine for a public action endpoint; override (or disable) via `cors`. */\nconst DEFAULT_CORS_HEADERS: Record<string, string> = {\n  \"Access-Control-Allow-Origin\": \"*\",\n  \"Access-Control-Allow-Methods\": \"GET, POST, OPTIONS\",\n  \"Access-Control-Allow-Headers\": \"Content-Type\",\n  \"Access-Control-Max-Age\": \"86400\",\n};\n\nexport interface IActionFetchHandlerOptions {\n  /**\n   * CORS headers merged onto every response (a preflight `OPTIONS` is answered `204` with them).\n   * Defaults to permissive `*`; pass `false` to attach no CORS headers at all.\n   */\n  cors?: Record<string, string> | false;\n  /** Which requests carry an action wire on `POST`. Default: pathname ends with `/action`. */\n  isActionPath?: (url: URL) => boolean;\n  /** Which requests are WebSocket upgrades. Default: pathname ends with `/ws`. */\n  isWebSocketPath?: (url: URL) => boolean;\n  /**\n   * Whether a request is a WebSocket upgrade for this endpoint, given the whole request (not just the\n   * URL). When set it *replaces* the default gate (an `Upgrade: websocket` header on an\n   * {@link isWebSocketPath} match) — use it when the discriminant needs a header or method, not only the\n   * path. Only consulted when {@link onWebSocketUpgrade} is present.\n   */\n  isWebSocketUpgrade?: (request: Request, url: URL) => boolean;\n  /**\n   * Perform the transport-specific WebSocket upgrade (e.g. a Durable Object's\n   * `new WebSocketPair()` + `ctx.acceptWebSocket()` returning a `101`). Omit for HTTP-only endpoints.\n   * Its response is returned as-is — a `101` upgrade carries no CORS headers.\n   */\n  onWebSocketUpgrade?: (request: Request, url: URL) => Response | Promise<Response>;\n  /** Forwarded to `ActionPayload_Result.toHttpResponse` — use the error's HTTP status (default true). */\n  useErrorStatus?: boolean;\n  /**\n   * Enable the secure exchange protocol (handshake + token sessions + body encryption) on the `/action`\n   * endpoint, mirroring an `ChannelAcceptor`'s `security`. The matching connector is a secure HTTP\n   * transport (`connectChannel(..., { transports: [{ carrier: httpCarrier(...) }] })`). When omitted, the\n   * endpoint speaks the plain protocol (the raw action wire is POSTed and the result is the response body).\n   */\n  security?: IExchangeAcceptorSecurity;\n  /**\n   * Optional server-side logger — called per inbound action request with its outcome. Threaded into the\n   * secure {@link ExchangeAcceptor} and used directly on the plain action POST, so both endpoint styles log.\n   */\n  logger?: IActionServeLogger;\n  /** Short carrier-kind label surfaced to the logger as the request's transport (default `\"http\"`). */\n  transportLabel?: string;\n}\n\n/**\n * Build the `fetch` handler a server/Durable-Object exposes for action traffic, folding in the\n * boilerplate every endpoint repeats: CORS (incl. the `OPTIONS` preflight), routing the `/action`\n * `POST` body through the runtime (`handleActionPayloadWire` → `waitForResultPayload` →\n * `toHttpResponse`), an optional WebSocket-upgrade hook, and a `404` fallback.\n *\n * It only touches web-standard `Request`/`Response`, so it stays transport-agnostic — the one\n * environment-specific bit (the WS upgrade) is injected via {@link IActionFetchHandlerOptions.onWebSocketUpgrade}:\n * ```ts\n * this.fetchHandler = createActionFetchHandler(this.runtime, {\n *   onWebSocketUpgrade: () => {\n *     const pair = new WebSocketPair();\n *     this.ctx.acceptWebSocket(pair[1]);\n *     return new Response(null, { status: 101, webSocket: pair[0] });\n *   },\n * });\n * // async fetch(request) { return this.fetchHandler(request); }\n * ```\n */\nexport function createActionFetchHandler(\n  runtime: ActionRuntime,\n  options: IActionFetchHandlerOptions = {},\n): (request: Request) => Promise<Response> {\n  const corsHeaders = options.cors === false ? {} : (options.cors ?? DEFAULT_CORS_HEADERS);\n  const isActionPath = options.isActionPath ?? ((url) => url.pathname.endsWith(\"/action\"));\n  const isWebSocketPath = options.isWebSocketPath ?? ((url) => url.pathname.endsWith(\"/ws\"));\n  const transportLabel = options.transportLabel ?? \"http\";\n  const exchangeAcceptor =\n    options.security != null\n      ? new ExchangeAcceptor({\n          runtime,\n          security: options.security,\n          logger: options.logger,\n          transportLabel,\n        })\n      : undefined;\n\n  const withCors = (response: Response): Response => {\n    if (options.cors === false) return response;\n    const headers = new Headers(response.headers);\n    for (const [key, value] of Object.entries(corsHeaders)) headers.set(key, value);\n    return new Response(response.body, { status: response.status, headers });\n  };\n\n  const badRequest = (message: string): Response =>\n    new Response(JSON.stringify({ error: message }), {\n      status: 400,\n      headers: { \"Content-Type\": \"application/json\" },\n    });\n\n  return async (request: Request): Promise<Response> => {\n    if (request.method === \"OPTIONS\") {\n      return withCors(new Response(null, { status: 204 }));\n    }\n\n    const url = new URL(request.url);\n\n    const isWebSocketUpgrade =\n      options.isWebSocketUpgrade ??\n      ((req: Request, u: URL) => req.headers.get(\"Upgrade\") === \"websocket\" && isWebSocketPath(u));\n\n    if (options.onWebSocketUpgrade != null && isWebSocketUpgrade(request, url)) {\n      return options.onWebSocketUpgrade(request, url);\n    }\n\n    if (request.method === \"POST\" && isActionPath(url)) {\n      // Secure exchange: the body is a protocol envelope (handshake or tokened/encrypted action); the\n      // acceptor drives the handshake + token session and returns the reply envelope inline.\n      if (exchangeAcceptor != null) {\n        const reply = await exchangeAcceptor.handlePost(await request.text());\n        return withCors(\n          new Response(reply, { status: 200, headers: { \"Content-Type\": \"application/json\" } }),\n        );\n      }\n\n      // Plain endpoint: the raw action wire is the POST body and the result is the response. Log the\n      // request up front (when it is a request wire) and report the outcome — the result rides this same\n      // response, so it returned over the same transport.\n      let body: unknown;\n      try {\n        body = await request.json();\n      } catch {\n        // Not JSON at all (scanners, stale tabs, corrupt clients) — a client problem, not a crash.\n        return withCors(badRequest(\"request body is not valid JSON\"));\n      }\n      const report =\n        options.logger != null &&\n        isActionPayload_Any_JsonObject(body) &&\n        body.type === EActionPayloadType.request\n          ? options.logger.onRequest(actionServeRequestInfo(body, { transport: transportLabel }))\n          : undefined;\n      const startedAt = Date.now();\n\n      let running: Awaited<ReturnType<ActionRuntime[\"handleActionPayloadWire\"]>>;\n      try {\n        running = await runtime.handleActionPayloadWire(body);\n      } catch (error) {\n        // Garbage that parsed as JSON but is not an action wire: answer a clean 400 instead of\n        // letting the NiceError escape as an uncaught exception + raw 500. Anything else is a\n        // genuine server-side failure and still propagates.\n        if (\n          error instanceof NiceError &&\n          error\n            .getIds()\n            .some(\n              (id) =>\n                id === EErrId_NiceAction.wire_not_action_data ||\n                id === EErrId_NiceAction.wire_action_not_payload,\n            )\n        ) {\n          report?.({\n            ok: false,\n            returnedVia: transportLabel,\n            durationMs: Date.now() - startedAt,\n            error: serveResultErrorInfo(error),\n          });\n          return withCors(badRequest(error.message));\n        }\n        throw error;\n      }\n      const result = await running.waitForResultPayload();\n\n      report?.(\n        result.result.ok\n          ? { ok: true, returnedVia: transportLabel, durationMs: Date.now() - startedAt }\n          : {\n              ok: false,\n              returnedVia: transportLabel,\n              durationMs: Date.now() - startedAt,\n              error: serveResultErrorInfo(result.result.error),\n            },\n      );\n      return withCors(result.toHttpResponse({ useErrorStatus: options.useErrorStatus }));\n    }\n\n    return withCors(new Response(\"Not found\", { status: 404 }));\n  };\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ChannelAcceptor, IAcceptorConnectionBinding } from \"../ChannelAcceptor\";\n\n/**\n * The composite value persisted to a connection's attachment: the consumer's own app state plus the\n * {@link ChannelAcceptor} routing binding. Co-storing them in one slot means a transport whose\n * sockets outlive process eviction (e.g. a Durable Object's hibernatable WebSocket) recovers both the\n * application identity *and* the action routing from a single attachment after a wake — no storage reads.\n */\nexport interface IConnectionAttachment<TApp> {\n  app?: TApp;\n  binding?: IAcceptorConnectionBinding;\n}\n\nexport interface IConnectionStateStoreOptions<TConn, TApp> {\n  /** Read a connection's raw attachment (e.g. `(ws) => ws.deserializeAttachment()`). */\n  read: (connection: TConn) => unknown;\n  /** Persist a connection's attachment (e.g. `(ws, value) => ws.serializeAttachment(value)`). */\n  write: (connection: TConn, value: IConnectionAttachment<TApp>) => void;\n  /**\n   * All currently-live connections (e.g. `() => ctx.getWebSockets()`). Used to replay routing bindings\n   * after a wake (via {@link createConnectionStateStore}) and to enumerate app state in\n   * {@link ConnectionStateStore.entries}.\n   */\n  getConnections: () => TConn[];\n  /**\n   * Optional Standard Schema (valibot, zod, …) validating the *app* portion on read. A value that\n   * fails validation reads back as `null` — the same lenient behavior as a hand-written safeParse\n   * helper. The binding is the library's own shape and is never validated.\n   */\n  schema?: StandardSchemaV1<unknown, TApp>;\n}\n\n/**\n * A typed per-connection state store that co-owns the app state and the acceptor handler's routing\n * binding in one attachment, so neither the consumer nor the handler has to hand-merge the two. Create\n * it through {@link createConnectionStateStore} (which also wires binding persistence and replays\n * surviving connections after a wake), then `get`/`set`/`clearApp` the app state directly.\n *\n * The mechanism is carrier-neutral — it only needs read/write/enumerate callbacks for the connection's\n * attachment — but it pays off on transports whose connections outlive process eviction (e.g. a\n * Durable Object's hibernatable WebSockets), which is why it lives beside the hibernation adapter.\n *\n * ```ts\n * const players = createConnectionStateStore(serverHandler, {\n *   schema: vs_player,\n *   read: (ws) => ws.deserializeAttachment(),\n *   write: (ws, v) => ws.serializeAttachment(v),\n *   getConnections: () => ctx.getWebSockets(),\n * });\n * players.set(ws, player); // binding is preserved automatically\n * const player = players.get(ws);\n * ```\n */\nexport class ConnectionStateStore<TConn, TApp> {\n  constructor(private readonly options: IConnectionStateStoreOptions<TConn, TApp>) {}\n\n  /** The validated app state for a connection, or `null` if unset / invalid. */\n  get(connection: TConn): TApp | null {\n    return this._readAttachment(connection).app ?? null;\n  }\n\n  /** Set the app state, preserving the runtime binding already pinned to the connection. */\n  set(connection: TConn, app: TApp): void {\n    const existing = this._readAttachment(connection);\n    this.options.write(connection, { app, binding: existing.binding });\n  }\n\n  /** Clear the app state but keep the binding (e.g. a spectator that stopped watching). */\n  clearApp(connection: TConn): void {\n    const existing = this._readAttachment(connection);\n    this.options.write(connection, { binding: existing.binding });\n  }\n\n  /** Every live connection paired with its (validated) app state — for rebuilding in-memory state after a wake. */\n  entries(): [TConn, TApp | null][] {\n    return this.options\n      .getConnections()\n      .map((connection) => [connection, this._readAttachment(connection).app ?? null]);\n  }\n\n  /** @internal Persist a freshly-bound connection's binding, preserving any app state already stored. */\n  _persistBinding(connection: TConn, binding: IAcceptorConnectionBinding): void {\n    const existing = this._readAttachment(connection);\n    this.options.write(connection, { app: existing.app, binding });\n  }\n\n  /** @internal The persisted binding for a connection, if any (used to replay routing after a wake). */\n  _readBinding(connection: TConn): IAcceptorConnectionBinding | undefined {\n    return this._readAttachment(connection).binding;\n  }\n\n  private _readAttachment(connection: TConn): IConnectionAttachment<TApp> {\n    try {\n      const raw = this.options.read(connection);\n      if (typeof raw !== \"object\" || raw === null) return {};\n\n      const attachment = raw as IConnectionAttachment<TApp>;\n      const result: IConnectionAttachment<TApp> = {};\n      // The binding is our own serialized shape — trust it as written.\n      if (attachment.binding != null) result.binding = attachment.binding;\n      if (attachment.app !== undefined) {\n        const app = this._validateApp(attachment.app);\n        if (app !== undefined) result.app = app;\n      }\n      return result;\n    } catch {\n      return {};\n    }\n  }\n\n  private _validateApp(value: unknown): TApp | undefined {\n    const schema = this.options.schema;\n    if (schema == null) return value as TApp;\n    const result = schema[\"~standard\"].validate(value);\n    // App state is validated on a synchronous read path; an async schema can't be honored here.\n    if (result instanceof Promise) return undefined;\n    if (result.issues != null) return undefined;\n    return result.value;\n  }\n}\n\n/**\n * Build a per-connection {@link ConnectionStateStore} bound to an {@link ChannelAcceptor}: it registers\n * itself as the handler's connection-bound persistence callback (so bindings are written without\n * overwriting app state) and immediately replays every live connection's stored binding via\n * {@link ChannelAcceptor.rehydrate} — so on a transport that resumes after eviction (e.g. a\n * Durable Object waking from hibernation) both the app identity and the action routing come back from a\n * single attachment, with no storage reads and no hand-rolled merge.\n *\n * Lives outside the handler so the generic {@link ChannelAcceptor} stays free of any attachment/\n * hibernation concern — it exposes only the neutral `setOnConnectionBound` + `rehydrate`\n * hooks this builder drives.\n */\nexport function createConnectionStateStore<TConn, TApp>(\n  handler: ChannelAcceptor<TConn>,\n  options: IConnectionStateStoreOptions<TConn, TApp>,\n): ConnectionStateStore<TConn, TApp> {\n  const store = new ConnectionStateStore<TConn, TApp>(options);\n  handler.setOnConnectionBound((connection, binding) => store._persistBinding(connection, binding));\n\n  // Rebuild routing for sockets that survived an eviction.\n  for (const connection of options.getConnections()) {\n    const binding = store._readBinding(connection);\n    if (binding != null) handler.rehydrate(connection, binding);\n  }\n\n  return store;\n}\n","import type { ChannelAcceptor, IAcceptorConnectionBinding } from \"../ChannelAcceptor\";\n\nexport interface IHibernatableWsServerAdapterOptions<TConn> {\n  /** The handler to drive (from `createSecureChannelAcceptor` or `createChannelAcceptor`). */\n  handler: ChannelAcceptor<TConn>;\n  /** All currently-live connections — replayed on construction to rebuild bindings after a wake. */\n  getConnections: () => TConn[];\n  /** Read a connection's persisted binding (e.g. `(ws) => ws.deserializeAttachment()`). */\n  getAttachment: (connection: TConn) => IAcceptorConnectionBinding | undefined;\n  /** Persist a connection's binding when it is bound (e.g. `(ws, b) => ws.serializeAttachment(b)`). */\n  setAttachment: (connection: TConn, binding: IAcceptorConnectionBinding) => void;\n}\n\n/**\n * The neutral lifecycle surface for a duplex (push-capable) acceptor: feed it each inbound frame and tell\n * it when a connection goes away. Carrier-agnostic — a WebSocket, a WebRTC data channel, or any other\n * duplex connection drives the same two methods.\n */\nexport interface IDuplexConnectionRouter<TConn> {\n  /** Feed one inbound frame from a connection into the handler. */\n  receive: (connection: TConn, frame: string | ArrayBuffer | Uint8Array) => void;\n  /** Forget a connection (call on socket close/error). */\n  drop: (connection: TConn) => void;\n}\n\n/**\n * Wire the hibernation lifecycle for an acceptor handler on a transport whose connections outlive process\n * eviction (e.g. a Durable Object's hibernatable WebSockets). It owns persistence end to end:\n * registers `setAttachment` as the handler's connection-bound callback and immediately replays every\n * live connection's stored binding via `getAttachment`, so results/pushes still route after a wake.\n *\n * Layered on top of the generic {@link ChannelAcceptor} — it touches only the handler's neutral\n * `setOnConnectionBound` / `rehydrate` / `receive` / `drop` surface, so no\n * hibernation concern leaks into the handler itself.\n *\n * Construct it once when the handler is built, then forward connection events:\n * ```ts\n * const duplex = createHibernatableWsServerAdapter({ handler, getConnections, getAttachment, setAttachment });\n * // webSocketMessage(ws, msg) => duplex.receive(ws, msg);\n * // webSocketClose/Error(ws)  => duplex.drop(ws);\n * ```\n */\nexport function createHibernatableWsServerAdapter<TConn>(\n  options: IHibernatableWsServerAdapterOptions<TConn>,\n): IDuplexConnectionRouter<TConn> {\n  const { handler, getConnections, getAttachment, setAttachment } = options;\n\n  handler.setOnConnectionBound(setAttachment);\n\n  // Rebuild bindings for connections that survived an eviction.\n  for (const connection of getConnections()) {\n    const binding = getAttachment(connection);\n    if (binding != null) handler.rehydrate(connection, binding);\n  }\n\n  return {\n    receive: (connection, frame) => handler.receive(connection, frame),\n    drop: (connection) => handler.drop(connection),\n  };\n}\n"],"mappings":";;;;;;;;;AAIA,IAAsB,aAAtB,MAKA;CAMa;CACA;CACA;CAPX;CACA;CACA;CAEA,YACE,MACA,SACA,IACA;EAHS,KAAA,OAAA;EACA,KAAA,UAAA;EACA,KAAA,KAAA;EAET,KAAK,SAAS,QAAQ;EACtB,KAAK,aAAa,QAAQ;EAC1B,KAAK,SAAS,QAAQ,aAAa;CACrC;CAEA,eAAgE;EAC9D,OAAO;GACL,MAAM,KAAK;GACX,QAAQ,KAAK;GACb,YAAY,KAAK;GACjB,IAAI,KAAK;EACX;CACF;CAEA,eAAiC;EAC/B,OAAO,KAAK,UAAU,KAAK,aAAa,CAAC;CAC3C;AACF;;;ACzBA,IAAsB,gBAAtB,cA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