@robota-sdk/agent-transport-ws 3.0.0-beta.78 → 3.0.0-beta.81

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,2 +1,2 @@
1
- import{createServer as e}from"node:http";import{WebSocket as t,WebSocketServer as n}from"ws";function r(e,t,n){if(n.type===`get-background-tasks`){t({type:`background_tasks`,tasks:e.listBackgroundTasks(n.filter)});return}if(n.type===`get-background-task`){a(e,t,n);return}if(n.type===`get-background-job-groups`){t({type:`background_job_groups`,groups:e.listBackgroundJobGroups()});return}if(n.type===`get-background-job-group`){s(e,t,n);return}if(n.type===`wait-background-job-group`){c(e,t,n);return}o(e,t,n)}function i(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}if(n.type===`cancel-background-task`){u(t,`cancel`,n.taskId,e.cancelBackgroundTask(n.taskId,n.reason));return}if(n.type===`close-background-task`){u(t,`close`,n.taskId,e.closeBackgroundTask(n.taskId));return}l(e,t,n)}function a(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}t({type:`background_task`,taskId:n.taskId,task:e.getBackgroundTask(n.taskId)??null})}function o(e,t,n){if(!n.taskId){t({type:`protocol_error`,message:`taskId is required`});return}e.readBackgroundTaskLog(n.taskId,n.cursor).then(e=>t({type:`background_task_log`,taskId:n.taskId,page:e}),e=>t({type:`protocol_error`,message:e.message}))}function s(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}t({type:`background_job_group`,groupId:n.groupId,group:e.getBackgroundJobGroup(n.groupId)??null})}function c(e,t,n){if(!n.groupId){t({type:`protocol_error`,message:`groupId is required`});return}e.waitBackgroundJobGroup(n.groupId).then(e=>t({type:`background_job_group`,groupId:n.groupId,group:e}),e=>t({type:`protocol_error`,message:e.message}))}function l(e,t,n){if(!n.input){t({type:`protocol_error`,message:`input is required`});return}u(t,`send`,n.taskId,e.sendBackgroundTask(n.taskId,n.input))}function u(e,t,n,r){r.then(()=>e({type:`background_task_control_result`,action:t,taskId:n,success:!0}),r=>e({type:`background_task_control_result`,action:t,taskId:n,success:!1,message:r.message}))}function d(e){let t=f(e.session,e.send);return{onMessage:p(e.session,e.send),cleanup:t}}function f(e,t){let n=e=>t({type:`user_message`,content:e}),r=e=>t({type:`text_delta`,delta:e}),i=e=>t({type:`tool_start`,state:e}),a=e=>t({type:`tool_end`,state:e}),o=e=>t({type:`thinking`,isThinking:e}),s=e=>t({type:`complete`,result:e}),c=e=>t({type:`interrupted`,result:e}),l=e=>t({type:`error`,message:e.message}),u=e=>t({type:`background_task_event`,event:e}),d=e=>t({type:`background_job_group_event`,event:e}),f=e=>t({type:`execution_workspace_event`,snapshot:e.snapshot});return e.on(`user_message`,n),e.on(`text_delta`,r),e.on(`tool_start`,i),e.on(`tool_end`,a),e.on(`thinking`,o),e.on(`complete`,s),e.on(`interrupted`,c),e.on(`error`,l),e.on(`background_task_event`,u),e.on(`background_job_group_event`,d),e.on(`execution_workspace_event`,f),()=>{e.off(`user_message`,n),e.off(`text_delta`,r),e.off(`tool_start`,i),e.off(`tool_end`,a),e.off(`thinking`,o),e.off(`complete`,s),e.off(`interrupted`,c),e.off(`error`,l),e.off(`background_task_event`,u),e.off(`background_job_group_event`,d),e.off(`execution_workspace_event`,f)}}function p(e,t){return n=>{let r=m(n,t);r&&h(e,t,r)}}function m(e,t){try{return JSON.parse(e)}catch{return t({type:`protocol_error`,message:`Invalid JSON`}),null}}function h(e,t,n){if(_(n)){x(e,t,n);return}if(v(n)){S(e,t,n);return}if(y(n)){r(e,t,n);return}if(b(n)){i(e,t,n);return}t({type:`protocol_error`,message:`Unknown message type: ${g(n)}`})}function g(e){return e.type}function _(e){return e.type===`submit`||e.type===`command`||e.type===`abort`||e.type===`cancel-queue`}function v(e){return e.type===`get-messages`||e.type===`get-context`||e.type===`get-executing`||e.type===`get-pending`||e.type===`get-execution-workspace`}function y(e){return e.type===`get-background-tasks`||e.type===`get-background-task`||e.type===`read-background-task-log`||e.type===`get-background-job-groups`||e.type===`get-background-job-group`||e.type===`wait-background-job-group`}function b(e){return e.type===`cancel-background-task`||e.type===`close-background-task`||e.type===`send-background-task`}function x(e,t,n){if(n.type===`submit`){if(!n.prompt){t({type:`protocol_error`,message:`prompt is required`});return}e.submit(n.prompt).catch(e=>{t({type:`protocol_error`,message:e.message})})}else if(n.type===`command`){if(!n.name){t({type:`protocol_error`,message:`name is required`});return}e.executeCommand(n.name,n.args??``).then(e=>{t({type:`command_result`,name:n.name,message:e?.message??`Unknown command: ${n.name}`,success:e?.success??!1,data:e?.data})},e=>{t({type:`protocol_error`,message:e.message})})}else n.type===`abort`?e.abort():e.cancelQueue()}function S(e,t,n){n.type===`get-messages`?t({type:`messages`,messages:e.getMessages()}):n.type===`get-context`?t({type:`context`,state:e.getContextState()}):n.type===`get-executing`?t({type:`executing`,executing:e.isExecuting()}):n.type===`get-execution-workspace`?t({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()}):t({type:`pending`,pending:e.getPendingPrompt()})}function C(e){let t=null,n=null;return{name:`ws`,onMessage:null,attach(e){t=e},async start(){if(!t)throw Error(`No session attached. Call attach() first.`);let r=d({session:t,send:e.send});n=r.cleanup,this.onMessage=r.onMessage},async stop(){n?.(),n=null,this.onMessage=null}}}const w=7070;var T=class{name=`ws`;defaultEnabled=!0;optionsSchema={port:{type:`number`,description:`WebSocket server port`,default:w},maxRetries:{type:`number`,description:`Port retry attempts when port is occupied`,default:20}};session=null;stopFn=null;port;maxRetries;constructor(e={}){this.port=e.port??w,this.maxRetries=e.maxRetries??20}attach(e){this.session=e}async start(){if(!this.session)throw Error(`WsTransport: attach() must be called before start()`);let e=await this.bindWithRetry(this.session,this.port,this.maxRetries);this.stopFn=e.stop}async stop(){await this.stopFn?.(),this.stopFn=null}validateOptions(e){let{port:t,maxRetries:n}=e;return!(t!==void 0&&(typeof t!=`number`||t<1||t>65535)||n!==void 0&&(typeof n!=`number`||n<0))}bindWithRetry(e,t,n){return this.tryBind(e,t).catch(r=>{if(r.code===`EADDRINUSE`&&n>0)return this.bindWithRetry(e,t+1,n-1);throw r})}tryBind(r,i){return new Promise((a,o)=>{let s=e((e,t)=>{t.writeHead(400).end(`WebSocket endpoint`)});s.on(`error`,e=>{s.close(),o(e)}),s.listen(i,`127.0.0.1`,()=>{let e=new n({server:s});e.on(`connection`,e=>{let n=n=>{e.readyState===t.OPEN&&e.send(JSON.stringify(n))},{onMessage:i,cleanup:a}=d({session:r,send:n});e.on(`message`,e=>i(String(e))),e.on(`close`,a),e.on(`error`,a),n({type:`messages`,messages:r.getMessages()}),n({type:`execution_workspace_event`,snapshot:r.getExecutionWorkspaceSnapshot()})}),a({stop:()=>new Promise(t=>{e.close(()=>s.close(()=>t()))})})})})}};export{T as WsTransport,d as createWsHandler,C as createWsTransport};
1
+ import{DEFAULT_MAX_PENDING_BYTES as e,createOutboundDelivery as t,createPendingStallClock as n,createSessionMessageHandler as r,decodeChannelFrame as i,encodeBinaryFrame as a,encodeChannelEventFrame as o,isOverPendingBudget as s}from"@robota-sdk/agent-transport";import{createServer as c}from"node:http";import{WebSocket as l,WebSocketServer as u}from"ws";import{timingSafeEqual as d}from"node:crypto";import{resolveAdmission as f}from"@robota-sdk/agent-transport/node";function p(e){let n=null,i=null,a=e=>Object.assign(Error(`WebSocket transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`ws`}),o={name:`ws`,lifecycle:Object.freeze({kind:`service`}),onMessage:null,attach(e){n=e},async start(){if(!n)throw a(`not-attached`);if(i)throw a(`already-started`);let s=t(e.send,(t,n)=>{c.cleanup(),i=null,o.onMessage=null,e.onDeliveryError?.(t,n)}),c=r({session:n,deliver:s,...e.driverId?{driverId:e.driverId}:{},...e.surface?{surface:e.surface}:{},...e.personalUsageReporter?{personalUsageReporter:e.personalUsageReporter}:{},...e.usageReporter?{usageReporter:e.usageReporter}:{},...e.storedSessionUsageReporter?{storedSessionUsageReporter:e.storedSessionUsageReporter}:{}});i=c.cleanup,this.onMessage=c.onMessage},async stop(){i?.(),i=null,this.onMessage=null,n=null}};return o}var m=class e{channels=new Map;sinks=new Set;addSink(e){return this.sinks.add(e),()=>{this.sinks.delete(e)}}registerChannel(e){if(this.channels.has(e.name))throw Error(`Channel "${e.name}" is already registered on this transport`);let t={descriptor:e,declaredEvents:new Set(e.events),eventHandlers:new Map,binaryHandlers:new Set,seq:0,open:!0};return this.channels.set(e.name,t),this.createHandle(e,t)}receive(e){let t=i(e);if(!t.ok)return t;let{frame:n}=t,r=this.channels.get(n.channel);if(!r||!r.open)return{ok:!1,error:`No channel registered for "${n.channel}"`};if(n.kind===`binary`){if(r.descriptor.binary!==!0)return{ok:!1,error:`Channel "${n.channel}" did not declare binary payload support`};for(let e of[...r.binaryHandlers])e(n);return{ok:!0,frame:n}}if(!r.declaredEvents.has(n.event))return{ok:!1,error:`Channel "${n.channel}" did not declare event "${n.event}"`};let a=r.eventHandlers.get(n.event);if(a)for(let e of[...a])e(n.payload,n);return{ok:!0,frame:n}}broadcast(e){for(let t of[...this.sinks])t(e)}static assertOpen(e){if(!e.open)throw Error(`Channel "${e.descriptor.name}" is closed`)}createHandle(t,n){return{descriptor:t,sendEvent:(r,i)=>{if(e.assertOpen(n),!n.declaredEvents.has(r))throw Error(`Channel "${t.name}" did not declare event "${r}"`);let a=n.seq;n.seq+=1,this.broadcast(o({kind:`event`,channel:t.name,seq:a,event:r,payload:i}))},sendBinary:r=>{if(e.assertOpen(n),t.binary!==!0)throw Error(`Channel "${t.name}" did not declare binary payload support`);let i=n.seq;n.seq+=1,this.broadcast(a({kind:`binary`,channel:t.name,seq:i,payload:r}))},onEvent:(r,i)=>{if(e.assertOpen(n),!n.declaredEvents.has(r))throw Error(`Channel "${t.name}" did not declare event "${r}"`);let a=n.eventHandlers.get(r)??new Set,o=i;return a.add(o),n.eventHandlers.set(r,a),()=>{a.delete(o)}},onBinary:t=>(e.assertOpen(n),n.binaryHandlers.add(t),()=>{n.binaryHandlers.delete(t)}),close:()=>{n.open=!1,n.eventHandlers.clear(),n.binaryHandlers.clear(),this.channels.delete(t.name)}}}};const h=new Set([`localhost`,`127.0.0.1`,`::1`,`[::1]`]);function g(e){if(!e)return null;if(e.startsWith(`[`))return e.slice(0,e.indexOf(`]`)+1)||null;let t=e.lastIndexOf(`:`);return t===-1?e:e.slice(0,t)}function _(e,t){let n=g(e.headers.host);return n===null?!1:h.has(n)||t.has(n)}function v(e,t){let n=e.headers.origin;if(n===void 0||t.has(n))return!0;try{return h.has(new URL(n).hostname)}catch{return!1}}function y(e,t){if(!t)return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&d(n,r)}function b(e){try{let t=new URL(e.url??``,`ws://127.0.0.1`).searchParams.get(`token`);if(t)return t}catch{}let t=e.headers[`sec-websocket-protocol`];return typeof t==`string`&&t.split(`,`)[0]?.trim()||null}function x(e){return f({...e.token===void 0?{}:{token:e.token},...e.open===!0?{open:!0}:{},...e.openReason===void 0?{}:{openReason:e.openReason}})}function S(e){return Array.isArray(e)?new Uint8Array(Buffer.concat(e)):e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var C=class{socket;cleanupProtocol=()=>void 0;detachSink=()=>void 0;closed=!1;stallClock=n();deliver;constructor(n){this.socket=n,this.deliver=t(e=>this.rawSend(e),()=>this.close(),()=>this.socket.bufferedAmount,e,this.stallClock)}deliverBinary=e=>{if(!this.closed&&this.socket.readyState===l.OPEN){if(s(this.socket.bufferedAmount)||this.stallClock.observe(this.socket.bufferedAmount)!==void 0){this.close();return}this.socket.send(e,{binary:!0},e=>{e&&this.close()})}};rawSend(e){if(this.socket.readyState!==l.OPEN)throw Error(`WebSocket is not open`);this.socket.send(JSON.stringify(e),e=>{e&&this.close()})}bindProtocolCleanup(e){this.cleanupProtocol=e}bindSinkDetach(e){this.detachSink=e}close=()=>{this.closed||(this.closed=!0,this.detachSink(),this.cleanupProtocol(),(this.socket.readyState===l.OPEN||this.socket.readyState===l.CONNECTING)&&this.socket.close(1011,`session event delivery failed`))}};function w(e){return{...e.personalUsageReporter?{personalUsageReporter:e.personalUsageReporter}:{},...e.usageReporter?{usageReporter:e.usageReporter}:{},...e.storedSessionUsageReporter?{storedSessionUsageReporter:e.storedSessionUsageReporter}:{}}}function T(e){return{...e.driverId?{driverId:e.driverId}:{},...e.surface?{surface:e.surface}:{},...w(e)}}function E(e){let{port:t,maxRetries:n}=e;return t!==void 0&&(typeof t!=`number`||t<1||t>65535)?!1:n===void 0||typeof n==`number`&&n>=0}function D(e,t){return Object.assign(Error(`${e} ${t}.`),{name:`TransportLifecycleError`,code:t,transportName:e})}var O=class{name=`ws`;lifecycle=Object.freeze({kind:`service`});defaultEnabled=!0;optionsSchema={port:{type:`number`,description:`WebSocket server port`,default:7070},maxRetries:{type:`number`,description:`Port retry attempts when port is occupied`,default:20}};session=null;stopFn=null;state=`detached`;startOperation;startCancelled=!1;port;maxRetries;token;allowedHosts;allowedOrigins;handlerOptions;channels=new m;resolvedPort;constructor(e={}){this.port=e.port??7070,this.maxRetries=e.maxRetries??20;let t=x(e);t.token!==null&&(this.token=t.token),this.allowedHosts=new Set(e.allowedHosts??[]),this.allowedOrigins=new Set(e.allowedOrigins??[]),this.handlerOptions=T(e)}attach(e){this.session=e,this.state=`attached`}registerChannel(e){return this.channels.registerChannel(e)}get boundPort(){return this.resolvedPort}get resolvedToken(){return this.token}async start(){if(!this.session)throw D(this.name,`not-attached`);if(this.state===`starting`||this.state===`ready`||this.state===`stopping`)throw D(this.name,`already-started`);this.state=`starting`,this.startCancelled=!1;let e=this.bindWithRetry(this.session,this.port,this.maxRetries);this.startOperation=e;let t;try{t=await e}catch(t){throw this.state===`starting`&&this.startOperation===e&&(this.startOperation=void 0,this.state=this.session?`attached`:`detached`),t}if(this.startCancelled||this.startOperation!==e)throw await t.stop(),this.state=this.session?`attached`:`detached`,Error(`WsTransport startup was stopped.`);this.stopFn=t.stop,this.resolvedPort=t.port,this.startOperation=void 0,this.state=`ready`}async stop(){if(this.state===`starting`){this.state=`stopping`,this.startCancelled=!0;try{await this.startOperation}catch{}}await this.stopFn?.(),this.stopFn=null,this.startOperation=void 0,this.resolvedPort=void 0,this.session=null,this.state=`detached`}configure(e){if(this.state!==`detached`&&this.state!==`attached`)throw D(this.name,`already-started`);if(!this.validateOptions(e))throw TypeError(`WsTransport options are invalid (port 1-65535, maxRetries >= 0).`);typeof e.port==`number`&&(this.port=e.port),typeof e.maxRetries==`number`&&(this.maxRetries=e.maxRetries)}validateOptions(e){return E(e)}bindWithRetry(e,t,n){return this.tryBind(e,t).catch(r=>{if(r.code===`EADDRINUSE`&&n>0)return this.bindWithRetry(e,t+1,n-1);throw r})}tryBind(e,t){return new Promise((n,i)=>{let a=c((e,t)=>{t.writeHead(400).end(`WebSocket endpoint`)});a.on(`error`,e=>{a.close(),i(e)});let o=this.token,s=this.allowedHosts,l=this.allowedOrigins,d=this.channels;a.listen(t,`127.0.0.1`,()=>{let i=new u({server:a,verifyClient:(e,t)=>{if(!_(e.req,s)){t(!1,403,`Forbidden host`);return}if(!v(e.req,l)){t(!1,403,`Forbidden origin`);return}t(!0)}});i.on(`connection`,(t,n)=>{if(o!==void 0&&!y(o,b(n))){t.close(1008,`unauthorized`);return}let i=new C(t),a=r({session:e,deliver:i.deliver,...this.handlerOptions});i.bindProtocolCleanup(a.cleanup),i.bindSinkDetach(d.addSink(e=>i.deliverBinary(e))),t.on(`message`,(e,t)=>{if(!t){a.onMessage(String(e));return}let n=d.receive(S(e));n.ok||i.deliver({type:`protocol_error`,message:n.error})}),t.on(`close`,i.close),t.on(`error`,i.close),i.deliver({type:`messages`,messages:e.getMessages()}),i.deliver({type:`execution_workspace_event`,snapshot:e.getExecutionWorkspaceSnapshot()})}),n({port:t,stop:()=>new Promise(e=>{for(let e of i.clients)e.close(1001,`server shutting down`);let t=setTimeout(()=>{for(let e of i.clients)e.terminate()},5e3);i.close(()=>{clearTimeout(t),a.close(()=>e())})})})})})}};export{m as PayloadChannelRegistry,O as WsTransport,p as createWsTransport};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/ws-background-messages.ts","../../src/ws-handler.ts","../../src/ws-transport.ts","../../src/ws-transport-configurable.ts"],"sourcesContent":["import type { TBackgroundControlAction, TClientMessage, TServerMessage } from './ws-protocol.js';\nimport type { IInteractiveSession } from '@robota-sdk/agent-interface-transport';\n\nexport function handleBackgroundQueryMessage(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<\n TClientMessage,\n | { type: 'get-background-tasks' | 'get-background-task' | 'read-background-task-log' }\n | {\n type:\n | 'get-background-job-groups'\n | 'get-background-job-group'\n | 'wait-background-job-group';\n }\n >,\n): void {\n if (msg.type === 'get-background-tasks') {\n send({ type: 'background_tasks', tasks: session.listBackgroundTasks(msg.filter) });\n return;\n }\n if (msg.type === 'get-background-task') {\n sendBackgroundTaskSnapshot(session, send, msg);\n return;\n }\n if (msg.type === 'get-background-job-groups') {\n send({ type: 'background_job_groups', groups: session.listBackgroundJobGroups() });\n return;\n }\n if (msg.type === 'get-background-job-group') {\n sendBackgroundJobGroupSnapshot(session, send, msg);\n return;\n }\n if (msg.type === 'wait-background-job-group') {\n sendBackgroundJobGroupWaitResult(session, send, msg);\n return;\n }\n sendBackgroundTaskLogPage(session, send, msg);\n}\n\nexport function handleBackgroundControlMessage(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<\n TClientMessage,\n { type: 'cancel-background-task' | 'close-background-task' | 'send-background-task' }\n >,\n): void {\n if (!msg.taskId) {\n send({ type: 'protocol_error', message: 'taskId is required' });\n return;\n }\n if (msg.type === 'cancel-background-task') {\n sendBackgroundTaskControlResult(\n send,\n 'cancel',\n msg.taskId,\n session.cancelBackgroundTask(msg.taskId, msg.reason),\n );\n return;\n }\n if (msg.type === 'close-background-task') {\n sendBackgroundTaskControlResult(\n send,\n 'close',\n msg.taskId,\n session.closeBackgroundTask(msg.taskId),\n );\n return;\n }\n sendBackgroundTaskInput(session, send, msg);\n}\n\nfunction sendBackgroundTaskSnapshot(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<TClientMessage, { type: 'get-background-task' }>,\n): void {\n if (!msg.taskId) {\n send({ type: 'protocol_error', message: 'taskId is required' });\n return;\n }\n send({\n type: 'background_task',\n taskId: msg.taskId,\n task: session.getBackgroundTask(msg.taskId) ?? null,\n });\n}\n\nfunction sendBackgroundTaskLogPage(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<TClientMessage, { type: 'read-background-task-log' }>,\n): void {\n if (!msg.taskId) {\n send({ type: 'protocol_error', message: 'taskId is required' });\n return;\n }\n session.readBackgroundTaskLog(msg.taskId, msg.cursor).then(\n (page) => send({ type: 'background_task_log', taskId: msg.taskId, page }),\n (error: Error) => send({ type: 'protocol_error', message: error.message }),\n );\n}\n\nfunction sendBackgroundJobGroupSnapshot(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<TClientMessage, { type: 'get-background-job-group' }>,\n): void {\n if (!msg.groupId) {\n send({ type: 'protocol_error', message: 'groupId is required' });\n return;\n }\n send({\n type: 'background_job_group',\n groupId: msg.groupId,\n group: session.getBackgroundJobGroup(msg.groupId) ?? null,\n });\n}\n\nfunction sendBackgroundJobGroupWaitResult(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<TClientMessage, { type: 'wait-background-job-group' }>,\n): void {\n if (!msg.groupId) {\n send({ type: 'protocol_error', message: 'groupId is required' });\n return;\n }\n session.waitBackgroundJobGroup(msg.groupId).then(\n (group) => send({ type: 'background_job_group', groupId: msg.groupId, group }),\n (error: Error) => send({ type: 'protocol_error', message: error.message }),\n );\n}\n\nfunction sendBackgroundTaskInput(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<TClientMessage, { type: 'send-background-task' }>,\n): void {\n if (!msg.input) {\n send({ type: 'protocol_error', message: 'input is required' });\n return;\n }\n sendBackgroundTaskControlResult(\n send,\n 'send',\n msg.taskId,\n session.sendBackgroundTask(msg.taskId, msg.input),\n );\n}\n\nfunction sendBackgroundTaskControlResult(\n send: (message: TServerMessage) => void,\n action: TBackgroundControlAction,\n taskId: string,\n operation: Promise<void>,\n): void {\n operation.then(\n () => send({ type: 'background_task_control_result', action, taskId, success: true }),\n (error: Error) =>\n send({\n type: 'background_task_control_result',\n action,\n taskId,\n success: false,\n message: error.message,\n }),\n );\n}\n","/**\n * WebSocket transport adapter — exposes IInteractiveSession over WebSocket.\n *\n * Framework-agnostic: works with any WebSocket implementation via\n * send/onMessage callbacks. No dependency on ws, uWebSockets, etc.\n *\n * Protocol: JSON messages with { type, ...payload } structure.\n * Server pushes IInteractiveSession events to client in real-time.\n */\n\nimport {\n handleBackgroundControlMessage,\n handleBackgroundQueryMessage,\n} from './ws-background-messages.js';\n\nimport type { TClientMessage, TServerMessage } from './ws-protocol.js';\nimport type {\n IExecutionResult,\n IExecutionWorkspaceEvent,\n IInteractiveSession,\n IToolState,\n TBackgroundJobGroupEvent,\n} from '@robota-sdk/agent-interface-transport';\nimport type { TBackgroundTaskEvent } from '@robota-sdk/agent-interface-transport';\n\nexport interface IWsHandlerOptions {\n /** IInteractiveSession to expose. */\n session: IInteractiveSession;\n /** Send a JSON message to the client. */\n send: (message: TServerMessage) => void;\n}\n\n/**\n * Create a WebSocket message handler for an IInteractiveSession.\n *\n * Returns:\n * - `onMessage(data)`: call this when the WebSocket receives a message\n * - `cleanup()`: call this when the WebSocket disconnects\n *\n * Usage:\n * ```typescript\n * const { onMessage, cleanup } = createWsHandler({\n * session: interactiveSession,\n * send: (msg) => ws.send(JSON.stringify(msg)),\n * });\n *\n * ws.on('message', (data) => onMessage(String(data)));\n * ws.on('close', cleanup);\n * ```\n */\nexport function createWsHandler(options: IWsHandlerOptions): {\n onMessage: (data: string) => void;\n cleanup: () => void;\n} {\n const cleanup = subscribeSessionEvents(options.session, options.send);\n const onMessage = createWsMessageHandler(options.session, options.send);\n\n return { onMessage, cleanup };\n}\n\nfunction subscribeSessionEvents(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n): () => void {\n const onUserMessage = (content: string): void => send({ type: 'user_message', content });\n const onTextDelta = (delta: string): void => send({ type: 'text_delta', delta });\n const onToolStart = (state: IToolState): void => send({ type: 'tool_start', state });\n const onToolEnd = (state: IToolState): void => send({ type: 'tool_end', state });\n const onThinking = (isThinking: boolean): void => send({ type: 'thinking', isThinking });\n const onComplete = (result: IExecutionResult): void => send({ type: 'complete', result });\n const onInterrupted = (result: IExecutionResult): void => send({ type: 'interrupted', result });\n const onError = (error: Error): void => send({ type: 'error', message: error.message });\n const onBackgroundTaskEvent = (event: TBackgroundTaskEvent): void =>\n send({ type: 'background_task_event', event });\n const onBackgroundJobGroupEvent = (event: TBackgroundJobGroupEvent): void =>\n send({ type: 'background_job_group_event', event });\n const onExecutionWorkspace = (event: IExecutionWorkspaceEvent): void =>\n send({ type: 'execution_workspace_event', snapshot: event.snapshot });\n\n session.on('user_message', onUserMessage);\n session.on('text_delta', onTextDelta);\n session.on('tool_start', onToolStart);\n session.on('tool_end', onToolEnd);\n session.on('thinking', onThinking);\n session.on('complete', onComplete);\n session.on('interrupted', onInterrupted);\n session.on('error', onError);\n session.on('background_task_event', onBackgroundTaskEvent);\n session.on('background_job_group_event', onBackgroundJobGroupEvent);\n session.on('execution_workspace_event', onExecutionWorkspace);\n\n return (): void => {\n session.off('user_message', onUserMessage);\n session.off('text_delta', onTextDelta);\n session.off('tool_start', onToolStart);\n session.off('tool_end', onToolEnd);\n session.off('thinking', onThinking);\n session.off('complete', onComplete);\n session.off('interrupted', onInterrupted);\n session.off('error', onError);\n session.off('background_task_event', onBackgroundTaskEvent);\n session.off('background_job_group_event', onBackgroundJobGroupEvent);\n session.off('execution_workspace_event', onExecutionWorkspace);\n };\n}\n\nfunction createWsMessageHandler(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n): (data: string) => void {\n return (data: string): void => {\n const msg = parseClientMessage(data, send);\n if (!msg) return;\n handleClientMessage(session, send, msg);\n };\n}\n\nfunction parseClientMessage(\n data: string,\n send: (message: TServerMessage) => void,\n): TClientMessage | null {\n try {\n return JSON.parse(data) as TClientMessage;\n } catch {\n send({ type: 'protocol_error', message: 'Invalid JSON' });\n return null;\n }\n}\n\nfunction handleClientMessage(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: TClientMessage,\n): void {\n if (isSessionControlMessage(msg)) {\n handleSessionControlMessage(session, send, msg);\n return;\n }\n if (isSessionQueryMessage(msg)) {\n handleSessionQueryMessage(session, send, msg);\n return;\n }\n if (isBackgroundQueryMessage(msg)) {\n handleBackgroundQueryMessage(session, send, msg);\n return;\n }\n if (isBackgroundControlMessage(msg)) {\n handleBackgroundControlMessage(session, send, msg);\n return;\n }\n send({ type: 'protocol_error', message: `Unknown message type: ${getMessageType(msg)}` });\n}\n\nfunction getMessageType(msg: TClientMessage): string {\n return (msg as { type: string }).type;\n}\n\nfunction isSessionControlMessage(\n msg: TClientMessage,\n): msg is Extract<TClientMessage, { type: 'submit' | 'command' | 'abort' | 'cancel-queue' }> {\n return (\n msg.type === 'submit' ||\n msg.type === 'command' ||\n msg.type === 'abort' ||\n msg.type === 'cancel-queue'\n );\n}\n\nfunction isSessionQueryMessage(msg: TClientMessage): msg is Extract<\n TClientMessage,\n {\n type:\n | 'get-messages'\n | 'get-context'\n | 'get-executing'\n | 'get-pending'\n | 'get-execution-workspace';\n }\n> {\n return (\n msg.type === 'get-messages' ||\n msg.type === 'get-context' ||\n msg.type === 'get-executing' ||\n msg.type === 'get-pending' ||\n msg.type === 'get-execution-workspace'\n );\n}\n\nfunction isBackgroundQueryMessage(\n msg: TClientMessage,\n): msg is Extract<\n TClientMessage,\n | { type: 'get-background-tasks' | 'get-background-task' | 'read-background-task-log' }\n | { type: 'get-background-job-groups' | 'get-background-job-group' | 'wait-background-job-group' }\n> {\n return (\n msg.type === 'get-background-tasks' ||\n msg.type === 'get-background-task' ||\n msg.type === 'read-background-task-log' ||\n msg.type === 'get-background-job-groups' ||\n msg.type === 'get-background-job-group' ||\n msg.type === 'wait-background-job-group'\n );\n}\n\nfunction isBackgroundControlMessage(\n msg: TClientMessage,\n): msg is Extract<\n TClientMessage,\n { type: 'cancel-background-task' | 'close-background-task' | 'send-background-task' }\n> {\n return (\n msg.type === 'cancel-background-task' ||\n msg.type === 'close-background-task' ||\n msg.type === 'send-background-task'\n );\n}\n\nfunction handleSessionControlMessage(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<TClientMessage, { type: 'submit' | 'command' | 'abort' | 'cancel-queue' }>,\n): void {\n if (msg.type === 'submit') {\n if (!msg.prompt) {\n send({ type: 'protocol_error', message: 'prompt is required' });\n return;\n }\n session.submit(msg.prompt).catch((error: Error) => {\n send({ type: 'protocol_error', message: error.message });\n });\n } else if (msg.type === 'command') {\n if (!msg.name) {\n send({ type: 'protocol_error', message: 'name is required' });\n return;\n }\n session.executeCommand(msg.name, msg.args ?? '').then(\n (result) => {\n send({\n type: 'command_result',\n name: msg.name,\n message: result?.message ?? `Unknown command: ${msg.name}`,\n success: result?.success ?? false,\n data: result?.data,\n });\n },\n (error: Error) => {\n send({ type: 'protocol_error', message: error.message });\n },\n );\n } else if (msg.type === 'abort') {\n session.abort();\n } else {\n session.cancelQueue();\n }\n}\n\nfunction handleSessionQueryMessage(\n session: IInteractiveSession,\n send: (message: TServerMessage) => void,\n msg: Extract<\n TClientMessage,\n {\n type:\n | 'get-messages'\n | 'get-context'\n | 'get-executing'\n | 'get-pending'\n | 'get-execution-workspace';\n }\n >,\n): void {\n if (msg.type === 'get-messages') {\n send({ type: 'messages', messages: session.getMessages() });\n } else if (msg.type === 'get-context') {\n send({ type: 'context', state: session.getContextState() });\n } else if (msg.type === 'get-executing') {\n send({ type: 'executing', executing: session.isExecuting() });\n } else if (msg.type === 'get-execution-workspace') {\n send({\n type: 'execution_workspace_event',\n snapshot: session.getExecutionWorkspaceSnapshot(),\n });\n } else {\n send({ type: 'pending', pending: session.getPendingPrompt() });\n }\n}\n","/**\n * ITransportAdapter implementation for WebSocket transport.\n *\n * Wraps createWsHandler into the unified ITransportAdapter interface.\n * After start(), the consumer must wire onMessage to their WebSocket.\n */\n\nimport { createWsHandler } from './ws-handler.js';\n\nimport type { TServerMessage } from './ws-protocol.js';\nimport type { IInteractiveSession, ITransportAdapter } from '@robota-sdk/agent-interface-transport';\n\nexport interface IWsTransportOptions {\n /** Send a JSON message to the connected WebSocket client. */\n send: (message: TServerMessage) => void;\n}\n\nexport function createWsTransport(\n options: IWsTransportOptions,\n): ITransportAdapter<IInteractiveSession> & { onMessage: ((data: string) => void) | null } {\n let session: IInteractiveSession | null = null;\n let cleanup: (() => void) | null = null;\n\n return {\n name: 'ws',\n onMessage: null,\n attach(s: IInteractiveSession) {\n session = s;\n },\n async start() {\n if (!session) throw new Error('No session attached. Call attach() first.');\n const handler = createWsHandler({ session, send: options.send });\n cleanup = handler.cleanup;\n this.onMessage = handler.onMessage;\n },\n async stop() {\n cleanup?.();\n cleanup = null;\n this.onMessage = null;\n },\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 Server } from 'node:http';\n\nimport { WebSocketServer, WebSocket } from 'ws';\n\nimport { createWsHandler } from './ws-handler.js';\n\nimport type { TServerMessage } from './ws-protocol.js';\nimport type { TUniversalValue } from '@robota-sdk/agent-core';\nimport type {\n IConfigurableTransport,\n IInteractiveSession,\n} from '@robota-sdk/agent-interface-transport';\n\nconst DEFAULT_PORT = 7070;\nconst DEFAULT_MAX_RETRIES = 20;\n\nexport interface IWsTransportConfig {\n port?: number;\n maxRetries?: number;\n}\n\nexport class WsTransport implements IConfigurableTransport<IInteractiveSession> {\n readonly name = 'ws';\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: IInteractiveSession | null = null;\n private stopFn: (() => Promise<void>) | null = null;\n private readonly port: number;\n private readonly maxRetries: number;\n\n constructor(config: IWsTransportConfig = {}) {\n this.port = config.port ?? DEFAULT_PORT;\n this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;\n }\n\n attach(session: IInteractiveSession): void {\n this.session = session;\n }\n\n async start(): Promise<void> {\n if (!this.session) throw new Error('WsTransport: attach() must be called before start()');\n const handle = await this.bindWithRetry(this.session, this.port, this.maxRetries);\n this.stopFn = handle.stop;\n }\n\n async stop(): Promise<void> {\n await this.stopFn?.();\n this.stopFn = null;\n }\n\n validateOptions(options: Record<string, TUniversalValue>): boolean {\n const { port, maxRetries } = options;\n if (port !== undefined && (typeof port !== 'number' || port < 1 || port > 65535)) return false;\n if (maxRetries !== undefined && (typeof maxRetries !== 'number' || maxRetries < 0))\n return false;\n return true;\n }\n\n private bindWithRetry(\n session: IInteractiveSession,\n port: number,\n retriesLeft: number,\n ): Promise<{ stop: () => Promise<void> }> {\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: IInteractiveSession,\n port: number,\n ): Promise<{ stop: () => Promise<void> }> {\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 httpServer.listen(port, '127.0.0.1', () => {\n const wss = new WebSocketServer({ server: httpServer });\n\n wss.on('connection', (ws: WebSocket) => {\n const send = (message: TServerMessage): void => {\n if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));\n };\n\n const { onMessage, cleanup } = createWsHandler({ session, send });\n\n ws.on('message', (data) => onMessage(String(data)));\n ws.on('close', cleanup);\n ws.on('error', cleanup);\n\n send({ type: 'messages', messages: session.getMessages() });\n send({\n type: 'execution_workspace_event',\n snapshot: session.getExecutionWorkspaceSnapshot(),\n });\n });\n\n resolve({\n stop: () =>\n new Promise<void>((res) => {\n wss.close(() => httpServer.close(() => res()));\n }),\n });\n });\n });\n }\n}\n"],"mappings":"6FAGA,SAAgB,EACd,EACA,EACA,EAUM,CACN,GAAI,EAAI,OAAS,uBAAwB,CACvC,EAAK,CAAE,KAAM,mBAAoB,MAAO,EAAQ,oBAAoB,EAAI,MAAM,CAAE,CAAC,EACjF,MACF,CACA,GAAI,EAAI,OAAS,sBAAuB,CACtC,EAA2B,EAAS,EAAM,CAAG,EAC7C,MACF,CACA,GAAI,EAAI,OAAS,4BAA6B,CAC5C,EAAK,CAAE,KAAM,wBAAyB,OAAQ,EAAQ,wBAAwB,CAAE,CAAC,EACjF,MACF,CACA,GAAI,EAAI,OAAS,2BAA4B,CAC3C,EAA+B,EAAS,EAAM,CAAG,EACjD,MACF,CACA,GAAI,EAAI,OAAS,4BAA6B,CAC5C,EAAiC,EAAS,EAAM,CAAG,EACnD,MACF,CACA,EAA0B,EAAS,EAAM,CAAG,CAC9C,CAEA,SAAgB,EACd,EACA,EACA,EAIM,CACN,GAAI,CAAC,EAAI,OAAQ,CACf,EAAK,CAAE,KAAM,iBAAkB,QAAS,oBAAqB,CAAC,EAC9D,MACF,CACA,GAAI,EAAI,OAAS,yBAA0B,CACzC,EACE,EACA,SACA,EAAI,OACJ,EAAQ,qBAAqB,EAAI,OAAQ,EAAI,MAAM,CACrD,EACA,MACF,CACA,GAAI,EAAI,OAAS,wBAAyB,CACxC,EACE,EACA,QACA,EAAI,OACJ,EAAQ,oBAAoB,EAAI,MAAM,CACxC,EACA,MACF,CACA,EAAwB,EAAS,EAAM,CAAG,CAC5C,CAEA,SAAS,EACP,EACA,EACA,EACM,CACN,GAAI,CAA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AAO,CAAI,CAAC,CAAC,EAClD,EAAG,GAAG,QAAS,CAAO,EACtB,EAAG,GAAG,QAAS,CAAO,EAEtB,EAAK,CAAE,KAAM,WAAY,SAAU,EAAQ,YAAY,CAAE,CAAC,EAC1D,EAAK,CACH,KAAM,4BACN,SAAU,EAAQ,8BAA8B,CAClD,CAAC,CACH,CAAC,EAED,EAAQ,CACN,SACE,IAAI,QAAe,GAAQ,CACzB,EAAI,UAAY,EAAW,UAAY,EAAI,CAAC,CAAC,CAC/C,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 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_DEADLIN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ED,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,21 +1,32 @@
1
1
  {
2
2
  "name": "@robota-sdk/agent-transport-ws",
3
- "version": "3.0.0-beta.78",
4
- "description": "WebSocket transport and protocol for the Robota SDK",
3
+ "version": "3.0.0-beta.81",
4
+ "description": "WebSocket carrier for the Robota SDK",
5
5
  "type": "module",
6
6
  "main": "dist/node/index.js",
7
7
  "types": "dist/node/index.d.ts",
8
8
  "exports": {
9
9
  ".": {
10
- "types": "./dist/node/index.d.ts",
11
10
  "source": "./src/index.ts",
12
11
  "node": {
13
- "import": "./dist/node/index.js",
14
- "require": "./dist/node/index.cjs"
12
+ "import": {
13
+ "types": "./dist/node/index.d.ts",
14
+ "default": "./dist/node/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/node/index.d.cts",
18
+ "default": "./dist/node/index.cjs"
19
+ }
15
20
  },
16
21
  "default": {
17
- "import": "./dist/node/index.js",
18
- "require": "./dist/node/index.cjs"
22
+ "import": {
23
+ "types": "./dist/node/index.d.ts",
24
+ "default": "./dist/node/index.js"
25
+ },
26
+ "require": {
27
+ "types": "./dist/node/index.d.cts",
28
+ "default": "./dist/node/index.cjs"
29
+ }
19
30
  }
20
31
  }
21
32
  },
@@ -35,28 +46,36 @@
35
46
  "src"
36
47
  ],
37
48
  "dependencies": {
38
- "ws": "^8.21.0",
39
- "@robota-sdk/agent-core": "3.0.0-beta.78",
40
- "@robota-sdk/agent-interface-transport": "3.0.0-beta.78"
49
+ "ws": "^8.21.1",
50
+ "@robota-sdk/agent-core": "3.0.0-beta.81",
51
+ "@robota-sdk/agent-interface-analytics": "3.0.0-beta.81",
52
+ "@robota-sdk/agent-transport": "3.0.0-beta.81",
53
+ "@robota-sdk/agent-interface-transport": "3.0.0-beta.81",
54
+ "@robota-sdk/agent-interface-session": "3.0.0-beta.81"
41
55
  },
42
56
  "devDependencies": {
43
57
  "@types/ws": "^8.18.1",
44
58
  "rimraf": "^5.0.10",
45
- "tsdown": "^0.22.2",
46
- "typescript": "^5.9.3",
59
+ "tsdown": "^0.22.14",
60
+ "tsx": "^4.23.1",
61
+ "typescript": "^6.0.3",
47
62
  "vitest": "^3.2.6"
48
63
  },
49
64
  "license": "AGPL-3.0-only OR LicenseRef-Commercial",
50
65
  "publishConfig": {
51
66
  "access": "public"
52
67
  },
68
+ "volta": {
69
+ "extends": "../../package.json"
70
+ },
53
71
  "scripts": {
54
- "build": "tsdown",
55
- "build:js": "tsdown --no-dts",
56
- "build:types": "tsdown --dts",
57
- "typecheck": "tsc --noEmit",
72
+ "build": "rimraf dist && tsdown",
73
+ "build:js": "pnpm run build",
74
+ "build:types": "pnpm run build",
75
+ "typecheck": "tsgo --noEmit && tsgo -p tsconfig.examples.json --noEmit",
58
76
  "test": "vitest run --passWithNoTests",
59
77
  "test:coverage": "vitest run --coverage --passWithNoTests",
60
- "clean": "rimraf dist"
78
+ "clean": "rimraf dist",
79
+ "scenario:verify": "pnpm exec tsx --conditions=source examples/verify-outbound-delivery-boundary.ts"
61
80
  }
62
81
  }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * ARCH-030 at the real WS carrier: a reply that resolves after the socket closed must reach
3
+ * `WsSessionDelivery`'s cleanup instead of escaping as an unhandled rejection.
4
+ *
5
+ * The protocol suite proves the boundary; this one proves the carrier is actually WIRED to it — the
6
+ * half that was missing before, because the carrier's cleanup was written, idempotent, and never called.
7
+ */
8
+
9
+ import { createTestInteractiveSession } from '@robota-sdk/agent-interface-session/testing';
10
+ import { createSessionMessageHandler } from '@robota-sdk/agent-transport';
11
+ import { describe, expect, it, vi } from 'vitest';
12
+ import { WebSocket } from 'ws';
13
+
14
+ import { WsSessionDelivery } from '../ws-session-delivery.js';
15
+ import { DEFAULT_MAX_PENDING_BYTES, DEFAULT_MAX_PENDING_MS } from '@robota-sdk/agent-transport';
16
+
17
+ import type { IInteractiveSession } from '@robota-sdk/agent-interface-session';
18
+
19
+ /** Collect unhandled rejections while `run` executes, then drain the queue Node reports them on. */
20
+ async function withUnhandledRejectionCapture(run: () => void | Promise<void>): Promise<unknown[]> {
21
+ const captured: unknown[] = [];
22
+ const existing = process.listeners('unhandledRejection');
23
+ for (const listener of existing) process.off('unhandledRejection', listener);
24
+ const collect = (reason: unknown): void => {
25
+ captured.push(reason);
26
+ };
27
+ process.on('unhandledRejection', collect);
28
+ try {
29
+ await run();
30
+ await new Promise((resolve) => setTimeout(resolve, 20));
31
+ } finally {
32
+ process.off('unhandledRejection', collect);
33
+ for (const listener of existing)
34
+ process.on('unhandledRejection', listener as NodeJS.UnhandledRejectionListener);
35
+ }
36
+ return captured;
37
+ }
38
+
39
+ /** A socket whose `readyState` and `bufferedAmount` the test controls, so both are deterministic. */
40
+ function createControllableSocket(): {
41
+ socket: WebSocket;
42
+ close: () => void;
43
+ setBuffered: (bytes: number) => void;
44
+ } {
45
+ const state = { readyState: WebSocket.OPEN as number, bufferedAmount: 0 };
46
+ const socket = {
47
+ get readyState(): number {
48
+ return state.readyState;
49
+ },
50
+ get bufferedAmount(): number {
51
+ return state.bufferedAmount;
52
+ },
53
+ send: vi.fn(),
54
+ close: vi.fn(() => {
55
+ state.readyState = WebSocket.CLOSED;
56
+ }),
57
+ } as unknown as WebSocket;
58
+ return {
59
+ socket,
60
+ close: () => {
61
+ state.readyState = WebSocket.CLOSED;
62
+ },
63
+ setBuffered: (bytes: number) => {
64
+ state.bufferedAmount = bytes;
65
+ },
66
+ };
67
+ }
68
+
69
+ describe('WsSessionDelivery + the outbound boundary (ARCH-030)', () => {
70
+ it('a command resolving after the socket closed runs cleanup once and leaks no rejection', async () => {
71
+ const { socket, close } = createControllableSocket();
72
+ const delivery = new WsSessionDelivery(socket);
73
+ const detachSink = vi.fn();
74
+ delivery.bindSinkDetach(detachSink);
75
+
76
+ let releaseCommand: (() => void) | undefined;
77
+ const gate = new Promise<void>((resolve) => {
78
+ releaseCommand = resolve;
79
+ });
80
+ const executed: string[] = [];
81
+ const session: IInteractiveSession = createTestInteractiveSession({
82
+ executeCommand: (name: string) =>
83
+ gate.then(() => {
84
+ executed.push(name);
85
+ return { success: true, message: 'done' };
86
+ }),
87
+ } as Partial<IInteractiveSession>);
88
+
89
+ const handler = createSessionMessageHandler({ session, deliver: delivery.deliver });
90
+ delivery.bindProtocolCleanup(handler.cleanup);
91
+
92
+ const rejections = await withUnhandledRejectionCapture(async () => {
93
+ handler.onMessage(JSON.stringify({ type: 'command', name: 'status' }));
94
+ close();
95
+ releaseCommand?.();
96
+ });
97
+
98
+ expect(rejections).toEqual([]);
99
+ expect(executed).toEqual(['status']); // the command still committed
100
+ expect(detachSink).toHaveBeenCalledTimes(1); // the carrier's cleanup finally runs
101
+ // The socket was already CLOSED when the reply failed, so `close()` has nothing left to close —
102
+ // what matters is that the cleanup path ran at all, which it never did before ARCH-030.
103
+ expect(socket.close).not.toHaveBeenCalled();
104
+
105
+ // Latched: a second late frame does not run cleanup again.
106
+ delivery.deliver({ type: 'history_cleared' });
107
+ expect(detachSink).toHaveBeenCalledTimes(1);
108
+ });
109
+
110
+ // NOT a proof of the boundary latch — `WsSessionDelivery.closed` already made this cleanup idempotent
111
+ // before ARCH-030, so this case would pass either way. It pins that the boundary sitting ABOVE that
112
+ // latch did not change the carrier's observable behaviour. The latch itself is red-proved in the
113
+ // protocol suite (`outbound-delivery.test.ts` → 'latches: a connection reports at most one …').
114
+ it('runs the carrier cleanup once for a burst of outbound frames after the close', () => {
115
+ const { socket, close } = createControllableSocket();
116
+ const delivery = new WsSessionDelivery(socket);
117
+ const cleanup = vi.fn();
118
+ delivery.bindProtocolCleanup(cleanup);
119
+ close();
120
+
121
+ delivery.deliver({ type: 'history_cleared' });
122
+ delivery.deliver({ type: 'executing', executing: false });
123
+ delivery.deliver({ type: 'protocol_error', message: 'third' });
124
+
125
+ expect(cleanup).toHaveBeenCalledTimes(1);
126
+ });
127
+ });
128
+
129
+ describe('#2306: one drain clock governs both halves of the socket', () => {
130
+ it('a peer under the byte budget that never drains is closed, from either half', () => {
131
+ vi.useFakeTimers();
132
+ try {
133
+ const { socket, setBuffered } = createControllableSocket();
134
+ const delivery = new WsSessionDelivery(socket);
135
+
136
+ setBuffered(1_048_576); // 1 MiB: far under 8 MiB, and it never reaches zero
137
+ delivery.deliverBinary(new Uint8Array([1])); // the clock starts on the binary half
138
+ expect(socket.send).toHaveBeenCalledTimes(1);
139
+
140
+ vi.advanceTimersByTime(DEFAULT_MAX_PENDING_MS + 1);
141
+ setBuffered(1_048_000);
142
+ delivery.deliver({ type: 'protocol_error', message: 'judged on the text half' });
143
+
144
+ expect(socket.send).toHaveBeenCalledTimes(1); // not sent
145
+ expect(socket.close).toHaveBeenCalledTimes(1);
146
+ } finally {
147
+ vi.useRealTimers();
148
+ }
149
+ });
150
+ });
151
+
152
+ describe("ARCH-030: payload frames share the text protocol's budget", () => {
153
+ it('refuses a binary frame when the socket is over budget, and closes once', () => {
154
+ // Until this path existed, TRANS-001 payload frames went straight to `socket.send` — outside the
155
+ // boundary, with no budget. `bufferedAmount` does not distinguish text from binary, so a peer
156
+ // that stopped reading accumulated payload frames invisibly to a budget guarding only the JSON
157
+ // half of the same socket.
158
+ const { socket, setBuffered } = createControllableSocket();
159
+ const delivery = new WsSessionDelivery(socket);
160
+
161
+ delivery.deliverBinary(new Uint8Array([1, 2, 3]));
162
+ expect(socket.send).toHaveBeenCalledTimes(1);
163
+
164
+ setBuffered(DEFAULT_MAX_PENDING_BYTES + 1);
165
+ delivery.deliverBinary(new Uint8Array([4, 5, 6]));
166
+
167
+ expect(socket.send).toHaveBeenCalledTimes(1); // not sent
168
+ expect(socket.close).toHaveBeenCalledTimes(1);
169
+ });
170
+
171
+ it('the SAME budget governs both halves of one socket', () => {
172
+ // The property that makes this shared rather than duplicated: bytes pending because of binary
173
+ // frames close the connection when a JSON reply is attempted, and the reverse. One socket, one
174
+ // reading, one limit.
175
+ const { socket, setBuffered } = createControllableSocket();
176
+ const delivery = new WsSessionDelivery(socket);
177
+
178
+ setBuffered(DEFAULT_MAX_PENDING_BYTES + 1);
179
+ delivery.deliver({ type: 'protocol_error', message: 'over budget from binary backlog' });
180
+
181
+ expect(socket.send).not.toHaveBeenCalled();
182
+ expect(socket.close).toHaveBeenCalledTimes(1);
183
+ });
184
+
185
+ it('does not send on a socket that is not open, and does not close it a second time', () => {
186
+ const { socket, close } = createControllableSocket();
187
+ const delivery = new WsSessionDelivery(socket);
188
+ close();
189
+
190
+ delivery.deliverBinary(new Uint8Array([1]));
191
+
192
+ expect(socket.send).not.toHaveBeenCalled();
193
+ expect(socket.close).not.toHaveBeenCalled();
194
+ });
195
+ });