Skip to content

Add WebSocket support: Responses API, Realtime API, and Gemini Live - #20

Merged
jpr5 merged 11 commits into
mainfrom
feat/websocket-responses-api
Mar 11, 2026
Merged

jpr5 merged 11 commits into
mainfrom
feat/websocket-responses-api

Conversation

@jpr5

@jpr5 jpr5 commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

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

  • pnpm test — 436 tests pass (396 existing + 40 new across 3 WS test files + framing tests)
  • pnpm build — TypeScript compiles clean
  • pnpm run lint — eslint clean
  • pnpm run format:check — prettier clean
  • Code reviewed with 2 parallel review agents, all findings addressed

🤖 Generated with Claude Code

@pkg-pr-new

pkg-pr-new Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/CopilotKit/llmock/@copilotkit/llmock@20

commit: c41d0a3

jpr5 added 8 commits March 11, 2026 11:03
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
jpr5 force-pushed the feat/websocket-responses-api branch from dc578b9 to 31e0b59 Compare March 11, 2026 18:03
Comment thread src/ws-framing.ts Resolved
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).
jpr5 added 3 commits March 11, 2026 11:13
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 jpr5 changed the title Add WebSocket support for OpenAI Responses API Add WebSocket support: Responses API, Realtime API, and Gemini Live Mar 11, 2026
@jpr5
jpr5 merged commit e214995 into main Mar 11, 2026
8 checks passed
@jpr5
jpr5 deleted the feat/websocket-responses-api branch March 11, 2026 18:23
@jpr5 jpr5 mentioned this pull request Mar 11, 2026
2 tasks done
jpr5 added a commit that referenced this pull request Mar 11, 2026
## Summary
- Bumps package version from 1.1.1 to 1.2.0 to reflect the WebSocket API
support added in PR #20 and #21

## Test plan
- [x] All 436 tests pass
- [x] Lint and prettier clean
@jpr5 jpr5 mentioned this pull request Mar 19, 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
## Summary
- Bumps package version from 1.1.1 to 1.2.0 to reflect the WebSocket API
support added in PR #20 and #21

## Test plan
- [x] All 436 tests pass
- [x] Lint and prettier clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant