Repository navigation
Add WebSocket support: Responses API, Realtime API, and Gemini Live - #20
Merged
Merged
Conversation
commit: |
Minimal WebSocket server implementation using only Node.js builtins (node:crypto, node:events). Supports text frames, ping/pong, close handshake, client frame unmasking, and partial frame buffering. Designed to be reusable across future WebSocket API phases.
Export buildTextStreamEvents, buildToolCallStreamEvents, and ResponsesSSEEvent from responses.ts for reuse. Add ws-responses.ts which accepts response.create messages over WebSocket and streams back the same Responses API events as the HTTP handler, serializing per-connection to prevent event interleaving.
Add server.on('upgrade') routing /v1/responses to the WebSocket
handler. Track active connections for cleanup on server.close().
Register error listeners to prevent uncaught exceptions. Export
WebSocket types and functions from the public API.
14 unit tests for ws-framing (handshake, frame parsing, ping/pong, close, server send, lifecycle) and 9 integration tests for ws-responses (text/tool/error fixtures over WS, malformed JSON, wrong message type, journal with method WS, multi-request on same connection, path rejection).
Implement /v1/realtime WebSocket endpoint supporting: - session.created/updated lifecycle events - conversation.item.create with item buffering - response.create with text streaming (response.text.delta) and tool calls (response.function_call_arguments.delta) - Conversation state accumulation across response cycles - Promise chain serialization to prevent event interleaving
Implement WebSocket endpoint for Gemini Live streaming protocol: - setup/setupComplete handshake - clientContent with text turns → serverContent streaming - toolCall responses for function call fixtures - toolResponse handling for multi-turn conversations - Setup enforcement (rejects pre-setup messages) - Conversation history rollback on fixture match failure
- Add /v1/realtime upgrade route (model from query string) - Add Gemini BidiGenerateContent upgrade route - Refactor upgrade handler to share connection tracking logic - Add socket.destroy() in upgrade error catch for safety - Extract shared WS test client to ws-test-client.ts - Export new handlers from index.ts
Document what's not implemented and areas for improvement: WebSocket audio/binary/compression gaps, streaming interruption, fixture limitations, testing gaps, and CLI enhancements.
jpr5
force-pushed
the
feat/websocket-responses-api
branch
from
March 11, 2026 18:03
dc578b9 to
31e0b59
Compare
4 tasks done
jpr5
added a commit
that referenced
this pull request
Mar 11, 2026
Three issues in WebSocketConnection per PR #20 review: 1. Server-initiated close() now emits the close event after socket.destroy(), so listeners (activeConnections.delete) always fire instead of being skipped by the closed guard. 2. Move emit("close") inside the if(!this.closed) guard for client-initiated OP_CLOSE, preventing double emission on duplicate close frames. 3. Stop parseFrames loop when closed, preventing processing of buffered frames after OP_CLOSE (per RFC 6455 §5.5.1).
Three issues in WebSocketConnection per PR #20 review: 1. Server-initiated close() now emits the close event after socket.destroy(), so listeners (activeConnections.delete) always fire instead of being skipped by the closed guard. 2. Move emit("close") inside the if(!this.closed) guard for client-initiated OP_CLOSE, preventing double emission on duplicate close frames. 3. Stop parseFrames loop when closed, preventing processing of buffered frames after OP_CLOSE (per RFC 6455 §5.5.1).
- Log console.warn for malformed JSON in fixture tool call arguments
(gemini.ts, ws-gemini-live.ts) instead of silently falling back to {}
- Log console.error before catch blocks in WS error handlers
(ws-responses.ts, ws-realtime.ts, ws-gemini-live.ts)
- Warn on missing required fields in Realtime conversation items
- Fix waitForMessages timeout/resolver leak in test client
- Log unexpected non-socket-destroyed errors in writeFrame
Improve error visibility across WebSocket handlers
jpr5
added a commit
that referenced
this pull request
Mar 11, 2026
1 of 4 tasks
jpr5
added a commit
that referenced
this pull request
Apr 3, 2026
Three issues in WebSocketConnection per PR #20 review: 1. Server-initiated close() now emits the close event after socket.destroy(), so listeners (activeConnections.delete) always fire instead of being skipped by the closed guard. 2. Move emit("close") inside the if(!this.closed) guard for client-initiated OP_CLOSE, preventing double emission on duplicate close frames. 3. Stop parseFrames loop when closed, preventing processing of buffered frames after OP_CLOSE (per RFC 6455 §5.5.1).
jpr5
added a commit
that referenced
this pull request
Apr 3, 2026
) ## Summary Adds WebSocket transport support across three OpenAI/Google APIs, all sharing the same fixture pool and matching infrastructure as the existing HTTP/SSE endpoints. ### WebSocket framing layer (`ws-framing.ts`) - Zero-dependency RFC 6455 implementation (~250 lines) using only `node:crypto` and `node:events` - Text frames, ping/pong, close handshake, client frame unmasking, partial frame buffering, continuation frames - Correct close-frame lifecycle: server-initiated close emits events, no double emission on duplicate frames, parsing stops after close ### OpenAI Responses API (`ws-responses.ts`) - WebSocket handler for `/v1/responses` — sends the same Responses API events as the HTTP handler, but as individual WS text frames instead of SSE - Reuses existing `buildTextStreamEvents` / `buildToolCallStreamEvents` / `matchFixture` pipeline ### OpenAI Realtime API (`ws-realtime.ts`) - WebSocket handler for `/v1/realtime` — text and tool call paths only (audio/multimodal out of scope) - `session.created/updated` lifecycle, `conversation.item.create` buffering, `response.create` with streaming deltas - Full event sequence: `response.created` → `output_item.added` → `text.delta`/`function_call_arguments.delta` → done events → `response.done` - Conversation state accumulates across response cycles (assistant responses fed back into context) ### Gemini Live BidiGenerateContent (`ws-gemini-live.ts`) - WebSocket handler for `/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent` - `setup`/`setupComplete` handshake, `clientContent` text streaming, `toolCall`/`toolResponse` flow - Chunked `serverContent` with `turnComplete` signaling - Setup enforcement (rejects pre-setup messages), conversation history rollback on fixture match failure ### Server integration - `server.on('upgrade')` routes for all three WebSocket paths with shared connection tracking - Active connection cleanup on `server.close()`, per-connection message serialization via promise chains - Model extracted from query string for Realtime (`?model=`), defaults for others ### Shared test client - `ws-test-client.ts` — raw `net.Socket` + manual WS framing, used by all three test suites - Zero test dependencies beyond vitest ### README - Future Direction section documenting out-of-scope items: audio/multimodal, binary frames, compression, session persistence, streaming interruption, fixture limitations, CLI enhancements ## Test plan - [x] `pnpm test` — 436 tests pass (396 existing + 40 new across 3 WS test files + framing tests) - [x] `pnpm build` — TypeScript compiles clean - [x] `pnpm run lint` — eslint clean - [x] `pnpm run format:check` — prettier clean - [x] Code reviewed with 2 parallel review agents, all findings addressed 🤖 Generated with [Claude Code](https://claude.com/claude-code)
jpr5
added a commit
that referenced
this pull request
Apr 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds WebSocket transport support across three OpenAI/Google APIs, all sharing the same fixture pool and matching infrastructure as the existing HTTP/SSE endpoints.
WebSocket framing layer (
ws-framing.ts)node:cryptoandnode:eventsOpenAI Responses API (
ws-responses.ts)/v1/responses— sends the same Responses API events as the HTTP handler, but as individual WS text frames instead of SSEbuildTextStreamEvents/buildToolCallStreamEvents/matchFixturepipelineOpenAI Realtime API (
ws-realtime.ts)/v1/realtime— text and tool call paths only (audio/multimodal out of scope)session.created/updatedlifecycle,conversation.item.createbuffering,response.createwith streaming deltasresponse.created→output_item.added→text.delta/function_call_arguments.delta→ done events →response.doneGemini Live BidiGenerateContent (
ws-gemini-live.ts)/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentsetup/setupCompletehandshake,clientContenttext streaming,toolCall/toolResponseflowserverContentwithturnCompletesignalingServer integration
server.on('upgrade')routes for all three WebSocket paths with shared connection trackingserver.close(), per-connection message serialization via promise chains?model=), defaults for othersShared test client
ws-test-client.ts— rawnet.Socket+ manual WS framing, used by all three test suitesREADME
Test plan
pnpm test— 436 tests pass (396 existing + 40 new across 3 WS test files + framing tests)pnpm build— TypeScript compiles cleanpnpm run lint— eslint cleanpnpm run format:check— prettier clean🤖 Generated with Claude Code