File size: 9,320 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 | import type { SDKMessage } from '../entrypoints/agentSdkTypes.js'
import type {
SDKControlCancelRequest,
SDKControlPermissionRequest,
SDKControlRequest,
SDKControlResponse,
} from '../entrypoints/sdk/controlTypes.js'
import { logForDebugging } from '../utils/debug.js'
import { logError } from '../utils/log.js'
import {
type RemoteMessageContent,
sendEventToRemoteSession,
} from '../utils/teleport/api.js'
import {
SessionsWebSocket,
type SessionsWebSocketCallbacks,
} from './SessionsWebSocket.js'
/**
* Type guard to check if a message is an SDKMessage (not a control message)
*/
function isSDKMessage(
message:
| SDKMessage
| SDKControlRequest
| SDKControlResponse
| SDKControlCancelRequest,
): message is SDKMessage {
return (
message.type !== 'control_request' &&
message.type !== 'control_response' &&
message.type !== 'control_cancel_request'
)
}
/**
* Simple permission response for remote sessions.
* This is a simplified version of PermissionResult for CCR communication.
*/
export type RemotePermissionResponse =
| {
behavior: 'allow'
updatedInput: Record<string, unknown>
}
| {
behavior: 'deny'
message: string
}
export type RemoteSessionConfig = {
sessionId: string
getAccessToken: () => string
orgUuid: string
/** True if session was created with an initial prompt that's being processed */
hasInitialPrompt?: boolean
/**
* When true, this client is a pure viewer. Ctrl+C/Escape do NOT send
* interrupt to the remote agent; 60s reconnect timeout is disabled;
* session title is never updated. Used by `claude assistant`.
*/
viewerOnly?: boolean
}
export type RemoteSessionCallbacks = {
/** Called when an SDKMessage is received from the session */
onMessage: (message: SDKMessage) => void
/** Called when a permission request is received from CCR */
onPermissionRequest: (
request: SDKControlPermissionRequest,
requestId: string,
) => void
/** Called when the server cancels a pending permission request */
onPermissionCancelled?: (
requestId: string,
toolUseId: string | undefined,
) => void
/** Called when connection is established */
onConnected?: () => void
/** Called when connection is lost and cannot be restored */
onDisconnected?: () => void
/** Called on transient WS drop while reconnect backoff is in progress */
onReconnecting?: () => void
/** Called on error */
onError?: (error: Error) => void
}
/**
* Manages a remote CCR session.
*
* Coordinates:
* - WebSocket subscription for receiving messages from CCR
* - HTTP POST for sending user messages to CCR
* - Permission request/response flow
*/
export class RemoteSessionManager {
private websocket: SessionsWebSocket | null = null
private pendingPermissionRequests: Map<string, SDKControlPermissionRequest> =
new Map()
constructor(
private readonly config: RemoteSessionConfig,
private readonly callbacks: RemoteSessionCallbacks,
) {}
/**
* Connect to the remote session via WebSocket
*/
connect(): void {
logForDebugging(
`[RemoteSessionManager] Connecting to session ${this.config.sessionId}`,
)
const wsCallbacks: SessionsWebSocketCallbacks = {
onMessage: message => this.handleMessage(message),
onConnected: () => {
logForDebugging('[RemoteSessionManager] Connected')
this.callbacks.onConnected?.()
},
onClose: () => {
logForDebugging('[RemoteSessionManager] Disconnected')
this.callbacks.onDisconnected?.()
},
onReconnecting: () => {
logForDebugging('[RemoteSessionManager] Reconnecting')
this.callbacks.onReconnecting?.()
},
onError: error => {
logError(error)
this.callbacks.onError?.(error)
},
}
this.websocket = new SessionsWebSocket(
this.config.sessionId,
this.config.orgUuid,
this.config.getAccessToken,
wsCallbacks,
)
void this.websocket.connect()
}
/**
* Handle messages from WebSocket
*/
private handleMessage(
message:
| SDKMessage
| SDKControlRequest
| SDKControlResponse
| SDKControlCancelRequest,
): void {
// Handle control requests (permission prompts from CCR)
if (message.type === 'control_request') {
this.handleControlRequest(message)
return
}
// Handle control cancel requests (server cancelling a pending permission prompt)
if (message.type === 'control_cancel_request') {
const { request_id } = message
const pendingRequest = this.pendingPermissionRequests.get(request_id)
logForDebugging(
`[RemoteSessionManager] Permission request cancelled: ${request_id}`,
)
this.pendingPermissionRequests.delete(request_id)
this.callbacks.onPermissionCancelled?.(
request_id,
pendingRequest?.tool_use_id,
)
return
}
// Handle control responses (acknowledgments)
if (message.type === 'control_response') {
logForDebugging('[RemoteSessionManager] Received control response')
return
}
// Forward SDK messages to callback (type guard ensures proper narrowing)
if (isSDKMessage(message)) {
this.callbacks.onMessage(message)
}
}
/**
* Handle control requests from CCR (e.g., permission requests)
*/
private handleControlRequest(request: SDKControlRequest): void {
const { request_id, request: inner } = request
if (inner.subtype === 'can_use_tool') {
logForDebugging(
`[RemoteSessionManager] Permission request for tool: ${inner.tool_name}`,
)
this.pendingPermissionRequests.set(request_id, inner)
this.callbacks.onPermissionRequest(inner, request_id)
} else {
// Send an error response for unrecognized subtypes so the server
// doesn't hang waiting for a reply that never comes.
logForDebugging(
`[RemoteSessionManager] Unsupported control request subtype: ${inner.subtype}`,
)
const response: SDKControlResponse = {
type: 'control_response',
response: {
subtype: 'error',
request_id,
error: `Unsupported control request subtype: ${inner.subtype}`,
},
}
this.websocket?.sendControlResponse(response)
}
}
/**
* Send a user message to the remote session via HTTP POST
*/
async sendMessage(
content: RemoteMessageContent,
opts?: { uuid?: string },
): Promise<boolean> {
logForDebugging(
`[RemoteSessionManager] Sending message to session ${this.config.sessionId}`,
)
const success = await sendEventToRemoteSession(
this.config.sessionId,
content,
opts,
)
if (!success) {
logError(
new Error(
`[RemoteSessionManager] Failed to send message to session ${this.config.sessionId}`,
),
)
}
return success
}
/**
* Respond to a permission request from CCR
*/
respondToPermissionRequest(
requestId: string,
result: RemotePermissionResponse,
): void {
const pendingRequest = this.pendingPermissionRequests.get(requestId)
if (!pendingRequest) {
logError(
new Error(
`[RemoteSessionManager] No pending permission request with ID: ${requestId}`,
),
)
return
}
this.pendingPermissionRequests.delete(requestId)
const response: SDKControlResponse = {
type: 'control_response',
response: {
subtype: 'success',
request_id: requestId,
response: {
behavior: result.behavior,
...(result.behavior === 'allow'
? { updatedInput: result.updatedInput }
: { message: result.message }),
},
},
}
logForDebugging(
`[RemoteSessionManager] Sending permission response: ${result.behavior}`,
)
this.websocket?.sendControlResponse(response)
}
/**
* Check if connected to the remote session
*/
isConnected(): boolean {
return this.websocket?.isConnected() ?? false
}
/**
* Send an interrupt signal to cancel the current request on the remote session
*/
cancelSession(): void {
logForDebugging('[RemoteSessionManager] Sending interrupt signal')
this.websocket?.sendControlRequest({ subtype: 'interrupt' })
}
/**
* Get the session ID
*/
getSessionId(): string {
return this.config.sessionId
}
/**
* Disconnect from the remote session
*/
disconnect(): void {
logForDebugging('[RemoteSessionManager] Disconnecting')
this.websocket?.close()
this.websocket = null
this.pendingPermissionRequests.clear()
}
/**
* Force reconnect the WebSocket.
* Useful when the subscription becomes stale after container shutdown.
*/
reconnect(): void {
logForDebugging('[RemoteSessionManager] Reconnecting WebSocket')
this.websocket?.reconnect()
}
}
/**
* Create a remote session config from OAuth tokens
*/
export function createRemoteSessionConfig(
sessionId: string,
getAccessToken: () => string,
orgUuid: string,
hasInitialPrompt = false,
viewerOnly = false,
): RemoteSessionConfig {
return {
sessionId,
getAccessToken,
orgUuid,
hasInitialPrompt,
viewerOnly,
}
}
|