@robota-sdk/agent-transport-ws 3.0.0-beta.82 → 3.0.0-beta.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/ws-transport.ts","../../src/payload-channels.ts","../../src/ws-connection-guards.ts","../../src/ws-message-data.ts","../../src/ws-session-delivery.ts","../../src/ws-transport-config.ts","../../src/ws-transport-configurable.ts"],"sourcesContent":["/**\n * ITransportAdapter implementation for WebSocket transport.\n *\n * Wraps createSessionMessageHandler into the unified ITransportAdapter interface.\n * After start(), the consumer must wire onMessage to their WebSocket.\n */\n\nimport { createOutboundDelivery, createSessionMessageHandler } from '@robota-sdk/agent-transport';\n\nimport type { TUsageSurface } from '@robota-sdk/agent-interface-analytics';\nimport type { TDriverId } from '@robota-sdk/agent-interface-session';\nimport type {\n ITransportAdapter,\n ITransportLifecycleError,\n} from '@robota-sdk/agent-interface-transport';\nimport type {\n IProtocolSession,\n ISessionMessageHandlerOptions,\n TServerMessage,\n} from '@robota-sdk/agent-transport';\n\nexport interface IWsTransportOptions {\n /** Send a JSON message to the connected WebSocket client. */\n send: (message: TServerMessage) => void;\n /** Owning socket lifecycle callback for outbound session-event delivery failures. */\n onDeliveryError?: (error: Error, event: string) => void;\n personalUsageReporter?: ISessionMessageHandlerOptions['personalUsageReporter'];\n usageReporter?: ISessionMessageHandlerOptions['usageReporter'];\n storedSessionUsageReporter?: ISessionMessageHandlerOptions['storedSessionUsageReporter'];\n driverId?: TDriverId;\n surface?: TUsageSurface;\n}\n\nexport interface IWsTransport extends ITransportAdapter<IProtocolSession> {\n onMessage: ((data: string) => void) | null;\n}\n\nexport function createWsTransport(options: IWsTransportOptions): IWsTransport {\n let session: IProtocolSession | null = null;\n let cleanup: (() => void) | null = null;\n const lifecycleError = (code: ITransportLifecycleError['code']): ITransportLifecycleError =>\n Object.assign(new Error(`WebSocket transport ${code}.`), {\n name: 'TransportLifecycleError' as const,\n code,\n transportName: 'ws',\n });\n\n const transport: IWsTransport = {\n name: 'ws',\n lifecycle: Object.freeze({ kind: 'service' }),\n onMessage: null,\n attach(s: IProtocolSession) {\n session = s;\n },\n async start() {\n if (!session) throw lifecycleError('not-attached');\n if (cleanup) throw lifecycleError('already-started');\n // ARCH-030: this adapter is the carrier here, so it builds the connection's outbound boundary\n // from its own injected sink and its own failure policy, then passes it down.\n const deliver = createOutboundDelivery(options.send, (error, event) => {\n handler.cleanup();\n cleanup = null;\n transport.onMessage = null;\n options.onDeliveryError?.(error, event);\n });\n const handler = createSessionMessageHandler({\n session,\n deliver,\n ...(options.driverId ? { driverId: options.driverId } : {}),\n ...(options.surface ? { surface: options.surface } : {}),\n ...(options.personalUsageReporter\n ? { personalUsageReporter: options.personalUsageReporter }\n : {}),\n ...(options.usageReporter ? { usageReporter: options.usageReporter } : {}),\n ...(options.storedSessionUsageReporter\n ? { storedSessionUsageReporter: options.storedSessionUsageReporter }\n : {}),\n });\n cleanup = handler.cleanup;\n this.onMessage = handler.onMessage;\n },\n async stop() {\n cleanup?.();\n cleanup = null;\n this.onMessage = null;\n session = null;\n },\n };\n return transport;\n}\n","/**\n * Payload-agnostic channel registry (TRANS-001) — the transport-side half of\n * {@link IPayloadChannelHost}.\n *\n * Owns the multiplexing the carrier needs and nothing else: which channels exist, what each one\n * declared, per-channel outbound `seq`, the attached connection sinks, and inbound routing. It is\n * completely blind to payload semantics — a channel carrying audio, a file, or app events is the\n * same object to this class.\n *\n * Every rejection is EXPLICIT: an undeclared event, binary traffic on a text-only channel, or a\n * frame for an unregistered channel comes back as a stated error the carrier reports to the peer.\n * Nothing is silently dropped or defaulted.\n */\n\nimport {\n decodeChannelFrame,\n encodeBinaryFrame,\n encodeChannelEventFrame,\n} from '@robota-sdk/agent-transport';\n\nimport type {\n IBinaryFrame,\n IChannelDescriptor,\n IChannelEventFrame,\n IPayloadChannel,\n IPayloadChannelHost,\n TChannelEventMap,\n TChannelReceiveResult,\n} from '@robota-sdk/agent-interface-transport';\n\n/** Delivers an encoded frame to one attached connection. */\nexport type TChannelSink = (frame: Uint8Array) => void;\n\ntype TBinaryHandler = (frame: IBinaryFrame) => void;\n/**\n * Storage type for a consumer's event handler. `never` parameters make every concrete\n * `(payload: TEvents[K], frame: IChannelEventFrame<TEvents[K]>) => void` assignable to it, so the\n * per-channel handler sets stay heterogeneous without an `unknown` double-cast. The declared-event\n * check at both `onEvent` and `receive` is what keeps the erased types honest at runtime.\n */\ntype TEventHandler = (payload: never, frame: never) => void;\n\n/** Per-channel mutable state. Kept private to the registry — consumers only see `IPayloadChannel`. */\ninterface IChannelState {\n readonly descriptor: IChannelDescriptor;\n readonly declaredEvents: ReadonlySet<string>;\n readonly eventHandlers: Map<string, Set<TEventHandler>>;\n readonly binaryHandlers: Set<TBinaryHandler>;\n seq: number;\n open: boolean;\n}\n\nexport class PayloadChannelRegistry implements IPayloadChannelHost {\n private readonly channels = new Map<string, IChannelState>();\n private readonly sinks = new Set<TChannelSink>();\n\n /**\n * Attach a connection. Every frame a channel sends is fanned out to all attached sinks; the\n * returned function detaches (call it on socket close).\n */\n addSink(sink: TChannelSink): () => void {\n this.sinks.add(sink);\n return (): void => {\n this.sinks.delete(sink);\n };\n }\n\n registerChannel<TEvents extends TChannelEventMap>(\n descriptor: IChannelDescriptor<TEvents>,\n ): IPayloadChannel<TEvents> {\n if (this.channels.has(descriptor.name)) {\n throw new Error(`Channel \"${descriptor.name}\" is already registered on this transport`);\n }\n const state: IChannelState = {\n descriptor: descriptor as IChannelDescriptor,\n declaredEvents: new Set<string>(descriptor.events),\n eventHandlers: new Map(),\n binaryHandlers: new Set(),\n seq: 0,\n open: true,\n };\n this.channels.set(descriptor.name, state);\n return this.createHandle<TEvents>(descriptor, state);\n }\n\n /**\n * Route one inbound encoded frame to its channel's handlers. The result states exactly what\n * happened so the carrier can answer the peer (a `protocol_error`) instead of dropping it.\n */\n receive(bytes: Uint8Array): TChannelReceiveResult {\n const decoded = decodeChannelFrame(bytes);\n if (!decoded.ok) return decoded;\n\n const { frame } = decoded;\n const state = this.channels.get(frame.channel);\n if (!state || !state.open) {\n return { ok: false, error: `No channel registered for \"${frame.channel}\"` };\n }\n\n if (frame.kind === 'binary') {\n if (state.descriptor.binary !== true) {\n return {\n ok: false,\n error: `Channel \"${frame.channel}\" did not declare binary payload support`,\n };\n }\n for (const handler of [...state.binaryHandlers]) handler(frame);\n return { ok: true, frame };\n }\n\n if (!state.declaredEvents.has(frame.event)) {\n return {\n ok: false,\n error: `Channel \"${frame.channel}\" did not declare event \"${frame.event}\"`,\n };\n }\n const handlers = state.eventHandlers.get(frame.event);\n if (handlers) {\n for (const handler of [...handlers]) handler(frame.payload as never, frame as never);\n }\n return { ok: true, frame };\n }\n\n /** Fan one encoded frame out to every attached connection. */\n private broadcast(frame: Uint8Array): void {\n for (const sink of [...this.sinks]) sink(frame);\n }\n\n /** Assert the channel is still open before any send/subscribe. */\n private static assertOpen(state: IChannelState): void {\n if (!state.open) throw new Error(`Channel \"${state.descriptor.name}\" is closed`);\n }\n\n private createHandle<TEvents extends TChannelEventMap>(\n descriptor: IChannelDescriptor<TEvents>,\n state: IChannelState,\n ): IPayloadChannel<TEvents> {\n return {\n descriptor,\n\n sendEvent: <K extends keyof TEvents & string>(event: K, payload: TEvents[K]): void => {\n PayloadChannelRegistry.assertOpen(state);\n if (!state.declaredEvents.has(event)) {\n throw new Error(`Channel \"${descriptor.name}\" did not declare event \"${event}\"`);\n }\n const seq = state.seq;\n state.seq += 1;\n this.broadcast(\n encodeChannelEventFrame({\n kind: 'event',\n channel: descriptor.name,\n seq,\n event,\n payload,\n }),\n );\n },\n\n sendBinary: (payload: Uint8Array): void => {\n PayloadChannelRegistry.assertOpen(state);\n if (descriptor.binary !== true) {\n throw new Error(`Channel \"${descriptor.name}\" did not declare binary payload support`);\n }\n const seq = state.seq;\n state.seq += 1;\n this.broadcast(\n encodeBinaryFrame({ kind: 'binary', channel: descriptor.name, seq, payload }),\n );\n },\n\n onEvent: <K extends keyof TEvents & string>(\n event: K,\n handler: (payload: TEvents[K], frame: IChannelEventFrame<TEvents[K]>) => void,\n ): (() => void) => {\n PayloadChannelRegistry.assertOpen(state);\n if (!state.declaredEvents.has(event)) {\n throw new Error(`Channel \"${descriptor.name}\" did not declare event \"${event}\"`);\n }\n const set = state.eventHandlers.get(event) ?? new Set<TEventHandler>();\n const typed: TEventHandler = handler;\n set.add(typed);\n state.eventHandlers.set(event, set);\n return (): void => {\n set.delete(typed);\n };\n },\n\n onBinary: (handler: (frame: IBinaryFrame) => void): (() => void) => {\n PayloadChannelRegistry.assertOpen(state);\n state.binaryHandlers.add(handler);\n return (): void => {\n state.binaryHandlers.delete(handler);\n };\n },\n\n close: (): void => {\n state.open = false;\n state.eventHandlers.clear();\n state.binaryHandlers.clear();\n this.channels.delete(descriptor.name);\n },\n };\n }\n}\n","/**\n * Connection-admission guards for the WS transport (SEC-001 / GUI-002).\n *\n * Pure, socket-free predicates over the HTTP upgrade request — token minting/comparison plus the\n * `Host` and `Origin` allow-lists. Split out of `ws-transport-configurable.ts` so the transport file\n * carries lifecycle and frame routing only; the admission policy is independently readable and the\n * transport module stays within the file-size ratchet.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\n\nimport { resolveAdmission } from '@robota-sdk/agent-transport/node';\n\nimport type { ITransportAdmission } from '@robota-sdk/agent-interface-transport';\nimport type { IncomingMessage } from 'node:http';\n\n/**\n * Host names that are always loopback (port stripped by the caller). IPv4 bind only, so `[::1]`\n * inbound is moot, but accepting it is harmless.\n */\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);\n\n/** Strip the `:port` suffix from a Host/authority (port-agnostic — `bindWithRetry` can walk the port). */\nfunction hostname(hostHeader: string | undefined): string | null {\n if (!hostHeader) return null;\n if (hostHeader.startsWith('[')) return hostHeader.slice(0, hostHeader.indexOf(']') + 1) || null;\n const colon = hostHeader.lastIndexOf(':');\n return colon === -1 ? hostHeader : hostHeader.slice(0, colon);\n}\n\n/**\n * The upgrade `Host` must be a loopback name (port-agnostic) or an explicitly allowed host — closes\n * DNS rebinding. A missing `Host` is rejected (a well-formed HTTP/1.1 client always sends one).\n */\nexport function hostAllowed(req: IncomingMessage, allowedHosts: ReadonlySet<string>): boolean {\n const host = hostname(req.headers.host);\n if (host === null) return false;\n return LOOPBACK_HOSTS.has(host) || allowedHosts.has(host);\n}\n\n/**\n * A browser sends an unforgeable `Origin`; require it to be loopback or explicitly allowed. A\n * non-browser client omits `Origin` (allowed here — the token is its gate). Closes the browser\n * drive-by hole.\n */\nexport function originAllowed(req: IncomingMessage, allowedOrigins: ReadonlySet<string>): boolean {\n const origin = req.headers.origin;\n if (origin === undefined) return true; // non-browser client; token still required\n if (allowedOrigins.has(origin)) return true;\n try {\n return LOOPBACK_HOSTS.has(new URL(origin).hostname);\n } catch {\n return false; // malformed Origin → reject\n }\n}\n\n/**\n * Constant-time token comparison. Returns false on any length mismatch (never throws), so an\n * absent/short/long presented token is a plain reject, not an error.\n */\nexport function tokenMatches(expected: string, presented: string | null | undefined): boolean {\n if (!presented) return false;\n const a = Buffer.from(expected);\n const b = Buffer.from(presented);\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n\n/** Read the presented token from the upgrade request: `?token=` query param, else the WS subprotocol. */\nexport function presentedToken(req: IncomingMessage): string | null {\n try {\n const url = new URL(req.url ?? '', 'ws://127.0.0.1');\n const q = url.searchParams.get('token');\n if (q) return q;\n } catch {\n // malformed URL → fall through to the subprotocol header\n }\n const proto = req.headers['sec-websocket-protocol'];\n return typeof proto === 'string' ? proto.split(',')[0]?.trim() || null : null;\n}\n\n/**\n * This transport's admission decision, asked of the shared seam.\n *\n * Lives here rather than in the transport file because this module already owns the admission\n * policy — token comparison and the Host/Origin allow-lists — and the transport file carries\n * lifecycle and frame routing. The split is also what keeps that file inside its size ratchet.\n */\nexport function resolveWsAdmission(config: {\n token?: string;\n open?: boolean;\n openReason?: string;\n}): ITransportAdmission {\n // No fabricated reason. The first version filled one in for any caller that omitted it, which made\n // WS the one transport where `{ open: true }` alone was accepted — HTTP and WebRTC both refuse it.\n // Review found that: a reason invented on the caller's behalf reads, to the next person, as a\n // decision somebody made. The whole point of requiring it is that nobody can produce one by\n // accident, so the seam is asked the question exactly as it was given.\n return resolveAdmission({\n ...(config.token !== undefined ? { token: config.token } : {}),\n ...(config.open === true ? { open: true } : {}),\n ...(config.openReason !== undefined ? { openReason: config.openReason } : {}),\n });\n}\n","import type { RawData } from 'ws';\n\n/** Normalize the `ws` inbound payload variants to one binary view. */\nexport function toBytes(data: RawData): Uint8Array {\n if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data));\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n}\n","import {\n createOutboundDelivery,\n createPendingStallClock,\n DEFAULT_MAX_PENDING_BYTES,\n isOverPendingBudget,\n} from '@robota-sdk/agent-transport';\nimport { WebSocket } from 'ws';\n\nimport type {\n IPendingStallClock,\n TOutboundDeliver,\n TServerMessage,\n} from '@robota-sdk/agent-transport';\n\n/**\n * Connection-scoped session delivery lifecycle shared by sync and async WebSocket failures.\n *\n * ARCH-030: {@link deliver} is the ONLY way out of this class. The raw sink — the `readyState` check\n * plus `socket.send` — is private, so no caller can put a frame on this socket outside the connection's\n * one outbound boundary. That is not stylistic: the previous shape exposed a public `send` that threw\n * on a closed socket, and every reply the protocol handler produced went through it unguarded.\n */\nexport class WsSessionDelivery {\n private cleanupProtocol = (): void => undefined;\n private detachSink = (): void => undefined;\n private closed = false;\n /**\n * Issue #2306: ONE drain clock for the socket. `bufferedAmount` does not distinguish text from\n * binary, so both halves observe the same clock — a slow reader of payload frames is caught when a\n * JSON reply is attempted, and the reverse.\n */\n private readonly stallClock: IPendingStallClock = createPendingStallClock();\n\n /**\n * The connection's outbound boundary. Built here, from this class's own sink and its own `close`\n * policy, and passed DOWN into `createSessionMessageHandler` — the carrier owns both halves, so it builds the\n * boundary rather than handing the protocol layer a raw sink to wrap.\n */\n readonly deliver: TOutboundDeliver;\n\n constructor(private readonly socket: WebSocket) {\n this.deliver = createOutboundDelivery(\n (message) => this.rawSend(message),\n () => this.close(),\n // ARCH-030 / issue #1734: the socket's own count of what it has accepted and not yet written.\n // Read at call time — it changes underneath.\n () => this.socket.bufferedAmount,\n DEFAULT_MAX_PENDING_BYTES,\n this.stallClock,\n );\n }\n\n /**\n * Put a TRANS-001 payload frame on this socket, under the SAME budget and the same close policy as\n * the text protocol (ARCH-030 / issue #1734).\n *\n * A WebSocket carries two kinds of outbound frame over one socket, and until this existed the\n * binary half went straight to `socket.send` — outside the boundary, with no budget, and with a\n * failure that could only surface as a throw inside a listener. `bufferedAmount` does not\n * distinguish the two, so a non-reading peer accumulating payload frames was invisible to a budget\n * that only guarded the other half.\n *\n * It is not `deliver`: that boundary is typed for `TServerMessage` and its brand is what makes a\n * raw send unusable where a protocol frame is required. Widening it to accept bytes would remove\n * the property the brand exists for.\n */\n readonly deliverBinary = (frame: Uint8Array): void => {\n if (this.closed) return;\n if (this.socket.readyState !== WebSocket.OPEN) return;\n if (\n isOverPendingBudget(this.socket.bufferedAmount) ||\n this.stallClock.observe(this.socket.bufferedAmount) !== undefined\n ) {\n this.close();\n return;\n }\n this.socket.send(frame, { binary: true }, (error) => {\n if (error) this.close();\n });\n };\n\n private rawSend(message: TServerMessage): void {\n if (this.socket.readyState !== WebSocket.OPEN) throw new Error('WebSocket is not open');\n this.socket.send(JSON.stringify(message), (error) => {\n if (error) this.close();\n });\n }\n\n bindProtocolCleanup(cleanup: () => void): void {\n this.cleanupProtocol = cleanup;\n }\n\n bindSinkDetach(detach: () => void): void {\n this.detachSink = detach;\n }\n\n readonly close = (): void => {\n if (this.closed) return;\n this.closed = true;\n this.detachSink();\n this.cleanupProtocol();\n if (\n this.socket.readyState === WebSocket.OPEN ||\n this.socket.readyState === WebSocket.CONNECTING\n ) {\n this.socket.close(1011, 'session event delivery failed');\n }\n };\n}\n","/**\n * The construction contract for `WsTransport` — what a caller decides before the server exists.\n *\n * Split from `ws-transport-configurable.ts` under the file-size ceiling, and the seam is the\n * honest one: everything here is a decision the CALLER makes (port, retries, admission — SEC-008's\n * `token`/`open`/`openReason` contract lives in these doc comments), while the class next door is\n * what the transport DOES with those decisions.\n */\n\nimport type { TUsageSurface } from '@robota-sdk/agent-interface-analytics';\nimport type { TDriverId } from '@robota-sdk/agent-interface-session';\nimport type { ITransportLifecycleError } from '@robota-sdk/agent-interface-transport';\nimport type { ISessionMessageHandlerOptions } from '@robota-sdk/agent-transport';\n\nexport const DEFAULT_PORT = 7070;\nexport const DEFAULT_MAX_RETRIES = 20;\n\nexport interface IWsTransportConfig {\n /** Trusted server-assigned identity for turns submitted over this product surface. */\n driverId?: TDriverId;\n /** Trusted product surface, independent from the connection's driver identity. */\n surface?: TUsageSurface;\n /** Host-owned cross-session usage read model, forwarded unchanged to the protocol handler. */\n personalUsageReporter?: ISessionMessageHandlerOptions['personalUsageReporter'];\n /** Host-owned current-session trace/cost producer, forwarded unchanged to the protocol handler. */\n usageReporter?: ISessionMessageHandlerOptions['usageReporter'];\n /** Host-owned stored-session trace/cost producer for personal-usage drill-down. */\n storedSessionUsageReporter?: ISessionMessageHandlerOptions['storedSessionUsageReporter'];\n port?: number;\n maxRetries?: number;\n /**\n * OPTIONAL explicit loopback auth token. When set, every connection MUST present a matching token\n * (query param `?token=` or the `Sec-WebSocket-Protocol` subprotocol) or the socket is closed BEFORE any\n * session data is emitted (GUI-002; the GUI sidecar sets `ROBOTA_WS_TOKEN`). SEC-001: when this is unset\n * AND `open` is not `true`, the transport AUTO-MINTS a random per-launch token (secure by default) —\n * `resolvedToken` exposes it so the surface can deliver it to the co-located client (a `0600` connection\n * file / the served monitor's injected `ws-url`). An explicit token here wins over the auto-mint — but NOT\n * over `open`: SEC-008 makes a token together with `open: true` a contradiction that throws, rather\n * than a precedence one side quietly wins.\n */\n token?: string;\n /**\n * SEC-001 discouraged opt-out: when `true`, run WITHOUT auth (no token, no auto-mint) — the pre-SEC-001\n * open loopback behavior. NOT RECOMMENDED (any local process or browser page can then drive+authorize the\n * session); mirrors Jupyter's `c.ServerApp.token = ''`.\n *\n * SEC-008: `open: true` together with a non-empty `token` is REJECTED, not resolved by precedence. The\n * two ask for opposite things, and picking a winner silently is how a caller ends up with the admission\n * it did not choose. `resolveAdmission` decides that for every transport, so they cannot differ.\n */\n open?: boolean;\n /** SEC-008: why running with no credential is correct here. Required when `open` is true. */\n openReason?: string;\n /**\n * SEC-001 defense-in-depth: extra host names (beyond `localhost`/`127.0.0.1`/`::1`) accepted in the\n * upgrade `Host` header. The `Host` allow-list closes DNS-rebinding independently of the token.\n */\n allowedHosts?: readonly string[];\n /**\n * SEC-001 defense-in-depth: extra browser `Origin`s (beyond loopback) accepted on the upgrade — e.g. the\n * `apps/agent-web` app origin. A browser sends an unforgeable `Origin`; a non-browser client omits it (and\n * is gated by the token instead). Closes the \"any web page in any browser\" hole before history is emitted.\n */\n allowedOrigins?: readonly string[];\n}\n\ntype TUsageReporters = Pick<\n ISessionMessageHandlerOptions,\n 'personalUsageReporter' | 'usageReporter' | 'storedSessionUsageReporter'\n>;\n\n/** Remove absent reporters so exact-optional handler options remain truthful. */\nfunction configuredUsageReporters(config: IWsTransportConfig): TUsageReporters {\n return {\n ...(config.personalUsageReporter\n ? { personalUsageReporter: config.personalUsageReporter }\n : {}),\n ...(config.usageReporter ? { usageReporter: config.usageReporter } : {}),\n ...(config.storedSessionUsageReporter\n ? { storedSessionUsageReporter: config.storedSessionUsageReporter }\n : {}),\n };\n}\n\ntype TConfiguredHandlerOptions = Pick<\n ISessionMessageHandlerOptions,\n 'driverId' | 'surface' | 'personalUsageReporter' | 'usageReporter' | 'storedSessionUsageReporter'\n>;\n\n/** Project immutable transport attribution/reporters into each protocol handler. */\nexport function configuredWsHandlerOptions(config: IWsTransportConfig): TConfiguredHandlerOptions {\n return {\n ...(config.driverId ? { driverId: config.driverId } : {}),\n ...(config.surface ? { surface: config.surface } : {}),\n ...configuredUsageReporters(config),\n };\n}\n\nexport function validTransportOptions(options: Readonly<Record<string, unknown>>): boolean {\n const { port, maxRetries } = options;\n if (port !== undefined && (typeof port !== 'number' || port < 1 || port > 65535)) return false;\n return maxRetries === undefined || (typeof maxRetries === 'number' && maxRetries >= 0);\n}\n\nexport function transportLifecycleError(\n transportName: string,\n code: ITransportLifecycleError['code'],\n): ITransportLifecycleError {\n return Object.assign(new Error(`${transportName} ${code}.`), {\n name: 'TransportLifecycleError' as const,\n code,\n transportName,\n });\n}\n","/**\n * Self-contained WS transport implementing IConfigurableTransport.\n * Owns the WebSocket server lifecycle (ws package), started/stopped via the transport registry.\n */\n\nimport { createServer, type IncomingMessage, type Server } from 'node:http';\n\nimport { createSessionMessageHandler } from '@robota-sdk/agent-transport';\nimport { WebSocketServer } from 'ws';\n\nimport { PayloadChannelRegistry } from './payload-channels.js';\nimport {\n hostAllowed,\n originAllowed,\n presentedToken,\n resolveWsAdmission,\n tokenMatches,\n} from './ws-connection-guards.js';\nimport { toBytes } from './ws-message-data.js';\nimport { WsSessionDelivery } from './ws-session-delivery.js';\nimport {\n DEFAULT_MAX_RETRIES,\n DEFAULT_PORT,\n configuredWsHandlerOptions,\n transportLifecycleError,\n validTransportOptions,\n} from './ws-transport-config.js';\n\nimport type { IWsTransportConfig } from './ws-transport-config.js';\nimport type { TUniversalValue } from '@robota-sdk/agent-core';\nimport type {\n IChannelDescriptor,\n IConfigurableTransport,\n IPayloadChannel,\n IPayloadChannelHost,\n TChannelEventMap,\n} from '@robota-sdk/agent-interface-transport';\nimport type { IProtocolSession } from '@robota-sdk/agent-transport';\nimport type { RawData, WebSocket } from 'ws';\n\n/**\n * RUNTIME-13: forced-terminate deadline for `stop()`. `WebSocketServer.close()` fires its callback only after\n * every client socket is gone, so a still-connected client would hang `stop()` forever. We send a close frame\n * (1001 \"going away\") to each client, then `terminate()` any socket still open at this deadline — the RFC 6455\n * + `ws` + drain-then-force convention (a WS close handshake completes in well under a second; 5s is generous).\n */\nconst WS_STOP_TERMINATE_DEADLINE_MS = 5000;\n\n/**\n * TRANS-001: the WS transport is a payload-agnostic CARRIER that routes by WebSocket frame opcode —\n * TEXT frames go to the text-agent protocol profile (`createSessionMessageHandler`), BINARY frames go to the\n * consumer-declared channels. The two profiles share one connection and never constrain each other.\n */\nexport class WsTransport\n implements IConfigurableTransport<IProtocolSession>, IPayloadChannelHost\n{\n readonly name = 'ws';\n readonly lifecycle = Object.freeze({ kind: 'service' as const });\n readonly defaultEnabled = true;\n readonly optionsSchema = {\n port: { type: 'number', description: 'WebSocket server port', default: DEFAULT_PORT },\n maxRetries: {\n type: 'number',\n description: 'Port retry attempts when port is occupied',\n default: DEFAULT_MAX_RETRIES,\n },\n };\n\n private session: IProtocolSession | null = null;\n private stopFn: (() => Promise<void>) | null = null;\n private state: 'detached' | 'attached' | 'starting' | 'ready' | 'stopping' = 'detached';\n private startOperation: Promise<{ stop: () => Promise<void>; port: number }> | undefined;\n private startCancelled = false;\n private port: number;\n private maxRetries: number;\n private readonly token?: string;\n private readonly allowedHosts: ReadonlySet<string>;\n private readonly allowedOrigins: ReadonlySet<string>;\n private readonly handlerOptions: ReturnType<typeof configuredWsHandlerOptions>;\n private readonly channels = new PayloadChannelRegistry();\n private resolvedPort?: number;\n\n constructor(config: IWsTransportConfig = {}) {\n this.port = config.port ?? DEFAULT_PORT;\n this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;\n // SEC-001/SEC-008: secure by default, decided by the shared seam rather than a copy here — see\n // SPEC § Transport Admission. A failed mint throws out of the constructor (fail-closed).\n const admission = resolveWsAdmission(config);\n if (admission.token !== null) this.token = admission.token;\n this.allowedHosts = new Set(config.allowedHosts ?? []);\n this.allowedOrigins = new Set(config.allowedOrigins ?? []);\n this.handlerOptions = configuredWsHandlerOptions(config);\n }\n\n attach(session: IProtocolSession): void {\n this.session = session;\n this.state = 'attached';\n }\n\n /**\n * TRANS-001: declare an app-level channel carried on this transport's connections. The channel's\n * events and opaque binary frames ride alongside the text-agent protocol on the SAME socket — the\n * transport never inspects the payloads. Register before or after `start()`; a channel opened\n * later is served by every already-connected client.\n */\n registerChannel<TEvents extends TChannelEventMap>(\n descriptor: IChannelDescriptor<TEvents>,\n ): IPayloadChannel<TEvents> {\n return this.channels.registerChannel(descriptor);\n }\n\n /** Actually-bound port after start; undefined before start. */\n get boundPort(): number | undefined {\n return this.resolvedPort;\n }\n\n /**\n * SEC-001: the resolved auth token (explicit or auto-minted), or `undefined` in the discouraged `open`\n * mode. The surface reads this to deliver the token to the co-located client (a `0600` connection file /\n * the served monitor's injected `ws-url`). Never logged by the transport itself.\n */\n get resolvedToken(): string | undefined {\n return this.token;\n }\n\n async start(): Promise<void> {\n if (!this.session) throw transportLifecycleError(this.name, 'not-attached');\n if (this.state === 'starting' || this.state === 'ready' || this.state === 'stopping') {\n throw transportLifecycleError(this.name, 'already-started');\n }\n this.state = 'starting';\n this.startCancelled = false;\n const operation = this.bindWithRetry(this.session, this.port, this.maxRetries);\n this.startOperation = operation;\n let handle: Awaited<typeof operation>;\n try {\n handle = await operation;\n } catch (error) {\n if (this.state === 'starting' && this.startOperation === operation) {\n this.startOperation = undefined;\n this.state = this.session ? 'attached' : 'detached';\n }\n throw error;\n }\n if (this.startCancelled || this.startOperation !== operation) {\n await handle.stop();\n this.state = this.session ? 'attached' : 'detached';\n throw new Error('WsTransport startup was stopped.');\n }\n this.stopFn = handle.stop;\n this.resolvedPort = handle.port;\n this.startOperation = undefined;\n this.state = 'ready';\n }\n\n async stop(): Promise<void> {\n if (this.state === 'starting') {\n this.state = 'stopping';\n this.startCancelled = true;\n try {\n await this.startOperation;\n } catch {\n // The start caller owns bind failure; stop still clears lifecycle state.\n }\n }\n await this.stopFn?.();\n this.stopFn = null;\n this.startOperation = undefined;\n this.resolvedPort = undefined;\n this.session = null;\n this.state = 'detached';\n }\n\n /** TRANS-002 (issue #2480): persisted `port`/`maxRetries` reach the server through here, before start. */\n configure(options: Record<string, TUniversalValue>): void {\n if (this.state !== 'detached' && this.state !== 'attached') {\n throw transportLifecycleError(this.name, 'already-started');\n }\n if (!this.validateOptions(options)) {\n throw new TypeError('WsTransport options are invalid (port 1-65535, maxRetries >= 0).');\n }\n if (typeof options['port'] === 'number') this.port = options['port'];\n if (typeof options['maxRetries'] === 'number') this.maxRetries = options['maxRetries'];\n }\n\n validateOptions(options: Record<string, TUniversalValue>): boolean {\n return validTransportOptions(options);\n }\n\n private bindWithRetry(\n session: IProtocolSession,\n port: number,\n retriesLeft: number,\n ): Promise<{ stop: () => Promise<void>; port: number }> {\n return this.tryBind(session, port).catch((err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE' && retriesLeft > 0)\n return this.bindWithRetry(session, port + 1, retriesLeft - 1);\n throw err;\n });\n }\n\n private tryBind(\n session: IProtocolSession,\n port: number,\n ): Promise<{ stop: () => Promise<void>; port: number }> {\n return new Promise((resolve, reject) => {\n const httpServer: Server = createServer((_, res) => {\n res.writeHead(400).end('WebSocket endpoint');\n });\n\n httpServer.on('error', (err: NodeJS.ErrnoException) => {\n httpServer.close();\n reject(err);\n });\n\n const expectedToken = this.token;\n const allowedHosts = this.allowedHosts;\n const allowedOrigins = this.allowedOrigins;\n const channels = this.channels;\n httpServer.listen(port, '127.0.0.1', () => {\n const wss = new WebSocketServer({\n server: httpServer,\n // Reject disallowed Host/Origin before the protocol upgrade or any session data.\n verifyClient: (\n info: { origin: string; secure: boolean; req: IncomingMessage },\n cb: (res: boolean, code?: number, message?: string) => void,\n ) => {\n if (!hostAllowed(info.req, allowedHosts)) {\n cb(false, 403, 'Forbidden host');\n return;\n }\n if (!originAllowed(info.req, allowedOrigins)) {\n cb(false, 403, 'Forbidden origin');\n return;\n }\n cb(true);\n },\n });\n\n wss.on('connection', (ws: WebSocket, req: IncomingMessage) => {\n // Reject unauthenticated peers before sending history or accepting prompt responses.\n if (expectedToken !== undefined && !tokenMatches(expectedToken, presentedToken(req))) {\n ws.close(1008, 'unauthorized');\n return;\n }\n\n const delivery = new WsSessionDelivery(ws);\n const handler = createSessionMessageHandler({\n session,\n deliver: delivery.deliver,\n ...this.handlerOptions,\n });\n delivery.bindProtocolCleanup(handler.cleanup);\n\n delivery.bindSinkDetach(\n // ARCH-030: through the connection's own delivery, so payload frames share the text\n // protocol's backpressure budget and its close policy. The bare `readyState` check plus\n // `ws.send` that stood here was the last outbound path on this socket outside the\n // boundary.\n channels.addSink((frame: Uint8Array) => delivery.deliverBinary(frame)),\n );\n\n // Route by frame opcode: TEXT → the text-agent protocol profile, BINARY → the\n // payload-agnostic channels. An unroutable channel frame is answered with an explicit\n // `protocol_error` rather than silently dropped.\n ws.on('message', (data: RawData, isBinary: boolean) => {\n if (!isBinary) {\n handler.onMessage(String(data));\n return;\n }\n const result = channels.receive(toBytes(data));\n if (!result.ok) delivery.deliver({ type: 'protocol_error', message: result.error });\n });\n ws.on('close', delivery.close);\n ws.on('error', delivery.close);\n\n delivery.deliver({ type: 'messages', messages: session.getMessages() });\n delivery.deliver({\n type: 'execution_workspace_event',\n snapshot: session.getExecutionWorkspaceSnapshot(),\n });\n });\n\n resolve({\n port,\n stop: () =>\n new Promise<void>((res) => {\n // RUNTIME-13: graceful-then-forced shutdown. Send a close frame to each client so well-behaved\n // peers close cleanly; terminate any socket still open at the deadline so `wss.close()`'s\n // all-clients-gone callback can never hang. `verifyClient`/token gates are connection-time and\n // untouched here (SEC-001 preserved).\n for (const client of wss.clients) client.close(1001, 'server shutting down');\n const deadline = setTimeout(() => {\n for (const client of wss.clients) client.terminate();\n }, WS_STOP_TERMINATE_DEADLINE_MS);\n wss.close(() => {\n clearTimeout(deadline);\n httpServer.close(() => res());\n });\n }),\n });\n });\n });\n }\n}\n"],"mappings":"sdAqCA,SAAgB,EAAkB,EAA4C,CAC5E,IAAI,EAAmC,KACnC,EAA+B,KAC7B,EAAkB,GACtB,OAAO,OAAW,MAAM,uBAAuB,EAAK,EAAE,EAAG,CACvD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d,aAAa,CAAQ,EACrB,EAAW,UAAY,EAAI,CAAC,CAC9B,CAAC,CACH,CAAC,CACL,CAAC,CACH,CAAC,CACH,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/ws-transport.ts","../../src/payload-channels.ts","../../src/ws-connection-guards.ts","../../src/ws-message-data.ts","../../src/ws-session-delivery.ts","../../src/ws-transport-config.ts","../../src/ws-transport-configurable.ts"],"sourcesContent":["/**\n * ITransportAdapter implementation for WebSocket transport.\n *\n * Wraps createSessionMessageHandler into the unified ITransportAdapter interface.\n * After start(), the consumer must wire onMessage to their WebSocket.\n */\n\nimport { createOutboundDelivery, createSessionMessageHandler } from '@robota-sdk/agent-transport';\n\nimport type { TUsageSurface } from '@robota-sdk/agent-interface-analytics';\nimport type { TDriverId } from '@robota-sdk/agent-interface-session';\nimport type {\n ITransportAdapter,\n ITransportLifecycleError,\n} from '@robota-sdk/agent-interface-transport';\nimport type {\n IProtocolSession,\n ISessionMessageHandlerOptions,\n TServerMessage,\n} from '@robota-sdk/agent-transport';\n\nexport interface IWsTransportOptions {\n /** Send a JSON message to the connected WebSocket client. */\n send: (message: TServerMessage) => void;\n /** Owning socket lifecycle callback for outbound session-event delivery failures. */\n onDeliveryError?: (error: Error, event: string) => void;\n personalUsageReporter?: ISessionMessageHandlerOptions['personalUsageReporter'];\n usageReporter?: ISessionMessageHandlerOptions['usageReporter'];\n storedSessionUsageReporter?: ISessionMessageHandlerOptions['storedSessionUsageReporter'];\n sessionDirectory?: ISessionMessageHandlerOptions['sessionDirectory'];\n driverId?: TDriverId;\n surface?: TUsageSurface;\n}\n\nexport interface IWsTransport extends ITransportAdapter<IProtocolSession> {\n onMessage: ((data: string) => void) | null;\n}\n\nexport function createWsTransport(options: IWsTransportOptions): IWsTransport {\n let session: IProtocolSession | null = null;\n let cleanup: (() => void) | null = null;\n const lifecycleError = (code: ITransportLifecycleError['code']): ITransportLifecycleError =>\n Object.assign(new Error(`WebSocket transport ${code}.`), {\n name: 'TransportLifecycleError' as const,\n code,\n transportName: 'ws',\n });\n\n const transport: IWsTransport = {\n name: 'ws',\n lifecycle: Object.freeze({ kind: 'service' }),\n onMessage: null,\n attach(s: IProtocolSession) {\n session = s;\n },\n async start() {\n if (!session) throw lifecycleError('not-attached');\n if (cleanup) throw lifecycleError('already-started');\n // ARCH-030: this adapter is the carrier here, so it builds the connection's outbound boundary\n // from its own injected sink and its own failure policy, then passes it down.\n const deliver = createOutboundDelivery(options.send, (error, event) => {\n handler.cleanup();\n cleanup = null;\n transport.onMessage = null;\n options.onDeliveryError?.(error, event);\n });\n const handler = createSessionMessageHandler({\n session,\n deliver,\n ...(options.driverId ? { driverId: options.driverId } : {}),\n ...(options.surface ? { surface: options.surface } : {}),\n ...(options.personalUsageReporter\n ? { personalUsageReporter: options.personalUsageReporter }\n : {}),\n ...(options.usageReporter ? { usageReporter: options.usageReporter } : {}),\n ...(options.storedSessionUsageReporter\n ? { storedSessionUsageReporter: options.storedSessionUsageReporter }\n : {}),\n ...(options.sessionDirectory ? { sessionDirectory: options.sessionDirectory } : {}),\n });\n cleanup = handler.cleanup;\n this.onMessage = handler.onMessage;\n },\n async stop() {\n cleanup?.();\n cleanup = null;\n this.onMessage = null;\n session = null;\n },\n };\n return transport;\n}\n","/**\n * Payload-agnostic channel registry (TRANS-001) — the transport-side half of\n * {@link IPayloadChannelHost}.\n *\n * Owns the multiplexing the carrier needs and nothing else: which channels exist, what each one\n * declared, per-channel outbound `seq`, the attached connection sinks, and inbound routing. It is\n * completely blind to payload semantics — a channel carrying audio, a file, or app events is the\n * same object to this class.\n *\n * Every rejection is EXPLICIT: an undeclared event, binary traffic on a text-only channel, or a\n * frame for an unregistered channel comes back as a stated error the carrier reports to the peer.\n * Nothing is silently dropped or defaulted.\n */\n\nimport {\n decodeChannelFrame,\n encodeBinaryFrame,\n encodeChannelEventFrame,\n} from '@robota-sdk/agent-transport';\n\nimport type {\n IBinaryFrame,\n IChannelDescriptor,\n IChannelEventFrame,\n IPayloadChannel,\n IPayloadChannelHost,\n TChannelEventMap,\n TChannelReceiveResult,\n} from '@robota-sdk/agent-interface-transport';\n\n/** Delivers an encoded frame to one attached connection. */\nexport type TChannelSink = (frame: Uint8Array) => void;\n\ntype TBinaryHandler = (frame: IBinaryFrame) => void;\n/**\n * Storage type for a consumer's event handler. `never` parameters make every concrete\n * `(payload: TEvents[K], frame: IChannelEventFrame<TEvents[K]>) => void` assignable to it, so the\n * per-channel handler sets stay heterogeneous without an `unknown` double-cast. The declared-event\n * check at both `onEvent` and `receive` is what keeps the erased types honest at runtime.\n */\ntype TEventHandler = (payload: never, frame: never) => void;\n\n/** Per-channel mutable state. Kept private to the registry — consumers only see `IPayloadChannel`. */\ninterface IChannelState {\n readonly descriptor: IChannelDescriptor;\n readonly declaredEvents: ReadonlySet<string>;\n readonly eventHandlers: Map<string, Set<TEventHandler>>;\n readonly binaryHandlers: Set<TBinaryHandler>;\n seq: number;\n open: boolean;\n}\n\nexport class PayloadChannelRegistry implements IPayloadChannelHost {\n private readonly channels = new Map<string, IChannelState>();\n private readonly sinks = new Set<TChannelSink>();\n\n /**\n * Attach a connection. Every frame a channel sends is fanned out to all attached sinks; the\n * returned function detaches (call it on socket close).\n */\n addSink(sink: TChannelSink): () => void {\n this.sinks.add(sink);\n return (): void => {\n this.sinks.delete(sink);\n };\n }\n\n registerChannel<TEvents extends TChannelEventMap>(\n descriptor: IChannelDescriptor<TEvents>,\n ): IPayloadChannel<TEvents> {\n if (this.channels.has(descriptor.name)) {\n throw new Error(`Channel \"${descriptor.name}\" is already registered on this transport`);\n }\n const state: IChannelState = {\n descriptor: descriptor as IChannelDescriptor,\n declaredEvents: new Set<string>(descriptor.events),\n eventHandlers: new Map(),\n binaryHandlers: new Set(),\n seq: 0,\n open: true,\n };\n this.channels.set(descriptor.name, state);\n return this.createHandle<TEvents>(descriptor, state);\n }\n\n /**\n * Route one inbound encoded frame to its channel's handlers. The result states exactly what\n * happened so the carrier can answer the peer (a `protocol_error`) instead of dropping it.\n */\n receive(bytes: Uint8Array): TChannelReceiveResult {\n const decoded = decodeChannelFrame(bytes);\n if (!decoded.ok) return decoded;\n\n const { frame } = decoded;\n const state = this.channels.get(frame.channel);\n if (!state || !state.open) {\n return { ok: false, error: `No channel registered for \"${frame.channel}\"` };\n }\n\n if (frame.kind === 'binary') {\n if (state.descriptor.binary !== true) {\n return {\n ok: false,\n error: `Channel \"${frame.channel}\" did not declare binary payload support`,\n };\n }\n for (const handler of [...state.binaryHandlers]) handler(frame);\n return { ok: true, frame };\n }\n\n if (!state.declaredEvents.has(frame.event)) {\n return {\n ok: false,\n error: `Channel \"${frame.channel}\" did not declare event \"${frame.event}\"`,\n };\n }\n const handlers = state.eventHandlers.get(frame.event);\n if (handlers) {\n for (const handler of [...handlers]) handler(frame.payload as never, frame as never);\n }\n return { ok: true, frame };\n }\n\n /** Fan one encoded frame out to every attached connection. */\n private broadcast(frame: Uint8Array): void {\n for (const sink of [...this.sinks]) sink(frame);\n }\n\n /** Assert the channel is still open before any send/subscribe. */\n private static assertOpen(state: IChannelState): void {\n if (!state.open) throw new Error(`Channel \"${state.descriptor.name}\" is closed`);\n }\n\n private createHandle<TEvents extends TChannelEventMap>(\n descriptor: IChannelDescriptor<TEvents>,\n state: IChannelState,\n ): IPayloadChannel<TEvents> {\n return {\n descriptor,\n\n sendEvent: <K extends keyof TEvents & string>(event: K, payload: TEvents[K]): void => {\n PayloadChannelRegistry.assertOpen(state);\n if (!state.declaredEvents.has(event)) {\n throw new Error(`Channel \"${descriptor.name}\" did not declare event \"${event}\"`);\n }\n const seq = state.seq;\n state.seq += 1;\n this.broadcast(\n encodeChannelEventFrame({\n kind: 'event',\n channel: descriptor.name,\n seq,\n event,\n payload,\n }),\n );\n },\n\n sendBinary: (payload: Uint8Array): void => {\n PayloadChannelRegistry.assertOpen(state);\n if (descriptor.binary !== true) {\n throw new Error(`Channel \"${descriptor.name}\" did not declare binary payload support`);\n }\n const seq = state.seq;\n state.seq += 1;\n this.broadcast(\n encodeBinaryFrame({ kind: 'binary', channel: descriptor.name, seq, payload }),\n );\n },\n\n onEvent: <K extends keyof TEvents & string>(\n event: K,\n handler: (payload: TEvents[K], frame: IChannelEventFrame<TEvents[K]>) => void,\n ): (() => void) => {\n PayloadChannelRegistry.assertOpen(state);\n if (!state.declaredEvents.has(event)) {\n throw new Error(`Channel \"${descriptor.name}\" did not declare event \"${event}\"`);\n }\n const set = state.eventHandlers.get(event) ?? new Set<TEventHandler>();\n const typed: TEventHandler = handler;\n set.add(typed);\n state.eventHandlers.set(event, set);\n return (): void => {\n set.delete(typed);\n };\n },\n\n onBinary: (handler: (frame: IBinaryFrame) => void): (() => void) => {\n PayloadChannelRegistry.assertOpen(state);\n state.binaryHandlers.add(handler);\n return (): void => {\n state.binaryHandlers.delete(handler);\n };\n },\n\n close: (): void => {\n state.open = false;\n state.eventHandlers.clear();\n state.binaryHandlers.clear();\n this.channels.delete(descriptor.name);\n },\n };\n }\n}\n","/**\n * Connection-admission guards for the WS transport (SEC-001 / GUI-002).\n *\n * Pure, socket-free predicates over the HTTP upgrade request — token minting/comparison plus the\n * `Host` and `Origin` allow-lists. Split out of `ws-transport-configurable.ts` so the transport file\n * carries lifecycle and frame routing only; the admission policy is independently readable and the\n * transport module stays within the file-size ratchet.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\n\nimport { resolveAdmission } from '@robota-sdk/agent-transport/node';\n\nimport type { ITransportAdmission } from '@robota-sdk/agent-interface-transport';\nimport type { IncomingMessage } from 'node:http';\n\n/**\n * Host names that are always loopback (port stripped by the caller). IPv4 bind only, so `[::1]`\n * inbound is moot, but accepting it is harmless.\n */\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);\n\n/** Strip the `:port` suffix from a Host/authority (port-agnostic — `bindWithRetry` can walk the port). */\nfunction hostname(hostHeader: string | undefined): string | null {\n if (!hostHeader) return null;\n if (hostHeader.startsWith('[')) return hostHeader.slice(0, hostHeader.indexOf(']') + 1) || null;\n const colon = hostHeader.lastIndexOf(':');\n return colon === -1 ? hostHeader : hostHeader.slice(0, colon);\n}\n\n/**\n * The upgrade `Host` must be a loopback name (port-agnostic) or an explicitly allowed host — closes\n * DNS rebinding. A missing `Host` is rejected (a well-formed HTTP/1.1 client always sends one).\n */\nexport function hostAllowed(req: IncomingMessage, allowedHosts: ReadonlySet<string>): boolean {\n const host = hostname(req.headers.host);\n if (host === null) return false;\n return LOOPBACK_HOSTS.has(host) || allowedHosts.has(host);\n}\n\n/**\n * A browser sends an unforgeable `Origin`; require it to be loopback or explicitly allowed. A\n * non-browser client omits `Origin` (allowed here — the token is its gate). Closes the browser\n * drive-by hole.\n */\nexport function originAllowed(req: IncomingMessage, allowedOrigins: ReadonlySet<string>): boolean {\n const origin = req.headers.origin;\n if (origin === undefined) return true; // non-browser client; token still required\n if (allowedOrigins.has(origin)) return true;\n try {\n return LOOPBACK_HOSTS.has(new URL(origin).hostname);\n } catch {\n return false; // malformed Origin → reject\n }\n}\n\n/**\n * Constant-time token comparison. Returns false on any length mismatch (never throws), so an\n * absent/short/long presented token is a plain reject, not an error.\n */\nexport function tokenMatches(expected: string, presented: string | null | undefined): boolean {\n if (!presented) return false;\n const a = Buffer.from(expected);\n const b = Buffer.from(presented);\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n\n/** Read the presented token from the upgrade request: `?token=` query param, else the WS subprotocol. */\nexport function presentedToken(req: IncomingMessage): string | null {\n try {\n const url = new URL(req.url ?? '', 'ws://127.0.0.1');\n const q = url.searchParams.get('token');\n if (q) return q;\n } catch {\n // malformed URL → fall through to the subprotocol header\n }\n const proto = req.headers['sec-websocket-protocol'];\n return typeof proto === 'string' ? proto.split(',')[0]?.trim() || null : null;\n}\n\n/**\n * This transport's admission decision, asked of the shared seam.\n *\n * Lives here rather than in the transport file because this module already owns the admission\n * policy — token comparison and the Host/Origin allow-lists — and the transport file carries\n * lifecycle and frame routing. The split is also what keeps that file inside its size ratchet.\n */\nexport function resolveWsAdmission(config: {\n token?: string;\n open?: boolean;\n openReason?: string;\n}): ITransportAdmission {\n // No fabricated reason. The first version filled one in for any caller that omitted it, which made\n // WS the one transport where `{ open: true }` alone was accepted — HTTP and WebRTC both refuse it.\n // Review found that: a reason invented on the caller's behalf reads, to the next person, as a\n // decision somebody made. The whole point of requiring it is that nobody can produce one by\n // accident, so the seam is asked the question exactly as it was given.\n return resolveAdmission({\n ...(config.token !== undefined ? { token: config.token } : {}),\n ...(config.open === true ? { open: true } : {}),\n ...(config.openReason !== undefined ? { openReason: config.openReason } : {}),\n });\n}\n","import type { RawData } from 'ws';\n\n/** Normalize the `ws` inbound payload variants to one binary view. */\nexport function toBytes(data: RawData): Uint8Array {\n if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data));\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n}\n","import {\n createOutboundDelivery,\n createPendingStallClock,\n DEFAULT_MAX_PENDING_BYTES,\n isOverPendingBudget,\n} from '@robota-sdk/agent-transport';\nimport { WebSocket } from 'ws';\n\nimport type {\n IPendingStallClock,\n TOutboundDeliver,\n TServerMessage,\n} from '@robota-sdk/agent-transport';\n\n/**\n * Connection-scoped session delivery lifecycle shared by sync and async WebSocket failures.\n *\n * ARCH-030: {@link deliver} is the ONLY way out of this class. The raw sink — the `readyState` check\n * plus `socket.send` — is private, so no caller can put a frame on this socket outside the connection's\n * one outbound boundary. That is not stylistic: the previous shape exposed a public `send` that threw\n * on a closed socket, and every reply the protocol handler produced went through it unguarded.\n */\nexport class WsSessionDelivery {\n private cleanupProtocol = (): void => undefined;\n private detachSink = (): void => undefined;\n private closed = false;\n /**\n * Issue #2306: ONE drain clock for the socket. `bufferedAmount` does not distinguish text from\n * binary, so both halves observe the same clock — a slow reader of payload frames is caught when a\n * JSON reply is attempted, and the reverse.\n */\n private readonly stallClock: IPendingStallClock = createPendingStallClock();\n\n /**\n * The connection's outbound boundary. Built here, from this class's own sink and its own `close`\n * policy, and passed DOWN into `createSessionMessageHandler` — the carrier owns both halves, so it builds the\n * boundary rather than handing the protocol layer a raw sink to wrap.\n */\n readonly deliver: TOutboundDeliver;\n\n constructor(private readonly socket: WebSocket) {\n this.deliver = createOutboundDelivery(\n (message) => this.rawSend(message),\n () => this.close(),\n // ARCH-030 / issue #1734: the socket's own count of what it has accepted and not yet written.\n // Read at call time — it changes underneath.\n () => this.socket.bufferedAmount,\n DEFAULT_MAX_PENDING_BYTES,\n this.stallClock,\n );\n }\n\n /**\n * Put a TRANS-001 payload frame on this socket, under the SAME budget and the same close policy as\n * the text protocol (ARCH-030 / issue #1734).\n *\n * A WebSocket carries two kinds of outbound frame over one socket, and until this existed the\n * binary half went straight to `socket.send` — outside the boundary, with no budget, and with a\n * failure that could only surface as a throw inside a listener. `bufferedAmount` does not\n * distinguish the two, so a non-reading peer accumulating payload frames was invisible to a budget\n * that only guarded the other half.\n *\n * It is not `deliver`: that boundary is typed for `TServerMessage` and its brand is what makes a\n * raw send unusable where a protocol frame is required. Widening it to accept bytes would remove\n * the property the brand exists for.\n */\n readonly deliverBinary = (frame: Uint8Array): void => {\n if (this.closed) return;\n if (this.socket.readyState !== WebSocket.OPEN) return;\n if (\n isOverPendingBudget(this.socket.bufferedAmount) ||\n this.stallClock.observe(this.socket.bufferedAmount) !== undefined\n ) {\n this.close();\n return;\n }\n this.socket.send(frame, { binary: true }, (error) => {\n if (error) this.close();\n });\n };\n\n private rawSend(message: TServerMessage): void {\n if (this.socket.readyState !== WebSocket.OPEN) throw new Error('WebSocket is not open');\n this.socket.send(JSON.stringify(message), (error) => {\n if (error) this.close();\n });\n }\n\n bindProtocolCleanup(cleanup: () => void): void {\n this.cleanupProtocol = cleanup;\n }\n\n bindSinkDetach(detach: () => void): void {\n this.detachSink = detach;\n }\n\n readonly close = (): void => {\n if (this.closed) return;\n this.closed = true;\n this.detachSink();\n this.cleanupProtocol();\n if (\n this.socket.readyState === WebSocket.OPEN ||\n this.socket.readyState === WebSocket.CONNECTING\n ) {\n this.socket.close(1011, 'session event delivery failed');\n }\n };\n}\n","/**\n * The construction contract for `WsTransport` — what a caller decides before the server exists.\n *\n * Split from `ws-transport-configurable.ts` under the file-size ceiling, and the seam is the\n * honest one: everything here is a decision the CALLER makes (port, retries, admission — SEC-008's\n * `token`/`open`/`openReason` contract lives in these doc comments), while the class next door is\n * what the transport DOES with those decisions.\n */\n\nimport type { TUsageSurface } from '@robota-sdk/agent-interface-analytics';\nimport type { ISessionBinder, TDriverId } from '@robota-sdk/agent-interface-session';\nimport type { ITransportLifecycleError } from '@robota-sdk/agent-interface-transport';\nimport type { IProtocolSession, ISessionMessageHandlerOptions } from '@robota-sdk/agent-transport';\n\nexport const DEFAULT_PORT = 7070;\nexport const DEFAULT_MAX_RETRIES = 20;\n\nexport interface IWsTransportConfig {\n /** Trusted server-assigned identity for turns submitted over this product surface. */\n driverId?: TDriverId;\n /** Trusted product surface, independent from the connection's driver identity. */\n surface?: TUsageSurface;\n /** Host-owned cross-session usage read model, forwarded unchanged to the protocol handler. */\n personalUsageReporter?: ISessionMessageHandlerOptions['personalUsageReporter'];\n /** Host-owned current-session trace/cost producer, forwarded unchanged to the protocol handler. */\n usageReporter?: ISessionMessageHandlerOptions['usageReporter'];\n /** Host-owned stored-session trace/cost producer for personal-usage drill-down. */\n storedSessionUsageReporter?: ISessionMessageHandlerOptions['storedSessionUsageReporter'];\n /** Host-owned session directory (#3189): lets every connection list, start and switch sessions. */\n sessionDirectory?: ISessionMessageHandlerOptions['sessionDirectory'];\n /**\n * #3189: gives each connection a binding of its own — its own session and its own directory view —\n * so one connection's switch moves only that connection. Released when the connection closes. When\n * set, a connection uses its binding's session and directory instead of the attached session and\n * `sessionDirectory`; without it every connection shares the attached session.\n */\n sessionBinder?: ISessionBinder<IProtocolSession>;\n port?: number;\n maxRetries?: number;\n /**\n * OPTIONAL explicit loopback auth token. When set, every connection MUST present a matching token\n * (query param `?token=` or the `Sec-WebSocket-Protocol` subprotocol) or the socket is closed BEFORE any\n * session data is emitted (GUI-002; the GUI sidecar sets `ROBOTA_WS_TOKEN`). SEC-001: when this is unset\n * AND `open` is not `true`, the transport AUTO-MINTS a random per-launch token (secure by default) —\n * `resolvedToken` exposes it so the surface can deliver it to the co-located client (a `0600` connection\n * file / the served monitor's injected `ws-url`). An explicit token here wins over the auto-mint — but NOT\n * over `open`: SEC-008 makes a token together with `open: true` a contradiction that throws, rather\n * than a precedence one side quietly wins.\n */\n token?: string;\n /**\n * SEC-001 discouraged opt-out: when `true`, run WITHOUT auth (no token, no auto-mint) — the pre-SEC-001\n * open loopback behavior. NOT RECOMMENDED (any local process or browser page can then drive+authorize the\n * session); mirrors Jupyter's `c.ServerApp.token = ''`.\n *\n * SEC-008: `open: true` together with a non-empty `token` is REJECTED, not resolved by precedence. The\n * two ask for opposite things, and picking a winner silently is how a caller ends up with the admission\n * it did not choose. `resolveAdmission` decides that for every transport, so they cannot differ.\n */\n open?: boolean;\n /** SEC-008: why running with no credential is correct here. Required when `open` is true. */\n openReason?: string;\n /**\n * SEC-001 defense-in-depth: extra host names (beyond `localhost`/`127.0.0.1`/`::1`) accepted in the\n * upgrade `Host` header. The `Host` allow-list closes DNS-rebinding independently of the token.\n */\n allowedHosts?: readonly string[];\n /**\n * SEC-001 defense-in-depth: extra browser `Origin`s (beyond loopback) accepted on the upgrade — e.g. the\n * `apps/agent-web` app origin. A browser sends an unforgeable `Origin`; a non-browser client omits it (and\n * is gated by the token instead). Closes the \"any web page in any browser\" hole before history is emitted.\n */\n allowedOrigins?: readonly string[];\n}\n\ntype TUsageReporters = Pick<\n ISessionMessageHandlerOptions,\n 'personalUsageReporter' | 'usageReporter' | 'storedSessionUsageReporter'\n>;\n\n/** Remove absent reporters so exact-optional handler options remain truthful. */\nfunction configuredUsageReporters(config: IWsTransportConfig): TUsageReporters {\n return {\n ...(config.personalUsageReporter\n ? { personalUsageReporter: config.personalUsageReporter }\n : {}),\n ...(config.usageReporter ? { usageReporter: config.usageReporter } : {}),\n ...(config.storedSessionUsageReporter\n ? { storedSessionUsageReporter: config.storedSessionUsageReporter }\n : {}),\n };\n}\n\ntype TConfiguredHandlerOptions = Pick<\n ISessionMessageHandlerOptions,\n | 'driverId'\n | 'surface'\n | 'personalUsageReporter'\n | 'usageReporter'\n | 'storedSessionUsageReporter'\n | 'sessionDirectory'\n>;\n\n/** Project immutable transport attribution/reporters into each protocol handler. */\nexport function configuredWsHandlerOptions(config: IWsTransportConfig): TConfiguredHandlerOptions {\n return {\n ...(config.driverId ? { driverId: config.driverId } : {}),\n ...(config.surface ? { surface: config.surface } : {}),\n ...configuredUsageReporters(config),\n ...(config.sessionDirectory ? { sessionDirectory: config.sessionDirectory } : {}),\n };\n}\n\nexport function validTransportOptions(options: Readonly<Record<string, unknown>>): boolean {\n const { port, maxRetries } = options;\n if (port !== undefined && (typeof port !== 'number' || port < 1 || port > 65535)) return false;\n return maxRetries === undefined || (typeof maxRetries === 'number' && maxRetries >= 0);\n}\n\nexport function transportLifecycleError(\n transportName: string,\n code: ITransportLifecycleError['code'],\n): ITransportLifecycleError {\n return Object.assign(new Error(`${transportName} ${code}.`), {\n name: 'TransportLifecycleError' as const,\n code,\n transportName,\n });\n}\n","/**\n * Self-contained WS transport implementing IConfigurableTransport.\n * Owns the WebSocket server lifecycle (ws package), started/stopped via the transport registry.\n */\n\nimport { createServer, type IncomingMessage, type Server } from 'node:http';\n\nimport { createSessionMessageHandler } from '@robota-sdk/agent-transport';\nimport { WebSocketServer } from 'ws';\n\nimport { PayloadChannelRegistry } from './payload-channels.js';\nimport {\n hostAllowed,\n originAllowed,\n presentedToken,\n resolveWsAdmission,\n tokenMatches,\n} from './ws-connection-guards.js';\nimport { toBytes } from './ws-message-data.js';\nimport { WsSessionDelivery } from './ws-session-delivery.js';\nimport {\n DEFAULT_MAX_RETRIES,\n DEFAULT_PORT,\n configuredWsHandlerOptions,\n transportLifecycleError,\n validTransportOptions,\n} from './ws-transport-config.js';\n\nimport type { IWsTransportConfig } from './ws-transport-config.js';\nimport type { TUniversalValue } from '@robota-sdk/agent-core';\nimport type { ISessionBinder, ISessionBinding } from '@robota-sdk/agent-interface-session';\nimport type {\n IChannelDescriptor,\n IConfigurableTransport,\n IPayloadChannel,\n IPayloadChannelHost,\n TChannelEventMap,\n} from '@robota-sdk/agent-interface-transport';\nimport type { IProtocolSession } from '@robota-sdk/agent-transport';\nimport type { RawData, WebSocket } from 'ws';\n\n/**\n * RUNTIME-13: forced-terminate deadline for `stop()`. `WebSocketServer.close()` fires its callback only after\n * every client socket is gone, so a still-connected client would hang `stop()` forever. We send a close frame\n * (1001 \"going away\") to each client, then `terminate()` any socket still open at this deadline — the RFC 6455\n * + `ws` + drain-then-force convention (a WS close handshake completes in well under a second; 5s is generous).\n */\nconst WS_STOP_TERMINATE_DEADLINE_MS = 5000;\n\n/**\n * TRANS-001: the WS transport is a payload-agnostic CARRIER that routes by WebSocket frame opcode —\n * TEXT frames go to the text-agent protocol profile (`createSessionMessageHandler`), BINARY frames go to the\n * consumer-declared channels. The two profiles share one connection and never constrain each other.\n */\nexport class WsTransport implements IConfigurableTransport<IProtocolSession>, IPayloadChannelHost {\n readonly name = 'ws';\n readonly lifecycle = Object.freeze({ kind: 'service' as const });\n readonly defaultEnabled = true;\n readonly optionsSchema = {\n port: { type: 'number', description: 'WebSocket server port', default: DEFAULT_PORT },\n maxRetries: {\n type: 'number',\n description: 'Port retry attempts when port is occupied',\n default: DEFAULT_MAX_RETRIES,\n },\n };\n\n private session: IProtocolSession | null = null;\n private stopFn: (() => Promise<void>) | null = null;\n private state: 'detached' | 'attached' | 'starting' | 'ready' | 'stopping' = 'detached';\n private startOperation: Promise<{ stop: () => Promise<void>; port: number }> | undefined;\n private startCancelled = false;\n private port: number;\n private maxRetries: number;\n private readonly token?: string;\n private readonly allowedHosts: ReadonlySet<string>;\n private readonly allowedOrigins: ReadonlySet<string>;\n private readonly handlerOptions: ReturnType<typeof configuredWsHandlerOptions>;\n private readonly sessionBinder: ISessionBinder<IProtocolSession> | undefined;\n private readonly channels = new PayloadChannelRegistry();\n private resolvedPort?: number;\n\n constructor(config: IWsTransportConfig = {}) {\n this.port = config.port ?? DEFAULT_PORT;\n this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;\n // SEC-001/SEC-008: secure by default, decided by the shared seam rather than a copy here — see\n // SPEC § Transport Admission. A failed mint throws out of the constructor (fail-closed).\n const admission = resolveWsAdmission(config);\n if (admission.token !== null) this.token = admission.token;\n this.allowedHosts = new Set(config.allowedHosts ?? []);\n this.allowedOrigins = new Set(config.allowedOrigins ?? []);\n this.handlerOptions = configuredWsHandlerOptions(config);\n this.sessionBinder = config.sessionBinder;\n }\n\n attach(session: IProtocolSession): void {\n this.session = session;\n this.state = 'attached';\n }\n\n /**\n * TRANS-001: declare an app-level channel carried on this transport's connections. The channel's\n * events and opaque binary frames ride alongside the text-agent protocol on the SAME socket — the\n * transport never inspects the payloads. Register before or after `start()`; a channel opened\n * later is served by every already-connected client.\n */\n registerChannel<TEvents extends TChannelEventMap>(\n descriptor: IChannelDescriptor<TEvents>,\n ): IPayloadChannel<TEvents> {\n return this.channels.registerChannel(descriptor);\n }\n\n /** Actually-bound port after start; undefined before start. */\n get boundPort(): number | undefined {\n return this.resolvedPort;\n }\n\n /**\n * SEC-001: the resolved auth token (explicit or auto-minted), or `undefined` in the discouraged `open`\n * mode. The surface reads this to deliver the token to the co-located client (a `0600` connection file /\n * the served monitor's injected `ws-url`). Never logged by the transport itself.\n */\n get resolvedToken(): string | undefined {\n return this.token;\n }\n\n async start(): Promise<void> {\n if (!this.session) throw transportLifecycleError(this.name, 'not-attached');\n if (this.state === 'starting' || this.state === 'ready' || this.state === 'stopping') {\n throw transportLifecycleError(this.name, 'already-started');\n }\n this.state = 'starting';\n this.startCancelled = false;\n const operation = this.bindWithRetry(this.session, this.port, this.maxRetries);\n this.startOperation = operation;\n let handle: Awaited<typeof operation>;\n try {\n handle = await operation;\n } catch (error) {\n if (this.state === 'starting' && this.startOperation === operation) {\n this.startOperation = undefined;\n this.state = this.session ? 'attached' : 'detached';\n }\n throw error;\n }\n if (this.startCancelled || this.startOperation !== operation) {\n await handle.stop();\n this.state = this.session ? 'attached' : 'detached';\n throw new Error('WsTransport startup was stopped.');\n }\n this.stopFn = handle.stop;\n this.resolvedPort = handle.port;\n this.startOperation = undefined;\n this.state = 'ready';\n }\n\n async stop(): Promise<void> {\n if (this.state === 'starting') {\n this.state = 'stopping';\n this.startCancelled = true;\n try {\n await this.startOperation;\n } catch {\n // The start caller owns bind failure; stop still clears lifecycle state.\n }\n }\n await this.stopFn?.();\n this.stopFn = null;\n this.startOperation = undefined;\n this.resolvedPort = undefined;\n this.session = null;\n this.state = 'detached';\n }\n\n /** TRANS-002 (issue #2480): persisted `port`/`maxRetries` reach the server through here, before start. */\n configure(options: Record<string, TUniversalValue>): void {\n if (this.state !== 'detached' && this.state !== 'attached') {\n throw transportLifecycleError(this.name, 'already-started');\n }\n if (!this.validateOptions(options)) {\n throw new TypeError('WsTransport options are invalid (port 1-65535, maxRetries >= 0).');\n }\n if (typeof options['port'] === 'number') this.port = options['port'];\n if (typeof options['maxRetries'] === 'number') this.maxRetries = options['maxRetries'];\n }\n\n validateOptions(options: Record<string, TUniversalValue>): boolean {\n return validTransportOptions(options);\n }\n\n /**\n * The connection's binding, `{ binding: undefined }` without a binder, or `null` when the host\n * would not bind it (shutting down, say): the socket is then closed before any session data.\n */\n private bindConnection(\n ws: WebSocket,\n ): { binding: ISessionBinding<IProtocolSession> | undefined } | null {\n if (!this.sessionBinder) return { binding: undefined };\n try {\n return { binding: this.sessionBinder.bind('drive') };\n } catch {\n ws.close(1013, 'session unavailable');\n return null;\n }\n }\n\n private bindWithRetry(\n session: IProtocolSession,\n port: number,\n retriesLeft: number,\n ): Promise<{ stop: () => Promise<void>; port: number }> {\n return this.tryBind(session, port).catch((err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE' && retriesLeft > 0)\n return this.bindWithRetry(session, port + 1, retriesLeft - 1);\n throw err;\n });\n }\n\n private tryBind(\n session: IProtocolSession,\n port: number,\n ): Promise<{ stop: () => Promise<void>; port: number }> {\n return new Promise((resolve, reject) => {\n const httpServer: Server = createServer((_, res) => {\n res.writeHead(400).end('WebSocket endpoint');\n });\n\n httpServer.on('error', (err: NodeJS.ErrnoException) => {\n httpServer.close();\n reject(err);\n });\n\n const expectedToken = this.token;\n const allowedHosts = this.allowedHosts;\n const allowedOrigins = this.allowedOrigins;\n const channels = this.channels;\n httpServer.listen(port, '127.0.0.1', () => {\n const wss = new WebSocketServer({\n server: httpServer,\n // Reject disallowed Host/Origin before the protocol upgrade or any session data.\n verifyClient: (\n info: { origin: string; secure: boolean; req: IncomingMessage },\n cb: (res: boolean, code?: number, message?: string) => void,\n ) => {\n if (!hostAllowed(info.req, allowedHosts)) {\n cb(false, 403, 'Forbidden host');\n return;\n }\n if (!originAllowed(info.req, allowedOrigins)) {\n cb(false, 403, 'Forbidden origin');\n return;\n }\n cb(true);\n },\n });\n\n wss.on('connection', (ws: WebSocket, req: IncomingMessage) => {\n // Reject unauthenticated peers before sending history or accepting prompt responses.\n if (expectedToken !== undefined && !tokenMatches(expectedToken, presentedToken(req))) {\n ws.close(1008, 'unauthorized');\n return;\n }\n\n // #3189: with a binder, this connection gets its own session and directory, so its\n // switch (and the `session_switched` that follows) stays on this connection. Every WS\n // connection drives: this carrier has no observe role.\n const bound = this.bindConnection(ws);\n if (bound === null) return;\n const { binding } = bound;\n const connectionSession = binding?.session ?? session;\n const delivery = new WsSessionDelivery(ws);\n const handler = createSessionMessageHandler({\n session: connectionSession,\n deliver: delivery.deliver,\n ...this.handlerOptions,\n ...(binding ? { sessionDirectory: binding.directory } : {}),\n });\n delivery.bindProtocolCleanup(() => {\n handler.cleanup();\n binding?.release();\n });\n\n delivery.bindSinkDetach(\n // ARCH-030: through the connection's own delivery, so payload frames share the text\n // protocol's backpressure budget and its close policy. The bare `readyState` check plus\n // `ws.send` that stood here was the last outbound path on this socket outside the\n // boundary.\n channels.addSink((frame: Uint8Array) => delivery.deliverBinary(frame)),\n );\n\n // Route by frame opcode: TEXT → the text-agent protocol profile, BINARY → the\n // payload-agnostic channels. An unroutable channel frame is answered with an explicit\n // `protocol_error` rather than silently dropped.\n ws.on('message', (data: RawData, isBinary: boolean) => {\n if (!isBinary) {\n handler.onMessage(String(data));\n return;\n }\n const result = channels.receive(toBytes(data));\n if (!result.ok) delivery.deliver({ type: 'protocol_error', message: result.error });\n });\n ws.on('close', delivery.close);\n ws.on('error', delivery.close);\n\n delivery.deliver({ type: 'messages', messages: connectionSession.getMessages() });\n delivery.deliver({\n type: 'execution_workspace_event',\n snapshot: connectionSession.getExecutionWorkspaceSnapshot(),\n });\n });\n\n resolve({\n port,\n stop: () =>\n new Promise<void>((res) => {\n // RUNTIME-13: graceful-then-forced shutdown. Send a close frame to each client so well-behaved\n // peers close cleanly; terminate any socket still open at the deadline so `wss.close()`'s\n // all-clients-gone callback can never hang. `verifyClient`/token gates are connection-time and\n // untouched here (SEC-001 preserved).\n for (const client of wss.clients) client.close(1001, 'server shutting down');\n const deadline = setTimeout(() => {\n for (const client of wss.clients) client.terminate();\n }, WS_STOP_TERMINATE_DEADLINE_MS);\n wss.close(() => {\n clearTimeout(deadline);\n httpServer.close(() => res());\n });\n }),\n });\n });\n });\n }\n}\n"],"mappings":"sdAsCA,SAAgB,EAAkB,EAA4C,CAC5E,IAAI,EAAmC,KACnC,EAA+B,KAC7B,EAAkB,GACtB,OAAO,OAAW,MAAM,uBAAuB,EAAK,EAAE,EAAG,CACvD,KAAM,0BACN,OACA,cAAe,IACjB,CAAC,EAEG,EAA0B,CAC9B,KAAM,KACN,UAAW,OAAO,OAAO,CAAE,KAAM,SAAU,CAAC,EAC5C,UAAW,KACX,OAAO,EAAqB,CAC1B,EAAU,CACZ,EACA,MAAM,OAAQ,CACZ,GAAI,CAAC,EAAS,MAAM,EAAe,cAAc,EACjD,GAAI,EAAS,MAAM,E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AY,SAAU,EAAkB,YAAY,CAAE,CAAC,EAChF,EAAS,QAAQ,CACf,KAAM,4BACN,SAAU,EAAkB,8BAA8B,CAC5D,CAAC,CACH,CAAC,EAED,EAAQ,CACN,OACA,SACE,IAAI,QAAe,GAAQ,CAKzB,IAAK,IAAM,KAAU,EAAI,QAAS,EAAO,MAAM,KAAM,sBAAsB,EAC3E,IAAM,EAAW,eAAiB,CAChC,IAAK,IAAM,KAAU,EAAI,QAAS,EAAO,UAAU,CACrD,EAAG,GAA6B,EAChC,EAAI,UAAY,CACd,aAAa,CAAQ,EACrB,EAAW,UAAY,EAAI,CAAC,CAC9B,CAAC,CACH,CAAC,CACL,CAAC,CACH,CAAC,CACH,CAAC,CACH,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robota-sdk/agent-transport-ws",
3
- "version": "3.0.0-beta.82",
3
+ "version": "3.0.0-beta.83",
4
4
  "description": "WebSocket carrier for the Robota SDK",
5
5
  "type": "module",
6
6
  "main": "dist/node/index.js",
@@ -28,7 +28,8 @@
28
28
  "default": "./dist/node/index.cjs"
29
29
  }
30
30
  }
31
- }
31
+ },
32
+ "./package.json": "./package.json"
32
33
  },
