import { accountRequiredMessage } from './desktop-mode.js'; // src/lib/game-client.ts import { WsConnectionState } from '../sdk/types.js'; import { AuthStore } from './auth.js'; import { ServerRegistry } from './server-registry.js'; import { HttpTransport, ApiError } from './http-transport.js'; import { WsClient, type WsCloseInfo, type WsInputFrame, type WsProtocolErrorInfo, type WsRecoveryStartedInfo, type GameSyncResumeState, } from '../runtime/ws-client.js'; import { RuntimeLogger } from '../runtime/runtime-logger.js'; import { ThreadedWsClient, type ThreadedWsClientConfig } from '../runtime/threaded-ws-client.js'; import type { RawWsMessageSink } from '../runtime/raw-ws-log.js'; import type { GameSyncPerceptionReport, GameSyncRuntimeReport } from '../runtime/game-sync-protocol.js'; import type { QueueMode } from './competition.js'; import type { CreateRoomOptions, RoomEntryMetadata, RoomType, TrainingRoomType, } from './room.js'; import { synthesizeConfiguredTts } from './custom-tts.js'; import type { TransportResponse } from '../short-command/transport-response.js'; import { lobbyHostHeaders, resolveLobbyHostContext, validateLobbyHostContext, type LobbyHostContext } from './lobby-host-context.js'; export { ApiError } from './http-transport.js'; export interface GameClientConfig { /** One stable host context for Lobby participation and socket reconnects. */ hostContext?: LobbyHostContext; lobbyUrl: string; gameServerUrl?: string; apiKey: string; agentName?: string; enableWs?: boolean; /** Owner-scoped raw GameSync capture. Its lifecycle remains with the caller. */ rawWsMessageSink?: RawWsMessageSink; /** Cancels owner-scoped HTTP work before Action authority is released. */ signal?: AbortSignal; /** Owner-only Source transport isolation. Ephemeral clients do not start an ingress Worker. */ gameSyncIngress?: Omit; } export interface GameServerDiscoveryResult { /** Preserves the old boolean meaning: a usable GameServer route changed. */ readonly routeChanged: boolean; /** Latest authoritative Lobby participation response, when the probe succeeded. */ readonly queue?: Record; } export interface GameActionRequest { action: string; name?: string; description?: string; target?: string; target_seat?: number; target_x?: number; target_y?: number; task_name?: string; text?: string; thinking_content?: string; audio_url?: string; } function agentMetadataHeaders(options: RoomEntryMetadata): Record | undefined { const headers: Record = {}; if (options.agentType) headers['X-Agent-Type'] = options.agentType; if (options.monitorStatus) headers['X-Monitor-Status'] = options.monitorStatus; if (options.llmModel) headers['X-LLM-Model'] = options.llmModel; return Object.keys(headers).length > 0 ? headers : undefined; } export class GameClient { private resolvedHostContext?: LobbyHostContext; private readonly hostEnvironment: NodeJS.ProcessEnv; private http: HttpTransport; private ws: Pick | null = null; private readonly gameSyncIngress?: GameClientConfig['gameSyncIngress']; private readonly closingIngress = new Set>(); private transportGeneration = 0; /** Last continuously reduced v2 baseline, retained across failed socket replacements. */ private gameSyncResumeState?: GameSyncResumeState; /** Queue/room-owned game identity that the retained baseline must belong to. */ private expectedGameSyncGameId?: string; private wsCloseHandlers: Array<(info: WsCloseInfo) => void> = []; private wsInputFrameHandlers: Array<{ handler: (frame: WsInputFrame) => void; unsubscribe?: () => void; }> = []; private wsConnectionOpenedHandlers: Array<{ handler: (connectionId: string) => void; unsubscribe?: () => void; }> = []; private wsLivenessHandlers: Array<{ handler: (connectionId: string, atMs: number) => void; unsubscribe?: () => void; }> = []; private wsProtocolErrorHandlers: Array<{ handler: (info: WsProtocolErrorInfo) => void; unsubscribe?: () => void; }> = []; private wsRecoveryStartedHandlers: Array<{ handler: (info: WsRecoveryStartedInfo) => void; unsubscribe?: () => void; }> = []; private registry: ServerRegistry; private apiKey: string; private enableWs: boolean; private readonly rawWsMessageSink?: RawWsMessageSink; private log = new RuntimeLogger(); private lastCustomTtsWarning: string | null = null; /** 最近一次 TTS 降级警告,供 CLI 命令纳入 stdout JSON 输出。 */ get ttsWarning(): string | null { return this.lastCustomTtsWarning; } constructor(config: GameClientConfig) { this.resolvedHostContext = config.hostContext ? validateLobbyHostContext(config.hostContext) : undefined; this.hostEnvironment = { CLAWCLAW_IS_DESKTOP: process.env.CLAWCLAW_IS_DESKTOP, CLAWCLAW_HOST_INSTANCE_ID: process.env.CLAWCLAW_HOST_INSTANCE_ID, CLAWCLAW_HOST_SESSION_ID: process.env.CLAWCLAW_HOST_SESSION_ID, }; this.apiKey = config.apiKey; this.enableWs = config.enableWs ?? false; this.rawWsMessageSink = config.rawWsMessageSink; this.gameSyncIngress = config.gameSyncIngress; this.registry = new ServerRegistry({ lobbyUrl: config.lobbyUrl, gameServerUrl: config.gameServerUrl, agentName: config.agentName, }); this.http = new HttpTransport(config.apiKey, this.registry, {}, config.signal); } // ─── Factory Methods ─── /** * Create GameClient from active auth profile. * Used by both runtime listeners (ws: true) and CLI commands (ws: false). */ static fromAuth(opts?: { ws?: boolean; authStore?: AuthStore; rawWsMessageSink?: RawWsMessageSink; signal?: AbortSignal; }): GameClient { const store = opts?.authStore ?? new AuthStore(); const profile = store.getActive(); if (!profile) { throw new Error(accountRequiredMessage('No active auth profile. Run: clawclaw-cli account register')); } return new GameClient({ lobbyUrl: profile.serverUrl, gameServerUrl: profile.gameServerUrl, apiKey: profile.apiKey, agentName: profile.agentName, enableWs: opts?.ws ?? false, rawWsMessageSink: opts?.rawWsMessageSink, signal: opts?.signal, }); } /** Get current server addresses. */ get addresses() { return this.registry.addresses; } /** * Structured transport result for migrated short-command handlers. Existing * typed methods keep their legacy throw/JSON behavior. */ requestRaw( method: string, path: string, body?: unknown, headers?: Record, ): Promise { return this.http.requestRaw(method, path, body, headers); } // ─── Game API (→ game server) ─── /** GameSync v2 carries observations only; all Actions use acknowledged HTTP. */ async submitAction(action: GameActionRequest): Promise { const preparedAction = await this.prepareAction(action); return this.http.post('/api/v1/game/action', preparedAction); } /** * Submit through the acknowledged HTTP request/response boundary even while * the owner has an active WS stream. Agent-facing commands must not call a * fire-and-forget WS send a confirmed success. */ async submitActionConfirmed(action: GameActionRequest): Promise { const preparedAction = await this.prepareActionForConfirmedSubmission(action); return this.submitPreparedActionConfirmed(preparedAction); } /** * Reversible preparation phase for an acknowledged Action. Runtime adapters * may revalidate local authority after this resolves and before calling the * corresponding submit method. */ async prepareActionForConfirmedSubmission( action: GameActionRequest, ): Promise { return this.prepareAction(action); } /** Irreversible confirmed Action endpoint; input must already be prepared. */ async submitPreparedActionConfirmed(action: GameActionRequest, signal?: AbortSignal): Promise { return this.http.postRaw('/api/v1/game/action', action, undefined, signal); } private async prepareAction(action: GameActionRequest): Promise { let preparedAction = action; if (action.action === 'speech' && typeof action.text === 'string' && action.text.length > 0 && !action.audio_url) { try { const synthesized = await synthesizeConfiguredTts(action.text); if (synthesized) { const { audio_url } = await this.uploadAudio( synthesized.audio, synthesized.filename, synthesized.contentType, ); preparedAction = { ...action, audio_url }; this.lastCustomTtsWarning = null; } } catch (err) { const message = err instanceof Error ? err.message : String(err); if (message !== this.lastCustomTtsWarning) { console.error(`Custom TTS failed: ${message}. Sending speech without audio.`); this.lastCustomTtsWarning = message; } this.log.warn('CUSTOM_TTS_FAILED', message); } } return preparedAction; } async uploadAudio( filePathOrBuffer: string | Buffer, filename?: string, contentType = 'audio/mpeg', ): Promise<{ audio_url: string }> { const form = new FormData(); if (typeof filePathOrBuffer === 'string') { const { existsSync, readFileSync } = await import('fs'); const { basename } = await import('path'); if (!existsSync(filePathOrBuffer)) { throw new Error(`Audio file not found: ${filePathOrBuffer}`); } const buffer = readFileSync(filePathOrBuffer); form.append('file', new Blob([buffer as any], { type: contentType }), filename ?? basename(filePathOrBuffer)); } else { form.append('file', new Blob([filePathOrBuffer as any], { type: contentType }), filename ?? 'audio.mp3'); } const response = await this.http.postRaw('/api/v1/agents/upload_audio', form); const result = response.body.kind === 'json' ? response.body.value as any : null; if ( response.status < 200 || response.status >= 300 || !result || typeof result !== 'object' || result.success === false ) { throw new ApiError( response.status, response.body.rawText, 'POST', '/api/v1/agents/upload_audio', response, ); } const audioUrl = result?.audio_url ?? result?.data?.audio_url; if (!audioUrl) { throw new Error(`upload_audio: unexpected response: ${JSON.stringify(result)}`); } return { audio_url: audioUrl }; } // ─── Agent API (→ lobby) ─── /** * Register a new agent. No auth required. * Server expects multipart/form-data with optional name/description/avatar fields. */ async registerAgent(opts: { name?: string; description?: string; avatarUrl?: string; avatarFile?: string; inviteCode?: string; }): Promise { const form = new FormData(); if (opts.name) form.append('name', opts.name); if (opts.description) form.append('description', opts.description); if (opts.inviteCode) form.append('invite_code', opts.inviteCode); if (opts.avatarUrl) form.append('avatar_url', opts.avatarUrl); if (opts.avatarFile) { const { readFileSync } = await import('fs'); const { basename } = await import('path'); const buf = readFileSync(opts.avatarFile); form.append('avatar_file', new Blob([buf]), basename(opts.avatarFile)); } return this.http.post('/api/v1/agents/register', form); } async renameAgent(name: string): Promise { return this.http.request('PATCH', '/api/v1/agents/name', { name }); } async login(apiKey: string): Promise { return this.http.post('/api/v1/agents/login', { api_key: apiKey }); } async getMe(): Promise { return this.http.get('/api/v1/agents/me'); } // ─── Queue API (→ lobby, auto game server discovery) ─── /** Lazy so login, Hub and read-only status remain usable before host setup. */ get lobbyHostContext(): LobbyHostContext { return this.resolvedHostContext ??= resolveLobbyHostContext(this.hostEnvironment); } private async enterLobby(path: string, body: unknown, metadata: RoomEntryMetadata): Promise { const response = await this.http.postRaw(path, body, { ...agentMetadataHeaders(metadata), ...lobbyHostHeaders(this.lobbyHostContext), }); if (response.status < 200 || response.status >= 300 || (response.body.kind === 'json' && (response.body.value as { success?: unknown } | null)?.success === false)) { throw new ApiError(response.status, response.body.rawText, 'POST', path, response); } if (response.body.kind !== 'json') throw new SyntaxError(`Unexpected non-JSON response from ${path}`); return response.body.value; } async joinQueue(options: string | { gameType?: string; mode?: QueueMode; agentType?: string; monitorStatus?: 'on' | 'off'; llmModel?: string } = 'clawclaw'): Promise { const gameType = typeof options === 'string' ? options : (options.gameType ?? 'clawclaw'); const mode = typeof options === 'string' ? 'match' : (options.mode ?? 'match'); const agentType = typeof options === 'string' ? undefined : options.agentType; const monitorStatus = typeof options === 'string' ? undefined : options.monitorStatus; const llmModel = typeof options === 'string' ? undefined : options.llmModel; // These headers are only consumed by /queue/join, so they are attached // per-request rather than to every call: // X-Agent-Type — the agent platform (e.g. claude-code, openclaw) // X-Monitor-Status — whether the Claude Code Monitor tool is on/off this match // X-LLM-Model — the exact/canonical reasoning model ID the lobster (龙虾) agent runs as this match const result = await this.enterLobby('/api/v1/queue/join', { game_type: gameType, mode }, { agentType, monitorStatus, llmModel }); this.registry.updateFromQueueResponse(result); return result; } async getQueueStatus(gameType?: string): Promise { const query = gameType ? `?game_type=${encodeURIComponent(gameType)}` : ''; const result = await this.http.get(`/api/v1/queue/status${query}`); this.registry.updateFromQueueResponse(result); return result; } async leaveQueue(gameType?: string): Promise { const query = gameType ? `?game_type=${encodeURIComponent(gameType)}` : ''; return this.http.post(`/api/v1/queue/leave${query}`, undefined, { 'X-Client-Type': 'agent' }); } /** Leave the active game. Normal matches require death; a training owner may abandon while alive. */ async leaveGame(): Promise { return this.http.post('/api/v1/game/leave'); } // ─── Room API (→ lobby) ─── async createRoom(options: RoomType | CreateRoomOptions = {}): Promise { const normalized = typeof options === 'string' ? { roomType: options } : options; return normalized.roomType ? this.enterLobby('/api/v1/room/create', { room_type: normalized.roomType }, normalized) : this.enterLobby('/api/v1/room/create', undefined, normalized); } async joinRoom(roomCode: string, metadata: RoomEntryMetadata = {}): Promise { return this.enterLobby('/api/v1/room/join', { room_code: roomCode }, metadata); } async getRoomStatus(): Promise { return this.http.get('/api/v1/room/status'); } async leaveRoom(): Promise { return this.http.post('/api/v1/room/leave'); } async startRoom(): Promise { return this.http.post('/api/v1/room/start'); } async setTrainingRoomMode(roomType: TrainingRoomType): Promise { return this.http.request('PUT', '/api/v1/room/training/mode', { room_type: roomType }); } async setTrainingRoleLock(characterId: number): Promise { return this.http.request('PUT', '/api/v1/room/training/role-lock', { character_id: characterId }); } async clearTrainingRoleLock(): Promise { return this.http.request('DELETE', '/api/v1/room/training/role-lock'); } async chatRoom(content: string): Promise { return this.http.post('/api/v1/room/chat', { content }); } async chatRoomConfirmed(content: string): Promise { return this.http.postRaw('/api/v1/room/chat', { content }); } get lobbyAgentWsUrl(): string { return this.registry.lobbyAgentWsUrl; } setRoomGameServer(gameServerName: string): void { this.registry.setGatewayGameServerName(gameServerName); } setGameServerUrl(url: string): void { this.registry.setGameServerUrl(url); } // ─── Economy / Leaderboard ─── async getLeaderboard(page?: number, limit?: number): Promise { const params = new URLSearchParams(); if (page != null) params.set('page', String(page)); if (limit != null) params.set('limit', String(limit)); const query = params.toString() ? `?${params.toString()}` : ''; return this.http.get(`/api/v1/leaderboard${query}`); } async getCompetitionStatus(): Promise { return this.http.get('/api/v1/competition/status'); } async getMyCompetitionRank(): Promise { return this.http.get('/api/v1/leaderboard/competition/me'); } async getSettlement(): Promise { return this.http.get('/api/v1/game/settlement'); } async getGameHistory(page?: number, limit?: number): Promise { const params = new URLSearchParams(); if (page != null) params.set('page', String(page)); if (limit != null) params.set('limit', String(limit)); const query = params.toString() ? `?${params.toString()}` : ''; return this.http.get(`/api/v1/game/history${query}`); } // ─── Connection Management ─── /** Bind resumable GameSync state to the game selected by Source lifecycle. */ setExpectedGameSyncGameId(gameId: string | undefined): void { const expected = gameId?.trim() || undefined; if (this.expectedGameSyncGameId !== expected) { this.expectedGameSyncGameId = expected; if (!expected || this.gameSyncResumeState?.gameId !== expected) { this.gameSyncResumeState = undefined; } return; } if (expected && this.gameSyncResumeState?.gameId !== expected) { this.gameSyncResumeState = undefined; } } /** Connect WebSocket to the current server (game server or lobby). */ async connectWs(): Promise { if (!this.enableWs) return false; if (this.wsConnected) return true; const wsUrl = this.registry.wsUrl; if (!wsUrl) { this.log.warn('WS_CONNECT', 'no game server URL for WebSocket'); return false; } const resumeState = this.resumeStateForExpectedGame( this.ws?.resumeState ?? this.gameSyncResumeState, ); if (resumeState) this.gameSyncResumeState = resumeState; if (this.ws) { this.ws.clearHandlers(); await this.stopWs(this.ws); this.markWsHandlersDetached(); } const newWs = this.createWs({ url: wsUrl, apiKey: this.apiKey, rawMessageSink: this.rawWsMessageSink, ...(resumeState ? { resumeState } : {}), }); this.ws = newWs; this.attachWsHandlers(); try { await newWs.connect(); return true; } catch { this.rememberGameSyncResumeState(newWs.resumeState); this.log.warn('WS_CONNECT', 'GameSync WebSocket connection failed; runtime will retry'); await this.stopWs(newWs); this.ws = null; this.markWsHandlersDetached(); return false; } } /** Disconnect WebSocket. */ disconnectWs(options: { preserveGameSyncResumeState?: boolean } = {}): void { if (options.preserveGameSyncResumeState) { this.rememberGameSyncResumeState(this.ws?.resumeState); } if (this.ws) { this.stopWs(this.ws); this.ws = null; } if (!options.preserveGameSyncResumeState) { this.gameSyncResumeState = undefined; this.expectedGameSyncGameId = undefined; } } /** Commit one Source-accepted GameSync frame and advance its resumable ACK. */ acknowledgeGameSync(ackToken: string, immediate = false): void { this.ws?.acknowledge(ackToken, immediate); this.rememberGameSyncResumeState(this.ws?.resumeState); } /** Send display-only perception output over the active GameSync connection. */ reportGameSyncPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean { return this.ws?.reportPerceptions(perceptions) ?? false; } /** A report must still belong to the Source-accepted game/connection it describes. */ reportGameSyncRuntime(report: GameSyncRuntimeReport, gameId: string, connectionId: string): boolean { if (this.ws?.connectionId !== connectionId || this.ws?.resumeState?.gameId !== gameId) return false; return this.ws.reportRuntime(report); } get gameSyncLocale(): 'zh-CN' | 'en-US' { return this.ws?.resumeState?.locale ?? this.gameSyncResumeState?.locale ?? 'zh-CN'; } /** * Try to discover game server from /queue/status. * If found and WS is enabled, reconnects WS to the game server. * Returns both the usable-route decision and the authoritative queue probe. * * Note: uses http.get directly instead of getQueueStatus() to avoid * double-calling registry.updateFromQueueResponse(). */ async discoverGameServer(): Promise { try { const result = await this.http.get('/api/v1/queue/status'); const changed = this.registry.updateFromQueueResponse(result); if (changed && this._gameServerUrl) { this.log.info('GAME_SERVER_DISCOVERED', `url=${this._gameServerUrl}`); if (this.enableWs) { await this.reconnectWsToGameServer(); } return { routeChanged: true, queue: structuredClone(result) }; } return { routeChanged: false, queue: structuredClone(result) }; } catch { /* queue/status unavailable */ } return { routeChanged: false }; } /** Reconnect WS to the current game server address. */ async reconnectWsToGameServer(): Promise { const wsUrl = this.registry.wsUrl; if (!wsUrl) return; const resumeState = this.resumeStateForExpectedGame( this.ws?.resumeState ?? this.gameSyncResumeState, ); if (resumeState) this.gameSyncResumeState = resumeState; if (this.ws) { this.ws.clearHandlers(); await this.stopWs(this.ws); this.markWsHandlersDetached(); } const newWs = this.createWs({ url: wsUrl, apiKey: this.apiKey, rawMessageSink: this.rawWsMessageSink, ...(resumeState ? { resumeState } : {}), }); this.ws = newWs; this.attachWsHandlers(); try { await newWs.connect(); this.log.info('WS_RECONNECT', `connected to ${wsUrl}`); } catch { this.rememberGameSyncResumeState(newWs.resumeState); this.log.warn('WS_RECONNECT', 'GameSync WebSocket reconnect failed; runtime will retry'); await this.stopWs(newWs); this.ws = null; this.markWsHandlersDetached(); } } /** Get the current game server URL. */ get _gameServerUrl(): string | null { return this.registry.gameServerUrl; } // ─── GameSync v2 proxy ─── onWsClose(handler: (info: WsCloseInfo) => void): () => void { this.wsCloseHandlers.push(handler); return () => { const idx = this.wsCloseHandlers.indexOf(handler); if (idx >= 0) this.wsCloseHandlers.splice(idx, 1); }; } onInputFrame(handler: (frame: WsInputFrame) => void): () => void { const entry = { handler, unsubscribe: undefined as (() => void) | undefined }; this.wsInputFrameHandlers.push(entry); if (this.ws) entry.unsubscribe = this.ws.onInputFrame(handler); return () => { entry.unsubscribe?.(); const idx = this.wsInputFrameHandlers.indexOf(entry); if (idx >= 0) this.wsInputFrameHandlers.splice(idx, 1); }; } onWsConnectionOpened(handler: (connectionId: string) => void): () => void { const entry = { handler, unsubscribe: undefined as (() => void) | undefined }; this.wsConnectionOpenedHandlers.push(entry); if (this.ws) entry.unsubscribe = this.ws.onConnectionOpened(handler); return () => { entry.unsubscribe?.(); const idx = this.wsConnectionOpenedHandlers.indexOf(entry); if (idx >= 0) this.wsConnectionOpenedHandlers.splice(idx, 1); }; } onWsLiveness(handler: (connectionId: string, atMs: number) => void): () => void { const entry = { handler, unsubscribe: undefined as (() => void) | undefined }; this.wsLivenessHandlers.push(entry); if (this.ws) entry.unsubscribe = this.ws.onLiveness(handler); return () => { entry.unsubscribe?.(); const idx = this.wsLivenessHandlers.indexOf(entry); if (idx >= 0) this.wsLivenessHandlers.splice(idx, 1); }; } onWsProtocolError(handler: (info: WsProtocolErrorInfo) => void): () => void { const entry = { handler, unsubscribe: undefined as (() => void) | undefined }; this.wsProtocolErrorHandlers.push(entry); if (this.ws) entry.unsubscribe = this.ws.onProtocolError(handler); return () => { entry.unsubscribe?.(); const idx = this.wsProtocolErrorHandlers.indexOf(entry); if (idx >= 0) this.wsProtocolErrorHandlers.splice(idx, 1); }; } onWsRecoveryStarted(handler: (info: WsRecoveryStartedInfo) => void): () => void { const entry = { handler, unsubscribe: undefined as (() => void) | undefined }; this.wsRecoveryStartedHandlers.push(entry); if (this.ws) entry.unsubscribe = this.ws.onRecoveryStarted(handler); return () => { entry.unsubscribe?.(); const idx = this.wsRecoveryStartedHandlers.indexOf(entry); if (idx >= 0) this.wsRecoveryStartedHandlers.splice(idx, 1); }; } get wsConnected(): boolean { return this.ws?.connected ?? false; } /** True while the owned WsClient is connecting, connected, or auto-reconnecting. */ get wsConnectionActive(): boolean { return this.ws !== null && this.ws.state !== WsConnectionState.Disconnected; } get wsConnectionId(): string | null { return this.ws?.connectionId || null; } private attachWsHandlers(): void { if (!this.ws) return; const attachedWs = this.ws; attachedWs.onInputFrame(() => { this.rememberGameSyncResumeState(attachedWs.resumeState); }); for (const entry of this.wsInputFrameHandlers) { entry.unsubscribe = this.ws.onInputFrame(entry.handler); } for (const entry of this.wsConnectionOpenedHandlers) { entry.unsubscribe = this.ws.onConnectionOpened(entry.handler); } for (const entry of this.wsLivenessHandlers) { entry.unsubscribe = this.ws.onLiveness(entry.handler); } for (const entry of this.wsProtocolErrorHandlers) { entry.unsubscribe = this.ws.onProtocolError(entry.handler); } for (const entry of this.wsRecoveryStartedHandlers) { entry.unsubscribe = this.ws.onRecoveryStarted(entry.handler); } this.ws.onDisconnect((info) => { for (const handler of this.wsCloseHandlers) handler(info); }); } private markWsHandlersDetached(): void { for (const entry of this.wsInputFrameHandlers) entry.unsubscribe = undefined; for (const entry of this.wsConnectionOpenedHandlers) entry.unsubscribe = undefined; for (const entry of this.wsLivenessHandlers) entry.unsubscribe = undefined; for (const entry of this.wsProtocolErrorHandlers) entry.unsubscribe = undefined; for (const entry of this.wsRecoveryStartedHandlers) entry.unsubscribe = undefined; } private createWs(config: ConstructorParameters[0]): Pick { if (!this.gameSyncIngress) return new WsClient(config); const { rawMessageSink: _sink, ...options } = config; return new ThreadedWsClient({ ...options, ...this.gameSyncIngress, transportGeneration: ++this.transportGeneration }); } private stopWs(ws: Pick): Promise { ws.disconnect(); if (ws instanceof ThreadedWsClient) { const closing = ws.close(); this.closingIngress.add(closing); void closing.finally(() => this.closingIngress.delete(closing)); return closing; } return Promise.resolve(); } /** Drain Source-owned ingress and raw journals before Owner telemetry closes. */ async closeGameSyncTransports(): Promise { this.disconnectWs(); await Promise.allSettled([...this.closingIngress]); } private rememberGameSyncResumeState(candidate: GameSyncResumeState | undefined): void { if (!candidate) return; const expected = this.expectedGameSyncGameId; if (expected && candidate.gameId !== expected) { this.gameSyncResumeState = undefined; return; } if (!expected) this.expectedGameSyncGameId = candidate.gameId; this.gameSyncResumeState = structuredClone(candidate); } private resumeStateForExpectedGame( candidate: GameSyncResumeState | undefined, ): GameSyncResumeState | undefined { if (!candidate) return undefined; const expected = this.expectedGameSyncGameId; if (expected && candidate.gameId !== expected) { this.gameSyncResumeState = undefined; return undefined; } if (!expected) this.expectedGameSyncGameId = candidate.gameId; return structuredClone(candidate); } }