{"version":3,"file":"isolation-CO0NiK8R.mjs","names":["#port","#hooks","#pending","#streams","#outbox","#hostcallHandlers","#hostcallQuotas","#maxHostcallBytes","#unsubscribe","#onMessage","#ready","#send","#dispatchHostcall","#terminated","#sendOrQueue","#acceptedHostcalls","#concurrentHostcalls","#callAborts","#streamAborts","#hostcalls","#e","#t"],"sources":["../src/batteries/isolation/types.ts","../src/batteries/isolation/exceptions.ts","../src/batteries/isolation/validation.ts","../src/batteries/isolation/protocol.ts","../node_modules/.pnpm/neotraverse@0.6.18/node_modules/neotraverse/dist/modern/min/modern.js","../src/batteries/isolation/codec.ts","../src/batteries/isolation/crash_policy.ts","../src/batteries/isolation/observability.ts","../src/batteries/isolation/serve.ts","../src/batteries/isolation/host.ts","../src/batteries/isolation/browser.ts","../src/batteries/isolation/isolate_function.ts"],"sourcesContent":["/**\n * Spec DSL + mapped facade/implementation types for the isolation battery.\n *\n * @remarks\n * This module has **zero imports** — not even a type-only import from `@nhtio/adk` core\n * (CONTRIBUTING.md Design Decision #13, tier 2: locally-declared structural duck-types). A caller\n * describes an isolated service once, with {@link defineIsolatedService}, and gets back a spec object\n * that:\n *\n * - the HOST side maps to an {@link IsolatedFacade} (a plain object of promise-returning methods +\n *   stream-returning functions) via `createIsolatedService` (see `host.ts`);\n * - the GUEST side maps to an {@link IsolatedImplementation} the caller must provide via `serveIsolated`\n *   (see `serve.ts`).\n *\n * The descriptor factories ({@link method}, {@link stream}, {@link event}) are phantom-typed: at\n * runtime they return a small plain object carrying only the declared runtime options (`signal`,\n * `codec`); the `A`/`R`/`D`/`P` type parameters never materialize as runtime values — they exist purely\n * so the mapped types below can recover the exact argument/return/delta/payload shapes from a spec\n * object's inferred type.\n */\n\n/**\n * Serialization strategy for a single method/stream call's arguments — see `codec.ts` for the tiered\n * codec this selects. `'auto'` (the default when omitted) traverses each argument and escalates only\n * the exotic leaves it finds; `'raw'` skips traversal entirely (trust the caller — cheapest, but unsafe\n * for values containing functions/Errors/custom-encodables); `'encoded'` whole-value encodes every\n * argument via the optional `@nhtio/encoder` peer. A caller may also inject a literal `{ encode, decode\n * }` pair to bring their own codec, bypassing both the traversal and the encoder peer entirely.\n */\nexport type CodecMode =\n  | 'auto'\n  | 'raw'\n  | 'encoded'\n  | {\n      /** Serialize a single value to a wire-safe string. May be sync or async. */\n      encode: (value: unknown) => string | Promise<string>\n      /** Reconstruct a value from a string produced by this codec's `encode`. May be sync or async. */\n      decode: (encoded: string) => unknown | Promise<unknown>\n    }\n\n/** Runtime options accepted by {@link method}. */\nexport interface MethodOptions {\n  /**\n   * When `true`, the facade's generated method accepts a trailing `AbortSignal` and the guest\n   * implementation receives a trailing {@link IsolationCallContext} carrying that signal. When\n   * omitted/`false`, a trailing signal argument is still accepted on the facade (for call-site\n   * uniformity) but is not forwarded anywhere meaningful — the implementation is never given a context\n   * parameter.\n   */\n  signal?: boolean\n  /** Override the codec tier for this method's arguments and return value. Default: `'auto'`. */\n  codec?: CodecMode\n}\n\n/** Runtime options accepted by {@link stream}. */\nexport interface StreamOptions {\n  /** Override the codec tier for this stream's arguments and deltas. Default: `'auto'`. */\n  codec?: CodecMode\n}\n\n/**\n * A method descriptor produced by {@link method}. Carries the declared runtime options plus phantom\n * (never-constructed) fields that pin down the argument tuple and return type for the mapped types\n * below — reading `descriptor.__args`/`descriptor.__result` at the TYPE level only, never at runtime.\n */\nexport interface MethodDescriptor<\n  A extends unknown[] = unknown[],\n  R = unknown,\n> extends MethodOptions {\n  /** Discriminant identifying this descriptor as a method (vs. a stream or event). */\n  readonly kind: 'method'\n  /** Phantom-only: never assigned a real value. Pins the argument tuple type. */\n  readonly __args?: A\n  /** Phantom-only: never assigned a real value. Pins the resolved result type. */\n  readonly __result?: R\n}\n\n/** A stream descriptor produced by {@link stream}. Phantom-typed like {@link MethodDescriptor}. */\nexport interface StreamDescriptor<\n  A extends unknown[] = unknown[],\n  D = unknown,\n> extends StreamOptions {\n  /** Discriminant identifying this descriptor as a stream (vs. a method or event). */\n  readonly kind: 'stream'\n  /** Phantom-only: never assigned a real value. Pins the argument tuple type. */\n  readonly __args?: A\n  /** Phantom-only: never assigned a real value. Pins the per-chunk delta type. */\n  readonly __delta?: D\n}\n\n/** An event descriptor produced by {@link event}. Phantom-typed like {@link MethodDescriptor}. */\nexport interface EventDescriptor<P = unknown> {\n  /** Discriminant identifying this descriptor as an event (vs. a method or stream). */\n  readonly kind: 'event'\n  /** Phantom-only: never assigned a real value. Pins the event payload type. */\n  readonly __payload?: P\n}\n\n/**\n * Declare a request/response method on an isolated service's spec — the host gets a\n * `(...args) => Promise<R>` facade method; the guest implementation returns (or resolves to) `R`\n * directly (or throws/rejects, crossing back as a rejected promise on the host).\n *\n * @typeParam A - The method's argument tuple, e.g. `[MyArgs]` or `[string, number]`.\n * @typeParam R - The method's resolved result type.\n * @param opts - See {@link MethodOptions}. `opts.signal` opts this method into abort-signal plumbing.\n */\nexport const method = <A extends unknown[], R>(\n  opts: MethodOptions = {}\n): MethodDescriptor<A, R> => ({\n  kind: 'method',\n  signal: opts.signal,\n  codec: opts.codec,\n})\n\n/**\n * Declare a fire-and-forward streaming method on an isolated service's spec — the host gets a\n * `(...args) => ReadableStream<D>` facade method (synchronous: the stream is returned immediately, fed\n * by deltas as they cross the wire); the guest implementation returns (or is called to produce) a\n * `ReadableStream<D>` or `AsyncIterable<D>`.\n *\n * @typeParam A - The stream's argument tuple.\n * @typeParam D - The type of each streamed delta/chunk.\n * @param opts - See {@link StreamOptions}.\n */\nexport const stream = <A extends unknown[], D>(\n  opts: StreamOptions = {}\n): StreamDescriptor<A, D> => ({\n  kind: 'stream',\n  codec: opts.codec,\n})\n\n/**\n * Declare an unsolicited event channel on an isolated service's spec — the guest-side implementation\n * factory receives an `emit(payload)` function for this channel; the host subscribes via\n * `service.on(channel, fn)`. Events are never implemented by the guest's per-method object (there is no\n * \"handler\" to provide) — they are purely an outbound notification channel.\n *\n * @typeParam P - The event payload type.\n */\nexport const event = <P>(): EventDescriptor<P> => ({ kind: 'event' })\n\n/** The shape of a `methods` map passed to {@link defineIsolatedService}: request/response descriptors\n *  keyed by method name. */\nexport type MethodMap = Record<string, MethodDescriptor<unknown[], unknown>>\n/** The shape of a `streams` map passed to {@link defineIsolatedService}: fire-and-forward streaming\n *  descriptors keyed by stream name. */\nexport type StreamMap = Record<string, StreamDescriptor<unknown[], unknown>>\n/** The shape of an `events` map passed to {@link defineIsolatedService}: unsolicited-notification\n *  descriptors keyed by channel name. */\nexport type EventMap = Record<string, EventDescriptor<unknown>>\n\n/** Input shape accepted by {@link defineIsolatedService}. */\nexport interface IsolatedServiceSpecInput<\n  M extends MethodMap = MethodMap,\n  S extends StreamMap = StreamMap,\n  E extends EventMap = EventMap,\n> {\n  /** Used in error messages and observability reports to identify this service. */\n  name: string\n  /** Request/response methods, keyed by name. Default `{}`. */\n  methods?: M\n  /** Fire-and-forward streaming methods, keyed by name. Default `{}`. */\n  streams?: S\n  /** Unsolicited event channels, keyed by name. Default `{}`. */\n  events?: E\n}\n\n/**\n * A fully-resolved isolated-service spec, as returned by {@link defineIsolatedService}. Consumed by\n * both `createIsolatedService` (host.ts) and `serveIsolated` (serve.ts) to type-check the facade /\n * implementation respectively, and read at runtime for wire validation (method/stream/event name\n * lookups).\n */\nexport interface IsolatedServiceSpec<\n  M extends MethodMap = MethodMap,\n  S extends StreamMap = StreamMap,\n  E extends EventMap = EventMap,\n> {\n  /** Identifies this service in error messages and observability reports. */\n  readonly name: string\n  /** Request/response method descriptors, keyed by name. */\n  readonly methods: M\n  /** Fire-and-forward streaming descriptors, keyed by name. */\n  readonly streams: S\n  /** Unsolicited event-channel descriptors, keyed by name. */\n  readonly events: E\n}\n\n/**\n * Resolve an isolated-service spec input into its final {@link IsolatedServiceSpec} shape — filling in\n * `{}` defaults for omitted `methods`/`streams`/`events`. Pure and zero-import: performs NO validation\n * (no duplicate-name check, no empty-`name` check). This is the primitive the public,\n * validating `defineIsolatedService` (exported from `validation.ts` and re-exported from this\n * battery's `index.ts` barrel) delegates to after it validates the input — call this directly only\n * from tests that intentionally want to bypass validation.\n */\nexport const resolveIsolatedServiceSpec = <\n  M extends MethodMap = Record<never, never>,\n  S extends StreamMap = Record<never, never>,\n  E extends EventMap = Record<never, never>,\n>(\n  input: IsolatedServiceSpecInput<M, S, E>\n): IsolatedServiceSpec<M, S, E> => ({\n  name: input.name,\n  methods: (input.methods ?? {}) as M,\n  streams: (input.streams ?? {}) as S,\n  events: (input.events ?? {}) as E,\n})\n\n// ── Call context / stream handle (guest-side) ───────────────────────────────────────────────────────\n\n/**\n * Trailing parameter a guest method implementation receives when its descriptor declared\n * `{ signal: true }`. Carries the {@link AbortSignal} the host aborts to cancel this in-flight call.\n */\nexport interface IsolationCallContext {\n  /** Aborts when the host sends an `abort` envelope for this call's id. */\n  signal: AbortSignal\n}\n\n/**\n * Trailing parameter every guest stream implementation receives (regardless of declared options).\n * Carries the {@link AbortSignal} the host aborts (via `stream:cancel`) when the reader cancels the\n * host-side `ReadableStream`.\n */\nexport interface StreamHandle {\n  /** Aborts when the host sends a `stream:cancel` envelope for this stream's id. */\n  signal: AbortSignal\n}\n\n// ── Mapped facade / implementation types ────────────────────────────────────────────────────────────\n\n/** Recover a method descriptor's argument tuple type. */\ntype MethodArgs<D> = D extends MethodDescriptor<infer A, unknown> ? A : never\n/** Recover a method descriptor's result type. */\ntype MethodResult<D> = D extends MethodDescriptor<unknown[], infer R> ? R : never\n/** Recover a stream descriptor's argument tuple type. */\ntype StreamArgs<D> = D extends StreamDescriptor<infer A, unknown> ? A : never\n/** Recover a stream descriptor's delta type. */\ntype StreamDelta<D> = D extends StreamDescriptor<unknown[], infer Dl> ? Dl : never\n/** Recover an event descriptor's payload type. */\ntype EventPayload<D> = D extends EventDescriptor<infer P> ? P : never\n\n/**\n * The host-side callable facade a {@link IsolatedServiceSpec} maps to — `.api` on the\n * `IsolatedService` returned by `createIsolatedService`. Every declared method becomes an async\n * function returning `Promise<R>` and accepting an optional trailing `AbortSignal` (accepted uniformly\n * regardless of whether the method declared `{ signal: true }` — a signal handed to a method that\n * didn't opt in is simply not forwarded to the guest). Every declared stream becomes a synchronous\n * function returning a `ReadableStream<D>` immediately.\n */\nexport type IsolatedFacade<S extends IsolatedServiceSpec> = {\n  [K in keyof S['methods']]: (\n    ...args: [...MethodArgs<S['methods'][K]>, signal?: AbortSignal]\n  ) => Promise<MethodResult<S['methods'][K]>>\n} & {\n  [K in keyof S['streams']]: (\n    ...args: StreamArgs<S['streams'][K]>\n  ) => ReadableStream<StreamDelta<S['streams'][K]>>\n}\n\n/**\n * The guest-side implementation object a caller of `serveIsolated` must provide — one function per\n * declared method/stream. Method implementations may return their result synchronously or as a\n * `Promise`. Every method implementation accepts an optional trailing {@link IsolationCallContext}\n * uniformly (a deliberate typing simplification — see remarks below); at RUNTIME a context is only ever\n * constructed and passed when the method descriptor declared `{ signal: true }`, so an implementation\n * that ignores the parameter for a non-`signal` method simply never receives one. Stream implementations\n * may return a `ReadableStream<D>` or any `AsyncIterable<D>` (e.g. an async generator), and always\n * receive a trailing {@link StreamHandle}. Declared `events` are NOT part of this object — see\n * `serveIsolated`'s factory `emit` parameter.\n *\n * @remarks\n * Conditioning the trailing parameter's presence on `S['methods'][K] extends { signal: true }` at the\n * type level runs into a genuine TypeScript inference gap: the `method<A, R>({ signal: true })` factory\n * can't carry `signal`'s literal-`true` value through to the mapped type without the descriptor's\n * optional `signal?: boolean` property widening back to `boolean` (or `true | undefined`) well before the\n * conditional type gets to test it, making the `extends { signal: true }` branch either never trigger or\n * trigger unconditionally. Rather than reach for `const`-generic phantom-typing surgery to fight that,\n * this mapped type intentionally accepts the simpler, slightly-less-precise contract: the trailing\n * context is always optionally typed, regardless of the descriptor's declared `signal` option.\n */\nexport type IsolatedImplementation<S extends IsolatedServiceSpec> = {\n  [K in keyof S['methods']]: (\n    ...args: [...MethodArgs<S['methods'][K]>, ctx?: IsolationCallContext]\n  ) => MethodResult<S['methods'][K]> | Promise<MethodResult<S['methods'][K]>>\n} & {\n  [K in keyof S['streams']]: (\n    ...args: [...StreamArgs<S['streams'][K]>, handle: StreamHandle]\n  ) => ReadableStream<StreamDelta<S['streams'][K]>> | AsyncIterable<StreamDelta<S['streams'][K]>>\n}\n\n/** Emit an event declared on a spec — the guest-side capability handed alongside the implementation. */\nexport type IsolatedEmitter<S extends IsolatedServiceSpec> = {\n  [K in keyof S['events']]: (payload: EventPayload<S['events'][K]>) => void\n}\n\n/** A typed event-channel listener for the host-side `IsolatedService.on(channel, fn)`. */\nexport type IsolatedEventListener<S extends IsolatedServiceSpec, K extends keyof S['events']> = (\n  payload: EventPayload<S['events'][K]>\n) => void\n\n// ── Transport-facing duck contracts (PortLike / IsolationTransport) ────────────────────────────────\n\n/**\n * The minimal message-passing duck the wire protocol (`protocol.ts`) is built over. A `Worker` /\n * `MessagePort` (`post` = `postMessage`, `onMessage` wraps `addEventListener('message', ...)`) and a\n * Node `ChildProcess` / `process` (`post` = `.send`, `onMessage` wraps `.on('message', ...)`) both\n * satisfy this structurally — the shared protocol is exercised against linked in-memory fake ports; the\n * browser and Node transports wire it to the real transports.\n */\nexport interface PortLike {\n  /** Send a message across the port. Fire-and-forget — no delivery confirmation at this layer. */\n  post(msg: unknown): void\n  /** Subscribe to inbound messages. Returns an unsubscribe function. */\n  onMessage(fn: (msg: unknown) => void): () => void\n}\n\n/** Information about a crashed isolated guest, reported via `IsolationTransport.onCrash`. */\nexport interface CrashInfo {\n  /** Human-readable crash reason (exit signal, uncaught exception message, etc.). */\n  reason: string\n  /** Process exit code, when known (child_process transports). */\n  code?: number | null\n  /** Process exit signal, when known (child_process transports). */\n  signal?: string | null\n}\n\n/**\n * The environment-specific spawn/lifecycle duck a host-side transport implements — the Web Worker\n * and Node child_process transports each provide one; `createIsolatedService` (host.ts) drives only this\n * interface, never a concrete Worker/ChildProcess type.\n */\nexport interface IsolationTransport {\n  /** Spawn (or reuse) the guest and resolve once a {@link PortLike} is ready to exchange envelopes. */\n  connect(): Promise<PortLike>\n  /** Tear down the guest unconditionally (kill/terminate). May be sync or async. */\n  terminate(): void | Promise<void>\n  /** Subscribe to crash notifications (unexpected exit/termination). Returns an unsubscribe function. */\n  onCrash(fn: (info: CrashInfo) => void): () => void\n}\n","/**\n * Battery-scoped exception constructors for the isolation battery.\n *\n * @remarks\n * Minted via `createException` from `@nhtio/adk/factories`, matching every other bundled battery's\n * convention (see e.g. the transformers.js STT adapter's `exceptions.ts`).\n */\n\nimport { createException } from '@nhtio/adk/factories'\n\n/**\n * Thrown when `serveIsolated()` cannot duck-detect a supported guest environment — neither\n * `globalThis.self.postMessage` (Web Worker) nor `globalThis.process?.send` (node child_process) is\n * present. Fatal: there is no meaningful guest to serve.\n */\nexport const E_ISOLATION_UNSUPPORTED_ENV = createException<[string]>(\n  'E_ISOLATION_UNSUPPORTED_ENV',\n  'Cannot serve an isolated service: %s',\n  'E_ISOLATION_UNSUPPORTED_ENV',\n  500,\n  true\n)\n\n/**\n * Thrown when the codec must escalate a value past the `'raw'` tier (an exotic leaf: function, Error,\n * or registered custom-encodable) but the optional `@nhtio/encoder` peer is not installed. Printf arg:\n * the offending argument path. Non-fatal: a caller can catch this and pass the value through their own\n * BYO codec instead.\n */\nexport const E_ISOLATION_ENCODER_REQUIRED = createException<[string]>(\n  'E_ISOLATION_ENCODER_REQUIRED',\n  \"Cannot encode isolation payload at %s: install the optional peer '@nhtio/encoder' (or supply a BYO codec) to cross function/Error/custom-encodable values\",\n  'E_ISOLATION_ENCODER_REQUIRED',\n  528,\n  false\n)\n\n/**\n * Thrown when a value cannot be encoded even with the encoder peer available — most commonly a\n * circular reference that ALSO contains an exotic leaf (a plain circular raw value is fine; see\n * `codec.ts`), or the encoder itself rejects the value. Wraps the encoder's own\n * `E_CIRCULAR_REFERENCE`/`E_UNENCODABLE_VALUE` as `cause`.\n */\nexport const E_ISOLATION_UNENCODABLE = createException<[string]>(\n  'E_ISOLATION_UNENCODABLE',\n  'Cannot encode isolation payload at %s: value is unencodable',\n  'E_ISOLATION_UNENCODABLE',\n  500,\n  false\n)\n\n/**\n * Thrown by `IsolatedService` calls made while the guest has not yet signaled `ready` and the\n * configured `readyTimeoutMs` has elapsed. Printf arg: the elapsed timeout in milliseconds.\n */\nexport const E_ISOLATION_READY_TIMEOUT = createException<[number]>(\n  'E_ISOLATION_READY_TIMEOUT',\n  'Isolated service did not become ready within %dms',\n  'E_ISOLATION_READY_TIMEOUT',\n  504,\n  false\n)\n\n/**\n * Thrown to reject every in-flight call and error every open stream when an `IsolatedService` is\n * disposed or recycled — the guest connection those calls/streams were bound to no longer exists.\n */\nexport const E_ISOLATED_TERMINATED = createException<[string]>(\n  'E_ISOLATED_TERMINATED',\n  'Isolated service %s was terminated',\n  'E_ISOLATED_TERMINATED',\n  499,\n  false\n)\n\n/**\n * Thrown by `IsolatedService` calls made (or in flight) after the guest crashed and\n * `autoRespawn`/manual `recycle()` has not yet brought it back. Printf arg: the service name.\n */\nexport const E_ISOLATED_CRASHED = createException<[string]>(\n  'E_ISOLATED_CRASHED',\n  'Isolated service %s has crashed',\n  'E_ISOLATED_CRASHED',\n  503,\n  false\n)\n\n/**\n * Thrown when an isolation battery options bag (spec input, host options, codec options, crash-policy\n * options) fails eager validation — e.g. an unknown top-level key, or a duplicate name across a spec's\n * `methods`/`streams`/`events`. Fatal: config bugs fail loud, not at first use.\n */\nexport const E_INVALID_ISOLATION_OPTIONS = createException<[string]>(\n  'E_INVALID_ISOLATION_OPTIONS',\n  'Invalid isolation battery options: %s',\n  'E_INVALID_ISOLATION_OPTIONS',\n  529,\n  true\n)\n","/**\n * Runtime validation schemas and wrappers for the isolation battery's option bags and spec shape.\n *\n * @remarks\n * Follows the repo's eager-validation convention (see the transformers.js STT adapter's\n * `validation.ts`): `@nhtio/validation` schemas with `.unknown(false)` so typos in an options bag fail\n * loud at construction time, never silently at first use. This module also installs the public,\n * validating {@link defineIsolatedService} — re-exported from this battery's `index.ts` barrel — on top\n * of `types.ts`'s pure {@link resolveIsolatedServiceSpec} primitive.\n */\n\nimport { isError } from '@nhtio/adk/guards'\nimport { E_INVALID_ISOLATION_OPTIONS } from './exceptions'\nimport { validator, ValidationError } from '@nhtio/validation'\nimport {\n  resolveIsolatedServiceSpec,\n  type EventMap,\n  type IsolatedServiceSpec,\n  type IsolatedServiceSpecInput,\n  type MethodMap,\n  type StreamMap,\n} from './types'\n\nconst isValidationError = (value: unknown): value is ValidationError =>\n  isError(value) && Array.isArray((value as ValidationError).details)\n\nconst formatValidationDetails = (err: ValidationError): string =>\n  err.details.map((d) => d.message).join(' and ')\n\n/** Validator schema for the `{ name, methods?, streams?, events? }` shape `defineIsolatedService` takes. */\nexport const isolatedServiceSpecInputSchema = validator\n  .object<{ name: string; methods?: object; streams?: object; events?: object }>({\n    name: validator.string().min(1).required(),\n    methods: validator.object().unknown(true).optional(),\n    streams: validator.object().unknown(true).optional(),\n    events: validator.object().unknown(true).optional(),\n  })\n  .unknown(false)\n\n/**\n * Validate a spec input against {@link isolatedServiceSpecInputSchema} AND the cross-map name-collision\n * rule (a name may not appear in more than one of `methods`/`streams`/`events` — methods and streams\n * both become properties of the same {@link @nhtio/adk/batteries/isolation!IsolatedFacade} object, so a\n * collision there would silently shadow one implementation with the other).\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} on any failure.\n */\nexport const validateIsolatedServiceSpecInput = <\n  M extends MethodMap,\n  S extends StreamMap,\n  E extends EventMap,\n>(\n  input: IsolatedServiceSpecInput<M, S, E>\n): IsolatedServiceSpecInput<M, S, E> => {\n  const { value, error } = isolatedServiceSpecInputSchema.validate(input, {\n    abortEarly: false,\n    convert: false,\n  })\n  if (error && isValidationError(error)) {\n    throw new E_INVALID_ISOLATION_OPTIONS([formatValidationDetails(error)], { cause: error })\n  }\n  const methodNames = Object.keys(input.methods ?? {})\n  const streamNames = Object.keys(input.streams ?? {})\n  const eventNames = Object.keys(input.events ?? {})\n  const seen = new Map<string, 'methods' | 'streams' | 'events'>()\n  for (const [names, bucket] of [\n    [methodNames, 'methods'],\n    [streamNames, 'streams'],\n    [eventNames, 'events'],\n  ] as const) {\n    for (const name of names) {\n      const existing = seen.get(name)\n      if (existing) {\n        throw new E_INVALID_ISOLATION_OPTIONS([\n          `name \"${name}\" is declared in both \"${existing}\" and \"${bucket}\" — every method/stream/event name must be unique across the whole spec`,\n        ])\n      }\n      seen.set(name, bucket)\n    }\n  }\n  return value as IsolatedServiceSpecInput<M, S, E>\n}\n\n/**\n * Define an isolated service's spec — validates `input` eagerly (see\n * {@link validateIsolatedServiceSpecInput}) then resolves it via\n * {@link @nhtio/adk/batteries/isolation!resolveIsolatedServiceSpec}. This is the public entry point\n * re-exported as `defineIsolatedService` from this battery's `index.ts` barrel.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} when the spec fails\n *   validation (missing/empty `name`, unknown top-level key, or a name collision across\n *   `methods`/`streams`/`events`).\n */\nexport const defineIsolatedServiceValidated = <\n  M extends MethodMap = Record<never, never>,\n  S extends StreamMap = Record<never, never>,\n  E extends EventMap = Record<never, never>,\n>(\n  input: IsolatedServiceSpecInput<M, S, E>\n): IsolatedServiceSpec<M, S, E> =>\n  resolveIsolatedServiceSpec(validateIsolatedServiceSpecInput(input))\n\n/** Shape of the `encodables` option shared by host + serve options (sugar for encoder `registerClass`). */\nconst encodablesSchema = validator.array().items(validator.function()).optional()\n\n/** Shape of the {@link @nhtio/adk/batteries/isolation!IsolationObservabilityHooks} block, spread into\n *  both host + serve option schemas. */\nconst observabilityHooksShape = {\n  onIsolation: validator.function().optional(),\n  onSpawn: validator.function().optional(),\n  onDispose: validator.function().optional(),\n  onRecycle: validator.function().optional(),\n  onCrashReport: validator.function().optional(),\n  onRespawnAuto: validator.function().optional(),\n  onCall: validator.function().optional(),\n  onStream: validator.function().optional(),\n  onAbort: validator.function().optional(),\n  onWire: validator.function().optional(),\n  onCodecEscalate: validator.function().optional(),\n  debugPayloads: validator.boolean().optional(),\n}\n\n/** Shape of the `autoRespawn` option shared by every `createIsolatedService`-flavored options bag\n *  (`isolatedServiceOptionsSchema` and, via the browser transport, `spawnIsolatedOptionsSchema`). Hoisted rather than\n *  re-declared so both schemas stay in lockstep. */\nconst autoRespawnSchema = validator\n  .object({\n    policy: validator\n      .custom((v, h) =>\n        v && typeof (v as { record?: unknown }).record === 'function' ? v : h.error('any.invalid')\n      )\n      .required(),\n  })\n  .unknown(false)\n  .optional()\n\n/** Validator schema for `createIsolatedService`'s options bag. */\nexport const isolatedServiceOptionsSchema = validator\n  .object<{\n    readyTimeoutMs?: number\n    disposeGraceMs?: number\n    autoRespawn?: object\n    encodables?: unknown[]\n  }>({\n    readyTimeoutMs: validator.number().positive().optional(),\n    disposeGraceMs: validator.number().positive().optional(),\n    autoRespawn: autoRespawnSchema,\n    encodables: encodablesSchema,\n    ...observabilityHooksShape,\n  })\n  .unknown(false)\n\n/**\n * Validate `createIsolatedService`'s options bag.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} on failure.\n */\nexport const validateIsolatedServiceOptions = <T extends object>(input: T | undefined): T => {\n  if (input === undefined) return {} as T\n  const { value, error } = isolatedServiceOptionsSchema.validate(input, {\n    abortEarly: false,\n    convert: false,\n  })\n  if (error && isValidationError(error)) {\n    throw new E_INVALID_ISOLATION_OPTIONS([formatValidationDetails(error)], { cause: error })\n  }\n  return value as T\n}\n\n/** Validator schema for `serveIsolated`/`serveIsolatedOverPort`'s options bag. */\nexport const serveIsolatedOptionsSchema = validator\n  .object<{ encodables?: unknown[] }>({\n    encodables: encodablesSchema,\n    ...observabilityHooksShape,\n  })\n  .unknown(false)\n\n/**\n * Validate `serveIsolated`/`serveIsolatedOverPort`'s options bag.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} on failure.\n */\nexport const validateServeIsolatedOptions = <T extends object>(input: T | undefined): T => {\n  if (input === undefined) return {} as T\n  const { value, error } = serveIsolatedOptionsSchema.validate(input, {\n    abortEarly: false,\n    convert: false,\n  })\n  if (error && isValidationError(error)) {\n    throw new E_INVALID_ISOLATION_OPTIONS([formatValidationDetails(error)], { cause: error })\n  }\n  return value as T\n}\n\n// ── Browser transport: `spawnIsolated`/`createWorkerTransport` options ─────────────────────────────────────\n\n/** A value is `URL`-like when it structurally exposes a string `href` (real `URL` instances, and\n *  anything sufficiently duck-compatible) — this schema never imports the DOM `URL` type; see\n *  `browser.ts`'s module doc for why. */\nconst looksLikeUrl = (value: unknown): boolean =>\n  Boolean(value) &&\n  typeof value === 'object' &&\n  typeof (value as { href?: unknown }).href === 'string'\n\n/** Shape of `SpawnIsolatedOptions.worker` — a guest script `string | URL`, or a {@link\n *  @nhtio/adk/batteries/isolation!WorkerResolver} function. Validated via `custom()` (mirrors\n *  `isolatedServiceOptionsSchema`'s `autoRespawn.policy` duck-check pattern) rather than\n *  `alternatives()`, since a `URL` instance is not itself expressible as a plain validator schema. */\nconst workerSpecSchema = validator\n  .custom((v, h) =>\n    typeof v === 'string' || typeof v === 'function' || looksLikeUrl(v) ? v : h.error('any.invalid')\n  )\n  .required()\n\n/** Shape of the optional `workerOptions` dictionary forwarded to `new Worker(url, workerOptions)`. */\nconst workerOptionsSchema = validator\n  .object<{ type?: string; credentials?: string; name?: string }>({\n    type: validator.string().valid('classic', 'module').optional(),\n    credentials: validator.string().valid('omit', 'same-origin', 'include').optional(),\n    name: validator.string().optional(),\n  })\n  .unknown(false)\n  .optional()\n\n/** Validator schema for `spawnIsolated`/`createWorkerTransport`'s options bag — every field {@link\n *  isolatedServiceOptionsSchema} accepts, plus `worker`/`workerOptions`.\n *\n * @remarks\n * Deliberately NOT built via `isolatedServiceOptionsSchema.keys({...})`: `@nhtio/validation`'s `.keys()`\n * is typed to return `this` (the ORIGINAL object schema's type parameter), so TypeScript rejects a\n * `worker`/`workerOptions` key that isn't already part of that type param, even though the runtime\n * behavior of `.keys()` is correct (verified separately — it does properly extend both the allowed-key\n * set and required-ness at runtime). Declaring a sibling schema that repeats the shared fields (via the\n * hoisted `autoRespawnSchema`/`encodablesSchema`/`observabilityHooksShape` fragments, so nothing is\n * duplicated by VALUE) keeps both the runtime schema and its static type in sync without a `.keys()`\n * type-level workaround. */\nexport const spawnIsolatedOptionsSchema = validator\n  .object<{\n    readyTimeoutMs?: number\n    disposeGraceMs?: number\n    autoRespawn?: object\n    encodables?: unknown[]\n    worker: string\n    workerOptions?: object\n  }>({\n    readyTimeoutMs: validator.number().positive().optional(),\n    disposeGraceMs: validator.number().positive().optional(),\n    autoRespawn: autoRespawnSchema,\n    encodables: encodablesSchema,\n    ...observabilityHooksShape,\n    worker: workerSpecSchema,\n    workerOptions: workerOptionsSchema,\n  })\n  .unknown(false)\n\n/**\n * Validate `spawnIsolated`/`createWorkerTransport`'s options bag.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} on failure (missing\n *   `worker`, a `worker` that is neither a string/URL/function, or an unknown top-level key).\n */\nexport const validateSpawnIsolatedOptions = <T extends object>(input: T): T => {\n  const { value, error } = spawnIsolatedOptionsSchema.validate(input, {\n    abortEarly: false,\n    convert: false,\n  })\n  if (error && isValidationError(error)) {\n    throw new E_INVALID_ISOLATION_OPTIONS([formatValidationDetails(error)], { cause: error })\n  }\n  return value as T\n}\n","/**\n * Wire protocol — envelope shapes and the transport-agnostic {@link HostEndpoint}/{@link GuestEndpoint}\n * correlation engines built on top of {@link PortLike}.\n *\n * @remarks\n * Generalizes the pattern hand-rolled per-battery in\n * `docs/.vitepress/theme/components/agent/litert_lm_worker_proxy.ts` +\n * `litert_lm_worker.ts` (id-correlated one-shot calls, a persistent stream-sink map fed by unsolicited\n * events, string-only error crossing) into a reusable, method/stream/event-name-generic core. Both\n * endpoint classes are PURE over {@link PortLike} — no `Worker`/`postMessage`/`process.send` reference\n * anywhere in this module; the browser and Node transports supply concrete `PortLike` adapters, while\n * this file is exercised only against linked in-memory fake ports (see the unit specs).\n *\n * `HostEndpoint` queues every outbound call/stream-start made before the guest's `ready` envelope\n * arrives, then flushes the queue in order once it does. `GuestEndpoint` requires no such queueing (it\n * only ever reacts to inbound envelopes).\n */\n\nimport { isError } from '@nhtio/adk/guards'\nimport type { PortLike } from './types'\n\n// ── Wire value + error shapes ────────────────────────────────────────────────────────────────────────\n\n/**\n * A single argument/result value as it crosses the wire — the codec's (`codec.ts`) output shape. `enc:\n * 'raw'` ships the value (mostly) untouched; `enc: 'nhtio'` ships an `@nhtio/encoder`-encoded string\n * (or a BYO-codec-encoded string). `transfer` is a pass-through marker the browser transport unwraps into a `postMessage` transfer list;\n * Node transports ignore it.\n */\nexport type WireValue =\n  | { enc: 'raw'; v: unknown; transfer?: unknown[] }\n  | { enc: 'nhtio'; v: string }\n\n/**\n * An error as it crosses the wire. `message`/`name`/`stack` are ALWAYS present baseline string fields\n * (never omitted, regardless of encoder availability) so error-classification-by-message-signature\n * always works even when the encoder is unavailable or fails to decode. `nhtio` carries the\n * `@nhtio/encoder`-encoded original `Error` instance when BOTH sides advertised `encoderAvailable` on\n * `ready` — the receiving side decodes it for full fidelity (custom error subclasses, extra\n * properties) and falls back silently to the baseline fields on any decode failure.\n */\nexport interface WireError {\n  /** Baseline error message — always populated, even when `nhtio` is absent or fails to decode. */\n  message: string\n  /** Baseline error name (e.g. `'TypeError'`) — always populated. */\n  name: string\n  /** Baseline stack trace, when the original error had one — always forwarded as-is (never re-derived). */\n  stack?: string\n  /** `@nhtio/encoder`-encoded original `Error`, when both sides have the encoder. */\n  nhtio?: string\n}\n\n// ── Envelopes ────────────────────────────────────────────────────────────────────────────────────────\n\n/** Host → guest envelopes. */\nexport type HostToGuestEnvelope =\n  | { t: 'call'; id: string; method: string; args: WireValue[] }\n  | { t: 'hostresult'; id: string; ok: true; value: WireValue | string }\n  | { t: 'hostresult'; id: string; ok: false; error?: WireError; value?: string }\n  | { t: 'abort'; id: string }\n  | { t: 'stream:start'; id: string; stream: string; args: WireValue[] }\n  | { t: 'stream:cancel'; id: string; reason?: WireValue }\n  | { t: 'shutdown' }\n\n/** Guest → host envelopes. */\nexport type GuestToHostEnvelope =\n  | { t: 'ready'; encoderAvailable: boolean }\n  | { t: 'hostcall'; id: string; method: string; args: WireValue[] }\n  | { t: 'result'; id: string; ok: true; value: WireValue }\n  | { t: 'result'; id: string; ok: false; error: WireError }\n  | { t: 'stream:delta'; id: string; delta: WireValue }\n  | { t: 'stream:end'; id: string }\n  | { t: 'stream:error'; id: string; error: WireError }\n  | { t: 'event'; channel: string; payload: WireValue }\n\n/** Either direction's envelope — used by generic wire-tracing hooks. */\nexport type WireEnvelope = HostToGuestEnvelope | GuestToHostEnvelope\n\nlet idSeq = 0\n/** Monotonic id generator shared by both endpoints (module-scoped counter — fine across many\n *  instances in one realm since ids are only ever compared within a single connection). */\nexport const nextCorrelationId = (): string => `c${(idSeq += 1)}`\n\n// ── Host endpoint ────────────────────────────────────────────────────────────────────────────────────\n\ninterface PendingCall {\n  resolve: (value: WireValue) => void\n  reject: (err: Error) => void\n}\n\ninterface StreamSink {\n  push: (delta: WireValue) => void\n  end: () => void\n  error: (err: WireError) => void\n}\n\n/** Hooks {@link HostEndpoint} invokes on protocol-level events; `host.ts` wires these to the\n *  observability layer + guest-event fan-out. All optional. */\nexport interface HostcallQuotas {\n  /** Per-request deadline in milliseconds. */\n  hostcallTimeoutMs: number\n  /** Maximum accepted requests for one evaluation. */\n  maxHostcallsPerEvaluation: number\n  /** Maximum concurrently running requests. */\n  maxConcurrentHostcalls: number\n}\n\n/** Host-side capability registry. The handler receives decoded wire arguments. */\nexport type HostcallHandler = (\n  args: WireValue[],\n  signal: AbortSignal\n) => WireValue | Promise<WireValue>\n\n/** UTF-8 producer-side measurement used by both RPC realms. */\nexport const measureHostcallBytes = (value: unknown): number => {\n  const text = JSON.stringify(value)\n  return new TextEncoder().encode(text === undefined ? 'undefined' : text).byteLength\n}\n\n/**\n * Callback surface for observing host-endpoint lifecycle and guest-originated events.\n *\n * @remarks Hooks are notifications only; dispatch and correlation remain owned by the endpoint.\n */\nexport interface HostEndpointHooks {\n  /** The guest's `ready` envelope arrived. */\n  onReady?: (info: { encoderAvailable: boolean }) => void\n  /** An `event` envelope arrived for `channel`. */\n  onEvent?: (channel: string, payload: WireValue) => void\n  /** A guest-to-host capability request arrived. It is deliberately independent of `call`. */\n  onHostcall?: (id: string, method: string, args: WireValue[]) => void\n  /** Any envelope was sent (`dir: 'out'`) or received (`dir: 'in'`) — for wire tracing. */\n  onEnvelope?: (dir: 'out' | 'in', envelope: WireEnvelope) => void\n}\n\n/**\n * Host-side correlation engine over a {@link PortLike}. Queues calls/stream-starts made before `ready`\n * and flushes them in order once it arrives; tracks in-flight calls (one-shot, resolved/rejected by a\n * `result` envelope) and open streams (persistent, fed by `stream:delta`/`stream:end`/`stream:error`\n * until closed). `terminate()` rejects every in-flight call and errors every open stream with a\n * caller-supplied reason (the message text `host.ts` uses is `E_ISOLATED_TERMINATED`'s message).\n */\nexport class HostEndpoint {\n  readonly #port: PortLike\n  readonly #hooks: HostEndpointHooks\n  readonly #pending = new Map<string, PendingCall>()\n  readonly #streams = new Map<string, StreamSink>()\n  readonly #outbox: HostToGuestEnvelope[] = []\n  readonly #hostcallHandlers: ReadonlyMap<string, HostcallHandler>\n  readonly #hostcallQuotas: HostcallQuotas | undefined\n  readonly #maxHostcallBytes: number | undefined\n  #acceptedHostcalls = 0\n  #concurrentHostcalls = 0\n  #ready = false\n  #unsubscribe: () => void\n  #terminated = false\n\n  constructor(\n    port: PortLike,\n    hooks: HostEndpointHooks = {},\n    hostcalls: {\n      handlers?: ReadonlyMap<string, HostcallHandler>\n      quotas?: HostcallQuotas\n      maxHostcallBytes?: number\n    } = {}\n  ) {\n    this.#port = port\n    this.#hooks = hooks\n    this.#hostcallHandlers = hostcalls.handlers ?? new Map()\n    this.#hostcallQuotas = hostcalls.quotas\n    this.#maxHostcallBytes = hostcalls.maxHostcallBytes\n    this.#unsubscribe = port.onMessage(this.#onMessage)\n  }\n\n  /** Whether the guest has signaled `ready` yet. */\n  get isReady(): boolean {\n    return this.#ready\n  }\n\n  /** Number of calls currently awaiting a `result` envelope. Used by `host.ts` to report an accurate\n   *  `inFlight` count on a crash before `terminate()` clears the pending map. */\n  get pendingCallCount(): number {\n    return this.#pending.size\n  }\n\n  /** Number of streams currently open (started, not yet ended/errored). Used by `host.ts` alongside\n   *  {@link pendingCallCount} to report an accurate `inFlight` count on a crash. */\n  get openStreamCount(): number {\n    return this.#streams.size\n  }\n\n  #send(envelope: HostToGuestEnvelope): void {\n    this.#hooks.onEnvelope?.('out', envelope)\n    this.#port.post(envelope)\n  }\n\n  #sendOrQueue(envelope: HostToGuestEnvelope): void {\n    if (this.#ready) {\n      this.#send(envelope)\n    } else {\n      this.#outbox.push(envelope)\n    }\n  }\n\n  #onMessage = (msg: unknown): void => {\n    const envelope = msg as GuestToHostEnvelope\n    if (!envelope || typeof (envelope as { t?: unknown }).t !== 'string') return\n    this.#hooks.onEnvelope?.('in', envelope)\n    switch (envelope.t) {\n      case 'ready': {\n        this.#ready = true\n        this.#hooks.onReady?.({ encoderAvailable: envelope.encoderAvailable })\n        // Flush queued calls/stream-starts in the exact order they were made.\n        const queued = this.#outbox.splice(0, this.#outbox.length)\n        for (const q of queued) this.#send(q)\n        return\n      }\n      case 'hostcall': {\n        this.#hooks.onHostcall?.(envelope.id, envelope.method, envelope.args)\n        void this.#dispatchHostcall(envelope)\n        return\n      }\n      case 'result': {\n        const pending = this.#pending.get(envelope.id)\n        if (!pending) return\n        this.#pending.delete(envelope.id)\n        if (envelope.ok) {\n          pending.resolve(envelope.value)\n        } else {\n          pending.reject(wireErrorToError(envelope.error))\n        }\n        return\n      }\n      case 'stream:delta': {\n        this.#streams.get(envelope.id)?.push(envelope.delta)\n        return\n      }\n      case 'stream:end': {\n        const sink = this.#streams.get(envelope.id)\n        this.#streams.delete(envelope.id)\n        sink?.end()\n        return\n      }\n      case 'stream:error': {\n        const sink = this.#streams.get(envelope.id)\n        this.#streams.delete(envelope.id)\n        sink?.error(envelope.error)\n        return\n      }\n      case 'event': {\n        this.#hooks.onEvent?.(envelope.channel, envelope.payload)\n        return\n      }\n    }\n  }\n\n  /**\n   * Issue a request/response call. Resolves with the guest's returned {@link WireValue}, rejects with a\n   * reconstructed `Error` (see {@link wireErrorToError}) on failure or on `terminate()`.\n   */\n  call(method: string, args: WireValue[]): { id: string; promise: Promise<WireValue> } {\n    if (this.#terminated) {\n      const id = nextCorrelationId()\n      return { id, promise: Promise.reject(new Error('HostEndpoint has been terminated')) }\n    }\n    const id = nextCorrelationId()\n    const promise = new Promise<WireValue>((resolve, reject) => {\n      this.#pending.set(id, { resolve, reject })\n    })\n    this.#sendOrQueue({ t: 'call', id, method, args })\n    return { id, promise }\n  }\n\n  async #dispatchHostcall(\n    envelope: Extract<GuestToHostEnvelope, { t: 'hostcall' }>\n  ): Promise<void> {\n    const handler = this.#hostcallHandlers.get(envelope.method)\n    if (!handler) {\n      this.hostresult(envelope.id, {\n        ok: false,\n        error: { name: 'Error', message: `Unknown host method \"${envelope.method}\"` },\n      })\n      return\n    }\n    const quotas = this.#hostcallQuotas\n    if (\n      quotas &&\n      (this.#acceptedHostcalls >= quotas.maxHostcallsPerEvaluation ||\n        this.#concurrentHostcalls >= quotas.maxConcurrentHostcalls)\n    ) {\n      this.hostresult(envelope.id, {\n        ok: false,\n        error: { name: 'Error', message: 'Hostcall quota exceeded' },\n      })\n      return\n    }\n    this.#acceptedHostcalls += 1\n    this.#concurrentHostcalls += 1\n    let released = false\n    const release = (): void => {\n      if (!released) {\n        released = true\n        this.#concurrentHostcalls -= 1\n      }\n    }\n    const capabilityAbort = new AbortController()\n    let timer: ReturnType<typeof setTimeout> | undefined\n    const timeout = quotas?.hostcallTimeoutMs\n    const timedOut = new Promise<never>((_, reject) => {\n      if (timeout === undefined) return\n      timer = setTimeout(() => reject(new Error('Hostcall timed out')), timeout)\n    })\n    try {\n      const value = await Promise.race([\n        Promise.resolve().then(() => handler(envelope.args, capabilityAbort.signal)),\n        timedOut,\n      ])\n      if (timer) clearTimeout(timer)\n      release()\n      if (\n        this.#maxHostcallBytes !== undefined &&\n        measureHostcallBytes(value) > this.#maxHostcallBytes\n      ) {\n        this.hostresult(envelope.id, { ok: false, value: 'too-many-bytes' })\n      } else {\n        this.hostresult(envelope.id, { ok: true, value })\n      }\n    } catch (error) {\n      if (timer) clearTimeout(timer)\n      release()\n      this.hostresult(envelope.id, {\n        ok: false,\n        error: { name: 'Error', message: isError(error) ? error.message : String(error) },\n      })\n    }\n  }\n\n  /** Post a guest capability result. Unknown/late ids are harmlessly ignored by the guest. */\n  hostresult(\n    id: string,\n    result:\n      | { ok: true; value: WireValue | string }\n      | { ok: false; error?: WireError; value?: string }\n  ): void {\n    if (this.#terminated) return\n    this.#send({ t: 'hostresult', id, ...result })\n  }\n\n  /** Send an `abort` envelope for an in-flight call's id. Does not itself reject the call — the guest\n   *  is expected to respond with a `result` (ok:false) once it observes the abort. */\n  abort(id: string): void {\n    this.#sendOrQueue({ t: 'abort', id })\n  }\n\n  /**\n   * Start a fire-and-forward stream. Returns the correlation id immediately (before the guest\n   * necessarily even exists, if not yet `ready`) and a `sink` the caller wires to a `ReadableStream`\n   * controller.\n   */\n  startStream(stream: string, args: WireValue[], sink: StreamSink): string {\n    const id = nextCorrelationId()\n    this.#streams.set(id, sink)\n    this.#sendOrQueue({ t: 'stream:start', id, stream, args })\n    return id\n  }\n\n  /** Send a `stream:cancel` envelope and stop tracking the stream locally. */\n  cancelStream(id: string, reason?: WireValue): void {\n    this.#streams.delete(id)\n    this.#sendOrQueue({ t: 'stream:cancel', id, reason })\n  }\n\n  /** Send a `shutdown` envelope (graceful-exit request; does not itself tear down the port). */\n  shutdown(): void {\n    this.#send({ t: 'shutdown' })\n  }\n\n  /**\n   * Reject every in-flight call and error every open stream with `reason`, clear all queued-but-unsent\n   * envelopes, and unsubscribe from the port. Idempotent.\n   */\n  terminate(reason: string): void {\n    if (this.#terminated) return\n    this.#terminated = true\n    this.#outbox.length = 0\n    for (const [, p] of this.#pending) p.reject(new Error(reason))\n    this.#pending.clear()\n    const err: WireError = { message: reason, name: 'Error' }\n    for (const [, s] of this.#streams) s.error(err)\n    this.#streams.clear()\n    this.#unsubscribe()\n  }\n}\n\n/** Reconstruct an `Error` from a {@link WireError} baseline (name/message/stack only — the `nhtio`-rich\n *  path is decoded separately by the caller when an encoder is available; see `host.ts`). */\nexport const wireErrorToError = (wireError: WireError): Error => {\n  const err = new Error(wireError.message)\n  err.name = wireError.name\n  if (wireError.stack) err.stack = wireError.stack\n  return err\n}\n\n// ── Guest endpoint ───────────────────────────────────────────────────────────────────────────────────\n\n/** Hooks {@link GuestEndpoint} invokes for the guest server (`serve.ts`) to react to. */\nexport interface GuestEndpointHooks {\n  /** A `call` envelope arrived — resolve/reject `settle` with the method's outcome. */\n  onCall?: (id: string, method: string, args: WireValue[], signal: AbortSignal) => void\n  /** A host capability result arrived. */\n  onHostResult?: (\n    id: string,\n    result:\n      | { ok: true; value: WireValue | string }\n      | { ok: false; error?: WireError; value?: string }\n  ) => void\n  /** A `stream:start` envelope arrived — the handler pushes deltas via the returned sink. */\n  onStreamStart?: (id: string, stream: string, args: WireValue[], signal: AbortSignal) => void\n  /** A `stream:cancel` envelope arrived for an open stream id. */\n  onStreamCancel?: (id: string, reason?: WireValue) => void\n  /** A `shutdown` envelope arrived. */\n  onShutdown?: () => void\n  /** Any envelope was sent (`dir: 'out'`) or received (`dir: 'in'`) — for wire tracing. */\n  onEnvelope?: (dir: 'out' | 'in', envelope: WireEnvelope) => void\n}\n\n/**\n * Guest-side correlation engine over a {@link PortLike}. Owns per-call `AbortController`s (aborted on\n * an inbound `abort`/`stream:cancel` envelope) and exposes `settleCall`/`pushDelta`/`endStream`/\n * `errorStream` for `serve.ts` to report outcomes back across the wire.\n */\nexport class GuestEndpoint {\n  readonly #port: PortLike\n  readonly #hooks: GuestEndpointHooks\n  readonly #callAborts = new Map<string, AbortController>()\n  readonly #streamAborts = new Map<string, AbortController>()\n  readonly #hostcalls = new Map<\n    string,\n    { resolve: (value: WireValue | string) => void; reject: (error: Error) => void }\n  >()\n\n  constructor(port: PortLike, hooks: GuestEndpointHooks = {}) {\n    this.#port = port\n    this.#hooks = hooks\n    port.onMessage(this.#onMessage)\n  }\n\n  #send(envelope: GuestToHostEnvelope): void {\n    this.#hooks.onEnvelope?.('out', envelope)\n    this.#port.post(envelope)\n  }\n\n  #onMessage = (msg: unknown): void => {\n    const envelope = msg as HostToGuestEnvelope\n    if (!envelope || typeof (envelope as { t?: unknown }).t !== 'string') return\n    this.#hooks.onEnvelope?.('in', envelope)\n    switch (envelope.t) {\n      case 'hostresult': {\n        const pending = this.#hostcalls.get(envelope.id)\n        if (!pending) return\n        this.#hostcalls.delete(envelope.id)\n        if (envelope.ok) pending.resolve(envelope.value)\n        else if (envelope.value !== undefined) pending.reject(new Error(envelope.value))\n        else pending.reject(wireErrorToError(envelope.error!))\n        this.#hooks.onHostResult?.(envelope.id, envelope)\n        return\n      }\n      case 'call': {\n        const controller = new AbortController()\n        this.#callAborts.set(envelope.id, controller)\n        this.#hooks.onCall?.(envelope.id, envelope.method, envelope.args, controller.signal)\n        return\n      }\n      case 'abort': {\n        this.#callAborts.get(envelope.id)?.abort()\n        return\n      }\n      case 'stream:start': {\n        const controller = new AbortController()\n        this.#streamAborts.set(envelope.id, controller)\n        this.#hooks.onStreamStart?.(envelope.id, envelope.stream, envelope.args, controller.signal)\n        return\n      }\n      case 'stream:cancel': {\n        this.#streamAborts.get(envelope.id)?.abort()\n        this.#hooks.onStreamCancel?.(envelope.id, envelope.reason)\n        return\n      }\n      case 'shutdown': {\n        this.#hooks.onShutdown?.()\n        return\n      }\n    }\n  }\n\n  /** Issue a guest-to-host capability request using the separate hostcall id space. */\n  hostcall(\n    method: string,\n    args: WireValue[],\n    maxBytes?: number\n  ): { id: string; promise: Promise<WireValue | string> } {\n    const id = `h${nextCorrelationId()}`\n    if (maxBytes !== undefined && measureHostcallBytes({ method, args }) > maxBytes) {\n      return { id, promise: Promise.reject(new Error('Hostcall arguments exceed byte limit')) }\n    }\n    const promise = new Promise<WireValue | string>((resolve, reject) => {\n      this.#hostcalls.set(id, { resolve, reject })\n      this.#send({ t: 'hostcall', id, method, args })\n    })\n    return { id, promise }\n  }\n\n  /** Announce readiness. Must be sent exactly once, before any `result`/`stream:*`/`event` envelope. */\n  ready(encoderAvailable: boolean): void {\n    this.#send({ t: 'ready', encoderAvailable })\n  }\n\n  /** Report a successful call outcome and release the call's abort controller. */\n  settleOk(id: string, value: WireValue): void {\n    this.#callAborts.delete(id)\n    this.#send({ t: 'result', id, ok: true, value })\n  }\n\n  /** Report a failed call outcome and release the call's abort controller. */\n  settleError(id: string, error: WireError): void {\n    this.#callAborts.delete(id)\n    this.#send({ t: 'result', id, ok: false, error })\n  }\n\n  /** Push a stream delta. */\n  pushDelta(id: string, delta: WireValue): void {\n    this.#send({ t: 'stream:delta', id, delta })\n  }\n\n  /** Signal a stream's clean end and release its abort controller. */\n  endStream(id: string): void {\n    this.#streamAborts.delete(id)\n    this.#send({ t: 'stream:end', id })\n  }\n\n  /** Signal a stream's terminal error and release its abort controller. */\n  errorStream(id: string, error: WireError): void {\n    this.#streamAborts.delete(id)\n    this.#send({ t: 'stream:error', id, error })\n  }\n\n  /** Reject all guest capability requests when this endpoint is stopped. */\n  terminate(reason = 'GuestEndpoint has been terminated'): void {\n    for (const pending of this.#hostcalls.values()) pending.reject(new Error(reason))\n    this.#hostcalls.clear()\n  }\n\n  /** Emit an unsolicited event on `channel`. */\n  emit(channel: string, payload: WireValue): void {\n    this.#send({ t: 'event', channel, payload })\n  }\n}\n","var e=e=>Object.prototype.toString.call(e),t=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),o=t=>\"[object Date]\"===e(t),n=t=>\"[object RegExp]\"===e(t),r=t=>\"[object Error]\"===e(t),s=t=>\"[object Boolean]\"===e(t),l=t=>\"[object Number]\"===e(t),i=t=>\"[object String]\"===e(t),c=Array.isArray,u=Object.getOwnPropertyDescriptor,a=Object.prototype.propertyIsEnumerable,f=Object.getOwnPropertySymbols,p=Object.prototype.hasOwnProperty,h=Object.keys;function d(e){const t=h(e),o=f(e);for(let n=0;n<o.length;n++)a.call(e,o[n])&&t.push(o[n]);return t}function b(e,t){return!u(e,t)?.writable}function y(e,u){if(\"object\"==typeof e&&null!==e){let a;if(c(e))a=[];else if(o(e))a=new Date(e.getTime?e.getTime():e);else if(n(e))a=new RegExp(e);else if(r(e))a={message:e.message};else if(s(e)||l(e)||i(e))a=Object(e);else{if(t(e))return e.slice();a=Object.create(Object.getPrototypeOf(e))}const f=u.includeSymbols?d:h;for(const t of f(e))a[t]=e[t];return a}return e}var g={includeSymbols:!1,immutable:!1};function m(e,t,o=g){const n=[],r=[];let s=!0;const l=o.includeSymbols?d:h,i=!!o.immutable;return function e(u){const a=i?y(u,o):u,f={};let h=!0;const d={node:a,node_:u,path:[].concat(n),parent:r[r.length-1],parents:r,key:n[n.length-1],isRoot:0===n.length,level:n.length,circular:void 0,isLeaf:!1,notLeaf:!0,notRoot:!0,isFirst:!1,isLast:!1,update:function(e,t=!1){d.isRoot||(d.parent.node[d.key]=e),d.node=e,t&&(h=!1)},delete:function(e){delete d.parent.node[d.key],e&&(h=!1)},remove:function(e){c(d.parent.node)?d.parent.node.splice(d.key,1):delete d.parent.node[d.key],e&&(h=!1)},keys:null,before:function(e){f.before=e},after:function(e){f.after=e},pre:function(e){f.pre=e},post:function(e){f.post=e},stop:function(){s=!1},block:function(){h=!1}};if(!s)return d;function g(){if(\"object\"==typeof d.node&&null!==d.node){d.keys&&d.node_===d.node||(d.keys=l(d.node)),d.isLeaf=0===d.keys.length;for(let e=0;e<r.length;e++)if(r[e].node_===u){d.circular=r[e];break}}else d.isLeaf=!0,d.keys=null;d.notLeaf=!d.isLeaf,d.notRoot=!d.isRoot}g();const m=t(d,d.node);if(void 0!==m&&d.update&&d.update(m),f.before&&f.before(d,d.node),!h)return d;if(\"object\"==typeof d.node&&null!==d.node&&!d.circular){r.push(d),g();for(const[t,o]of Object.entries(d.keys??[])){n.push(o),f.pre&&f.pre(d,d.node[o],o);const r=e(d.node[o]);i&&p.call(d.node,o)&&!b(d.node,o)&&(d.node[o]=r.node),r.isLast=!!d.keys?.length&&+t==d.keys.length-1,r.isFirst=0==+t,f.post&&f.post(d,r),n.pop()}r.pop()}return f.after&&f.after(d,d.node),d}(e).node}var j=class{#e;#t;constructor(e,t=g){this.#e=e,this.#t=t}get(e){let t=this.#e;for(let o=0;t&&o<e.length;o++){const n=e[o];if(!p.call(t,n)||!this.#t.includeSymbols&&\"symbol\"==typeof n)return;t=t[n]}return t}has(e){let t=this.#e;for(let o=0;t&&o<e.length;o++){const n=e[o];if(!p.call(t,n)||!this.#t.includeSymbols&&\"symbol\"==typeof n)return!1;t=t[n]}return!0}set(e,t){let o=this.#e,n=0;for(n=0;n<e.length-1;n++){const t=e[n];p.call(o,t)||(o[t]={}),o=o[t]}return o[e[n]]=t,t}map(e){return m(this.#e,e,{immutable:!0,includeSymbols:!!this.#t.includeSymbols})}forEach(e){return this.#e=m(this.#e,e,this.#t),this.#e}reduce(e,t){const o=1===arguments.length;let n=o?this.#e:t;return this.forEach(((t,r)=>{t.isRoot&&o||(n=e(t,n,r))})),n}paths(){const e=[];return this.forEach((t=>{e.push(t.path)})),e}nodes(){const e=[];return this.forEach((t=>{e.push(t.node)})),e}clone(){const e=[],o=[],n=this.#t;return t(this.#e)?this.#e.slice():function t(r){for(let t=0;t<e.length;t++)if(e[t]===r)return o[t];if(\"object\"==typeof r&&null!==r){const s=y(r,n);e.push(r),o.push(s);const l=n.includeSymbols?d:h;for(const e of l(r))s[e]=t(r[e]);return e.pop(),o.pop(),s}return r}(this.#e)}};export{j as Traverse};","/**\n * Tiered codec — the cheapest sufficient wire serialization for each call/stream argument and result.\n *\n * @remarks\n * Three tiers, escalating only as far as a given value actually requires:\n *\n * 1. **`raw`** — the value crosses untouched (same reference on a linked in-memory port; structurally\n *    cloned by a real transport). Zero-copy, zero-clone at this layer. Used whenever a value contains\n *    no \"exotic\" leaf.\n * 2. **Path-sentineled raw** — a container that has ordinary JSON-safe data EXCEPT for a small number\n *    of exotic leaves (e.g. one callback buried in an options bag) is cloned ONLY along the paths that\n *    lead to those leaves, with each exotic leaf replaced by a `{ __nhtio$: <encoded string> }`\n *    sentinel; the rest of the container (and the caller's original object) is untouched.\n * 3. **`nhtio`** — a whole exotic value (a bare function/Error/custom-encodable passed directly as an\n *    argument) is encoded in full via `@nhtio/encoder` (or a BYO codec) and shipped as a plain string.\n *\n * \"Exotic leaf\" = a function, an `Error`, or (when the `@nhtio/encoder` peer is installed) a value the\n * encoder recognizes as a registered custom-encodable. `TypedArray`/`ArrayBuffer`/`DataView`/`Date`/\n * `RegExp`/`Map`/`Set` are treated as OPAQUE traversal leaves — the traverser never descends into their\n * contents (so a huge `Float32Array` costs O(1) traversal step, not O(bytes)) and they ship raw as-is\n * (a linked in-memory port hands the same reference through; a real transport structurally clones or\n * transfers them).\n *\n * The `@nhtio/encoder` peer is OPTIONAL and NEVER statically imported — every reference to it goes\n * through {@link loadEncoder}, a lazy + memoized dynamic `import()` with an injectable seam for tests.\n *\n * Circular references are fine at the `raw` tier (the traverser's `ctx.circular` flag stops descent\n * without escalating). A circular reference reachable only through an exotic leaf's container throws\n * `E_ISOLATION_UNENCODABLE` — the encoder itself cannot represent it either.\n */\n\nimport { Traverse, type TraverseContext } from 'neotraverse/modern'\nimport { isError, isInstanceOf, isObject } from '@nhtio/adk/guards'\nimport { E_ISOLATION_ENCODER_REQUIRED, E_ISOLATION_UNENCODABLE } from './exceptions'\nimport type { CodecMode } from './types'\nimport type { WireError, WireValue } from './protocol'\n\n// ── Encoder peer: lazy + memoized + injectable ──────────────────────────────────────────────────────\n\n/** The slice of `@nhtio/encoder`'s API surface this codec uses. Deliberately non-generic (`unknown` in,\n *  `unknown` out) — this codec always encodes/decodes values whose shape it cannot statically know, so\n *  the real encoder's `<T extends Encodable>`-constrained signature is narrowed away via\n *  {@link defaultEncoderLoader}'s adapter rather than reflected here. */\nexport interface EncoderModule {\n  /** Encode an arbitrary value to its `@nhtio/encoder` wire string. */\n  encode: (value: unknown) => string\n  /** Decode a `@nhtio/encoder` wire string back into the original value. */\n  decode: (encoded: string) => unknown\n  /** Register a class as custom-encodable so `encode`/`decode` round-trip its instances. */\n  registerClass: (ctor: { readonly name: string }) => void\n  /** Whether `value` is an instance of a class previously passed to `registerClass`. */\n  isCustomEncodable: (value: unknown) => boolean\n  /** Whether `value` is an `Error` (or subclass), per the encoder's own classification. */\n  isError: (value: unknown) => boolean\n}\n\n/** @internal Injectable loader seam so tests can simulate \"encoder not installed\" deterministically\n *  without actually uninstalling the real (installed) peer. Defaults to the real dynamic import. */\nexport type EncoderLoader = () => Promise<EncoderModule | undefined>\n\nconst defaultEncoderLoader: EncoderLoader = async () => {\n  try {\n    const [core, guards] = await Promise.all([\n      import('@nhtio/encoder'),\n      import('@nhtio/encoder/type_guards'),\n    ])\n    return {\n      // The real encoder's `encode`/`decode` are generic over its own `Encodable` union; this codec\n      // hands it values of unknown shape, so we narrow both to the codec-local `unknown`-based surface.\n      encode: core.encode as EncoderModule['encode'],\n      decode: core.decode as EncoderModule['decode'],\n      registerClass: core.registerClass as EncoderModule['registerClass'],\n      isCustomEncodable: guards.isCustomEncodable,\n      isError: guards.isError,\n    }\n  } catch {\n    return undefined\n  }\n}\n\nlet encoderLoader: EncoderLoader = defaultEncoderLoader\nlet memoizedEncoder: Promise<EncoderModule | undefined> | undefined\n\n/**\n * @internal Test-only seam: override the encoder loader (e.g. to simulate \"peer not installed\"). Pass\n * `undefined` to restore the default real dynamic import. Also clears the memoization cache.\n */\nexport const setEncoderLoaderForTests = (loader?: EncoderLoader): void => {\n  encoderLoader = loader ?? defaultEncoderLoader\n  memoizedEncoder = undefined\n}\n\n/** Lazily load (and memoize) the optional `@nhtio/encoder` peer. Resolves `undefined` when absent. */\nconst loadEncoder = (): Promise<EncoderModule | undefined> => {\n  if (!memoizedEncoder) memoizedEncoder = encoderLoader()\n  return memoizedEncoder\n}\n\n/** Whether the encoder peer is currently available. Used to populate `ready.encoderAvailable`. */\nexport const isEncoderAvailable = async (): Promise<boolean> => (await loadEncoder()) !== undefined\n\n// ── Transfer marker ──────────────────────────────────────────────────────────────────────────────────\n\nconst TRANSFER_MARKER = Symbol.for('@nhtio/adk/batteries/isolation:transfer')\n\ninterface TransferMarked {\n  [TRANSFER_MARKER]: true\n  value: unknown\n  transferables: unknown[]\n}\n\n/**\n * Mark `value` for transfer (rather than clone) across a `postMessage`-based transport — the Web Worker\n * transport unwraps this into the message's transfer list. The codec passes marked values through as\n * `raw` with `transferables` preserved on the {@link WireValue} envelope's `transfer` field. Node\n * transports ignore the marker entirely (structured-clone/pipe semantics don't have a transfer\n * list), so `transfer()` is safe to use in transport-agnostic code that may run over either.\n */\nexport const transfer = <T>(value: T, transferables: unknown[]): T => {\n  const marked: TransferMarked = { [TRANSFER_MARKER]: true, value, transferables }\n  return marked as unknown as T\n}\n\nconst isTransferMarked = (value: unknown): value is TransferMarked =>\n  isObject(value) && (value as Record<PropertyKey, unknown>)[TRANSFER_MARKER] === true\n\n// ── Exotic-leaf classification ───────────────────────────────────────────────────────────────────────\n\n/** Opaque-leaf types the traverser must never descend into (checked before the exotic-leaf probe). */\nconst isOpaqueContainer = (value: unknown): boolean =>\n  isInstanceOf(value, 'Date', Date) ||\n  isInstanceOf(value, 'RegExp', RegExp) ||\n  isInstanceOf(value, 'Map', Map) ||\n  isInstanceOf(value, 'Set', Set) ||\n  isInstanceOf(value, 'ArrayBuffer', ArrayBuffer) ||\n  ArrayBuffer.isView(value) // TypedArrays + DataView\n\nconst isPlainError = (value: unknown): value is Error => isError(value)\n\n/** Classify a leaf as exotic (needs encoding) given the currently-loaded encoder (if any). Returns the\n *  escalation reason string for observability, or `undefined` when the leaf is ordinary. */\nconst classifyExotic = (value: unknown, encoder: EncoderModule | undefined): string | undefined => {\n  if (typeof value === 'function') return 'function'\n  if (encoder ? encoder.isError(value) : isPlainError(value)) return 'error'\n  if (encoder && encoder.isCustomEncodable(value)) return 'custom-encodable'\n  return undefined\n}\n\n// ── Path-clone helper ─────────────────────────────────────────────────────────────────────────────────\n\n/** Clone only the containers along `path` (shallow-clone each ancestor), never the caller's original\n *  object, and never siblings off the path. Returns the new root plus a setter for the leaf at `path`. */\nconst cloneAlongPath = (\n  root: unknown,\n  path: PropertyKey[]\n): { root: unknown; setLeaf: (value: unknown) => void } => {\n  if (path.length === 0) {\n    let leafHolder = root\n    return {\n      root: leafHolder,\n      setLeaf: (value) => {\n        leafHolder = value\n      },\n    }\n  }\n  const shallowClone = (node: unknown): unknown => {\n    if (Array.isArray(node)) return node.slice()\n    if (node && typeof node === 'object') return { ...(node as Record<PropertyKey, unknown>) }\n    return node\n  }\n  const newRoot = shallowClone(root) as Record<PropertyKey, unknown>\n  let cursor: Record<PropertyKey, unknown> = newRoot\n  for (let i = 0; i < path.length - 1; i++) {\n    const key = path[i]\n    const cloned = shallowClone(cursor[key]) as Record<PropertyKey, unknown>\n    cursor[key] = cloned\n    cursor = cloned\n  }\n  const lastKey = path[path.length - 1]\n  return {\n    root: newRoot,\n    setLeaf: (value) => {\n      cursor[lastKey] = value\n    },\n  }\n}\n\n// ── Encode (per-argument) ────────────────────────────────────────────────────────────────────────────\n\n/** Result of scanning an argument for exotic leaves. */\ninterface ExoticScan {\n  /** Every exotic leaf found, with its path from the argument's root. */\n  leaves: Array<{ path: PropertyKey[]; value: unknown; reason: string }>\n  /** `true` when a circular reference was found ANYWHERE reachable only via an exotic-leaf subtree\n   *  (i.e. traversal reached a cycle while already inside/leading to exotic territory is irrelevant —\n   *  what matters is whether the OVERALL value has both a cycle and an exotic leaf, since the encoder\n   *  cannot represent either the whole value nor a sentineled fragment that itself cycles back outside\n   *  the cloned path). */\n  circular: boolean\n}\n\nconst scanForExotic = (arg: unknown, encoder: EncoderModule | undefined): ExoticScan => {\n  const leaves: ExoticScan['leaves'] = []\n  let circular = false\n  if (arg === null || typeof arg !== 'object') {\n    const reason = classifyExotic(arg, encoder)\n    if (reason) leaves.push({ path: [], value: arg, reason })\n    return { leaves, circular }\n  }\n  new Traverse(arg).forEach((ctx: TraverseContext, node: unknown) => {\n    if (ctx.circular) {\n      circular = true\n      return\n    }\n    // Opaque containers (including the root itself, e.g. a bare TypedArray argument): never exotic,\n    // block descent so traversal costs O(container) rather than O(bytes) for large typed arrays.\n    if (isOpaqueContainer(node)) {\n      ctx.block()\n      return\n    }\n    const reason = classifyExotic(node, encoder)\n    if (reason) {\n      leaves.push({ path: ctx.path.slice(), value: node, reason })\n      ctx.block()\n    }\n  })\n  return { leaves, circular }\n}\n\n/** Options threaded through {@link encodeArgument} for observability + BYO-codec support. */\nexport interface CodecContext {\n  /** Codec mode/override for this argument (method/stream-level `codec` option). Default `'auto'`. */\n  mode?: CodecMode\n  /** Called once per exotic leaf found in `'auto'` mode, before encoding it — observability hook seam\n   *  (`host.ts`/`serve.ts` wire this to `codec:escalate` reports). Given the ARGUMENT-RELATIVE path\n   *  (e.g. `['onProgress']`) and the classification reason. */\n  onEscalate?: (path: PropertyKey[], reason: string) => void\n  /** Human-readable label for this argument, used in thrown exception messages (e.g. `'args[0]'`). */\n  label: string\n}\n\n/**\n * Encode a single call/stream argument (or return value) into a {@link WireValue} per the tiered\n * strategy described in this module's header.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_ISOLATION_ENCODER_REQUIRED} when escalation is needed\n *   but no encoder (peer or BYO) is available.\n * @throws {@link @nhtio/adk/batteries/isolation!E_ISOLATION_UNENCODABLE} when a value contains a\n *   circular reference alongside an exotic leaf, or the encoder itself rejects the value.\n */\nexport const encodeArgument = async (arg: unknown, ctx: CodecContext): Promise<WireValue> => {\n  const mode = ctx.mode ?? 'auto'\n\n  if (mode === 'raw') {\n    return toRawWireValue(arg)\n  }\n\n  if (typeof mode === 'object') {\n    // BYO codec: whole-value encode via the injected functions, verbatim.\n    const encoded = await mode.encode(arg)\n    return { enc: 'nhtio', v: encoded }\n  }\n\n  if (mode === 'encoded') {\n    const encoder = await loadEncoder()\n    if (!encoder) {\n      throw new E_ISOLATION_ENCODER_REQUIRED([ctx.label])\n    }\n    try {\n      return { enc: 'nhtio', v: encoder.encode(arg) }\n    } catch (err) {\n      throw new E_ISOLATION_UNENCODABLE([ctx.label], { cause: err })\n    }\n  }\n\n  // mode === 'auto'\n  const encoder = await loadEncoder()\n  const { leaves, circular } = scanForExotic(arg, encoder)\n\n  if (leaves.length === 0) {\n    // No exotic leaves anywhere — including if `arg` itself is circular but plain. Ship raw untouched.\n    return toRawWireValue(arg)\n  }\n\n  if (circular) {\n    // A circular reference co-exists with an exotic leaf — the encoder cannot represent this shape.\n    throw new E_ISOLATION_UNENCODABLE([ctx.label])\n  }\n\n  if (leaves.length === 1 && leaves[0].path.length === 0) {\n    // The WHOLE argument is itself exotic (a bare function/Error/custom-encodable) — encode it directly.\n    if (!encoder) throw new E_ISOLATION_ENCODER_REQUIRED([ctx.label])\n    ctx.onEscalate?.([], leaves[0].reason)\n    try {\n      return { enc: 'nhtio', v: encoder.encode(arg) }\n    } catch (err) {\n      throw new E_ISOLATION_UNENCODABLE([ctx.label], { cause: err })\n    }\n  }\n\n  if (!encoder) {\n    throw new E_ISOLATION_ENCODER_REQUIRED([`${ctx.label}${formatPath(leaves[0].path)}`])\n  }\n\n  // Path-clone along each exotic leaf's path ONLY, replacing it with a `{ __nhtio$ }` sentinel. Never\n  // mutates the caller's original object; siblings off every exotic path stay untouched (same refs).\n  let root = arg\n  for (const leaf of leaves) {\n    ctx.onEscalate?.(leaf.path, leaf.reason)\n    let encodedLeaf: string\n    try {\n      encodedLeaf = encoder.encode(leaf.value)\n    } catch (err) {\n      throw new E_ISOLATION_UNENCODABLE([`${ctx.label}${formatPath(leaf.path)}`], { cause: err })\n    }\n    const { root: newRoot, setLeaf } = cloneAlongPath(root, leaf.path)\n    setLeaf({ __nhtio$: encodedLeaf })\n    root = newRoot\n  }\n  return toRawWireValue(root)\n}\n\nconst formatPath = (path: PropertyKey[]): string =>\n  path.length === 0 ? '' : `.${path.map(String).join('.')}`\n\n/** Build a `raw` {@link WireValue}, unwrapping a {@link transfer} marker into the envelope's\n *  `transfer` field when present. */\nconst toRawWireValue = (value: unknown): WireValue => {\n  if (isTransferMarked(value)) {\n    return { enc: 'raw', v: value.value, transfer: value.transferables }\n  }\n  return { enc: 'raw', v: value }\n}\n\n// ── Decode (per-argument) ────────────────────────────────────────────────────────────────────────────\n\n/** A raw value's sentinel shape for a path-cloned exotic leaf. */\ninterface NhtioSentinel {\n  __nhtio$: string\n}\n\nconst isNhtioSentinel = (value: unknown): value is NhtioSentinel =>\n  isObject(value) &&\n  typeof (value as Record<string, unknown>).__nhtio$ === 'string' &&\n  Object.keys(value as object).length === 1\n\n/**\n * Decode a {@link WireValue} back into the original value, rehydrating any `{ __nhtio$ }` sentinels\n * found while re-traversing a `raw` payload.\n *\n * @param wireValue - The value as it arrived over the wire.\n * @param mode - The SAME codec mode the sender used to encode it (needed for the BYO-codec case; ignored\n *   otherwise — the wire tier (`raw` vs `nhtio`) is otherwise self-describing).\n * @param label - Human-readable label for thrown exception messages.\n */\nexport const decodeArgument = async (\n  wireValue: WireValue,\n  mode: CodecMode | undefined,\n  label: string\n): Promise<unknown> => {\n  if (wireValue.enc === 'nhtio') {\n    if (typeof mode === 'object') {\n      return mode.decode(wireValue.v)\n    }\n    const encoder = await loadEncoder()\n    if (!encoder) throw new E_ISOLATION_ENCODER_REQUIRED([label])\n    try {\n      return encoder.decode(wireValue.v)\n    } catch (err) {\n      throw new E_ISOLATION_UNENCODABLE([label], { cause: err })\n    }\n  }\n\n  // enc === 'raw': re-traverse looking for `{ __nhtio$ }` sentinels to rehydrate. Fast-path: primitives\n  // and objects with no sentinel anywhere pass through completely untouched (same reference).\n  const raw = wireValue.v\n  if (raw === null || typeof raw !== 'object') return raw\n  if (isNhtioSentinel(raw)) {\n    const encoder = await loadEncoder()\n    if (!encoder) throw new E_ISOLATION_ENCODER_REQUIRED([label])\n    try {\n      return encoder.decode(raw.__nhtio$)\n    } catch (err) {\n      throw new E_ISOLATION_UNENCODABLE([label], { cause: err })\n    }\n  }\n\n  const sentinelPaths: PropertyKey[][] = []\n  new Traverse(raw).forEach((ctx: TraverseContext, node: unknown) => {\n    if (ctx.circular) return\n    // Uniform opaque-container short-circuit (including at the root) — same O(container)-not-O(bytes)\n    // requirement as `scanForExotic`'s encode-side traversal.\n    if (isOpaqueContainer(node)) {\n      ctx.block()\n      return\n    }\n    if (isNhtioSentinel(node)) {\n      sentinelPaths.push(ctx.path.slice())\n      ctx.block()\n    }\n  })\n  if (sentinelPaths.length === 0) return raw\n\n  const encoder = await loadEncoder()\n  if (!encoder) throw new E_ISOLATION_ENCODER_REQUIRED([label])\n  let root: unknown = raw\n  for (const path of sentinelPaths) {\n    const traverseHelper = new Traverse(root)\n    const sentinel = traverseHelper.get(path as PropertyKey[]) as NhtioSentinel\n    let decoded: unknown\n    try {\n      decoded = encoder.decode(sentinel.__nhtio$)\n    } catch (err) {\n      throw new E_ISOLATION_UNENCODABLE([`${label}${formatPath(path)}`], { cause: err })\n    }\n    const { root: newRoot, setLeaf } = cloneAlongPath(root, path)\n    setLeaf(decoded)\n    root = newRoot\n  }\n  return root\n}\n\n/** Register classes for `@nhtio/encoder`'s custom-encodable round-trip (sugar over `registerClass`,\n *  called lazily once the encoder is loaded). Throws `E_ISOLATION_ENCODER_REQUIRED` when classes are\n *  listed but the peer is not installed. */\nexport const registerEncodableClasses = async (\n  encodables: ReadonlyArray<{ readonly name: string }>\n): Promise<void> => {\n  if (encodables.length === 0) return\n  const encoder = await loadEncoder()\n  if (!encoder) {\n    throw new E_ISOLATION_ENCODER_REQUIRED(['encodables option'])\n  }\n  for (const ctor of encodables) {\n    encoder.registerClass(ctor as never)\n  }\n}\n\n// ── Error crossing (WireError) ───────────────────────────────────────────────────────────────────────\n\n/**\n * Build a {@link WireError} from a thrown value. The baseline `message`/`name`/`stack` fields are\n * ALWAYS populated (never omitted regardless of encoder availability) — error-classification-by-\n * message-signature must keep working even when the encoder is unavailable or a decode later fails.\n * When `includeRich` is `true` (both sides advertised `encoderAvailable`), ALSO attempts to encode the\n * original error via `@nhtio/encoder` onto `nhtio` — best-effort: an encode failure silently omits\n * `nhtio` rather than failing the whole error-crossing.\n */\nexport const toWireError = async (err: unknown, includeRich: boolean): Promise<WireError> => {\n  const isErr = isError(err)\n  const message = isErr ? err.message : typeof err === 'string' ? err : String(err)\n  const name = isErr ? err.name : 'Error'\n  const stack = isErr ? err.stack : undefined\n  const wireError: WireError = { message, name, stack }\n  if (includeRich && isErr) {\n    const encoder = await loadEncoder()\n    if (encoder) {\n      try {\n        wireError.nhtio = encoder.encode(err)\n      } catch {\n        // Best-effort rich path — the baseline fields already carry full message/name/stack fidelity.\n      }\n    }\n  }\n  return wireError\n}\n\n/**\n * Reconstruct an `Error` from a {@link WireError}, preferring the `nhtio`-encoded original when present\n * and decodable. Falls back silently to the baseline `name`/`message`/`stack` fields on ANY decode\n * failure (missing encoder, corrupt payload, version mismatch) — the baseline is always sufficient for\n * message-signature-based classification.\n */\nexport const fromWireError = async (wireError: WireError): Promise<Error> => {\n  if (wireError.nhtio) {\n    const encoder = await loadEncoder()\n    if (encoder) {\n      try {\n        const decoded = encoder.decode(wireError.nhtio)\n        if (isError(decoded)) return decoded\n      } catch {\n        // Fall through to the baseline reconstruction below.\n      }\n    }\n  }\n  const err = new Error(wireError.message)\n  err.name = wireError.name\n  if (wireError.stack) err.stack = wireError.stack\n  return err\n}\n","/**\n * Sliding-window crash-escalation policy for isolated services.\n *\n * @remarks\n * Generalizes the flagship agent's `GpuLossPolicy`\n * (`docs/.vitepress/theme/components/agent/gpu_loss_policy.ts`) — a 2-rung ladder specific to WebGPU\n * device loss — into a domain-neutral N-rung decider any `IsolationTransport` crash can consult. Pure\n * (no DOM/process access beyond the injected clock), so it is unit-testable in isolation and reusable\n * across the Web Worker and child_process transports without either depending on the other's\n * crash semantics.\n *\n * This module has zero imports beyond the language itself.\n */\n\n/** The escalation {@link CrashPolicy.record} decided for a single crash event. */\nexport type CrashVerdict = 'respawn' | 'giveUp'\n\n/** How long a run of crashes must fall within to count toward the same escalation window. */\nexport const DEFAULT_CRASH_POLICY_WINDOW_MS = 120_000\n\n/** How many crashes inside the window are tolerated (with `'respawn'`) before `'giveUp'`. */\nexport const DEFAULT_CRASH_POLICY_MAX_CRASHES = 3\n\n/** Options accepted by {@link createCrashPolicy}. */\nexport interface CrashPolicyOptions {\n  /** Sliding window, in ms; a crash older than this no longer counts toward escalation. Default 120_000. */\n  windowMs?: number\n  /** Crashes tolerated inside the window (inclusive) before `record()` returns `'giveUp'`. Default 3. */\n  maxCrashes?: number\n  /** Injectable clock (for tests). Default `Date.now`. */\n  now?: () => number\n}\n\n/** A sliding-window crash-escalation decider, as returned by {@link createCrashPolicy}. */\nexport interface CrashPolicy {\n  /**\n   * Record a crash event and return the escalation verdict: `'respawn'` while the number of crashes\n   * inside the current window (including this one) is still under `maxCrashes`, `'giveUp'` once it\n   * reaches `maxCrashes`. Prunes crashes older than the window before deciding, so a crash burst that\n   * cools off resets the count.\n   */\n  record(): CrashVerdict\n  /** Number of crashes currently inside the window (observability/tests). */\n  readonly recentCount: number\n  /** Clear the crash history (e.g. after a clean recovery + a settled session). */\n  reset(): void\n}\n\n/**\n * Build a sliding-window crash-escalation policy: the first `maxCrashes - 1` crashes inside `windowMs`\n * each return `'respawn'`; the `maxCrashes`-th (and every crash after it, while still inside the\n * window) returns `'giveUp'`. Two crashes spaced further apart than `windowMs` are each treated as a\n * fresh, first-in-window crash — an occasional isolated crash over a long-running session never\n * escalates.\n *\n * @param options - See {@link CrashPolicyOptions}.\n */\nexport const createCrashPolicy = (options: CrashPolicyOptions = {}): CrashPolicy => {\n  const windowMs = options.windowMs ?? DEFAULT_CRASH_POLICY_WINDOW_MS\n  const maxCrashes = options.maxCrashes ?? DEFAULT_CRASH_POLICY_MAX_CRASHES\n  const now = options.now ?? Date.now\n  let timestamps: number[] = []\n\n  const prune = (): void => {\n    const t = now()\n    timestamps = timestamps.filter((ts) => t - ts < windowMs)\n  }\n\n  return {\n    record(): CrashVerdict {\n      prune()\n      timestamps.push(now())\n      return timestamps.length >= maxCrashes ? 'giveUp' : 'respawn'\n    },\n    get recentCount(): number {\n      prune()\n      return timestamps.length\n    },\n    reset(): void {\n      timestamps = []\n    },\n  }\n}\n","/**\n * Shared observability contract for the isolation battery — spawn/dispose/recycle/crash/call/stream\n * lifecycle, wire-level tracing, and codec-escalation reporting.\n *\n * @remarks\n * Mirrors the shape of the LLM batteries' `BatteryLifecycleHooks`/`emitLifecycle` pattern\n * (`src/batteries/llm/chat_common/lifecycle.ts`): an aggregate firehose ({@link\n * IsolationObservabilityHooks.onIsolation}) fires on EVERY report, alongside a per-phase-group hook.\n * All hooks are optional and additive — omitting every hook leaves the battery's behavior byte-for-byte\n * unchanged, and {@link emitIsolationReport} skips assembling a report entirely when no relevant hook is\n * registered (zero overhead when unhooked).\n *\n * This module has zero imports beyond the language itself — `host.ts`/`serve.ts`/`protocol.ts` depend on\n * it, never the reverse.\n */\n\n/** The coarse phase groups an isolation report can belong to. */\nexport type IsolationReportPhase =\n  | 'spawn:start'\n  | 'spawn:ready'\n  | 'spawn:error'\n  | 'dispose:start'\n  | 'dispose:done'\n  | 'recycle:start'\n  | 'recycle:done'\n  | 'crash'\n  | 'respawn:auto'\n  | 'call:start'\n  | 'call:settle'\n  | 'stream:start'\n  | 'stream:end'\n  | 'stream:error'\n  | 'stream:cancel'\n  | 'abort:sent'\n  | 'wire:out'\n  | 'wire:in'\n  | 'codec:escalate'\n\n/**\n * A single normalized isolation observability report. Every phase stamps `phase`/`at`/`spawnCount` plus\n * its own extra fields (see the per-phase hook docs on {@link IsolationObservabilityHooks} for which\n * extra fields a given `phase` populates).\n */\nexport interface IsolationReport {\n  /** The phase this report describes. */\n  phase: IsolationReportPhase\n  /** ISO-8601 timestamp stamped when the report was emitted. */\n  at: string\n  /** The service's `name` (from its spec), when available. */\n  serviceName?: string\n  /** How many times this service's guest has been (re)spawned, including the current spawn. */\n  spawnCount: number\n  /** `spawn:ready` — time from `connect()` call to the `ready` envelope, in ms. */\n  bootMs?: number\n  /** `spawn:error` / `crash` — the underlying error/reason. */\n  error?: unknown\n  /** `dispose:done` — `true` when the grace period elapsed and `transport.terminate()` was forced. */\n  forced?: boolean\n  /** `crash` — the transport-reported crash reason. */\n  reason?: string\n  /** `crash` — process exit code, when known. */\n  code?: number | null\n  /** `crash` — process exit signal, when known. */\n  signal?: string | null\n  /** `crash` — number of calls that were in flight (and rejected) at the moment of the crash. */\n  inFlight?: number\n  /** `respawn:auto` — the crash-policy verdict that was consulted. */\n  verdict?: 'respawn' | 'giveUp'\n  /** `call:start` / `call:settle` — the method name. */\n  method?: string\n  /** `call:start` / `call:settle` — the correlation id. */\n  id?: string\n  /** `call:settle` — wall-clock duration of the call, in ms. */\n  durationMs?: number\n  /** `call:settle` — `true` when the call resolved; `false` when it rejected. */\n  ok?: boolean\n  /** `call:settle` (when `ok` is `false`) — the rejection's message. */\n  errorMessage?: string\n  /** `stream:start` / `stream:end` / `stream:error` / `stream:cancel` — the stream name. */\n  streamName?: string\n  /** `stream:end` / `stream:cancel` — total deltas observed before end/cancel. */\n  deltaCount?: number\n  /** `stream:end` — ms from `stream:start` to the first delta (`undefined` if none arrived). */\n  firstDeltaMs?: number\n  /** `stream:error` — the stream's terminal error. */\n  streamError?: unknown\n  /** `wire:out` / `wire:in` — the envelope's discriminant (`'call'`, `'result'`, `'stream:delta'`, …). */\n  kind?: string\n  /** `wire:out` / `wire:in` — which codec tier carried the payload (`'raw'` or `'nhtio'`), when known. */\n  tier?: string\n  /** `wire:out` / `wire:in` — a cheap `JSON.stringify(...).length`-style size estimate; computed ONLY\n   *  when a wire hook is registered (see {@link emitIsolationReport}). */\n  approxBytes?: number\n  /** `codec:escalate` — the argument path that needed to escalate past the `'raw'` tier. */\n  argPath?: string\n  /** `codec:escalate` — why it escalated (e.g. `'function'`, `'error'`, `'custom-encodable'`). */\n  escalateReason?: string\n  /** With `debugPayloads: true` on a `call:*`/`wire:*` report — the raw payload body. */\n  payload?: unknown\n}\n\n/** An isolation report consumer. */\nexport type IsolationReportCallback = (report: IsolationReport) => void\n\n/**\n * The opt-in observability option block mixed into `createIsolatedService`/`serveIsolated` options.\n * Every reported phase fires {@link onIsolation} (the firehose) AND its matching per-phase-group hook;\n * subscribe to either or both. All optional — omitting them leaves behavior byte-for-byte unchanged.\n */\nexport interface IsolationObservabilityHooks {\n  /** Fires on EVERY report (the firehose). */\n  onIsolation?: IsolationReportCallback\n  /** `spawn:start` / `spawn:ready` / `spawn:error` — guest connect lifecycle. */\n  onSpawn?: IsolationReportCallback\n  /** `dispose:start` / `dispose:done` — graceful-then-forced teardown. */\n  onDispose?: IsolationReportCallback\n  /** `recycle:start` / `recycle:done` — terminate + reconnect through the same transport. */\n  onRecycle?: IsolationReportCallback\n  /** `crash` — the transport reported an unexpected guest exit/termination. */\n  onCrashReport?: IsolationReportCallback\n  /** `respawn:auto` — an `autoRespawn` crash-policy verdict was consulted and acted on. */\n  onRespawnAuto?: IsolationReportCallback\n  /** `call:start` / `call:settle` — a single request/response method call. */\n  onCall?: IsolationReportCallback\n  /** `stream:start` / `stream:end` / `stream:error` / `stream:cancel` — a streaming method call. */\n  onStream?: IsolationReportCallback\n  /** `abort:sent` — the host sent an `abort` envelope for an in-flight call. */\n  onAbort?: IsolationReportCallback\n  /** `wire:out` / `wire:in` — every envelope crossing the wire (verbose; opt in deliberately). */\n  onWire?: IsolationReportCallback\n  /** `codec:escalate` — the codec escalated an argument past the `'raw'` tier. */\n  onCodecEscalate?: IsolationReportCallback\n  /** Include payload bodies on `call:*`/`wire:*` reports (see {@link IsolationReport.payload}).\n   *  Default `false` — payloads may be large/sensitive, so this is opt-in even when hooks are wired. */\n  debugPayloads?: boolean\n}\n\n/** The subset of {@link IsolationObservabilityHooks} keys that are per-phase-group report callbacks\n *  (excludes the firehose `onIsolation` and the non-callback `debugPayloads` flag). */\ntype PerPhaseGroupHookKey = Exclude<\n  keyof IsolationObservabilityHooks,\n  'onIsolation' | 'debugPayloads'\n>\n\n/** Map each phase to its per-phase-group hook key on {@link IsolationObservabilityHooks}. */\nconst PER_PHASE_GROUP_HOOK: Record<IsolationReportPhase, PerPhaseGroupHookKey> = {\n  'spawn:start': 'onSpawn',\n  'spawn:ready': 'onSpawn',\n  'spawn:error': 'onSpawn',\n  'dispose:start': 'onDispose',\n  'dispose:done': 'onDispose',\n  'recycle:start': 'onRecycle',\n  'recycle:done': 'onRecycle',\n  'crash': 'onCrashReport',\n  'respawn:auto': 'onRespawnAuto',\n  'call:start': 'onCall',\n  'call:settle': 'onCall',\n  'stream:start': 'onStream',\n  'stream:end': 'onStream',\n  'stream:error': 'onStream',\n  'stream:cancel': 'onStream',\n  'abort:sent': 'onAbort',\n  'wire:out': 'onWire',\n  'wire:in': 'onWire',\n  'codec:escalate': 'onCodecEscalate',\n}\n\n/** Invoke a consumer callback, swallowing any throw so a misbehaving hook never breaks the battery. */\nconst safeInvoke = (cb: IsolationReportCallback | undefined, report: IsolationReport): void => {\n  if (typeof cb !== 'function') return\n  try {\n    cb(report)\n  } catch {\n    // A throwing consumer hook must never abort a spawn, call, or stream. Intentionally swallowed.\n  }\n}\n\n/**\n * Returns `true` when at least one hook relevant to `phase` is registered — the guard\n * {@link emitIsolationReport} uses to skip assembling a report entirely (zero overhead when unhooked).\n */\nexport const hasIsolationHook = (\n  hooks: IsolationObservabilityHooks | undefined,\n  phase: IsolationReportPhase\n): boolean => Boolean(hooks && (hooks.onIsolation || hooks[PER_PHASE_GROUP_HOOK[phase]]))\n\n/**\n * Build an {@link IsolationReport} (stamping `at`) and dispatch it to the firehose\n * ({@link IsolationObservabilityHooks.onIsolation}) AND the per-phase-group hook for `phase`. A no-op\n * when `hooks` is undefined or carries no relevant callbacks — callers should additionally guard\n * expensive `extra` computation (e.g. `approxBytes` sizing) behind {@link hasIsolationHook} so it is\n * never computed when unhooked. Each callback is invoked through {@link safeInvoke}, so a throwing\n * consumer never disrupts the battery.\n *\n * @param hooks - The isolation observability hooks (may be undefined).\n * @param phase - The phase being reported.\n * @param base - `serviceName` + `spawnCount`, common to every report.\n * @param extra - Phase-specific fields (see {@link IsolationReport}).\n * @param now - Injectable clock for tests; defaults to `new Date().toISOString()`.\n */\nexport const emitIsolationReport = (\n  hooks: IsolationObservabilityHooks | undefined,\n  phase: IsolationReportPhase,\n  base: { serviceName?: string; spawnCount: number },\n  extra?: Omit<Partial<IsolationReport>, 'phase' | 'at' | 'serviceName' | 'spawnCount'>,\n  now: () => string = () => new Date().toISOString()\n): void => {\n  if (!hasIsolationHook(hooks, phase)) return\n  const report: IsolationReport = {\n    phase,\n    at: now(),\n    serviceName: base.serviceName,\n    spawnCount: base.spawnCount,\n    ...(extra ?? {}),\n  }\n  safeInvoke(hooks!.onIsolation, report)\n  safeInvoke(hooks![PER_PHASE_GROUP_HOOK[phase]], report)\n}\n","/**\n * Guest-side server — runs a caller's {@link IsolatedImplementation} against a {@link PortLike},\n * dispatching inbound `call`/`stream:start`/`stream:cancel`/`abort`/`shutdown` envelopes via a\n * {@link GuestEndpoint} and encoding results/deltas/errors back across the wire via the tiered codec.\n *\n * @remarks\n * `serveIsolatedOverPort` is the environment-neutral primitive: it takes an already-constructed\n * {@link PortLike}, so it works identically whether that port wraps a Web Worker's global scope, a\n * node `process`, or (as in the shared protocol's unit specs) a linked in-memory fake port. `serveIsolated` is the\n * convenience wrapper the browser and Node guest entry points call directly: it duck-detects the environment\n * (`globalThis.self.postMessage` → Worker; `globalThis.process?.send` → child_process) and builds the\n * matching `PortLike` itself — WITHOUT importing any `node:*` module (a plain `globalThis.process` duck\n * check, never `import 'node:...'`), keeping this module loadable in every environment.\n */\n\nimport { GuestEndpoint } from './protocol'\nimport { E_ISOLATION_UNSUPPORTED_ENV } from './exceptions'\nimport { validateServeIsolatedOptions } from './validation'\nimport {\n  emitIsolationReport,\n  hasIsolationHook,\n  type IsolationObservabilityHooks,\n} from './observability'\nimport {\n  decodeArgument,\n  encodeArgument,\n  isEncoderAvailable,\n  registerEncodableClasses,\n  toWireError,\n} from './codec'\nimport type { WireValue } from './protocol'\nimport type {\n  CodecMode,\n  IsolatedEmitter,\n  IsolatedImplementation,\n  IsolatedServiceSpec,\n  IsolationCallContext,\n  PortLike,\n  StreamHandle,\n} from './types'\n\n/** Options accepted by {@link serveIsolated}/{@link serveIsolatedOverPort}. */\nexport interface ServeIsolatedOptions extends IsolationObservabilityHooks {\n  /** Classes to register with `@nhtio/encoder`'s custom-encodable round-trip on this side (sugar over\n   *  `registerClass`; lazy — only touches the encoder peer when this array is non-empty). */\n  encodables?: ReadonlyArray<{ readonly name: string }>\n}\n\n/** The implementation factory `serveIsolated`/`serveIsolatedOverPort` calls once, up front, to obtain\n *  the guest-side method/stream implementations plus the `emit` capability for declared events. */\nexport type IsolatedImplementationFactory<S extends IsolatedServiceSpec> = (input: {\n  emit: IsolatedEmitter<S>\n  /** Issue a guest-to-host capability call. */\n  hostcall: (method: string, args: WireValue[], maxBytes?: number) => Promise<WireValue | string>\n}) => IsolatedImplementation<S>\n\nconst codecModeFor = (declared: CodecMode | undefined): CodecMode | undefined => declared\n\n/** Turn an `AsyncIterable`/`ReadableStream` into a uniform async-iterator-like reader with a\n *  best-effort `cancel()`. */\nconst toStreamReader = <D>(\n  source: ReadableStream<D> | AsyncIterable<D>\n): { next: () => Promise<IteratorResult<D>>; cancel: () => void } => {\n  if (Symbol.asyncIterator in source) {\n    const iterator = (source as AsyncIterable<D>)[Symbol.asyncIterator]()\n    return {\n      next: () => iterator.next(),\n      cancel: () => {\n        void iterator.return?.()\n      },\n    }\n  }\n  const reader = (source as ReadableStream<D>).getReader()\n  return {\n    next: () => reader.read() as Promise<IteratorResult<D>>,\n    cancel: () => {\n      void reader.cancel()\n    },\n  }\n}\n\n/**\n * Serve `spec` over an already-constructed {@link PortLike} — the environment-neutral primitive.\n * Builds the implementation via `factory`, wires a {@link GuestEndpoint} to it, and announces\n * readiness (`ready` envelope) once the encoder-availability probe resolves.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} when `options` fails\n *   validation.\n * @returns A `stop()` function that tears down the endpoint's port subscription. Does NOT itself close\n *   the port — callers own the port's lifecycle.\n */\nexport const serveIsolatedOverPort = <S extends IsolatedServiceSpec>(\n  spec: S,\n  factory: IsolatedImplementationFactory<S>,\n  port: PortLike,\n  options?: ServeIsolatedOptions\n): { stop: () => void } => {\n  const resolved = validateServeIsolatedOptions(options)\n  let spawnCount = 1\n  const emitReport = (\n    phase: Parameters<typeof emitIsolationReport>[1],\n    extra?: Parameters<typeof emitIsolationReport>[3]\n  ): void => emitIsolationReport(resolved, phase, { serviceName: spec.name, spawnCount }, extra)\n\n  let encoderAvailable = false\n  const openStreams = new Map<string, { cancel: () => void }>()\n\n  let endpoint: GuestEndpoint\n  const emitter = new Proxy(\n    {},\n    {\n      get: (_target, channel: string) => (payload: unknown) => {\n        void (async () => {\n          const wire = await encodeArgument(payload, {\n            label: `event ${channel}`,\n            onEscalate: (path, reason) =>\n              emitReport('codec:escalate', {\n                argPath: `${channel}${pathSuffix(path)}`,\n                escalateReason: reason,\n              }),\n          })\n          endpoint.emit(channel, wire)\n        })()\n      },\n    }\n  ) as IsolatedEmitter<S>\n\n  endpoint = new GuestEndpoint(port, {\n    onEnvelope: (dir, envelope) => {\n      if (!hasIsolationHook(resolved, dir === 'out' ? 'wire:out' : 'wire:in')) return\n      emitReport(dir === 'out' ? 'wire:out' : 'wire:in', { kind: envelope.t })\n    },\n    onCall: (id, methodName, args, signal) => {\n      void handleCall(id, methodName, args, signal)\n    },\n    onStreamStart: (id, streamName, args, signal) => {\n      void handleStreamStart(id, streamName, args, signal)\n    },\n    onStreamCancel: (id) => {\n      openStreams.get(id)?.cancel()\n      openStreams.delete(id)\n    },\n    onShutdown: () => {\n      // Best-effort: nothing more to clean up at this layer; the guest process/worker exit is the\n      // caller's responsibility (serveIsolated's environment-specific wrapper, or the consumer script).\n    },\n  })\n\n  // CONSTRUCTED BEFORE THE FACTORY RUNS, deliberately. The factory receives a `hostcall` capability\n  // that closes over `endpoint`, and a factory may legitimately invoke it SYNCHRONOUSLY — to fetch the\n  // configuration it needs in order to build the implementation. Calling the factory first left that\n  // closure reading an unassigned binding, so such a factory threw instead of producing a service.\n  //\n  // Safe in this order because the endpoint's handlers reach `implementation` only from inside\n  // `handleCall`/`handleStreamStart`, which run when a call arrives — never during construction — and\n  // there is no await between these two statements for an inbound message to interleave into.\n  const implementation = factory({\n    emit: emitter,\n    hostcall: (method, args, maxBytes) => endpoint.hostcall(method, args, maxBytes).promise,\n  })\n\n  const handleCall = async (\n    id: string,\n    methodName: string,\n    args: WireValue[],\n    signal: AbortSignal\n  ): Promise<void> => {\n    const descriptor = spec.methods[methodName]\n    const start = Date.now()\n    emitReport('call:start', { method: methodName, id })\n    try {\n      if (!descriptor) {\n        throw new Error(`Unknown method \"${methodName}\" on isolated service \"${spec.name}\"`)\n      }\n      const mode = codecModeFor(descriptor.codec)\n      const decodedArgs = await Promise.all(\n        args.map((a, i) => decodeArgument(a, mode, `${methodName} args[${i}]`))\n      )\n      const fn = (implementation as Record<string, (...a: unknown[]) => unknown>)[methodName]\n      const callArgs = descriptor.signal\n        ? [...decodedArgs, { signal } satisfies IsolationCallContext]\n        : decodedArgs\n      const result = await fn(...callArgs)\n      const wireResult = await encodeArgument(result, {\n        mode,\n        label: `${methodName} result`,\n        onEscalate: (path, reason) =>\n          emitReport('codec:escalate', {\n            argPath: `${methodName} result${pathSuffix(path)}`,\n            escalateReason: reason,\n          }),\n      })\n      endpoint.settleOk(id, wireResult)\n      emitReport('call:settle', {\n        method: methodName,\n        id,\n        durationMs: Date.now() - start,\n        ok: true,\n      })\n    } catch (err) {\n      const wireError = await toWireError(err, encoderAvailable)\n      endpoint.settleError(id, wireError)\n      emitReport('call:settle', {\n        method: methodName,\n        id,\n        durationMs: Date.now() - start,\n        ok: false,\n        errorMessage: wireError.message,\n      })\n    }\n  }\n\n  const handleStreamStart = async (\n    id: string,\n    streamName: string,\n    args: WireValue[],\n    signal: AbortSignal\n  ): Promise<void> => {\n    emitReport('stream:start', { streamName, id })\n    const descriptor = spec.streams[streamName]\n    let deltaCount = 0\n    const startedAt = Date.now()\n    let firstDeltaMs: number | undefined\n    try {\n      if (!descriptor) {\n        throw new Error(`Unknown stream \"${streamName}\" on isolated service \"${spec.name}\"`)\n      }\n      const mode = codecModeFor(descriptor.codec)\n      const decodedArgs = await Promise.all(\n        args.map((a, i) => decodeArgument(a, mode, `${streamName} args[${i}]`))\n      )\n      const fn = (implementation as Record<string, (...a: unknown[]) => unknown>)[streamName]\n      const handle: StreamHandle = { signal }\n      const source = (await fn(...decodedArgs, handle)) as\n        | ReadableStream<unknown>\n        | AsyncIterable<unknown>\n      const reader = toStreamReader(source)\n      openStreams.set(id, { cancel: reader.cancel })\n      while (true) {\n        const { value, done } = await reader.next()\n        if (done) break\n        deltaCount += 1\n        if (firstDeltaMs === undefined) firstDeltaMs = Date.now() - startedAt\n        const wireDelta = await encodeArgument(value, {\n          mode,\n          label: `${streamName} delta`,\n          onEscalate: (path, reason) =>\n            emitReport('codec:escalate', {\n              argPath: `${streamName} delta${pathSuffix(path)}`,\n              escalateReason: reason,\n            }),\n        })\n        endpoint.pushDelta(id, wireDelta)\n      }\n      openStreams.delete(id)\n      endpoint.endStream(id)\n      emitReport('stream:end', { streamName, id, deltaCount, firstDeltaMs })\n    } catch (err) {\n      openStreams.delete(id)\n      const wireError = await toWireError(err, encoderAvailable)\n      endpoint.errorStream(id, wireError)\n      emitReport('stream:error', { streamName, id, streamError: wireError })\n    }\n  }\n\n  // Probe encoder availability then announce readiness. Kept async but fire-and-forget from the\n  // constructor's perspective — `serveIsolatedOverPort` returns synchronously; the host's own queued-\n  // before-ready flush means no call is lost while this resolves.\n  void (async () => {\n    encoderAvailable = await isEncoderAvailable()\n    if (resolved.encodables && resolved.encodables.length > 0) {\n      await registerEncodableClasses(resolved.encodables)\n    }\n    endpoint.ready(encoderAvailable)\n    emitReport('spawn:ready', { bootMs: 0 })\n  })()\n\n  return {\n    stop: () => {\n      // `terminate()` FIRST: a pending `hostcall` lives in the endpoint's own map, not in\n      // `openStreams`, so cancelling streams alone left the guest's capability promise unsettled and\n      // whatever awaited it hanging for the life of the process. Stopping must settle every promise it\n      // owns, and a rejection is the honest outcome — the result is never coming.\n      endpoint.terminate('Isolated service stopped')\n      for (const [, s] of openStreams) s.cancel()\n      openStreams.clear()\n    },\n  }\n}\n\nconst pathSuffix = (path: PropertyKey[]): string =>\n  path.length === 0 ? '' : `.${path.map(String).join('.')}`\n\n/** Duck-detect a Web Worker global scope: `self.postMessage` present and NOT a node `process`. */\nconst detectWorkerScope = (): PortLike | undefined => {\n  const g = globalThis as unknown as {\n    self?: { postMessage?: (msg: unknown, ...rest: unknown[]) => void; addEventListener?: unknown }\n    postMessage?: (msg: unknown, ...rest: unknown[]) => void\n    addEventListener?: (type: string, fn: (ev: unknown) => void) => void\n    removeEventListener?: (type: string, fn: (ev: unknown) => void) => void\n  }\n  const scope = g.self ?? g\n  if (typeof scope.postMessage !== 'function' || typeof g.addEventListener !== 'function') {\n    return undefined\n  }\n  return {\n    post: (msg) => scope.postMessage!(msg),\n    onMessage: (fn) => {\n      const listener = (ev: unknown): void => fn((ev as { data: unknown }).data)\n      g.addEventListener!('message', listener)\n      return () => g.removeEventListener?.('message', listener)\n    },\n  }\n}\n\n/** Duck-detect a node child_process guest: `process.send` present. Accessed ONLY via `globalThis` —\n *  this module never `import`s `node:*` so it stays loadable unmodified in a Worker/browser bundle. */\nconst detectChildProcessScope = (): PortLike | undefined => {\n  const proc = (globalThis as unknown as { process?: NodeProcessLike }).process\n  if (!proc || typeof proc.send !== 'function') return undefined\n  return {\n    post: (msg) => proc.send!(msg),\n    onMessage: (fn) => {\n      const listener = (msg: unknown): void => fn(msg)\n      proc.on('message', listener)\n      return () => proc.off?.('message', listener)\n    },\n  }\n}\n\n/** Minimal structural shape of node's `process` this module reads — never imports `node:process`. */\ninterface NodeProcessLike {\n  send?: (msg: unknown) => void\n  on: (event: 'message', fn: (msg: unknown) => void) => void\n  off?: (event: 'message', fn: (msg: unknown) => void) => void\n}\n\n/**\n * Serve `spec` in the CURRENT environment, duck-detecting a Web Worker global scope\n * (`globalThis.self.postMessage`) or a node child_process (`globalThis.process.send`) — in that\n * order — and building the matching {@link PortLike} automatically. This module never imports any\n * `node:*` builtin, so it is safe to bundle for either target; the detection is a pure `globalThis`\n * duck check.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_ISOLATION_UNSUPPORTED_ENV} when neither environment\n *   is detected (e.g. called on a plain main-thread browser tab, or in a test with no fake `self`/\n *   `process.send`) — use {@link serveIsolatedOverPort} directly there instead.\n */\nexport const serveIsolated = <S extends IsolatedServiceSpec>(\n  spec: S,\n  factory: IsolatedImplementationFactory<S>,\n  options?: ServeIsolatedOptions\n): { stop: () => void } => {\n  const port = detectWorkerScope() ?? detectChildProcessScope()\n  if (!port) {\n    throw new E_ISOLATION_UNSUPPORTED_ENV([\n      'neither a Web Worker global scope (self.postMessage) nor a node child_process (process.send) was detected — use serveIsolatedOverPort with an explicit PortLike instead',\n    ])\n  }\n  return serveIsolatedOverPort(spec, factory, port, options)\n}\n","/**\n * Host-side facade builder — `createIsolatedService(spec, transport, options?)` drives an\n * {@link IsolationTransport} (spawn/terminate/crash duck), wires a {@link HostEndpoint} to the\n * connected {@link PortLike}, and returns an {@link IsolatedService} whose `.api` is a plain object of\n * promise-returning methods / `ReadableStream`-returning streams matching `spec`.\n *\n * @remarks\n * `.api` is built once, up front, by iterating `spec.methods`/`spec.streams` — NOT a `Proxy` — so every\n * call site gets ordinary, debuggable function properties. Calls/stream-starts made before the guest's\n * `ready` envelope arrives queue transparently inside `HostEndpoint`; a `readyTimeoutMs` watchdog (default\n * 30s) rejects the connection attempt with `E_ISOLATION_READY_TIMEOUT` if `ready` never arrives.\n *\n * `dispose()` asks the guest to shut down gracefully, gives it `disposeGraceMs` (default 2000ms) to exit\n * on its own, then forces `transport.terminate()` regardless. `recycle()` terminates and reconnects\n * through the SAME `transport.connect()` — the returned `IsolatedService` object's identity and every\n * `.on(...)` subscription survive a recycle; only in-flight work is rejected with `E_ISOLATED_TERMINATED`.\n *\n * A transport-reported crash (`transport.onCrash`) rejects in-flight calls/streams with\n * `E_ISOLATED_CRASHED`, flips `state` to `'crashed'`, and fans out to `.onCrash(...)` subscribers.  With\n * `autoRespawn: { policy }` opted in, a crash instead consults `policy.record()`: `'respawn'` triggers an\n * automatic `recycle()`, `'giveUp'` leaves the service crashed. Default: off.\n */\n\nimport { isError, isInstanceOf } from '@nhtio/adk/guards'\nimport { validateIsolatedServiceOptions } from './validation'\nimport { decodeArgument, encodeArgument, fromWireError } from './codec'\nimport { HostEndpoint, type HostcallHandler, type HostcallQuotas } from './protocol'\nimport { E_ISOLATED_CRASHED, E_ISOLATED_TERMINATED, E_ISOLATION_READY_TIMEOUT } from './exceptions'\nimport {\n  emitIsolationReport,\n  hasIsolationHook,\n  type IsolationObservabilityHooks,\n} from './observability'\nimport type { CrashPolicy } from './crash_policy'\nimport type {\n  CodecMode,\n  CrashInfo,\n  IsolatedEventListener,\n  IsolatedFacade,\n  IsolatedServiceSpec,\n  IsolationTransport,\n} from './types'\n\n/** Options accepted by {@link createIsolatedService}. */\nexport interface IsolatedServiceOptions extends IsolationObservabilityHooks {\n  /** Max time to wait for the guest's `ready` envelope after `transport.connect()` resolves. Default\n   *  `30_000`. Rejects the pending `connect`/first call with `E_ISOLATION_READY_TIMEOUT`. */\n  readyTimeoutMs?: number\n  /** Grace period `dispose()` gives the guest to exit cleanly after `shutdown` before forcing\n   *  `transport.terminate()`. Default `2000`. */\n  disposeGraceMs?: number\n  /** Opt-in automatic recovery: on a transport-reported crash, consult `policy.record()` and `recycle()`\n   *  automatically when it returns `'respawn'`. Default: not set (crashes are surfaced, never auto-healed). */\n  autoRespawn?: { policy: CrashPolicy }\n  /** Classes to register with `@nhtio/encoder`'s custom-encodable round-trip on this side. */\n  encodables?: ReadonlyArray<{ readonly name: string }>\n  /** Permitted guest-to-host capability handlers. */\n  hostcallHandlers?: ReadonlyMap<string, HostcallHandler>\n  /** Resolved quotas enforced for guest-to-host calls. */\n  hostcallQuotas?: HostcallQuotas\n  /** Producer-side argument/result byte cap. */\n  maxHostcallBytes?: number\n}\n\n/** Lifecycle state of an {@link IsolatedService}. */\nexport type IsolatedServiceState = 'starting' | 'ready' | 'crashed' | 'disposed'\n\n/** The host-side handle `createIsolatedService` returns. */\nexport interface IsolatedService<S extends IsolatedServiceSpec> {\n  /** The callable facade — one function per declared method/stream. */\n  readonly api: IsolatedFacade<S>\n  /** Subscribe to a declared event channel. Returns an unsubscribe function. Subscriptions survive\n   *  `recycle()` (the same underlying map is reused across guest respawns). */\n  on<K extends keyof S['events'] & string>(channel: K, fn: IsolatedEventListener<S, K>): () => void\n  /** Subscribe to crash notifications. Returns an unsubscribe function. */\n  onCrash(fn: (info: CrashInfo) => void): () => void\n  /** Current lifecycle state. */\n  readonly state: IsolatedServiceState\n  /** Send `shutdown`, wait up to `disposeGraceMs` for the guest to exit on its own, then force\n   *  `transport.terminate()` regardless. Idempotent past the first call. */\n  dispose(): Promise<void>\n  /** Terminate the current guest and reconnect through the same `transport.connect()`. Object identity\n   *  and `.on(...)` subscriptions survive; in-flight calls/streams reject with `E_ISOLATED_TERMINATED`. */\n  recycle(): Promise<void>\n}\n\nconst codecModeFor = (declared: CodecMode | undefined): CodecMode | undefined => declared\n\n/**\n * Build an {@link IsolatedService} over `transport` for `spec`. Connection + the first `ready` handshake\n * begin immediately (fire-and-forget internally); calls made before `ready` queue inside the underlying\n * {@link HostEndpoint} and flush in order once it arrives.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} when `options` fails\n *   validation.\n */\nexport const createIsolatedService = <S extends IsolatedServiceSpec>(\n  spec: S,\n  transport: IsolationTransport,\n  options?: IsolatedServiceOptions\n): IsolatedService<S> => {\n  const resolved = validateIsolatedServiceOptions(options)\n  const readyTimeoutMs = resolved.readyTimeoutMs ?? 30_000\n  const disposeGraceMs = resolved.disposeGraceMs ?? 2000\n\n  let spawnCount = 0\n  let state: IsolatedServiceState = 'starting'\n  let endpoint: HostEndpoint | undefined\n  let disposed = false\n  let unsubscribeCrash: (() => void) | undefined\n\n  const eventListeners = new Map<string, Set<(payload: unknown) => void>>()\n  const crashListeners = new Set<(info: CrashInfo) => void>()\n  const inFlightStreamCancels = new Set<() => void>()\n\n  const emitReport = (\n    phase: Parameters<typeof emitIsolationReport>[1],\n    extra?: Parameters<typeof emitIsolationReport>[3]\n  ): void => emitIsolationReport(resolved, phase, { serviceName: spec.name, spawnCount }, extra)\n\n  /** Resolves once the current guest connection is `ready` (or rejects on timeout/crash-before-ready). */\n  let connectPromise: Promise<void> = Promise.resolve()\n\n  const connect = (): Promise<void> => {\n    spawnCount += 1\n    state = 'starting'\n    emitReport('spawn:start')\n    const startedAt = Date.now()\n    connectPromise = (async () => {\n      const port = await transport.connect()\n      endpoint = new HostEndpoint(\n        port,\n        {\n          onReady: () => {\n            // The guest's `encoderAvailable` flag only matters to the guest's own `toWireError` rich-path\n            // decision (see serve.ts) — the host only ever DECODES wire errors (`fromWireError`), which\n            // self-describes via `WireError.nhtio` being present or absent, so nothing here needs to track\n            // it.\n            state = 'ready'\n          },\n          onEvent: (channel, payload) => {\n            void (async () => {\n              const decoded = await decodeArgument(payload, undefined, `event ${channel}`)\n              for (const fn of eventListeners.get(channel) ?? []) fn(decoded)\n            })()\n          },\n          onEnvelope: (dir, envelope) => {\n            if (!hasIsolationHook(resolved, dir === 'out' ? 'wire:out' : 'wire:in')) return\n            emitReport(dir === 'out' ? 'wire:out' : 'wire:in', { kind: envelope.t })\n          },\n        },\n        {\n          handlers: resolved.hostcallHandlers,\n          quotas: resolved.hostcallQuotas,\n          maxHostcallBytes: resolved.maxHostcallBytes,\n        }\n      )\n      await new Promise<void>((resolve, reject) => {\n        let settled = false\n        const timer = setTimeout(() => {\n          if (settled) return\n          settled = true\n          reject(new E_ISOLATION_READY_TIMEOUT([readyTimeoutMs]))\n        }, readyTimeoutMs)\n        const poll = (): void => {\n          if (settled) return\n          if (endpoint?.isReady) {\n            settled = true\n            clearTimeout(timer)\n            resolve()\n            return\n          }\n          // A guest that crashes BEFORE its `ready` envelope (bogus worker URL, top-level throw in the\n          // guest module, immediate child exit) must fail the connection immediately as a crash — not\n          // sit out the full ready timeout only to misreport it as E_ISOLATION_READY_TIMEOUT.\n          if (state === 'crashed') {\n            settled = true\n            clearTimeout(timer)\n            reject(new E_ISOLATED_CRASHED([spec.name]))\n            return\n          }\n          setTimeout(poll, 0)\n        }\n        poll()\n      })\n      emitReport('spawn:ready', { bootMs: Date.now() - startedAt })\n    })().catch((err) => {\n      state = 'crashed'\n      emitReport('spawn:error', { error: err })\n      throw err\n    })\n    return connectPromise\n  }\n\n  unsubscribeCrash = transport.onCrash((info) => {\n    handleCrash(info)\n  })\n\n  const handleCrash = (info: CrashInfo): void => {\n    if (state === 'disposed') return\n    const inFlight = (endpoint?.pendingCallCount ?? 0) + (endpoint?.openStreamCount ?? 0)\n    endpoint?.terminate(`Isolated service \"${spec.name}\" crashed: ${info.reason}`)\n    for (const cancel of inFlightStreamCancels) cancel()\n    inFlightStreamCancels.clear()\n    state = 'crashed'\n    emitReport('crash', { reason: info.reason, code: info.code, signal: info.signal, inFlight })\n    for (const fn of crashListeners) {\n      try {\n        fn(info)\n      } catch {\n        // A throwing crash subscriber must never break the fan-out to the remaining subscribers.\n      }\n    }\n    if (resolved.autoRespawn) {\n      const verdict = resolved.autoRespawn.policy.record()\n      emitReport('respawn:auto', { verdict })\n      if (verdict === 'respawn') {\n        void recycle()\n      }\n    }\n  }\n\n  const ensureReadyOrThrow = (): HostEndpoint => {\n    if (state === 'disposed') throw new E_ISOLATED_TERMINATED([spec.name])\n    if (state === 'crashed') throw new E_ISOLATED_CRASHED([spec.name])\n    if (!endpoint) throw new E_ISOLATED_TERMINATED([spec.name])\n    return endpoint\n  }\n\n  const callMethod = async (methodName: string, args: unknown[]): Promise<unknown> => {\n    await connectPromise\n    const ep = ensureReadyOrThrow()\n    const descriptor = spec.methods[methodName]\n    const mode = codecModeFor(descriptor?.codec)\n    // The facade accepts an optional trailing AbortSignal uniformly, regardless of whether the method\n    // declared `{ signal: true }` (see `IsolatedFacade` in types.ts). Since descriptors are phantom-typed\n    // (no runtime-recoverable argument arity), detect the trailing signal by instance check rather than\n    // by position — a signal handed to a method that didn't opt in is simply not forwarded to the guest.\n    const trailing = args[args.length - 1]\n    const hasTrailingSignal =\n      args.length > 0 &&\n      typeof AbortSignal !== 'undefined' &&\n      isInstanceOf(trailing, 'AbortSignal', AbortSignal)\n    const signal = hasTrailingSignal && descriptor?.signal ? (trailing as AbortSignal) : undefined\n    const callArgs = hasTrailingSignal ? args.slice(0, -1) : args\n    const wireArgs = await Promise.all(\n      callArgs.map((a, i) =>\n        encodeArgument(a, {\n          mode,\n          label: `${methodName} args[${i}]`,\n          onEscalate: (path, reason) =>\n            emitReport('codec:escalate', {\n              argPath: `${methodName} args[${i}]${path.length ? `.${path.map(String).join('.')}` : ''}`,\n              escalateReason: reason,\n            }),\n        })\n      )\n    )\n    const start = Date.now()\n    emitReport('call:start', { method: methodName })\n    const { id, promise } = ep.call(methodName, wireArgs)\n    if (signal) {\n      const onAbort = (): void => {\n        ep.abort(id)\n        emitReport('abort:sent', { method: methodName, id })\n      }\n      if (signal.aborted) onAbort()\n      else signal.addEventListener('abort', onAbort, { once: true })\n    }\n    try {\n      const wireResult = await promise\n      const result = await decodeArgument(wireResult, mode, `${methodName} result`)\n      emitReport('call:settle', {\n        method: methodName,\n        id,\n        durationMs: Date.now() - start,\n        ok: true,\n      })\n      return result\n    } catch (err) {\n      emitReport('call:settle', {\n        method: methodName,\n        id,\n        durationMs: Date.now() - start,\n        ok: false,\n        errorMessage: isError(err) ? err.message : String(err),\n      })\n      throw err\n    }\n  }\n\n  const startStream = (streamName: string, args: unknown[]): ReadableStream<unknown> => {\n    const descriptor = spec.streams[streamName]\n    const mode = codecModeFor(descriptor?.codec)\n    let deltaCount = 0\n    let firstDeltaMs: number | undefined\n    const startedAt = Date.now()\n    let cancelFn: (() => void) | undefined\n    // Deltas decode asynchronously, but `stream:end`/`stream:error` arrive synchronously behind\n    // them — so a naive `controller.close()` runs while the final delta is still awaiting its\n    // decode, and that enqueue is lost to an already-closed controller. Chain every sink callback\n    // onto one promise so the terminal signal cannot overtake a delta that preceded it on the wire.\n    let pumped: Promise<void> = Promise.resolve()\n    // A terminal transition is final: a decode error, a cancellation, or a second terminal wire\n    // event can all queue behind one, and touching the controller afterwards throws\n    // ERR_INVALID_STATE — which, at the tail of the chain, surfaces as an unhandled rejection.\n    let terminated = false\n    const sequence = (step: () => Promise<void> | void): void => {\n      pumped = pumped.then(async () => {\n        if (!terminated) await step()\n      }, undefined)\n    }\n    return new ReadableStream<unknown>({\n      start: (controller) => {\n        // Terminal-ness belongs to the controller OPERATION, not to the call site that queued it:\n        // a delta whose decode fails errors the controller from inside `push`, which is every bit\n        // as terminal as a `stream:end`. Latching at the call site missed that path and let a\n        // queued end close an already-errored controller.\n        const closeStream = (): void => {\n          if (terminated) return\n          terminated = true\n          controller.close()\n        }\n        const errorStream = (err: unknown): void => {\n          if (terminated) return\n          terminated = true\n          controller.error(err)\n        }\n        void (async () => {\n          try {\n            await connectPromise\n            const ep = ensureReadyOrThrow()\n            const wireArgs = await Promise.all(\n              args.map((a, i) =>\n                encodeArgument(a, {\n                  mode,\n                  label: `${streamName} args[${i}]`,\n                  onEscalate: (path, reason) =>\n                    emitReport('codec:escalate', {\n                      argPath: `${streamName} args[${i}]${path.length ? `.${path.map(String).join('.')}` : ''}`,\n                      escalateReason: reason,\n                    }),\n                })\n              )\n            )\n            emitReport('stream:start', { streamName })\n            const id = ep.startStream(streamName, wireArgs, {\n              push: (delta) => {\n                deltaCount += 1\n                if (firstDeltaMs === undefined) firstDeltaMs = Date.now() - startedAt\n                sequence(async () => {\n                  try {\n                    const decoded = await decodeArgument(delta, mode, `${streamName} delta`)\n                    controller.enqueue(decoded)\n                  } catch (err) {\n                    errorStream(err)\n                  }\n                })\n              },\n              end: () => {\n                sequence(() => {\n                  inFlightStreamCancels.delete(cancelFn!)\n                  emitReport('stream:end', { streamName, deltaCount, firstDeltaMs })\n                  closeStream()\n                })\n              },\n              error: (wireError) => {\n                sequence(async () => {\n                  inFlightStreamCancels.delete(cancelFn!)\n                  const err = await fromWireError(wireError)\n                  emitReport('stream:error', { streamName, streamError: err })\n                  errorStream(err)\n                })\n              },\n            })\n            cancelFn = () => ep.cancelStream(id)\n            inFlightStreamCancels.add(cancelFn)\n          } catch (err) {\n            // Setup failure (encode, connect, ready timeout) is terminal too, and can land after a\n            // sink callback has already queued — so it goes through the same latch.\n            errorStream(err)\n          }\n        })()\n      },\n      cancel: () => {\n        if (cancelFn) {\n          inFlightStreamCancels.delete(cancelFn)\n          cancelFn()\n          emitReport('stream:cancel', { streamName, deltaCount, firstDeltaMs })\n        }\n      },\n    })\n  }\n\n  const api = {} as Record<string, (...a: unknown[]) => unknown>\n  for (const methodName of Object.keys(spec.methods)) {\n    api[methodName] = (...args: unknown[]) => callMethod(methodName, args)\n  }\n  for (const streamName of Object.keys(spec.streams)) {\n    api[streamName] = (...args: unknown[]) => startStream(streamName, args)\n  }\n\n  const dispose = async (): Promise<void> => {\n    if (state === 'disposed') return\n    emitReport('dispose:start')\n    const ep = endpoint\n    // Ask nicely first (when there's a live, ready endpoint), then give the guest `disposeGraceMs` to\n    // exit on its own before forcing `transport.terminate()` unconditionally. Nothing at this layer\n    // reports \"the guest process/worker actually exited\" short of the transport's crash callback (which\n    // is reserved for UNEXPECTED exits) — so a graceful shutdown always ends in `transport.terminate()`\n    // being called, and `forced` reflects whether shutdown was even attempted vs. skipped outright.\n    const attemptedGraceful = Boolean(ep && state === 'ready')\n    if (attemptedGraceful) {\n      ep!.shutdown()\n      await new Promise<void>((resolve) => setTimeout(resolve, disposeGraceMs))\n    }\n    state = 'disposed'\n    unsubscribeCrash?.()\n    ep?.terminate(new E_ISOLATED_TERMINATED([spec.name]).message)\n    for (const cancel of inFlightStreamCancels) cancel()\n    inFlightStreamCancels.clear()\n    disposed = true\n    await transport.terminate()\n    emitReport('dispose:done', { forced: !attemptedGraceful })\n  }\n\n  const recycle = async (): Promise<void> => {\n    if (disposed) return\n    emitReport('recycle:start')\n    endpoint?.terminate(new E_ISOLATED_TERMINATED([spec.name]).message)\n    for (const cancel of inFlightStreamCancels) cancel()\n    inFlightStreamCancels.clear()\n    await transport.terminate()\n    await connect()\n    emitReport('recycle:done')\n  }\n\n  connect()\n\n  return {\n    api: api as IsolatedFacade<S>,\n    on: <K extends keyof S['events'] & string>(\n      channel: K,\n      fn: IsolatedEventListener<S, K>\n    ): (() => void) => {\n      let set = eventListeners.get(channel)\n      if (!set) {\n        set = new Set()\n        eventListeners.set(channel, set)\n      }\n      const wrapped = fn as (payload: unknown) => void\n      set.add(wrapped)\n      return () => set!.delete(wrapped)\n    },\n    onCrash: (fn) => {\n      crashListeners.add(fn)\n      return () => crashListeners.delete(fn)\n    },\n    get state() {\n      return state\n    },\n    dispose,\n    recycle,\n  }\n}\n","/**\n * Web Worker {@link IsolationTransport} + `spawnIsolated` convenience for browser isolation.\n *\n * @remarks\n * Implements the `IsolationTransport`/`PortLike` ducks declared (and treated as a read-only contract) in\n * `types.ts` against a real browser `Worker`, and nothing else: this module never touches `protocol.ts`,\n * `host.ts`, `serve.ts`, or `codec.ts` directly — it only produces the transport `createIsolatedService`\n * (from `host.ts`) drives.\n *\n * The project's tsconfig limits `lib` to `ESNext`, so the DOM `Worker`/`WorkerOptions` types referenced\n * below are not in scope by default (`ErrorEvent`/`MessageEvent` ARE ambiently available via\n * `@types/node`'s `web-globals/*.d.ts` global augmentation, but the DOM `Worker` class is not — only\n * node's unrelated `worker_threads.Worker` is). Re-declare here the **minimum** surface this module\n * touches, mirroring the OPFS storage battery's established convention (`src/batteries/storage/opfs/\n * index.ts`) — structurally compatible with the real DOM types, so callers pass real `Worker` instances\n * straight through.\n */\n\nimport { isObject } from '@nhtio/adk/guards'\nimport { createIsolatedService } from './host'\nimport { E_ISOLATION_UNSUPPORTED_ENV } from './exceptions'\nimport { validateSpawnIsolatedOptions } from './validation'\nimport type { IsolatedService, IsolatedServiceOptions } from './host'\nimport type { CrashInfo, IsolatedServiceSpec, IsolationTransport, PortLike } from './types'\n\n// ── Minimal locally-declared DOM surface (no `lib: \"dom\"` in this project's tsconfig) ──────────────────\n\n/** Minimal subset of the DOM `MessageEvent` interface this module touches. */\nexport interface BrowserMessageEvent {\n  /** The message payload delivered via `postMessage`. */\n  readonly data: unknown\n}\n\n/** Minimal subset of the DOM `ErrorEvent` interface this module touches — fired on a `Worker` instance\n *  when an uncaught error escapes the worker's top-level scope. */\nexport interface BrowserErrorEvent {\n  /** Human-readable error message. */\n  readonly message: string\n}\n\n/** Minimal subset of the DOM `WorkerOptions` dictionary this module forwards verbatim to `new\n *  Worker(url, options)` — used ONLY for the `string | URL` spawn form (a caller-supplied\n *  {@link WorkerResolver} constructs its own `Worker` however it likes, this dictionary never applies\n *  there). Classic scripts are the default (`type` omitted) — matching this repo's own LiteRT-LM Worker\n *  prototype (`docs/.vitepress/theme/components/agent/litert_lm_worker_proxy.ts`), which deliberately\n *  avoids `{ type: 'module' }` because Emscripten-style glue calls `importScripts()`, illegal in a module\n *  worker. Pass `{ type: 'module' }` explicitly when the guest script is an ES module. */\nexport interface BrowserWorkerOptions {\n  /** `'classic'` (default when omitted) or `'module'`. */\n  type?: 'classic' | 'module'\n  /** Worker credentials mode, forwarded verbatim. */\n  credentials?: 'omit' | 'same-origin' | 'include'\n  /** A developer-facing name for the worker (surfaced in devtools). */\n  name?: string\n}\n\n/** Minimal subset of the DOM `Worker` interface this module touches. Structurally compatible with the\n *  real DOM `Worker` — callers (and {@link WorkerResolver} implementations) pass/construct real `Worker`\n *  instances directly. */\nexport interface BrowserWorker {\n  /** Post a message to the worker, optionally transferring ownership of listed transferables. */\n  postMessage(message: unknown, transfer?: unknown[]): void\n  /** Subscribe to the worker's `'message'` event (fired on every `postMessage` received from the guest). */\n  addEventListener(type: 'message', listener: (ev: BrowserMessageEvent) => void): void\n  /** Subscribe to the worker's `'error'` event (fired when an uncaught error escapes the guest's\n   *  top-level scope). */\n  addEventListener(type: 'error', listener: (ev: BrowserErrorEvent) => void): void\n  /** Subscribe to the worker's `'messageerror'` event (fired when a received message could not be\n   *  deserialized). */\n  addEventListener(type: 'messageerror', listener: (ev: BrowserMessageEvent) => void): void\n  /** Unsubscribe a previously-added listener. */\n  removeEventListener(\n    type: 'message' | 'error' | 'messageerror',\n    listener: (ev: never) => void\n  ): void\n  /** Terminate the worker immediately — no further events, no graceful shutdown at this layer. */\n  terminate(): void\n}\n\n/** Ambient DOM globals this module reads. Declared locally (see the module doc) rather than pulled in\n *  via a `lib: \"dom\"` tsconfig change — `Worker`/`URL`'s constructor overload taking `WorkerOptions` are\n *  the only DOM-shaped pieces this file touches beyond what `@types/node`'s web-globals already provide\n *  (`ErrorEvent`/`MessageEvent`/`URL`/`Blob` are ambient there). */\ndeclare const Worker: {\n  new (scriptURL: string | URL, options?: BrowserWorkerOptions): BrowserWorker\n}\n\n// ── BYO spawner seam ────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Bring-your-own Worker spawner — the first-class seam for handing {@link spawnIsolated}/{@link\n * createWorkerTransport} a `Worker` constructed however the caller's bundler/pooling strategy demands\n * (a `new Worker(new URL(...), import.meta.url)` Vite/webpack pattern, a worker pool that recycles\n * threads, a test harness's Blob-URL worker, etc.). Called once per `connect()` (including every\n * `recycle()`) — see {@link createWorkerTransport}'s remarks for why this makes a resolver the SINGLE\n * source of Worker creation for a given transport.\n */\nexport type WorkerResolver = (ctx: {\n  spec: IsolatedServiceSpec\n}) => BrowserWorker | Promise<BrowserWorker>\n\n/** Options accepted by {@link spawnIsolated}/{@link createWorkerTransport}, layered on top of {@link\n *  IsolatedServiceOptions}. */\nexport interface SpawnIsolatedOptions extends IsolatedServiceOptions {\n  /**\n   * How to obtain the guest `Worker`:\n   *\n   * - A `string | URL` — the guest script's URL; `createWorkerTransport` constructs `new Worker(url,\n   *   workerOptions)` itself on every `connect()`.\n   * - A {@link WorkerResolver} — full control: bring a `Worker` from any bundler pattern or pool. Invoked\n   *   with `{ spec }` and may return a `Worker` synchronously or via a `Promise`.\n   */\n  worker: string | URL | WorkerResolver\n  /** Forwarded verbatim to `new Worker(url, workerOptions)` — used ONLY for the `string | URL` spawn\n   *  form (ignored when `worker` is a {@link WorkerResolver}, which constructs its own `Worker`).\n   *  Default: classic script (no `type`) — see {@link BrowserWorkerOptions}'s doc for why. */\n  workerOptions?: BrowserWorkerOptions\n}\n\nconst isWorkerResolver = (worker: string | URL | WorkerResolver): worker is WorkerResolver =>\n  typeof worker === 'function'\n\nconst isUrlLike = (value: unknown): value is URL =>\n  isObject(value) && typeof (value as { href?: unknown }).href === 'string'\n\n// ── Transfer-marker unwrapping ──────────────────────────────────────────────────────────────────────\n\n/** A single {@link WireValue}-shaped slot this module scans for a `transfer` marker. Deliberately NOT\n *  imported from `protocol.ts` (this module must not depend on the wire envelope shapes beyond this one\n *  structural field) — see {@link collectTransferables}'s remarks. */\ninterface WireValueLike {\n  enc?: unknown\n  v?: unknown\n  transfer?: unknown[]\n}\n\nconst asWireValueLike = (value: unknown): WireValueLike | undefined =>\n  isObject(value) ? (value as WireValueLike) : undefined\n\n/**\n * Collect every `transfer` list found on an outbound envelope's known `WireValue` positions —\n * `call.args[]` / `stream:start.args[]` (arrays), `result.value` (single), `stream:delta.delta` (single)\n * — into one flat transferables list for `postMessage(msg, transferables)`. Deliberately narrow and\n * cheap: rather than deep-traverse the whole envelope, this only reads the handful of top-level fields\n * the wire protocol ever puts a `WireValue` in, so envelopes without those fields (`ready`, `abort`,\n * `stream:cancel`, `shutdown`, `stream:end`, error variants) are skipped in O(1) with no property access\n * beyond the initial shape check.\n */\nconst collectTransferables = (envelope: unknown): unknown[] => {\n  const msg = asWireValueLike(envelope)\n  if (!msg) return []\n  const found: unknown[] = []\n  const take = (candidate: unknown): void => {\n    const wv = asWireValueLike(candidate)\n    if (wv && Array.isArray(wv.transfer)) found.push(...wv.transfer)\n  }\n  const args = (msg as { args?: unknown }).args\n  if (Array.isArray(args)) {\n    for (const a of args) take(a)\n  }\n  take((msg as { value?: unknown }).value)\n  take((msg as { delta?: unknown }).delta)\n  return found\n}\n\n// ── Worker transport ─────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Build an {@link IsolationTransport} that spawns/re-spawns a real browser `Worker` per {@link\n * SpawnIsolatedOptions.worker}.\n *\n * @remarks\n * `connect()` resolves the `Worker` (constructing it for a `string | URL` spec, or awaiting a {@link\n * WorkerResolver}), wraps it in a {@link PortLike} (`post` → `postMessage` with any {@link\n * @nhtio/adk/batteries/isolation!transfer}-marked values unwrapped into the transfer list; `onMessage` →\n * `addEventListener('message', ...)`), and wires the worker's `'error'`/`'messageerror'` events to the\n * transport's `onCrash` handlers. `terminate()` calls `worker.terminate()`. `createIsolatedService`'s\n * `recycle()` re-enters this SAME `connect()` — since a resolver is invoked fresh on every call, it is\n * the single source of Worker creation for the service's whole lifetime (every respawn goes through it,\n * never a cached instance).\n */\nexport const createWorkerTransport = (\n  spec: IsolatedServiceSpec,\n  options: SpawnIsolatedOptions\n): IsolationTransport => {\n  const resolved = validateSpawnIsolatedOptions(options)\n  if (typeof Worker === 'undefined') {\n    throw new E_ISOLATION_UNSUPPORTED_ENV([\n      'createWorkerTransport requires a browser Worker global — none was found on globalThis',\n    ])\n  }\n\n  let currentWorker: BrowserWorker | undefined\n  let onErrorListener: ((ev: BrowserErrorEvent) => void) | undefined\n  let onMessageErrorListener: ((ev: BrowserMessageEvent) => void) | undefined\n  const crashHandlers = new Set<(info: CrashInfo) => void>()\n\n  const resolveWorker = async (): Promise<BrowserWorker> => {\n    const { worker, workerOptions } = resolved\n    if (isWorkerResolver(worker)) {\n      return await worker({ spec })\n    }\n    const url = typeof worker === 'string' || isUrlLike(worker) ? worker : String(worker)\n    return new Worker(url, workerOptions)\n  }\n\n  const teardownListeners = (): void => {\n    if (currentWorker && onErrorListener) {\n      currentWorker.removeEventListener('error', onErrorListener)\n    }\n    if (currentWorker && onMessageErrorListener) {\n      currentWorker.removeEventListener('messageerror', onMessageErrorListener)\n    }\n    onErrorListener = undefined\n    onMessageErrorListener = undefined\n  }\n\n  const connect = async (): Promise<PortLike> => {\n    const worker = await resolveWorker()\n    currentWorker = worker\n\n    onErrorListener = (ev: BrowserErrorEvent): void => {\n      const reason = ev.message || `Isolated Worker for service \"${spec.name}\" crashed`\n      for (const fn of crashHandlers) fn({ reason })\n    }\n    onMessageErrorListener = (): void => {\n      for (const fn of crashHandlers) {\n        fn({\n          reason: `Isolated Worker for service \"${spec.name}\" sent an undeserializable message`,\n        })\n      }\n    }\n    worker.addEventListener('error', onErrorListener)\n    worker.addEventListener('messageerror', onMessageErrorListener)\n\n    const port: PortLike = {\n      post: (msg) => {\n        const transferables = collectTransferables(msg)\n        if (transferables.length > 0) {\n          worker.postMessage(msg, transferables)\n        } else {\n          worker.postMessage(msg)\n        }\n      },\n      onMessage: (fn) => {\n        const listener = (ev: BrowserMessageEvent): void => fn(ev.data)\n        worker.addEventListener('message', listener)\n        return () => worker.removeEventListener('message', listener as never)\n      },\n    }\n    return port\n  }\n\n  const terminate = (): void => {\n    teardownListeners()\n    currentWorker?.terminate()\n    currentWorker = undefined\n  }\n\n  return {\n    connect,\n    terminate,\n    onCrash: (fn) => {\n      crashHandlers.add(fn)\n      return () => crashHandlers.delete(fn)\n    },\n  }\n}\n\n/**\n * Sugar for `createIsolatedService(spec, createWorkerTransport(spec, options), options)` — spawn a\n * real Worker-backed {@link IsolatedService} in one call.\n *\n * @remarks\n * The transport-only keys (`worker`/`workerOptions`) are stripped before the remaining options reach\n * `createIsolatedService` — its validator is deliberately strict (unknown keys rejected), accepting\n * only the base {@link IsolatedServiceOptions} shape; the transport-only keys were already validated\n * (and consumed) by {@link createWorkerTransport}.\n *\n * @throws {@link @nhtio/adk/batteries/isolation!E_ISOLATION_UNSUPPORTED_ENV} when no browser `Worker`\n *   global is present.\n * @throws {@link @nhtio/adk/batteries/isolation!E_INVALID_ISOLATION_OPTIONS} when `options` fails\n *   validation.\n */\nexport const spawnIsolated = <S extends IsolatedServiceSpec>(\n  spec: S,\n  options: SpawnIsolatedOptions\n): IsolatedService<S> => {\n  const transport = createWorkerTransport(spec, options)\n  const serviceOptions: IsolatedServiceOptions = { ...options }\n  delete (serviceOptions as Partial<SpawnIsolatedOptions>).worker\n  delete (serviceOptions as Partial<SpawnIsolatedOptions>).workerOptions\n  return createIsolatedService(spec, transport, serviceOptions)\n}\n","/**\n * `isolateFunction` — the Blob-URL escape hatch: run a single plain function inside a throwaway,\n * source-rehydrated Worker, without the caller ever writing a guest script file.\n *\n * @remarks\n * **This is a `new Function`-based eval trust surface. Read this before using it.**\n *\n * Every other seam in this battery (`spawnIsolated`/`serveIsolated`/the Node child_process backend) runs a guest\n * script the CALLER wrote, deployed, and controls the provenance of. `isolateFunction` is the opposite:\n * it takes an in-memory function VALUE, serializes it via `fn.toString()` (through\n * `@nhtio/encoder/function_serializer`'s `FunctionSerializer.dehydrate`), embeds that source text\n * verbatim into a synthesized classic-Worker script, and has the Worker rehydrate it with `new\n * Function(...)` at guest-side startup — there is no way to run source-rehydration without `new\n * Function` (or `eval`), and this module does not attempt to pretend otherwise. That is why the single\n * call site that opts into this is a literal, non-optional `{ allowSourceRehydration: true }` — both a\n * TypeScript literal-type requirement (passing `false` or a widened `boolean` fails to compile) AND a\n * runtime check (so a caller that reaches this through untyped JS, or an `as any` cast, still cannot\n * skip the acknowledgement). Treat any function handed to `isolateFunction` exactly as you would treat a\n * string handed to `eval`: only ever pass functions whose source your own process produced/controls.\n * `fn.toString()` captures no closures — only named, module-scope-free source is portable across the\n * Blob boundary (see {@link https://github.com/nhtio/nhtio-encoder | @nhtio/encoder}'s\n * `FunctionSerializer` for exactly which shapes round-trip).\n *\n * Design, deliberately MINI rather than the full `protocol.ts` envelope:\n *\n * - Host → guest: `{ id: string; args: WireValue[] }`. Each argument is encoded via `codec.ts`'s\n *   {@link encodeArgument} in `'auto'` mode (so plain JSON-safe arguments cost nothing — they cross as\n *   `enc: 'raw'` and the guest's inline unwrap is a no-op property read). If an argument contains an\n *   exotic leaf (a function/Error/custom-encodable) `encodeArgument` would need to escalate past `raw`\n *   — but the guest Blob has no module imports, so it cannot load `@nhtio/encoder` to decode an `enc:\n *   'nhtio'` value. Rather than ship a doomed message, {@link isolateFunction}'s `invoke` rejects such\n *   calls up front with {@link E_ISOLATE_FUNCTION_ARG_UNSUPPORTED}.\n * - Guest → host: `{ id: string; ok: true; value: { enc: 'raw'; v: unknown } } | { id: string; ok:\n *   false; error: { message: string; name: string; stack?: string } }` — hand-rolled inline in the Blob\n *   source (no `codec.ts` import there either), but shaped compatibly with `protocol.ts`'s `WireValue`/\n *   `WireError` so the HOST side can decode results via the SAME {@link decodeArgument}/`fromWireError`\n *   helpers the shared isolation protocol already defines, rather than a third, bespoke decode path.\n *\n * `dispose()` terminates the Worker and revokes the Blob URL; every in-flight `invoke()` call, and every\n * call made afterward, rejects with {@link @nhtio/adk/batteries/isolation!E_ISOLATED_TERMINATED}. An\n * uncaught top-level error in the guest (e.g. `FunctionSerializer`'s rehydrator itself throwing) surfaces\n * as a Worker `'error'` event, at which point every in-flight call rejects with\n * {@link @nhtio/adk/batteries/isolation!E_ISOLATED_CRASHED} and the instance is marked crashed permanently\n * (no auto-respawn — this is a one-shot escape hatch, not a managed service; construct a new\n * {@link isolateFunction} instance to try again).\n */\n\nimport { nextCorrelationId } from './protocol'\nimport { isError, isObject } from '@nhtio/adk/guards'\nimport { createException } from '@nhtio/adk/factories'\nimport { decodeArgument, encodeArgument, fromWireError } from './codec'\nimport {\n  E_ISOLATED_CRASHED,\n  E_ISOLATED_TERMINATED,\n  E_ISOLATION_UNSUPPORTED_ENV,\n} from './exceptions'\nimport type { WireValue } from './protocol'\nimport type { BrowserErrorEvent, BrowserMessageEvent, BrowserWorker } from './browser'\n\n// ── Locally-declared ambient `Worker` (see `browser.ts`'s module doc for why this is per-file) ─────────\n\ndeclare const Worker: {\n  new (scriptURL: string | URL): BrowserWorker\n}\n\n// ── Local exceptions (this module cannot add to the read-only `exceptions.ts`) ──────────────────────────\n\n/**\n * Thrown when {@link isolateFunction} is called without the literal `{ allowSourceRehydration: true }`\n * acknowledgement. Fatal: this is a configuration/call-site error, caught before anything is spawned.\n */\nexport const E_ISOLATE_FUNCTION_REQUIRES_SOURCE_REHYDRATION = createException<[string]>(\n  'E_ISOLATE_FUNCTION_REQUIRES_SOURCE_REHYDRATION',\n  'isolateFunction(%s) requires explicit opt-in: pass { allowSourceRehydration: true }. This runs your ' +\n    \"function's source through `new Function` inside a Worker — treat it like `eval`.\",\n  'E_ISOLATE_FUNCTION_REQUIRES_SOURCE_REHYDRATION',\n  529,\n  true\n)\n\n/**\n * Thrown when the function passed to {@link isolateFunction} cannot be serialized —\n * `@nhtio/encoder/function_serializer`'s `FunctionSerializer.canSerialize` rejects native functions\n * (`fn.toString()` containing `[native code]`) and bound functions (which stringify the same way).\n * Fatal: detected before any Worker is spawned; there is no fallback representation to fall back to.\n */\nexport const E_ISOLATE_FUNCTION_UNSERIALIZABLE = createException<[string]>(\n  'E_ISOLATE_FUNCTION_UNSERIALIZABLE',\n  'isolateFunction(%s): the function cannot be serialized (native or bound functions have no ' +\n    'inspectable source) — pass a plain user-defined function instead',\n  'E_ISOLATE_FUNCTION_UNSERIALIZABLE',\n  529,\n  true\n)\n\n/**\n * Thrown when an `invoke()` argument contains an exotic leaf (a function/Error/custom-encodable) that\n * `codec.ts`'s tiered encoder would need to escalate past the `'raw'` tier. The isolated Blob guest has\n * no module imports (by design — no bare specifiers survive a Blob URL) and therefore cannot load\n * `@nhtio/encoder` to decode an `enc: 'nhtio'` value; `isolateFunction` only ever supports plain,\n * structured-cloneable arguments. Non-fatal: a caller can pass different, plain arguments instead.\n */\nexport const E_ISOLATE_FUNCTION_ARG_UNSUPPORTED = createException<[string]>(\n  'E_ISOLATE_FUNCTION_ARG_UNSUPPORTED',\n  'isolateFunction call argument at %s cannot cross into the isolated Blob worker: it contains a ' +\n    'function/Error/custom-encodable value, and the Blob guest has no encoder available to decode it — ' +\n    'pass only plain, structured-cloneable arguments',\n  'E_ISOLATE_FUNCTION_ARG_UNSUPPORTED',\n  528,\n  false\n)\n\n// ── Public options / handle shapes ──────────────────────────────────────────────────────────────────────\n\n/**\n * Options accepted by {@link isolateFunction}.\n *\n * @remarks\n * `allowSourceRehydration` MUST be the literal `true` — both at the type level (a widened `boolean`\n * fails to type-check) and at runtime (checked explicitly, so an untyped/`as any` call site cannot skip\n * the acknowledgement). See this module's doc comment for what that acknowledgement means.\n */\nexport interface IsolateFunctionOptions {\n  /** Explicit, non-optional acknowledgement that this function's source will be rehydrated via `new\n   *  Function` inside a Worker — an eval-equivalent trust surface. Must be the literal `true`. */\n  allowSourceRehydration: true\n  /** A developer-facing name, used in thrown exception messages and the Worker's `name` option.\n   *  Defaults to `fn.name` (or `'anonymous'` when the function itself has no name). */\n  name?: string\n}\n\n/** The live handle returned by {@link isolateFunction}. */\nexport interface IsolatedFunctionHandle<A extends unknown[], R> {\n  /**\n   * Invoke the isolated function with `args`, returning its result (or rejecting with whatever it\n   * threw/rejected with, reconstructed as a plain `Error`). Lazily spawns the guest Worker on the first\n   * call; subsequent calls reuse it.\n   *\n   * @throws {@link E_ISOLATE_FUNCTION_ARG_UNSUPPORTED} when an argument cannot cross into the guest.\n   * @throws {@link @nhtio/adk/batteries/isolation!E_ISOLATION_UNSUPPORTED_ENV} when no browser `Worker`\n   *   global is present.\n   * @throws {@link @nhtio/adk/batteries/isolation!E_ISOLATED_CRASHED} when the guest has crashed.\n   * @throws {@link @nhtio/adk/batteries/isolation!E_ISOLATED_TERMINATED} after `dispose()`.\n   */\n  invoke: (...args: A) => Promise<R>\n  /** Terminate the guest Worker and revoke its Blob URL. Every in-flight (and future) `invoke()` call\n   *  rejects with {@link @nhtio/adk/batteries/isolation!E_ISOLATED_TERMINATED}. Idempotent. */\n  dispose: () => void\n}\n\n// ── Guest Blob source builder ────────────────────────────────────────────────────────────────────────\n\n/** Build the classic-Worker source text embedding `dehydrated` (a `FunctionSerializer.dehydrate()`\n *  result) plus an inline rehydrator and mini `{id,args} -> {id,ok,value|error}` message loop. No\n *  `import`/`importScripts` anywhere — the dehydrated JSON is the ONLY thing carried across the Blob\n *  boundary; everything else is inlined so the guest never needs a module resolver. */\nconst buildGuestSource = (dehydrated: {\n  _encodedType: 'function'\n  _encodedValueType: 'string'\n  _encodedValue: string\n}): string => `\n\"use strict\";\nvar __dehydrated = ${JSON.stringify(dehydrated)};\nfunction __rehydrate(input) {\n  var src = input._encodedValue;\n  try {\n    return (new Function(\"return (\" + src + \")\"))();\n  } catch (e) {\n    return (new Function(\"return (function \" + src + \")\"))();\n  }\n}\nvar __fn = __rehydrate(__dehydrated);\nself.addEventListener(\"message\", function (ev) {\n  var id = ev.data.id;\n  var args = ev.data.args;\n  Promise.resolve()\n    .then(function () {\n      var plainArgs = args.map(function (wv) {\n        if (wv && wv.enc === \"raw\") return wv.v;\n        throw new Error(\n          \"isolateFunction guest cannot decode a non-raw argument — no encoder is available inside the isolated Blob worker\"\n        );\n      });\n      return __fn.apply(null, plainArgs);\n    })\n    .then(\n      function (result) {\n        self.postMessage({ id: id, ok: true, value: { enc: \"raw\", v: result } });\n      },\n      function (err) {\n        self.postMessage({\n          id: id,\n          ok: false,\n          error: {\n            message: err && err.message ? err.message : String(err),\n            name: err && err.name ? err.name : \"Error\",\n            stack: err && err.stack ? err.stack : undefined,\n          },\n        });\n      }\n    );\n});\n`\n\n// ── isolateFunction ──────────────────────────────────────────────────────────────────────────────────\n\ninterface MiniGuestEnvelope {\n  id: string\n  ok: boolean\n  value?: WireValue\n  error?: { message: string; name: string; stack?: string }\n}\n\nconst isMiniGuestEnvelope = (value: unknown): value is MiniGuestEnvelope =>\n  isObject(value) && typeof (value as { id?: unknown }).id === 'string'\n\n/**\n * Run `fn` inside a throwaway, source-rehydrated Worker. See this module's doc comment for the full\n * design and the trust-boundary implications of `allowSourceRehydration`.\n *\n * @throws {@link E_ISOLATE_FUNCTION_REQUIRES_SOURCE_REHYDRATION} when `allowSourceRehydration` is not\n *   the literal `true`.\n */\nexport const isolateFunction = <A extends unknown[], R>(\n  fn: (...args: A) => R | Promise<R>,\n  options: IsolateFunctionOptions\n): IsolatedFunctionHandle<A, R> => {\n  const label = options?.name ?? fn.name ?? 'anonymous'\n  if (!isObject(options) || options.allowSourceRehydration !== true) {\n    throw new E_ISOLATE_FUNCTION_REQUIRES_SOURCE_REHYDRATION([label])\n  }\n\n  let worker: BrowserWorker | undefined\n  let blobUrl: string | undefined\n  let disposed = false\n  let crashed = false\n  let setupPromise: Promise<BrowserWorker> | undefined\n  const pending = new Map<\n    string,\n    { resolve: (value: R) => void; reject: (reason: unknown) => void }\n  >()\n\n  const rejectAllPending = (reason: unknown): void => {\n    for (const { reject } of pending.values()) reject(reason)\n    pending.clear()\n  }\n\n  const setup = async (): Promise<BrowserWorker> => {\n    if (typeof Worker === 'undefined') {\n      throw new E_ISOLATION_UNSUPPORTED_ENV([\n        `isolateFunction(${label}) requires a browser Worker global — none was found on globalThis`,\n      ])\n    }\n    const { FunctionSerializer } = await import('@nhtio/encoder/function_serializer')\n    if (!FunctionSerializer.canSerialize(fn)) {\n      throw new E_ISOLATE_FUNCTION_UNSERIALIZABLE([label])\n    }\n    const dehydrated = FunctionSerializer.dehydrate(fn)\n    const source = buildGuestSource(dehydrated)\n    blobUrl = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }))\n    const w = new Worker(blobUrl)\n\n    const onMessage = (ev: BrowserMessageEvent): void => {\n      const envelope = ev.data\n      if (!isMiniGuestEnvelope(envelope)) return\n      const waiter = pending.get(envelope.id)\n      if (!waiter) return\n      pending.delete(envelope.id)\n      if (envelope.ok) {\n        void decodeArgument(envelope.value as WireValue, 'auto', `${label} result`).then(\n          (value) => waiter.resolve(value as R),\n          (err) => waiter.reject(err)\n        )\n      } else {\n        const wireError = envelope.error ?? {\n          message: 'unknown isolateFunction guest error',\n          name: 'Error',\n        }\n        void fromWireError(wireError).then((err) => waiter.reject(err))\n      }\n    }\n    const onError = (ev: BrowserErrorEvent): void => {\n      crashed = true\n      const reason = new E_ISOLATED_CRASHED([label], {\n        cause: isError(ev)\n          ? ev\n          : new Error(ev.message || `isolateFunction(${label}) guest crashed`),\n      })\n      rejectAllPending(reason)\n    }\n    w.addEventListener('message', onMessage)\n    w.addEventListener('error', onError)\n\n    worker = w\n    return w\n  }\n\n  const ensureWorker = (): Promise<BrowserWorker> => {\n    if (disposed) return Promise.reject(new E_ISOLATED_TERMINATED([label]))\n    if (crashed) return Promise.reject(new E_ISOLATED_CRASHED([label]))\n    if (!setupPromise) setupPromise = setup()\n    return setupPromise\n  }\n\n  const invoke = async (...args: A): Promise<R> => {\n    const w = await ensureWorker()\n    const encodedArgs = await Promise.all(\n      args.map((arg, index) =>\n        encodeArgument(arg, { mode: 'auto', label: `${label} args[${index}]` })\n      )\n    )\n    const badIndex = encodedArgs.findIndex((wv) => wv.enc !== 'raw')\n    if (badIndex !== -1) {\n      throw new E_ISOLATE_FUNCTION_ARG_UNSUPPORTED([`${label} args[${badIndex}]`])\n    }\n    const id = nextCorrelationId()\n    return new Promise<R>((resolve, reject) => {\n      pending.set(id, { resolve, reject })\n      w.postMessage({ id, args: encodedArgs })\n    })\n  }\n\n  const dispose = (): void => {\n    if (disposed) return\n    disposed = true\n    worker?.terminate()\n    if (blobUrl) URL.revokeObjectURL(blobUrl)\n    rejectAllPending(new E_ISOLATED_TERMINATED([label]))\n  }\n\n  return { invoke, dispose }\n}\n"],"x_google_ignoreList":[4],"mappings":";;;;;;;;;;;;;;;AA2GA,IAAa,UACX,OAAsB,CAAC,OACK;CAC5B,MAAM;CACN,QAAQ,KAAK;CACb,OAAO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