File size: 12,505 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | import { randomUUID } from 'crypto'
import { getOauthConfig } from '../constants/oauth.js'
import type { SDKMessage } from '../entrypoints/agentSdkTypes.js'
import type {
SDKControlCancelRequest,
SDKControlRequest,
SDKControlRequestInner,
SDKControlResponse,
} from '../entrypoints/sdk/controlTypes.js'
import { logForDebugging } from '../utils/debug.js'
import { errorMessage } from '../utils/errors.js'
import { logError } from '../utils/log.js'
import { getWebSocketTLSOptions } from '../utils/mtls.js'
import { getWebSocketProxyAgent, getWebSocketProxyUrl } from '../utils/proxy.js'
import { jsonParse, jsonStringify } from '../utils/slowOperations.js'
const RECONNECT_DELAY_MS = 2000
const MAX_RECONNECT_ATTEMPTS = 5
const PING_INTERVAL_MS = 30000
/**
* Maximum retries for 4001 (session not found). During compaction the
* server may briefly consider the session stale; a short retry window
* lets the client recover without giving up permanently.
*/
const MAX_SESSION_NOT_FOUND_RETRIES = 3
/**
* WebSocket close codes that indicate a permanent server-side rejection.
* The client stops reconnecting immediately.
* Note: 4001 (session not found) is handled separately with limited
* retries since it can be transient during compaction.
*/
const PERMANENT_CLOSE_CODES = new Set([
4003, // unauthorized
])
type WebSocketState = 'connecting' | 'connected' | 'closed'
type SessionsMessage =
| SDKMessage
| SDKControlRequest
| SDKControlResponse
| SDKControlCancelRequest
function isSessionsMessage(value: unknown): value is SessionsMessage {
if (typeof value !== 'object' || value === null || !('type' in value)) {
return false
}
// Accept any message with a string `type` field. Downstream handlers
// (sdkMessageAdapter, RemoteSessionManager) decide what to do with
// unknown types. A hardcoded allowlist here would silently drop new
// message types the backend starts sending before the client is updated.
return typeof value.type === 'string'
}
export type SessionsWebSocketCallbacks = {
onMessage: (message: SessionsMessage) => void
onClose?: () => void
onError?: (error: Error) => void
onConnected?: () => void
/** Fired when a transient close is detected and a reconnect is scheduled.
* onClose fires only for permanent close (server ended / attempts exhausted). */
onReconnecting?: () => void
}
// Common interface between globalThis.WebSocket and ws.WebSocket
type WebSocketLike = {
close(): void
send(data: string): void
ping?(): void // Bun & ws both support this
}
/**
* WebSocket client for connecting to CCR sessions via /v1/sessions/ws/{id}/subscribe
*
* Protocol:
* 1. Connect to wss://api.anthropic.com/v1/sessions/ws/{sessionId}/subscribe?organization_uuid=...
* 2. Send auth message: { type: 'auth', credential: { type: 'oauth', token: '...' } }
* 3. Receive SDKMessage stream from the session
*/
export class SessionsWebSocket {
private ws: WebSocketLike | null = null
private state: WebSocketState = 'closed'
private reconnectAttempts = 0
private sessionNotFoundRetries = 0
private pingInterval: NodeJS.Timeout | null = null
private reconnectTimer: NodeJS.Timeout | null = null
constructor(
private readonly sessionId: string,
private readonly orgUuid: string,
private readonly getAccessToken: () => string,
private readonly callbacks: SessionsWebSocketCallbacks,
) {}
/**
* Connect to the sessions WebSocket endpoint
*/
async connect(): Promise<void> {
if (this.state === 'connecting') {
logForDebugging('[SessionsWebSocket] Already connecting')
return
}
this.state = 'connecting'
const baseUrl = getOauthConfig().BASE_API_URL.replace('https://', 'wss://')
const url = `${baseUrl}/v1/sessions/ws/${this.sessionId}/subscribe?organization_uuid=${this.orgUuid}`
logForDebugging(`[SessionsWebSocket] Connecting to ${url}`)
// Get fresh token for each connection attempt
const accessToken = this.getAccessToken()
const headers = {
Authorization: `Bearer ${accessToken}`,
'anthropic-version': '2023-06-01',
}
if (typeof Bun !== 'undefined') {
// Bun's WebSocket supports headers/proxy options but the DOM typings don't
// eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
const ws = new globalThis.WebSocket(url, {
headers,
proxy: getWebSocketProxyUrl(url),
tls: getWebSocketTLSOptions() || undefined,
} as unknown as string[])
this.ws = ws
ws.addEventListener('open', () => {
logForDebugging(
'[SessionsWebSocket] Connection opened, authenticated via headers',
)
this.state = 'connected'
this.reconnectAttempts = 0
this.sessionNotFoundRetries = 0
this.startPingInterval()
this.callbacks.onConnected?.()
})
ws.addEventListener('message', (event: MessageEvent) => {
const data =
typeof event.data === 'string' ? event.data : String(event.data)
this.handleMessage(data)
})
ws.addEventListener('error', () => {
const err = new Error('[SessionsWebSocket] WebSocket error')
logError(err)
this.callbacks.onError?.(err)
})
// eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
ws.addEventListener('close', (event: CloseEvent) => {
logForDebugging(
`[SessionsWebSocket] Closed: code=${event.code} reason=${event.reason}`,
)
this.handleClose(event.code)
})
ws.addEventListener('pong', () => {
logForDebugging('[SessionsWebSocket] Pong received')
})
} else {
const { default: WS } = await import('ws')
const ws = new WS(url, {
headers,
agent: getWebSocketProxyAgent(url),
...getWebSocketTLSOptions(),
})
this.ws = ws
ws.on('open', () => {
logForDebugging(
'[SessionsWebSocket] Connection opened, authenticated via headers',
)
// Auth is handled via headers, so we're immediately connected
this.state = 'connected'
this.reconnectAttempts = 0
this.sessionNotFoundRetries = 0
this.startPingInterval()
this.callbacks.onConnected?.()
})
ws.on('message', (data: Buffer) => {
this.handleMessage(data.toString())
})
ws.on('error', (err: Error) => {
logError(new Error(`[SessionsWebSocket] Error: ${err.message}`))
this.callbacks.onError?.(err)
})
ws.on('close', (code: number, reason: Buffer) => {
logForDebugging(
`[SessionsWebSocket] Closed: code=${code} reason=${reason.toString()}`,
)
this.handleClose(code)
})
ws.on('pong', () => {
logForDebugging('[SessionsWebSocket] Pong received')
})
}
}
/**
* Handle incoming WebSocket message
*/
private handleMessage(data: string): void {
try {
const message: unknown = jsonParse(data)
// Forward SDK messages to callback
if (isSessionsMessage(message)) {
this.callbacks.onMessage(message)
} else {
logForDebugging(
`[SessionsWebSocket] Ignoring message type: ${typeof message === 'object' && message !== null && 'type' in message ? String(message.type) : 'unknown'}`,
)
}
} catch (error) {
logError(
new Error(
`[SessionsWebSocket] Failed to parse message: ${errorMessage(error)}`,
),
)
}
}
/**
* Handle WebSocket close
*/
private handleClose(closeCode: number): void {
this.stopPingInterval()
if (this.state === 'closed') {
return
}
this.ws = null
const previousState = this.state
this.state = 'closed'
// Permanent codes: stop reconnecting — server has definitively ended the session
if (PERMANENT_CLOSE_CODES.has(closeCode)) {
logForDebugging(
`[SessionsWebSocket] Permanent close code ${closeCode}, not reconnecting`,
)
this.callbacks.onClose?.()
return
}
// 4001 (session not found) can be transient during compaction: the
// server may briefly consider the session stale while the CLI worker
// is busy with the compaction API call and not emitting events.
if (closeCode === 4001) {
this.sessionNotFoundRetries++
if (this.sessionNotFoundRetries > MAX_SESSION_NOT_FOUND_RETRIES) {
logForDebugging(
`[SessionsWebSocket] 4001 retry budget exhausted (${MAX_SESSION_NOT_FOUND_RETRIES}), not reconnecting`,
)
this.callbacks.onClose?.()
return
}
this.scheduleReconnect(
RECONNECT_DELAY_MS * this.sessionNotFoundRetries,
`4001 attempt ${this.sessionNotFoundRetries}/${MAX_SESSION_NOT_FOUND_RETRIES}`,
)
return
}
// Attempt reconnection if we were connected
if (
previousState === 'connected' &&
this.reconnectAttempts < MAX_RECONNECT_ATTEMPTS
) {
this.reconnectAttempts++
this.scheduleReconnect(
RECONNECT_DELAY_MS,
`attempt ${this.reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS}`,
)
} else {
logForDebugging('[SessionsWebSocket] Not reconnecting')
this.callbacks.onClose?.()
}
}
private scheduleReconnect(delay: number, label: string): void {
this.callbacks.onReconnecting?.()
logForDebugging(
`[SessionsWebSocket] Scheduling reconnect (${label}) in ${delay}ms`,
)
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null
void this.connect()
}, delay)
}
private startPingInterval(): void {
this.stopPingInterval()
this.pingInterval = setInterval(() => {
if (this.ws && this.state === 'connected') {
try {
this.ws.ping?.()
} catch {
// Ignore ping errors, close handler will deal with connection issues
}
}
}, PING_INTERVAL_MS)
}
/**
* Stop ping interval
*/
private stopPingInterval(): void {
if (this.pingInterval) {
clearInterval(this.pingInterval)
this.pingInterval = null
}
}
/**
* Send a control response back to the session
*/
sendControlResponse(response: SDKControlResponse): void {
if (!this.ws || this.state !== 'connected') {
logError(new Error('[SessionsWebSocket] Cannot send: not connected'))
return
}
logForDebugging('[SessionsWebSocket] Sending control response')
this.ws.send(jsonStringify(response))
}
/**
* Send a control request to the session (e.g., interrupt)
*/
sendControlRequest(request: SDKControlRequestInner): void {
if (!this.ws || this.state !== 'connected') {
logError(new Error('[SessionsWebSocket] Cannot send: not connected'))
return
}
const controlRequest: SDKControlRequest = {
type: 'control_request',
request_id: randomUUID(),
request,
}
logForDebugging(
`[SessionsWebSocket] Sending control request: ${request.subtype}`,
)
this.ws.send(jsonStringify(controlRequest))
}
/**
* Check if connected
*/
isConnected(): boolean {
return this.state === 'connected'
}
/**
* Close the WebSocket connection
*/
close(): void {
logForDebugging('[SessionsWebSocket] Closing connection')
this.state = 'closed'
this.stopPingInterval()
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
}
if (this.ws) {
// Null out event handlers to prevent race conditions during reconnect.
// Under Bun (native WebSocket), onX handlers are the clean way to detach.
// Under Node (ws package), the listeners were attached with .on() in connect(),
// but since we're about to close and null out this.ws, no cleanup is needed.
this.ws.close()
this.ws = null
}
}
/**
* Force reconnect - closes existing connection and establishes a new one.
* Useful when the subscription becomes stale (e.g., after container shutdown).
*/
reconnect(): void {
logForDebugging('[SessionsWebSocket] Force reconnecting')
this.reconnectAttempts = 0
this.sessionNotFoundRetries = 0
this.close()
// Small delay before reconnecting (stored in reconnectTimer so it can be cancelled)
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null
void this.connect()
}, 500)
}
}
|