Real-time

WebSocket

Real-time bidirectional communication

WebSocket#

For real-time bidirectional communication, attach the WebSocket transport. Agents can execute commands, receive events, and manage sessions over a persistent connection.

typescript
import { createSurf } from '@surfjs/core'
import http from 'node:http'
ย 
const surf = await createSurf({
name: 'Realtime App',
commands: { /* ... */ },
events: {
'order.updated': {
description: 'Fired when an order status changes',
data: { orderId: { type: 'string' }, status: { type: 'string' } },
},
},
})
ย 
const server = http.createServer(/* express app or raw handler */)
ย 
// Attach WebSocket โ€” requires the 'ws' package
surf.wsHandler(server)
ย 
server.listen(3000)
ย 
// Emit events from anywhere in your code
surf.emit('order.updated', { orderId: 'ORD-789', status: 'shipped' })

WebSocket message protocol:

json
// Client โ†’ Server: execute a command
{ "type": "execute", "id": "req-1", "command": "search", "params": { "query": "laptop" } }
ย 
// Server โ†’ Client: command result
{ "type": "result", "id": "req-1", "ok": true, "result": { ... } }
ย 
// Client โ†’ Server: authenticate
{ "type": "auth", "token": "Bearer sk-..." }
ย 
// Client โ†’ Server: manage session
{ "type": "session", "action": "start" }
{ "type": "session", "action": "end", "sessionId": "sess_abc" }
ย 
// Server โ†’ Client: event
{ "type": "event", "event": "order.updated", "data": { ... } }

โš ๏ธ Note: WebSocket transport requires the ws package: npm install ws