33
34
  "repository": {
34
35
  "type": "git",
@@ -39,19 +40,20 @@
39
40
  "url": "https://github.com/woojubb/robota/issues"
40
41
  },
41
42
  "engines": {
42
- "node": ">=22.0.0"
43
+ "node": ">=22.12.0"
43
44
  },
44
45
  "files": [
45
46
  "dist",
46
- "src"
47
+ "src",
48
+ "CHANGELOG.md"
47
49
  ],
48
50
  "dependencies": {
49
51
  "ws": "^8.21.1",
50
- "@robota-sdk/agent-core": "3.0.0-beta.82",
51
- "@robota-sdk/agent-interface-analytics": "3.0.0-beta.82",
52
- "@robota-sdk/agent-interface-session": "3.0.0-beta.82",
53
- "@robota-sdk/agent-interface-transport": "3.0.0-beta.82",
54
- "@robota-sdk/agent-transport": "3.0.0-beta.82"
52
+ "@robota-sdk/agent-core": "3.0.0-beta.83",
53
+ "@robota-sdk/agent-interface-analytics": "3.0.0-beta.83",
54
+ "@robota-sdk/agent-interface-session": "3.0.0-beta.83",
55
+ "@robota-sdk/agent-interface-transport": "3.0.0-beta.83",
56
+ "@robota-sdk/agent-transport": "3.0.0-beta.83"
55
57
  },
56
58
  "devDependencies": {
57
59
  "@types/ws": "^8.18.1",
@@ -0,0 +1,269 @@
1
+ /**
2
+ * #3189: with a session binder, each WebSocket connection is bound to a session of its own. One
3
+ * connection's switch — and every event after it — stays on that connection, and the binding is
4
+ * released when the connection closes. Without a binder every connection shares the attached session.
5
+ */
6
+
7
+ import { createTestInteractiveSession } from '@robota-sdk/agent-interface-session/testing';
8
+ import { WebSocket } from 'ws';
9
+ import { afterEach, describe, expect, it, vi } from 'vitest';
10
+
11
+ import { WsTransport } from '../ws-transport-configurable.js';
12
+
13
+ import type { IWsTransportConfig } from '../ws-transport-config.js';
14
+ import type {
15
+ IInteractiveSession,
16
+ ISessionBinder,
17
+ ISessionBinding,
18
+ ISessionDirectory,
19
+ TSessionBindingRole,
20
+ } from '@robota-sdk/agent-interface-session';
21
+ import type { IProtocolSession, TServerMessage } from '@robota-sdk/agent-transport';
22
+
23
+ type TListener = (...args: unknown[]) => void;
24
+
25
+ interface IEmittingSession extends IInteractiveSession {
26
+ emit(event: string, payload?: unknown): void;
27
+ listenerCount(): number;
28
+ }
29
+
30
+ function emittingSession(label: string): IEmittingSession {
31
+ const listeners = new Map<string, Set<TListener>>();
32
+ const session = createTestInteractiveSession({
33
+ getMessages: () => [{ role: 'user', content: label }] as never,
34
+ getExecutionWorkspaceSnapshot: () => ({ entries: [] }) as never,
35
+ on: ((event: string, handler: TListener) => {
36
+ if (!listeners.has(event)) listeners.set(event, new Set());
37
+ listeners.get(event)!.add(handler);
38
+ }) as IInteractiveSession['on'],
39
+ off: ((event: string, handler: TListener) => {
40
+ listeners.get(event)?.delete(handler);
41
+ }) as IInteractiveSession['off'],
42
+ });
43
+ return Object.assign(session, {
44
+ emit: (event: string, payload?: unknown) =>
45
+ listeners.get(event)?.forEach((handler) => handler(payload)),
46
+ listenerCount: () => [...listeners.values()].reduce((sum, set) => sum + set.size, 0),
47
+ });
48
+ }
49
+
50
+ interface IFakeBinding extends ISessionBinding<IProtocolSession> {
51
+ readonly session: IEmittingSession;
52
+ readonly role: TSessionBindingRole;
53
+ readonly release: ReturnType<typeof vi.fn>;
54
+ /** Listeners on the session when `release` ran: the handler must have unsubscribed first. */
55
+ listenersAtRelease?: number;
56
+ }
57
+
58
+ /** A binder like the host's: its own session per connection, and a switch that moves only that one. */
59
+ function fakeBinder(overrides: Partial<ISessionDirectory> = {}): {
60
+ binder: ISessionBinder<IProtocolSession>;
61
+ bindings: IFakeBinding[];
62
+ } {
63
+ const bindings: IFakeBinding[] = [];
64
+ const binder: ISessionBinder<IProtocolSession> = {
65
+ bind: (role) => {
66
+ const session = emittingSession(`connection-${bindings.length + 1}`);
67
+ const directory: ISessionDirectory = {
68
+ listSessions: () => ({ currentSessionId: 's', sessions: [], unreadableSessionIds: [] }),
69
+ switchSession: async (sessionId) => session.emit('session_switched', { sessionId }),
70
+ newSession: async () => session.emit('session_switched', { sessionId: 'new' }),
71
+ ...overrides,
72
+ };
73
+ const binding: IFakeBinding = {
74
+ session,
75
+ directory,
76
+ role,
77
+ release: vi.fn(() => {
78
+ binding.listenersAtRelease = session.listenerCount();
79
+ }),
80
+ };
81
+ bindings.push(binding);
82
+ return binding;
83
+ },
84
+ };
85
+ return { binder, bindings };
86
+ }
87
+
88
+ const started: WsTransport[] = [];
89
+ afterEach(async () => {
90
+ while (started.length) await started.pop()!.stop();
91
+ });
92
+
93
+ async function startTransport(
94
+ config: IWsTransportConfig,
95
+ attached: IProtocolSession = emittingSession('attached'),
96
+ ): Promise<WsTransport> {
97
+ const transport = new WsTransport({
98
+ port: 17760,
99
+ maxRetries: 30,
100
+ open: true,
101
+ openReason: 'session-binder regression test',
102
+ ...config,
103
+ });
104
+ transport.attach(attached);
105
+ await transport.start();
106
+ started.push(transport);
107
+ return transport;
108
+ }
109
+
110
+ interface IClient {
111
+ ws: WebSocket;
112
+ received: TServerMessage[];
113
+ send(message: object): void;
114
+ close(): Promise<void>;
115
+ }
116
+
117
+ async function connect(transport: WsTransport): Promise<IClient> {
118
+ const ws = new WebSocket(`ws://127.0.0.1:${transport.boundPort}`);
119
+ const received: TServerMessage[] = [];
120
+ ws.on('message', (data) => received.push(JSON.parse(String(data)) as TServerMessage));
121
+ await new Promise<void>((resolve, reject) => {
122
+ ws.on('open', resolve);
123
+ ws.on('error', reject);
124
+ });
125
+ // The connection's initial frames arrive before anything the test does.
126
+ await vi.waitFor(() => expect(received.some((m) => m.type === 'messages')).toBe(true));
127
+ return {
128
+ ws,
129
+ received,
130
+ send: (message) => ws.send(JSON.stringify(message)),
131
+ close: async () => {
132
+ const closed = new Promise<void>((resolve) => ws.once('close', () => resolve()));
133
+ ws.close();
134
+ await closed;
135
+ },
136
+ };
137
+ }
138
+
139
+ const ofType = <T extends TServerMessage['type']>(
140
+ client: IClient,
141
+ type: T,
142
+ ): Array<Extract<TServerMessage, { type: T }>> =>
143
+ client.received.filter((m): m is Extract<TServerMessage, { type: T }> => m.type === type);
144
+
145
+ /** Frames already in flight have landed: a round trip on the same socket answers after them. */
146
+ async function settle(client: IClient, requestId: string): Promise<void> {
147
+ client.send({ type: 'list-sessions', requestId });
148
+ await vi.waitFor(() =>
149
+ expect(client.received.some((m) => 'requestId' in m && m.requestId === requestId)).toBe(true),
150
+ );
151
+ }
152
+
153
+ describe('WsTransport session binder (#3189)', () => {
154
+ it('binds each connection to its own session and keeps a switch on the connection that made it', async () => {
155
+ const { binder, bindings } = fakeBinder();
156
+ const transport = await startTransport({ sessionBinder: binder });
157
+ const a = await connect(transport);
158
+ const b = await connect(transport);
159
+
160
+ expect(bindings.map((binding) => binding.role)).toEqual(['drive', 'drive']);
161
+ expect(ofType(a, 'messages')[0]?.messages).toEqual([{ role: 'user', content: 'connection-1' }]);
162
+ expect(ofType(b, 'messages')[0]?.messages).toEqual([{ role: 'user', content: 'connection-2' }]);
163
+
164
+ a.send({ type: 'switch-session', sessionId: 'session-2', requestId: 'switch-1' });
165
+ await vi.waitFor(() =>
166
+ expect(ofType(a, 'session_switched')).toEqual([
167
+ { type: 'session_switched', event: { sessionId: 'session-2' } },
168
+ ]),
169
+ );
170
+ bindings[0]!.session.emit('text_delta', 'only for a');
171
+ await vi.waitFor(() =>
172
+ expect(ofType(a, 'text_delta')).toEqual([{ type: 'text_delta', delta: 'only for a' }]),
173
+ );
174
+
175
+ await settle(b, 'b-settled');
176
+ expect(ofType(b, 'session_switched')).toEqual([]);
177
+ expect(ofType(b, 'text_delta')).toEqual([]);
178
+
179
+ await a.close();
180
+ await b.close();
181
+ });
182
+
183
+ it('releases the binding when its connection closes, after the handler unsubscribed', async () => {
184
+ const { binder, bindings } = fakeBinder();
185
+ const transport = await startTransport({ sessionBinder: binder });
186
+ const a = await connect(transport);
187
+ const b = await connect(transport);
188
+
189
+ await a.close();
190
+ await vi.waitFor(() => expect(bindings[0]!.release).toHaveBeenCalledTimes(1));
191
+ expect(bindings[0]!.listenersAtRelease).toBe(0);
192
+ expect(bindings[1]!.release).not.toHaveBeenCalled();
193
+
194
+ await b.close();
195
+ await vi.waitFor(() => expect(bindings[1]!.release).toHaveBeenCalledTimes(1));
196
+ });
197
+
198
+ it('answers a refusal from the binding directory with session_change_failed and the requestId', async () => {
199
+ const { binder } = fakeBinder({
200
+ switchSession: async () => {
201
+ throw Object.assign(new Error('Answer the pending prompt first.'), {
202
+ name: 'SessionChangeRefusal',
203
+ code: 'prompt_pending',
204
+ });
205
+ },
206
+ });
207
+ const transport = await startTransport({ sessionBinder: binder });
208
+ const a = await connect(transport);
209
+
210
+ a.send({ type: 'switch-session', sessionId: 'session-2', requestId: 'switch-1' });
211
+ await vi.waitFor(() =>
212
+ expect(ofType(a, 'session_change_failed')).toEqual([
213
+ {
214
+ type: 'session_change_failed',
215
+ code: 'prompt_pending',
216
+ message: 'Answer the pending prompt first.',
217
+ requestId: 'switch-1',
218
+ },
219
+ ]),
220
+ );
221
+ await a.close();
222
+ });
223
+
224
+ it('closes the connection before any session data when the host will not bind it', async () => {
225
+ const binder: ISessionBinder<IProtocolSession> = {
226
+ bind: () => {
227
+ throw new Error('host is stopping');
228
+ },
229
+ };
230
+ const transport = await startTransport({ sessionBinder: binder });
231
+ const ws = new WebSocket(`ws://127.0.0.1:${transport.boundPort}`);
232
+ const received: string[] = [];
233
+ ws.on('message', (data) => received.push(String(data)));
234
+ const code = await new Promise<number>((resolve) => ws.once('close', resolve));
235
+ expect(code).toBe(1013);
236
+ expect(received).toEqual([]);
237
+ });
238
+
239
+ it('without a binder, every connection shares the attached session and hears its switch', async () => {
240
+ const attached = emittingSession('attached');
241
+ const transport = await startTransport({}, attached);
242
+ const a = await connect(transport);
243
+ const b = await connect(transport);
244
+
245
+ expect(ofType(a, 'messages')[0]?.messages).toEqual([{ role: 'user', content: 'attached' }]);
246
+ attached.emit('session_switched', { sessionId: 'session-2' });
247
+ for (const client of [a, b]) {
248
+ await vi.waitFor(() =>
249
+ expect(ofType(client, 'session_switched')).toEqual([
250
+ { type: 'session_switched', event: { sessionId: 'session-2' } },
251
+ ]),
252
+ );
253
+ }
254
+ // No directory either: a switch is answered, not dropped.
255
+ a.send({ type: 'switch-session', sessionId: 'session-3', requestId: 'switch-1' });
256
+ await vi.waitFor(() =>
257
+ expect(ofType(a, 'session_change_failed')).toEqual([
258
+ {
259
+ type: 'session_change_failed',
260
+ code: 'not_available',
261
+ message: 'Sessions cannot be switched on this host.',
262
+ requestId: 'switch-1',
263
+ },
264
+ ]),
265
+ );
266
+ await a.close();
267
+ await b.close();
268
+ });
269
+ });