import { startupSpan, timeStartup } from '../../../../../bin/startup-trace.mjs'; import { randomUUID } from 'node:crypto'; import { isInvalidHostContextError } from '../../../../lib/lobby-host-context.js'; import type { AuthProfile } from '../../../../lib/auth.js'; import { trainingCharacterId } from '../../../../lib/training-role.js'; import { apiErrorCode, apiErrorMessage, normalizeCompetitionStatusResponse, serializeError, } from '../../../../lib/competition.js'; import { DEFAULT_MATCH_TIMEOUT_MS, DEFAULT_WAITING_HEARTBEAT_MS, } from '../../../../lib/match-state.js'; import { businessFailureFromResult, classifyLeaveQueueResult, leaveFailureError, } from '../../../../lib/participation-leave.js'; import { isServiceMaintenanceApiError, parseServerServiceStatus, serverServiceStatusFromApiError, serverServiceStatusFromEnvelope, serviceStatusEvent, serviceStatusSignature, type ServerServiceStatus, } from '../../../../lib/service-status.js'; import { isRoomMode, isTrainingRoomMode, queueMode, queueRoomCode, queueStatus, unwrapData, type RoomSnapshot, type TrainingRoomType, } from '../../../../lib/room.js'; import type { WsCloseInfo, WsFrameMeta, WsInputFrame, WsRecoveryStartedInfo, } from '../../../ws-client.js'; import { type RuntimeInputAcceptance, type RuntimeInputBatch, type RuntimeSourceContext, type RuntimeSourceEvent, type RuntimeSourcePlugin, type RuntimeSourceStopHandle, } from '../../../framework/plugins/index.js'; import type { RuntimeScope } from '../../../framework/state/index.js'; import { normalizeGameSyncEventsSafely } from '../../../../pipeline/game-sync-event-normalization.js'; import { isSelfKillerMurderWitnessed } from '../../../../pipeline/event-hints.js'; import { projectClawclawRoomState, } from '../../../clawclaw-room-state.js'; import { clawclawStageFromGameEvents, clawclawStageFromGameState, isClawclawRuntimeState, type ClawclawRuntimeCause, type ClawclawRuntimeConnection, type ClawclawRuntimeStage, type ClawclawRuntimeState, type ClawclawRuntimeTransport, } from '../../runtime-state.js'; import { ClawclawGameTransport, type ClawclawGameTransportOutcome, type ClawclawGameTransportOptions, type ClawclawGameTransportPort, type ClawclawGameTransportStopReason, } from './game-transport.js'; import { ClawclawRoomTransport, type ClawclawRoomCloseDecision, type ClawclawRoomCloseInfo, type ClawclawRoomGameStarted, type ClawclawRoomTransportOptions, type ClawclawRoomTransportPort, } from './room-transport.js'; import { CLAWCLAW_GAME_WS_SOURCE, CLAWCLAW_LOBBY_HTTP_SOURCE, CLAWCLAW_LOCAL_CONTROL_SOURCE, CLAWCLAW_ROOM_WS_SOURCE, } from './source-transports.js'; import type { ClawclawSourceClient, ClawclawSourceCompletion, ClawclawSourceControlIntent, ClawclawSourceStartIntent, ClawclawSourceTransportFactory, } from './types.js'; interface RoomFrameMeta { connectionId: string; receivedAt: string; sourceSeq: number | string; sourceEventId?: string; replay?: boolean; } interface LifecycleContinue { kind: 'continue'; queue?: Record; } interface LifecycleComplete { kind: 'complete'; completion: ClawclawSourceCompletion; } type LifecycleStep = LifecycleContinue | LifecycleComplete; function competitionExitReason(code: string | undefined): string { switch (code) { case 'NO_ACTIVE_COMPETITION': return 'no_active_competition'; case 'COMPETITION_NOT_OPEN': return 'competition_not_open'; case 'ALREADY_IN_GAME': return 'already_in_game'; case 'INVALID_MODE': return 'invalid_mode'; default: return 'request_failed'; } } type GameAttachGate = | { kind: 'attached' } | { kind: 'outcome'; outcome: ClawclawGameTransportOutcome } | { kind: 'timeout' }; type ReconciledTransport = 'game_ws' | 'room_ws'; const GAME_TERMINAL_SETTLEMENT_ATTEMPTS = 2; const GAME_TERMINAL_SETTLEMENT_RETRY_MS = 250; interface SourceCoalescingBoundaryState { connected: boolean; ended: boolean; actionAllowed: boolean; } function nextSourceCoalescingBoundaryState( state: unknown, previous?: SourceCoalescingBoundaryState, ): SourceCoalescingBoundaryState | undefined { if (!isClawclawRuntimeState(state)) return previous; const connected = state.connection === 'connected'; const freshActionAllowed = state.game_snapshot.status === 'fresh' && state.game_snapshot.state.phase === 'wandering' && state.game_snapshot.state.you?.is_alive !== false; const actionAllowed = connected && state.stage === 'game' && (state.game_snapshot.status === 'fresh' ? freshActionAllowed : previous?.actionAllowed === true); return { connected, ended: state.stage === 'ended', actionAllowed, }; } function crossesSourceCoalescingBoundary( previous: SourceCoalescingBoundaryState | undefined, next: SourceCoalescingBoundaryState | undefined, ): boolean { if (!previous || !next) return false; return previous.connected !== next.connected || (!previous.ended && next.ended) || previous.actionAllowed !== next.actionAllowed; } export interface ClawclawSourcePluginOptions { client: ClawclawSourceClient; profile: Pick; initialIntent?: ClawclawSourceStartIntent; /** * Queue state already read by the Owner before Runtime construction. It is * consumed exactly once so Runtime session recovery and Source startup use * the same authoritative observation instead of racing two HTTP reads. */ initialQueueState?: Record; pollIntervalMs?: number; maxConsecutivePollFailures?: number; roomReturnPollMs?: number; matchWaitingIntervalMs?: number; matchTimeoutMs?: number; gameFirstStateTimeoutMs?: number; roomAttachReconcileAfterMs?: number; reconcileBaseDelayMs?: number; reconcileMaxDelayMs?: number; roomWebSocketFactory?: ClawclawRoomTransportOptions['webSocketFactory']; transports?: Partial; sleep?: (ms: number, signal: AbortSignal) => Promise; clock?: () => number; } function defaultSleep(ms: number, signal: AbortSignal): Promise { if (signal.aborted) return Promise.resolve(); return new Promise((resolve) => { const timer = setTimeout(finish, ms); const onAbort = (): void => finish(); function finish(): void { clearTimeout(timer); signal.removeEventListener('abort', onAbort); resolve(); } signal.addEventListener('abort', onAbort, { once: true }); }); } export function normalizeClawclawQueueState(value: unknown): Record { const unwrapped = unwrapData(value); return unwrapped && typeof unwrapped === 'object' && !Array.isArray(unwrapped) ? structuredClone(unwrapped) : {}; } function queueExitReceipt(value: unknown) { if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined; const { reason, initiator, at } = value as Record; if (typeof reason !== 'string' || !reason.trim()) return undefined; return { reason, initiator: initiator === 'ui' || initiator === 'agent' ? initiator : 'unknown', ...(typeof at === 'number' && Number.isFinite(at) ? { at } : {}), }; } export function clawclawQueueGameId(value: unknown): string | undefined { const data = normalizeClawclawQueueState(value); return typeof data.game_id === 'string' && data.game_id.length > 0 ? data.game_id : undefined; } function spectateUrl(value: unknown): string | undefined { const data = normalizeClawclawQueueState(value); const candidate = data.spectate_url ?? data.url; return typeof candidate === 'string' && candidate.length > 0 ? candidate : undefined; } function normalizeBackendEvent(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new TypeError('ClawClaw backend Event must be an object.'); } const raw = value as Record; if (typeof raw.type !== 'string' || raw.type.length === 0) { throw new TypeError('ClawClaw backend Event requires type.'); } const { type, data, ...rest } = raw; return { ...rest, ...(data && typeof data === 'object' && !Array.isArray(data) ? data : {}), type, }; } function eventSourceId(event: Record): string | undefined { const value = event.event_id ?? event.eventId; return value === undefined ? undefined : String(value); } function eventSourceSequence(event: Record): number | string | undefined { return event.source_seq ?? event.sequence ?? event.seq; } function sameScope(left: RuntimeScope, right: RuntimeScope): boolean { return left.adapterId === right.adapterId && left.accountId === right.accountId && left.sessionId === right.sessionId && left.segmentId === right.segmentId; } function numericGameTick(value: unknown): number | undefined { const tick = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN; return Number.isFinite(tick) ? tick : undefined; } export function isActiveClawclawQueueStatus(status: string | undefined): boolean { return status === 'queued' || status === 'already_in_queue' || status === 'allocating' || status === 'in_room' || status === 'allocated'; } /** * The only ClawClaw Source loaded by Runtime. It owns the complete external * lifecycle and submits one complete InputBatch for every meaningful input. */ export class ClawclawSourcePlugin implements RuntimeSourcePlugin, Record> { readonly kind = 'source' as const; readonly id = 'clawclaw.source'; readonly version = '2'; private readonly client: ClawclawSourceClient; private readonly profile: Pick; private readonly initialIntent: ClawclawSourceStartIntent; private readonly pollIntervalMs: number; private readonly maxConsecutivePollFailures: number; private readonly roomReturnPollMs: number; private readonly matchWaitingIntervalMs: number; private readonly matchTimeoutMs: number; private readonly gameFirstStateTimeoutMs: number; private readonly roomAttachReconcileAfterMs: number; private readonly reconcileBaseDelayMs: number; private readonly reconcileMaxDelayMs: number; private readonly roomWebSocketFactory?: ClawclawRoomTransportOptions['webSocketFactory']; private readonly createGameTransport: (options: ClawclawGameTransportOptions) => ClawclawGameTransportPort; private readonly createRoomTransport: (options: ClawclawRoomTransportOptions) => ClawclawRoomTransportPort; private readonly sleep: (ms: number, signal: AbortSignal) => Promise; private readonly clock: () => number; private initialQueueState?: Record; private readonly abortController = new AbortController(); private readonly sourceInstanceId = randomUUID(); private readonly gameConnectionsWithState = new Set(); private readonly roomConnectionsWithSnapshot = new Set(); private runtime: RuntimeSourceContext, Record> | null = null; private gameTransport?: ClawclawGameTransportPort; private roomTransport?: ClawclawRoomTransportPort; private activeGameConnectionId?: string; private activeRoomConnectionId?: string; private localSourceSeq = 0; private currentStage: ClawclawRuntimeStage = 'matching'; private currentTransport: ClawclawRuntimeTransport = 'none'; private currentConnection: ClawclawRuntimeConnection = 'disconnected'; private participationMode?: string; private currentQueue?: Record; private currentRoom?: Record; private trainingRoomControlOverlay: Record = {}; private pendingTrainingRoomType?: TrainingRoomType; private hasFreshGameSnapshot = false; private latestFreshGameState?: Record; private latestFreshGameTick?: number; private matchStartedAtMs?: number; private lastMatchWaitingAtMs?: number; private matchTimedOut = false; private lastServiceStatusSignature?: string; private started = false; private finished = false; private terminalStateSubmitted = false; private leaveRequested = false; private lifecyclePromise?: Promise; private controlTail: Promise = Promise.resolve(); private inputTail: Promise = Promise.resolve(); private sourceCoalescingBoundaryState?: SourceCoalescingBoundaryState; private actionSafetyGeneration = 0; private readonly reconcileAttempts: Record = { game_ws: 0, room_ws: 0, }; private resolveCompletion!: (completion: ClawclawSourceCompletion) => void; private readonly completionPromise: Promise; constructor(options: ClawclawSourcePluginOptions) { this.client = options.client; this.profile = options.profile; this.initialIntent = options.initialIntent ?? { kind: 'resume' }; this.initialQueueState = options.initialQueueState ? normalizeClawclawQueueState(options.initialQueueState) : undefined; this.participationMode = this.initialIntent.kind === 'match' ? this.initialIntent.mode ?? 'match' : this.initialIntent.kind === 'create_room' ? this.initialIntent.roomType ?? 'room' : this.initialIntent.kind === 'join_room' ? 'room' : undefined; this.pollIntervalMs = options.pollIntervalMs ?? 2_000; this.maxConsecutivePollFailures = options.maxConsecutivePollFailures ?? 3; this.roomReturnPollMs = options.roomReturnPollMs ?? 1_000; this.matchWaitingIntervalMs = Math.max( 1, options.matchWaitingIntervalMs ?? DEFAULT_WAITING_HEARTBEAT_MS, ); this.matchTimeoutMs = Math.max(1, options.matchTimeoutMs ?? DEFAULT_MATCH_TIMEOUT_MS); this.gameFirstStateTimeoutMs = Math.max(1, options.gameFirstStateTimeoutMs ?? 30_000); this.roomAttachReconcileAfterMs = Math.max(1, options.roomAttachReconcileAfterMs ?? 30_000); this.reconcileBaseDelayMs = Math.max(0, options.reconcileBaseDelayMs ?? 2_000); this.reconcileMaxDelayMs = Math.max( this.reconcileBaseDelayMs, options.reconcileMaxDelayMs ?? 30_000, ); this.roomWebSocketFactory = options.roomWebSocketFactory; this.createGameTransport = options.transports?.game ?? ((transportOptions) => new ClawclawGameTransport(transportOptions)); this.createRoomTransport = options.transports?.room ?? ((transportOptions) => new ClawclawRoomTransport(transportOptions)); this.sleep = options.sleep ?? defaultSleep; this.clock = options.clock ?? Date.now; this.completionPromise = new Promise((resolve) => { this.resolveCompletion = resolve; }); } start( runtime: RuntimeSourceContext, Record>, ): RuntimeSourceStopHandle { if (this.started) throw new Error('ClawClaw Source is already started.'); this.started = true; this.runtime = runtime; this.lifecyclePromise = this.runLifecycle().then( (completion) => this.completeLifecycle(completion), (error) => this.completeLifecycle( this.abortController.signal.aborted ? { reason: 'stopped' } : isServiceMaintenanceApiError(error) ? { reason: 'maintenance', error } : { reason: 'error', error }, ), ); return { stop: () => this.stop('shutdown'), }; } waitForCompletion(): Promise { return this.completionPromise; } submitIntent(intent: ClawclawSourceControlIntent): Promise | void> { if (!this.started || !this.runtime) throw new Error('ClawClaw Source is not started.'); const operation = this.controlTail.then(() => this.handleControlIntent(intent)); this.controlTail = operation.catch(() => {}); return operation; } /** Inserts an exact, non-coalescible boundary for an Agent Event query. */ async submitEventsQueryBoundary( requestId: string, ): Promise, Record>> { if (!this.started || !this.runtime || this.finished) { throw new Error('ClawClaw Source is not available for an Events query boundary.'); } if (typeof requestId !== 'string' || !requestId.trim()) { throw new TypeError('Events query requestId must not be empty.'); } const sourceSeq = ++this.localSourceSeq; const receivedAt = new Date().toISOString(); return this.enqueueInput(() => { return { scope: this.requireRuntime().currentSegment().scope, sourceId: CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId, connectionId: this.activeGameConnectionId ?? this.activeRoomConnectionId ?? 'events-query', sourceKey: `events-query:${this.sourceInstanceId}:${requestId}`, sourceSeq, state: { ...this.runtimeState('agent_events_query'), control: { type: 'events_query', request_id: requestId }, }, events: [], completeness: 'complete', coalescing: 'forbidden', receivedAt, }; }); } async stop(reason: 'shutdown' = 'shutdown'): Promise { if (this.finished) return; if (!this.abortController.signal.aborted) { try { await this.submitControlState({ kind: 'stop' }); } catch {} this.abortController.abort(new Error(reason)); } await Promise.allSettled([ this.gameTransport?.stop('shutdown'), this.roomTransport?.stop('shutdown'), ].filter((value): value is Promise => value !== undefined)); await this.controlTail.catch(() => {}); await this.lifecyclePromise; await this.inputTail.catch(() => {}); } private async runLifecycle(): Promise { let queue: Record | undefined = await this.applyInitialIntent(); while (!this.abortController.signal.aborted) { if (!queue) queue = await this.readQueueWithRetry(); if (this.abortController.signal.aborted) break; if (this.matchTimedOut) return { reason: 'match_timeout' }; const status = queueStatus(queue); if (status === 'queued' || status === 'already_in_queue' || status === 'allocating') { await this.sleep(this.pollIntervalMs, this.abortController.signal); queue = undefined; continue; } if (status === 'in_room') { const step = await this.runRoom(queue); if (step.kind === 'complete') return step.completion; queue = step.queue; continue; } if (status === 'allocated') { const step = await this.runGame(queue); if (step.kind === 'complete') return step.completion; queue = step.queue; continue; } if (status === 'not_in_queue') { if (this.currentStage !== 'ended') { this.currentStage = 'ended'; this.currentTransport = 'lobby_http'; this.currentConnection = 'connected'; await this.submitCurrentState('ending', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http'); } return { reason: this.leaveRequested ? 'left' : 'not_participating' }; } this.diagnostic('runtime.source.queue_status_unknown', { status }, 'warn'); await this.sleep(this.pollIntervalMs, this.abortController.signal); queue = undefined; } return { reason: 'stopped' }; } private async applyInitialIntent(): Promise> { if (this.initialIntent.kind === 'resume') { const queue = await this.readQueueRawWithRetry(); await this.acceptQueueState(queue, this.resumeLifecycleEvents(queue, 'resume')); return queue; } if (this.initialIntent.kind === 'match') { const existing = await timeStartup('match.initial_queue_status', () => this.readQueueRawWithRetry()); if (isActiveClawclawQueueStatus(queueStatus(existing))) { await this.acceptQueueState(existing, this.resumeLifecycleEvents(existing, 'match')); return existing; } this.requireInactiveParticipation(existing, 'start matchmaking'); let joined: Record; let serverStatus: ServerServiceStatus | undefined; try { const intent = this.initialIntent; const response = await timeStartup('match.join_queue', () => this.client.joinQueue({ gameType: 'clawclaw', mode: intent.mode ?? 'match', agentType: intent.agentType, monitorStatus: intent.monitorStatus, llmModel: intent.llmModel, })); serverStatus = serverServiceStatusFromEnvelope(response); joined = normalizeClawclawQueueState(response); } catch (error) { try { return await this.reconcileInitialRequest( 'join_queue', error, (queue) => isActiveClawclawQueueStatus(queueStatus(queue)), (queue) => [ this.sessionRecoveredEvent('join_queue', queue), this.joinedEvent(queue, { recovered: true }), ], ); } catch (reconciledError) { if (this.initialIntent.mode === 'competition') { await this.submitCompetitionStartFailure(reconciledError); } throw reconciledError; } } if (isActiveClawclawQueueStatus(queueStatus(joined))) { await this.acceptQueueState(joined, [this.joinedEvent(joined)], serverStatus); return joined; } const reconciled = await this.readQueueRawWithRetry(); await this.acceptQueueState( reconciled, [this.joinedEvent({ ...joined, ...reconciled })], serverStatus, ); if (isActiveClawclawQueueStatus(queueStatus(reconciled))) return reconciled; throw new Error('Match join completed without creating an active participation.'); } if (this.initialIntent.kind === 'create_room') { const existing = await this.readQueueRawWithRetry(); if (queueStatus(existing) === 'in_room') { await this.acceptQueueState(existing, this.resumeLifecycleEvents(existing, 'create_room')); return existing; } this.requireInactiveParticipation(existing, 'create a room'); let created: Record; let serverStatus: ServerServiceStatus | undefined; try { const response = await this.client.createRoom({ roomType: this.initialIntent.roomType, agentType: this.initialIntent.agentType, monitorStatus: this.initialIntent.monitorStatus, llmModel: this.initialIntent.llmModel, }); serverStatus = serverServiceStatusFromEnvelope(response); created = normalizeClawclawQueueState(response); } catch (error) { return this.reconcileInitialRequest( 'create_room', error, (queue) => queueStatus(queue) === 'in_room', (queue) => [ this.sessionRecoveredEvent('create_room', queue), this.roomEntryEvent('room_created', queue, { recovered: true }), ], ); } const queue = { status: 'in_room', mode: this.initialIntent.roomType ?? 'room', ...created, }; await this.acceptQueueState( queue, [this.roomEntryEvent('room_created', queue)], serverStatus, ); return queue; } const targetRoomCode = this.initialIntent.roomCode; const existing = await this.readQueueRawWithRetry(); const existingStatus = queueStatus(existing); const existingRoomCode = queueRoomCode(existing); if (existingStatus === 'in_room' && existingRoomCode === targetRoomCode) { await this.acceptQueueState(existing, this.resumeLifecycleEvents(existing, 'join_room')); return existing; } if (existingStatus === 'in_room') { if (!existingRoomCode) { throw new Error('Cannot switch rooms because the current room identity is unavailable.'); } await this.client.leaveRoom(); } else { this.requireInactiveParticipation(existing, `join room ${targetRoomCode}`); } let joined: Record; let serverStatus: ServerServiceStatus | undefined; try { const response = await this.client.joinRoom(targetRoomCode, { agentType: this.initialIntent.agentType, monitorStatus: this.initialIntent.monitorStatus, llmModel: this.initialIntent.llmModel, }); serverStatus = serverServiceStatusFromEnvelope(response); joined = normalizeClawclawQueueState(response); } catch (error) { return this.reconcileInitialRequest( 'join_room', error, (queue) => ( queueStatus(queue) === 'in_room' && queueRoomCode(queue) === targetRoomCode ), (queue) => [ this.sessionRecoveredEvent('join_room', queue), this.roomEntryEvent('room_joined', queue, { recovered: true }), ], ); } const queue = { status: 'in_room', mode: 'room', room_code: targetRoomCode, ...joined, }; await this.acceptQueueState( queue, [this.roomEntryEvent('room_joined', queue)], serverStatus, ); return queue; } private requireInactiveParticipation(queue: Record, operation: string): void { const status = queueStatus(queue); if (status === 'not_in_queue') return; if (status === 'allocated' && isRoomMode(queueMode(queue))) { throw new Error(`Cannot ${operation} while a room game is allocated.`); } if (isActiveClawclawQueueStatus(status)) { throw new Error(`Cannot ${operation} while participation status is ${status}.`); } throw new Error(`Cannot ${operation} because participation status is unknown.`); } private async reconcileInitialRequest( operation: string, originalError: unknown, accepted: (queue: Record) => boolean, lifecycleEvents: (queue: Record) => Record[], ): Promise> { const maintenance = serverServiceStatusFromApiError(originalError); // Invalid host declarations did not create a participation; do not adopt an unrelated one. if (isInvalidHostContextError(originalError)) throw originalError; if (maintenance) { await this.acceptServiceStatus(maintenance); throw originalError; } this.diagnostic('runtime.source.initial_request_reconcile', { operation, error: originalError instanceof Error ? originalError.message : String(originalError), }, 'warn'); let queue: Record; try { queue = await this.readQueueRawWithRetry(); } catch (reconcileError) { this.diagnostic('runtime.source.initial_request_reconcile_failed', { operation, error: reconcileError instanceof Error ? reconcileError.message : String(reconcileError), }, 'warn'); throw originalError; } if (!accepted(queue)) throw originalError; await this.acceptQueueState(queue, lifecycleEvents(queue)); this.diagnostic('runtime.source.initial_request_reconciled', { operation, status: queueStatus(queue), room_code: queueRoomCode(queue), game_id: clawclawQueueGameId(queue), }, 'info'); return queue; } private async readQueueWithRetry(): Promise> { const queue = await this.readQueueRawWithRetry(); await this.acceptQueueState(queue); return queue; } private async readQueueRawWithRetry(): Promise> { if (this.initialQueueState) { const queue = this.initialQueueState; this.initialQueueState = undefined; return structuredClone(queue); } let failures = 0; while (!this.abortController.signal.aborted) { try { return normalizeClawclawQueueState(await this.client.getQueueStatus('clawclaw')); } catch (error) { const maintenance = serverServiceStatusFromApiError(error); if (maintenance) { await this.acceptServiceStatus(maintenance); throw error; } failures += 1; this.currentTransport = 'lobby_http'; this.currentConnection = 'disconnected'; const message = error instanceof Error ? error.message : String(error); await this.submitCurrentState( 'transport_error', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http', [{ type: 'poll_error', message, consecutive_failures: failures, retrying: failures < this.maxConsecutivePollFailures, }], ); this.diagnostic('runtime.source.poll_failed', { consecutive_failures: failures, error: message, }, 'warn'); if (failures >= this.maxConsecutivePollFailures) throw error; await this.sleep(this.pollIntervalMs, this.abortController.signal); } } throw this.abortController.signal.reason ?? new Error('ClawClaw Source stopped.'); } private async acceptQueueState( queue: Record, lifecycleEvents: readonly Record[] = [], serverStatus?: ServerServiceStatus, ): Promise { const status = queueStatus(queue); const mode = queueMode(queue); const roomCode = queueRoomCode(queue); const gameId = clawclawQueueGameId(queue); const matching = status === 'queued' || status === 'already_in_queue' || status === 'allocating'; const exit = status === 'not_in_queue' && this.matchStartedAtMs !== undefined && !this.leaveRequested ? queueExitReceipt(queue.exit) : undefined; const genericRoomPoll = status === 'in_room' && mode === 'room'; if (mode && !(genericRoomPoll && isTrainingRoomMode(this.participationMode))) { this.participationMode = mode; this.requireRuntime().updateMode(mode); } const joined = matching && lifecycleEvents.some(event => event.type === 'joined'); if (matching) { if (joined) await timeStartup('match.activate_scope', () => this.ensureSegment('matching', mode)); else await this.ensureSegment('matching', mode); this.currentStage = 'matching'; } else if (status === 'in_room') { if (roomCode) this.requireRuntime().adoptResumeKey(roomCode); await this.ensureSegment('room', roomCode); this.currentStage = 'room'; } else if (status === 'allocated') { if (gameId && !isRoomMode(mode)) this.requireRuntime().adoptResumeKey(gameId); await this.ensureSegment('game', gameId); this.currentStage = 'loading'; } else if (status === 'not_in_queue') { this.currentStage = 'ended'; } else { this.currentStage = 'matching'; } this.currentTransport = 'lobby_http'; this.currentConnection = 'connected'; this.currentQueue = structuredClone(queue); this.currentRoom = undefined; this.hasFreshGameSnapshot = false; const events = [...lifecycleEvents]; if (matching) { events.push(...this.matchingLifecycleEvents(queue)); } else if (status === 'not_in_queue') { events.push(exit ? { type: 'match_exited', exit, ...(this.participationMode ? { game_mode: this.participationMode } : {}), } : { type: this.leaveRequested ? 'session_left' : 'not_in_queue', queue: structuredClone(queue), }); this.resetMatchingLifecycle(); } else if (status === 'in_room' || status === 'allocated') { this.resetMatchingLifecycle(); } const stop = joined ? startupSpan('match.submit_source') : undefined; await this.submitCurrentState( status === 'not_in_queue' ? 'ending' : matching ? 'matching_poll' : 'reconcile', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http', events, serverStatus && this.shouldEmitServiceStatus(serverStatus) ? [serviceStatusEvent(serverStatus)] : [], ); stop?.(); } private shouldEmitServiceStatus(status: ServerServiceStatus): boolean { const signature = serviceStatusSignature(status); const previous = this.lastServiceStatusSignature; this.lastServiceStatusSignature = signature; if (previous === signature) return false; return status.service_status !== 'available' || previous !== undefined; } private async acceptServiceStatus(status: ServerServiceStatus): Promise { if (!this.shouldEmitServiceStatus(status)) return; this.currentTransport = 'lobby_http'; this.currentConnection = 'connected'; await this.submitCurrentState( 'backend_event', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http', [], [serviceStatusEvent(status)], ); } private joinedEvent( queue: Record, flags: Record = {}, ): Record { const url = spectateUrl(queue); return { ...structuredClone(queue), queue: structuredClone(queue), ...(url ? { url } : {}), ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}), ...flags, type: 'joined', }; } private roomEntryEvent( type: 'room_created' | 'room_joined', queue: Record, flags: Record = {}, ): Record { const url = spectateUrl(queue); return { ...structuredClone(queue), ...(url ? { spectate_url: url } : {}), game_mode: queueMode(queue) ?? 'room', ...flags, type, }; } private sessionRecoveredEvent( operation: string, queue: Record, ): Record { return { type: 'session_recovered', operation, initial_request_confirmation: 'missing_or_failed', queue_reconciliation: 'active_participation_confirmed', local_history_completeness: 'possibly_incomplete', status: queueStatus(queue), ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}), ...(queueRoomCode(queue) ? { room_code: queueRoomCode(queue) } : {}), ...(clawclawQueueGameId(queue) ? { game_id: clawclawQueueGameId(queue) } : {}), }; } private async submitCompetitionStartFailure(error: unknown): Promise { const code = apiErrorCode(error); let competition: Record = { status: 'unavailable', active: null, is_open: null, }; if (this.client.getCompetitionStatus) { try { competition = normalizeCompetitionStatusResponse( await this.client.getCompetitionStatus(), ); } catch (statusError) { competition = { ...competition, error: serializeError(statusError), }; } } const serialized = serializeError(error); this.currentStage = 'ended'; this.currentTransport = 'lobby_http'; this.currentConnection = 'disconnected'; await this.submitCurrentState( 'ending', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http', [{ type: 'game_start_failed', game_mode: 'competition', exit_reason: competitionExitReason(code), error: { ...serialized, code: code ?? 'REQUEST_FAILED', message: apiErrorMessage(error), }, competition, }], ); } private resumeLifecycleEvents( queue: Record, source: ClawclawSourceStartIntent['kind'], ): Record[] { const status = queueStatus(queue); if (!isActiveClawclawQueueStatus(status)) return []; const resumed = { type: 'session_resumed', source, status, ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}), ...(queueRoomCode(queue) ? { room_code: queueRoomCode(queue) } : {}), ...(clawclawQueueGameId(queue) ? { game_id: clawclawQueueGameId(queue) } : {}), }; const roomParticipation = status === 'in_room' || (status === 'allocated' && isRoomMode(queueMode(queue))); return [ resumed, roomParticipation ? this.roomEntryEvent('room_joined', queue, { resumed: true }) : this.joinedEvent(queue, { resumed: true }), ]; } private matchingLifecycleEvents(queue: Record): Record[] { const now = this.clock(); const events: Record[] = []; if (this.matchStartedAtMs === undefined) { this.matchStartedAtMs = now; events.push({ type: 'match_start', ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}), }); } const waitedSecs = Math.max(0, Math.floor((now - this.matchStartedAtMs) / 1_000)); if ( this.lastMatchWaitingAtMs === undefined || now - this.lastMatchWaitingAtMs >= this.matchWaitingIntervalMs ) { this.lastMatchWaitingAtMs = now; events.push({ type: 'match_waiting', waited_secs: waitedSecs, ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}), }); } if (!this.matchTimedOut && now - this.matchStartedAtMs >= this.matchTimeoutMs) { this.matchTimedOut = true; events.push({ type: 'match_timeout', waited_secs: waitedSecs, queue: structuredClone(queue), ...(queueMode(queue) ? { game_mode: queueMode(queue) } : {}), }); } return events; } private resetMatchingLifecycle(): void { this.matchStartedAtMs = undefined; this.lastMatchWaitingAtMs = undefined; this.matchTimedOut = false; } private async runRoom(queue: Record): Promise { await this.stopGameTransport('manual'); const roomCode = queueRoomCode(queue); if (roomCode) this.requireRuntime().adoptResumeKey(roomCode); await this.ensureSegment('room', roomCode); this.currentStage = 'room'; this.currentTransport = 'room_ws'; this.currentConnection = 'disconnected'; this.currentQueue = structuredClone(queue); await this.submitCurrentState('reconcile', CLAWCLAW_ROOM_WS_SOURCE.sourceId, 'room-pending'); const transport = this.createRoomTransport({ url: this.client.lobbyAgentWsUrl, apiKey: this.profile.apiKey, hostContext: this.client.lobbyHostContext, webSocketFactory: this.roomWebSocketFactory, onOpened: async (connectionId, reconnected) => { this.activeRoomConnectionId = connectionId; this.requireRuntime().bindConnection(CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId); this.currentTransport = 'room_ws'; this.currentConnection = 'connected'; await this.submitCurrentState( 'control', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, [{ type: 'room_attached', reconnected }], ); }, onLiveness: (connectionId, atMs) => { this.requireRuntime().connectionLiveness(CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, atMs); }, onConnectionChanged: async (connectionId, state) => { this.requireRuntime().connectionChanged( CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, state, ); if (this.activeRoomConnectionId !== connectionId) return; this.currentConnection = state; await this.submitCurrentState('control', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId); }, onClosed: (connectionId, info) => this.handleRoomClose(connectionId, info), onFrame: (frame) => this.acceptRoomFrame(frame.snapshot, frame.type, frame.data, frame.meta, frame.terminalPhase), onDiagnostic: (name, attributes) => this.diagnostic(name, attributes, 'warn'), reconcileAfterMs: this.roomAttachReconcileAfterMs, }); this.roomTransport = transport; await transport.start(); const outcome = await transport.waitForOutcome(); await transport.flush(); if (this.roomTransport === transport) this.roomTransport = undefined; this.activeRoomConnectionId = undefined; if (outcome.reason === 'game_started') { this.applyGameRoute(outcome.event); const roomMode = isRoomMode(this.participationMode) ? this.participationMode : 'room'; return { kind: 'continue', queue: { status: 'allocated', mode: roomMode, room_code: outcome.roomCode ?? roomCode, participation: queue.participation ?? null, ...outcome.event, }, }; } if (outcome.reason === 'self_left') return { kind: 'complete', completion: { reason: 'left' } }; if (outcome.reason === 'room_destroyed') { return { kind: 'complete', completion: { reason: 'not_participating' } }; } if (outcome.reason === 'maintenance') { return { kind: 'complete', completion: { reason: 'maintenance' } }; } if (outcome.reason === 'replaced') return { kind: 'complete', completion: { reason: 'replaced' } }; if (outcome.reason === 'shutdown' || outcome.reason === 'manual' || outcome.reason === 'normal') { return { kind: 'complete', completion: { reason: 'stopped' } }; } if (outcome.reason === 'fatal' || outcome.reason === 'error') { return { kind: 'complete', completion: { reason: 'error', error: outcome.error } }; } await this.reconcileBackoff('room_ws', outcome.reason); return { kind: 'continue' }; } private async runGame(queue: Record): Promise { await this.stopRoomTransport('manual'); this.applyGameRoute(normalizeClawclawQueueState(queue)); const mode = queueMode(queue); if (mode) { this.participationMode = mode; this.requireRuntime().updateMode(mode); } const gameId = clawclawQueueGameId(queue); this.client.setExpectedGameSyncGameId(gameId); if (gameId && !isRoomMode(mode)) this.requireRuntime().adoptResumeKey(gameId); await this.ensureSegment('game', gameId); this.currentStage = 'loading'; this.currentTransport = 'game_ws'; this.currentConnection = 'disconnected'; this.currentQueue = structuredClone(queue); this.currentRoom = undefined; this.hasFreshGameSnapshot = false; await this.submitCurrentState('reconcile', CLAWCLAW_GAME_WS_SOURCE.sourceId, 'game-pending'); const transport = this.createGameTransport({ client: this.client, onFrame: (frame) => this.acceptGameFrame(frame), onConnectionOpened: async (connectionId, _reconnected) => { this.activeGameConnectionId = connectionId; this.requireRuntime().bindConnection(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId); this.currentTransport = 'game_ws'; // A physical socket is not action-ready until snapshot/resume finishes. this.currentConnection = 'reconnecting'; await this.submitCurrentState( 'control', CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, [], ); }, onLiveness: (connectionId, atMs) => { this.requireRuntime().connectionLiveness(CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, atMs); }, onClose: (connectionId, info) => this.handleGameClose(connectionId, info), onParticipationProbe: (participation) => this.handleGameParticipationProbe( gameId, participation, ), onConnectAttemptFailed: (error) => { this.diagnostic('runtime.source.connect_failed', { transport: 'game_ws', error: error instanceof Error ? error.message : String(error), }, 'warn'); }, onProtocolError: (info) => { this.diagnostic('runtime.input.rejected', { transport: 'game_ws', connection_id: info.connectionId, reason: info.reason, ...(info.details ? { details: info.details } : {}), }, 'warn'); }, onRecoveryStarted: (info) => this.handleGameRecoveryStarted(info), }); this.gameTransport = transport; await transport.start(); const attachOutcome = await this.waitForGameAttach(transport); const outcome = attachOutcome ?? await transport.waitForOutcome(); await transport.flush(); if (this.gameTransport === transport) this.gameTransport = undefined; this.activeGameConnectionId = undefined; const roomGame = isRoomMode(queueMode(queue)); if (outcome.reason === 'game_over' || outcome.reason === 'user_left') { if (roomGame) return this.waitForRoomReturn(outcome.reason, queue); return { kind: 'complete', completion: { reason: outcome.reason === 'game_over' ? 'game_over' : 'left' }, }; } if (outcome.reason === 'replaced') { this.activeGameConnectionId = undefined; return { kind: 'complete', completion: { reason: 'replaced' } }; } if (outcome.reason === 'shutdown' || outcome.reason === 'manual') { this.activeGameConnectionId = undefined; return { kind: 'complete', completion: { reason: 'stopped' } }; } if (outcome.reason === 'error') { this.diagnostic('runtime.source.game_transport_failed', { error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error), }, 'warn'); return { kind: 'complete', completion: { reason: 'error', error: outcome.error ?? new Error('GameSync transport failed.'), }, }; } if (outcome.reason === 'reconcile' && outcome.queueState) { const reconciledQueue = normalizeClawclawQueueState(outcome.queueState); await this.acceptQueueState(reconciledQueue); const status = queueStatus(reconciledQueue); if (status === 'not_in_queue') { return { kind: 'complete', completion: { reason: this.leaveRequested ? 'left' : 'not_participating' }, }; } return { kind: 'continue', queue: reconciledQueue }; } await this.reconcileBackoff('game_ws', outcome.reason); return { kind: 'continue' }; } private async handleGameParticipationProbe( gameId: string | undefined, value: Record, ): Promise { if (!gameId) return; const queue = normalizeClawclawQueueState(value); const status = queueStatus(queue); if (status !== 'not_in_queue' && status !== 'in_room') return; if (this.leaveRequested) return 'reconcile'; let settlement: Record | undefined; let settlementGameId: string | undefined; let settlementErrorCode: string | undefined; for (let attempt = 1; attempt <= GAME_TERMINAL_SETTLEMENT_ATTEMPTS; attempt += 1) { try { const candidate = unwrapData(await this.client.getSettlement()); if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) { settlementGameId = typeof candidate.game_id === 'string' ? candidate.game_id : undefined; if (settlementGameId === gameId) { settlement = structuredClone(candidate); break; } settlementErrorCode = settlementGameId ? 'SETTLEMENT_GAME_ID_MISMATCH' : 'SETTLEMENT_GAME_ID_MISSING'; } else { settlementErrorCode = 'SETTLEMENT_INVALID'; } } catch (error) { settlementErrorCode = apiErrorCode(error) ?? 'SETTLEMENT_UNAVAILABLE'; } if (attempt < GAME_TERMINAL_SETTLEMENT_ATTEMPTS) { await this.sleep(GAME_TERMINAL_SETTLEMENT_RETRY_MS, this.abortController.signal); } } if (settlement) { await this.submitRecoveredGameOver(gameId, queue, settlement); return 'game_over'; } await this.submitMissingGameTerminal( gameId, queue, settlementErrorCode ?? 'SETTLEMENT_UNAVAILABLE', settlementGameId, ); return 'reconcile'; } private async submitRecoveredGameOver( gameId: string, queue: Record, settlement: Record, ): Promise { const receivedAt = new Date().toISOString(); const sourceSeq = `settlement:${gameId}`; const winningFaction = typeof settlement.winning_faction === 'string' ? settlement.winning_faction : undefined; const winReason = typeof settlement.win_reason === 'string' ? settlement.win_reason : undefined; this.currentStage = 'ended'; this.currentTransport = 'lobby_http'; this.currentConnection = 'connected'; this.currentQueue = structuredClone(queue); await this.submit({ scope: this.requireRuntime().currentSegment().scope, sourceId: CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, connectionId: 'lobby-http', sourceKey: `game-terminal-recovered:${gameId}`, sourceSeq, state: this.runtimeState('ending'), events: [{ type: 'game_over_recovered', producer: 'local_synth', payload: { game_id: gameId, recovered: true, recovery_source: 'settlement_http', ...(winningFaction ? { winner: winningFaction, winning_faction: winningFaction } : {}), ...(winReason ? { reason: winReason, win_reason: winReason } : {}), ...(settlement.your_result && typeof settlement.your_result === 'object' ? { your_result: structuredClone(settlement.your_result) } : {}), ...(this.participationMode ? { game_mode: this.participationMode } : {}), }, sourceEventId: `game-terminal-recovered:${gameId}`, sourceSeq, receivedAt, }], completeness: 'complete', receivedAt, }); } private async submitMissingGameTerminal( gameId: string, queue: Record, settlementErrorCode: string, settlementGameId?: string, ): Promise { const receivedAt = new Date().toISOString(); const sourceSeq = `terminal-missing:${gameId}`; this.currentStage = 'ended'; this.currentTransport = 'lobby_http'; this.currentConnection = 'connected'; this.currentQueue = structuredClone(queue); await this.submit({ scope: this.requireRuntime().currentSegment().scope, sourceId: CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, connectionId: 'lobby-http', sourceKey: `game-terminal-missing:${gameId}`, sourceSeq, state: this.runtimeState('ending'), events: [{ type: 'game_terminal_missing', producer: 'local_synth', payload: { game_id: gameId, queue_status: queueStatus(queue), settlement_error_code: settlementErrorCode, ...(settlementGameId ? { settlement_game_id: settlementGameId } : {}), ...(this.participationMode ? { game_mode: this.participationMode } : {}), }, sourceEventId: `game-terminal-missing:${gameId}`, sourceSeq, receivedAt, }], completeness: 'complete', receivedAt, }); } private async waitForGameAttach( transport: ClawclawGameTransportPort, ): Promise { const outcomePromise = transport.waitForOutcome(); let timeout: ReturnType | undefined; const timeoutPromise = new Promise((resolve) => { timeout = setTimeout(() => resolve({ kind: 'timeout' }), this.gameFirstStateTimeoutMs); timeout.unref?.(); }); const outcomeGate = outcomePromise.then((outcome) => ({ kind: 'outcome', outcome })); const stateGate: Promise = transport .waitForFirstState({ signal: this.abortController.signal }) .then( () => ({ kind: 'attached' as const }), () => outcomeGate, ); const gate = await Promise.race([stateGate, outcomeGate, timeoutPromise]); if (timeout) clearTimeout(timeout); if (gate.kind === 'attached') return undefined; if (gate.kind === 'outcome') return gate.outcome; this.diagnostic('runtime.source.attach_timeout', { transport: 'game_ws', timeout_ms: this.gameFirstStateTimeoutMs, game_id: clawclawQueueGameId(this.currentQueue), }, 'warn'); await this.submitCurrentState( 'transport_error', CLAWCLAW_GAME_WS_SOURCE.sourceId, this.activeGameConnectionId ?? 'game-pending', [{ type: 'game_start_failed', code: 'GAME_STATE_TIMEOUT', message: `Game stream did not provide its first State within ${this.gameFirstStateTimeoutMs}ms.`, timeout_ms: this.gameFirstStateTimeoutMs, ...(clawclawQueueGameId(this.currentQueue) ? { game_id: clawclawQueueGameId(this.currentQueue) } : {}), }], ); await transport.stop('reconcile'); return outcomePromise; } private async waitForRoomReturn( endedReason: 'game_over' | 'user_left', previousQueue: Record, ): Promise { this.currentStage = 'settlement'; this.currentTransport = 'lobby_http'; this.currentConnection = 'connected'; this.currentQueue = structuredClone(previousQueue); this.currentRoom = undefined; this.hasFreshGameSnapshot = false; await this.submitCurrentState( 'reconcile', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http', [{ type: 'room_returning_to_lobby', reason: endedReason, ...(clawclawQueueGameId(previousQueue) ? { game_id: clawclawQueueGameId(previousQueue) } : {}), ...(queueRoomCode(previousQueue) ? { room_code: queueRoomCode(previousQueue) } : {}), }], ); while (!this.abortController.signal.aborted) { await this.sleep(this.roomReturnPollMs, this.abortController.signal); let queue: Record; try { queue = await this.readQueueRawWithRetry(); } catch (error) { const message = error instanceof Error ? error.message : String(error); await this.submitCurrentState( 'transport_error', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http', [{ type: 'room_lobby_reconnect_failed', message, error: { message }, }], ); throw error; } if (queueStatus(queue) === 'in_room') { await this.acceptQueueState(queue); return { kind: 'continue', queue }; } if (queueStatus(queue) !== 'allocated') { await this.acceptQueueState(queue, [{ type: 'room_lobby_missing', queue: structuredClone(queue), }]); return { kind: 'complete', completion: { reason: 'not_participating' } }; } this.currentStage = 'settlement'; this.currentTransport = 'lobby_http'; this.currentConnection = 'connected'; this.currentQueue = structuredClone(queue); this.hasFreshGameSnapshot = false; await this.submitCurrentState( 'reconcile', CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId, 'lobby-http', ); this.diagnostic('runtime.source.room_return_pending', { game_id: clawclawQueueGameId(queue), }); } throw this.abortController.signal.reason ?? new Error('ClawClaw Source stopped.'); } private async acceptGameFrame(frame: WsInputFrame): Promise { const sourceStartedAtMs = Date.now(); const segment = this.requireRuntime().currentSegment(); if ( frame.meta.origin === 'snapshot' && segment.kind === 'game' && segment.identity && segment.identity !== frame.meta.gameId ) { this.diagnostic('runtime.input.rejected', { transport: 'game_ws', reason: 'game_id_mismatch', expected_game_id: segment.identity, received_game_id: frame.meta.gameId, }, 'error'); return 'error'; } const rawState: unknown = frame.state; if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) { this.diagnostic('runtime.source.frame_rejected', { source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId, source_seq: frame.meta.sourceSeq, error_code: 'GAME_SYNC_STATE_INVALID', reason: 'state_not_object', }, 'error'); return; } const gameState = rawState as Record; const tick = frame.meta.domainTick; const stateTick = gameState.tick; if ( !Number.isInteger(tick) || tick < 0 || !Number.isInteger(stateTick) || Number(stateTick) < 0 || Number(stateTick) !== tick ) { this.diagnostic('runtime.source.frame_rejected', { source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId, source_seq: frame.meta.sourceSeq, error_code: 'GAME_SYNC_TICK_INVALID', reason: Number.isInteger(tick) && Number.isInteger(stateTick) ? 'tick_mismatch' : 'tick_missing_or_invalid', frame_tick: tick, state_tick: stateTick, }, 'error'); return; } const previousState = this.latestFreshGameState; const missingFields = new Set(); if (!Object.prototype.hasOwnProperty.call(gameState, 'phase')) missingFields.add('phase'); if (previousState) { for (const field of Object.keys(previousState)) { if (!Object.prototype.hasOwnProperty.call(gameState, field)) missingFields.add(field); } } if (missingFields.size > 0) { this.diagnostic('runtime.source.state_degraded', { source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId, source_seq: frame.meta.sourceSeq, error_code: 'GAME_SYNC_STATE_FIELDS_MISSING', missing_fields: [...missingFields].sort(), }, 'warn'); } let acceptedStage: ClawclawRuntimeStage | undefined; const acceptance = await this.enqueueInputIf(() => { if (this.currentStage === 'ended') return null; try { const scope = this.requireConnectionScope( CLAWCLAW_GAME_WS_SOURCE.sourceId, frame.meta.connectionId, ); const backendEvents = this.sourceEvents( frame.events, frame.meta, CLAWCLAW_GAME_WS_SOURCE.sourceId, undefined, gameState, ); const recoveryIdentity = `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:${frame.meta.connectionId}`; const recoveryEvents = frame.meta.origin === 'resume' || frame.meta.snapshotFallback ? this.localEvents([{ type: 'game_stream_reconnected', recovery: frame.meta.origin, replayed_event_count: frame.events.length, }], `${recoveryIdentity}:recovered`, frame.meta.receivedAt) : []; const events = [...backendEvents, ...recoveryEvents]; this.currentTransport = 'game_ws'; this.currentConnection = 'connected'; acceptedStage = clawclawStageFromGameEvents( frame.events, clawclawStageFromGameState(gameState), ); return { scope, sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId: frame.meta.connectionId, // A resume barrier has no sequence of its own. In the valid zero-replay // case its to_seq equals the last update accepted before disconnect, so // include the new connection identity to avoid retry-conflicting with // that earlier runtime input while preserving the backend sequence. sourceKey: frame.meta.origin === 'resume' ? `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:resume:${frame.meta.connectionId}` : `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`, sourceSeq: `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`, domainTick: tick, state: this.gameRuntimeState( acceptedStage, acceptedStage === 'ended' ? 'ending' : 'game_snapshot', { status: 'fresh', state: structuredClone(gameState), origin: frame.meta.origin }, ), events, completeness: frame.meta.snapshotFallback ? 'best_effort' : 'complete', receivedAt: frame.meta.receivedAt, }; } catch (error) { this.diagnostic('runtime.source.frame_rejected', { source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId, source_seq: frame.meta.sourceSeq, error_code: 'GAME_SYNC_FRAME_PROJECTION_FAILED', error_name: error instanceof Error ? error.name : 'Error', error: serializeError(error), }, 'error'); return null; } }, () => { this.currentStage = acceptedStage!; this.currentQueue = undefined; this.currentRoom = undefined; this.resetReconcileBackoff('game_ws'); this.hasFreshGameSnapshot = true; this.latestFreshGameState = structuredClone(gameState); this.latestFreshGameTick = tick; this.gameConnectionsWithState.add(frame.meta.connectionId); }); if (!acceptance) return; const ingress = frame.meta.ingress; if (ingress) { const acceptedAtMs = Date.now(); this.diagnostic('runtime.source.frame_admitted', { epoch_seq: acceptance.epoch.epochSeq, source_seq: frame.meta.sourceSeq, domain_tick: frame.meta.domainTick, transport_generation: ingress.transportGeneration, socket_received_at_ms: ingress.socketReceivedAtMs, decoded_at_ms: ingress.decodedAtMs, worker_posted_at_ms: ingress.workerPostedAtMs, owner_received_at_ms: ingress.ownerReceivedAtMs, source_started_at_ms: sourceStartedAtMs, source_accepted_at_ms: acceptedAtMs, decode_ms: ingress.decodeDurationMs, worker_handoff_ms: ingress.ownerReceivedAtMs === undefined || ingress.workerPostedAtMs === undefined ? undefined : Math.max(0, ingress.ownerReceivedAtMs - ingress.workerPostedAtMs), source_queue_ms: ingress.ownerReceivedAtMs === undefined ? undefined : Math.max(0, sourceStartedAtMs - ingress.ownerReceivedAtMs), source_admission_ms: Math.max(0, acceptedAtMs - sourceStartedAtMs), receive_to_admitted_ms: Math.max(0, acceptedAtMs - ingress.socketReceivedAtMs), outstanding_frames: ingress.outstandingFrames, outstanding_bytes: ingress.outstandingBytes, }); } if (typeof frame.meta.sourceSeq !== 'number') { throw new TypeError('GameSync frame sourceSeq must be numeric.'); } this.client.acknowledgeGameSync( frame.meta.ackToken, frame.meta.origin === 'snapshot' || frame.meta.origin === 'resume', ); if (acceptedStage === 'ended') return 'game_over'; } private async handleGameRecoveryStarted(info: WsRecoveryStartedInfo): Promise { if (this.activeGameConnectionId !== info.connectionId) return; this.requireRuntime().connectionChanged( CLAWCLAW_GAME_WS_SOURCE.sourceId, info.connectionId, 'reconnecting', ); this.currentTransport = 'game_ws'; this.currentConnection = 'reconnecting'; this.diagnostic('runtime.source.game_stream_recovery_started', { connection_id: info.connectionId, reason: info.reason, expected_seq: info.expectedSeq, received_seq: info.receivedSeq, }, 'warn'); await this.submitCurrentState( 'transport_error', CLAWCLAW_GAME_WS_SOURCE.sourceId, info.connectionId, ); } private async acceptRoomFrame( snapshot: RoomSnapshot | null, type: string, data: Record, meta: RoomFrameMeta, terminalPhase?: 'room_left', ): Promise { const previousRoomType = this.currentRoom?.room?.room_type; if (snapshot) { const roleConfig = Object.prototype.hasOwnProperty.call(snapshot, 'role_config') ? snapshot.role_config : this.trainingRoomControlOverlay.role_config; snapshot = type === 'room.snapshot' ? { ...this.trainingRoomControlOverlay, ...snapshot, ...(roleConfig !== undefined ? { role_config: roleConfig } : {}), } : { ...snapshot, ...this.trainingRoomControlOverlay }; } const currentRoomType = snapshot?.room_type; const roomTypeChangedElsewhere = type === 'room.snapshot' && data.sync_reason === 'room_type_changed' && isTrainingRoomMode(previousRoomType) && isTrainingRoomMode(currentRoomType) && previousRoomType !== currentRoomType && this.pendingTrainingRoomType !== currentRoomType; if ( type === 'room.snapshot' && data.sync_reason === 'room_type_changed' && isTrainingRoomMode(currentRoomType) ) { this.trainingRoomControlOverlay.room_type = currentRoomType; } const roomCode = snapshot?.room_code; if (roomCode) { this.requireRuntime().adoptResumeKey(roomCode); const current = this.requireRuntime().currentSegment(); if (current.kind !== 'room' || current.identity !== roomCode) { await this.ensureSegment('room', roomCode); this.requireRuntime().rebindConnectionScope( CLAWCLAW_ROOM_WS_SOURCE.sourceId, meta.connectionId, ); this.activeRoomConnectionId = meta.connectionId; } } const scope = this.requireConnectionScope(CLAWCLAW_ROOM_WS_SOURCE.sourceId, meta.connectionId); const hadSnapshot = this.roomConnectionsWithSnapshot.has(meta.connectionId); this.currentTransport = 'room_ws'; this.currentConnection = 'connected'; this.currentQueue = undefined; if (snapshot) { if (type === 'room.snapshot') this.resetReconcileBackoff('room_ws'); const roomMode = isTrainingRoomMode(snapshot.room_type) ? snapshot.room_type : 'room'; this.participationMode = roomMode; this.requireRuntime().updateMode(roomMode); this.currentRoom = projectClawclawRoomState(snapshot, { profileName: this.profile.agentName, receivedAt: meta.receivedAt, }); } else if (terminalPhase === 'room_left') { this.currentRoom = undefined; this.trainingRoomControlOverlay = {}; } if (terminalPhase === 'room_left') this.currentStage = 'ended'; else if (type === 'room.game_started' || snapshot?.status === 'playing') this.currentStage = 'loading'; else this.currentStage = 'room'; let rawEvents: Record[] = type === 'room.snapshot' ? roomTypeChangedElsewhere ? [{ type: 'room.type_changed', room_code: snapshot?.room_code, previous_room_type: previousRoomType, room_type: currentRoomType, sync_reason: 'room_type_changed', }] : [] : [{ type, ...data }]; if (type === 'service_status') { const serverStatus = parseServerServiceStatus(data); rawEvents = serverStatus && this.shouldEmitServiceStatus(serverStatus) ? [serviceStatusEvent(serverStatus)] : []; } await this.submit({ scope, sourceId: CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId: meta.connectionId, sourceKey: this.physicalSourceKey('room', meta), sourceSeq: `${meta.connectionId}:${String(meta.sourceSeq)}`, state: this.runtimeState(this.currentStage === 'ended' ? 'ending' : 'room_update'), events: this.sourceEvents(rawEvents, meta, CLAWCLAW_ROOM_WS_SOURCE.sourceId), completeness: meta.replay || !hadSnapshot ? 'best_effort' : 'complete', receivedAt: meta.receivedAt, }); if (snapshot) this.roomConnectionsWithSnapshot.add(meta.connectionId); } private async handleGameClose( connectionId: string, info: WsCloseInfo, ): Promise { const reason = (info.reason ?? '').trim().toLowerCase(); const userLeft = (info.code === 1000 && reason === 'left game') || info.code === 4001; const connectionReplaced = info.code === 4002 && reason === 'game_sync_replaced'; const fatalProtocolClose = info.code === 1002 || info.code === 4003 || (info.code === 4002 && !connectionReplaced); const nextConnection: ClawclawRuntimeConnection = ( userLeft || connectionReplaced || fatalProtocolClose ) ? 'disconnected' : 'reconnecting'; this.requireRuntime().connectionChanged( CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, nextConnection, ); this.currentTransport = 'game_ws'; this.currentConnection = nextConnection; if (userLeft) this.currentStage = 'ended'; const connectionEvents = userLeft ? [{ type: 'user_left_game', ...(this.participationMode ? { game_mode: this.participationMode } : {}), }] : connectionReplaced ? [] : [{ type: 'game_stream_disconnected', close_code: info.code, close_reason: info.reason, recoverable: !fatalProtocolClose, }]; await this.submitCurrentState( userLeft ? 'ending' : 'transport_error', CLAWCLAW_GAME_WS_SOURCE.sourceId, connectionId, connectionEvents, ); if (userLeft) return 'user_left'; // origin/dev uses 4000 when the routed GameServer no longer has an active // game for this player. Reconcile lobby participation instead of opening // the same terminal GameSync endpoint again. if (info.code === 4000 || info.code === 1000) return 'reconcile'; if (connectionReplaced) return 'replaced'; if (info.code === 4002) return 'error'; if (info.code === 4003 || info.code === 1002) return 'error'; this.diagnostic('runtime.source.input_gap', { transport: 'game_ws', connection_id: connectionId, close_code: info.code, close_reason: info.reason, recoverable: true, }, 'warn'); } private classifyRoomClose(code: number | undefined, reason: string): ClawclawRoomCloseDecision { if (code === 4002) return 'replaced'; if (code === 1000) return 'normal'; if (code === 4005) return 'room_destroyed'; if (code === 4006 || /service_maintenance/i.test(reason)) return 'maintenance'; if (code === 4001) return 'fatal'; if (code === 4003) return 'fatal'; if (code === 4004) return 'reconcile'; if (/not in room|already left/i.test(reason)) return 'reconcile'; return 'retry'; } private async handleRoomClose( connectionId: string, info: ClawclawRoomCloseInfo, ): Promise { const decision = this.classifyRoomClose(info.code, info.reason); if (decision === 'replaced') { this.currentConnection = 'disconnected'; await this.submitCurrentState('control', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, [{ type: 'lobby_connection_replaced', route: '/agent/ws', close_code: 4002, reason: info.reason, retryable: false, }]); } if (decision === 'room_destroyed') { this.requireRuntime().connectionChanged( CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, 'disconnected', ); this.currentTransport = 'room_ws'; this.currentConnection = 'disconnected'; this.currentStage = 'ended'; this.currentQueue = undefined; this.currentRoom = undefined; await this.submitCurrentState( 'ending', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, [{ type: 'room_destroyed', close_code: info.code, reason: info.reason || 'room_destroyed', }], ); return decision; } if ( info.reason === 'heartbeat_timeout' && this.activeRoomConnectionId === connectionId ) { this.currentTransport = 'room_ws'; this.currentConnection = 'reconnecting'; await this.submitCurrentState( 'transport_error', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, [{ type: 'room_ping_timeout', recoverable: true }], ); } return decision; } private async handleControlIntent( intent: ClawclawSourceControlIntent, ): Promise | void> { await this.submitControlState(intent); if (intent.kind === 'stop') { if (!this.abortController.signal.aborted) { this.abortController.abort(new Error('source_stop_intent')); } await Promise.allSettled([ this.gameTransport?.stop('manual'), this.roomTransport?.stop('manual'), ].filter((value): value is Promise => value !== undefined)); return; } if (intent.kind === 'start_room') { if (this.currentStage !== 'room') throw new Error('start_room requires the room stage.'); try { const result = await this.client.startRoom(); const serverStatus = serverServiceStatusFromEnvelope(result); if (serverStatus) await this.acceptServiceStatus(serverStatus); return result; } catch (error) { const maintenance = serverServiceStatusFromApiError(error); if (maintenance) await this.acceptServiceStatus(maintenance); throw error; } } if (intent.kind === 'training_mode') { this.requireTrainingRoomStage(intent.kind); this.pendingTrainingRoomType = intent.roomType; try { const result = await this.client.setTrainingRoomMode(intent.roomType); const failure = businessFailureFromResult(result, 'Failed to change training mode.'); if (failure) throw leaveFailureError(failure); await this.acceptTrainingRoomControlResult(result); return result; } finally { if (this.pendingTrainingRoomType === intent.roomType) { this.pendingTrainingRoomType = undefined; } } } if (intent.kind === 'training_role_lock') { this.requireTrainingRoomStage(intent.kind); const result = await this.client.setTrainingRoleLock(trainingCharacterId(intent.role)); const failure = businessFailureFromResult(result, 'Failed to lock the training role.'); if (failure) throw leaveFailureError(failure); await this.acceptTrainingRoomControlResult(result); return result; } if (intent.kind === 'training_role_clear') { this.requireTrainingRoomStage(intent.kind); const result = await this.client.clearTrainingRoleLock(); const failure = businessFailureFromResult(result, 'Failed to clear the training role lock.'); if (failure) throw leaveFailureError(failure); await this.acceptTrainingRoomControlResult(result, { roleConfigCleared: true }); return result; } this.leaveRequested = true; try { if ( this.currentTransport === 'game_ws' || this.currentStage === 'game' || this.currentStage === 'meeting' || this.currentStage === 'settlement' || this.currentStage === 'loading' ) { const result = await this.client.leaveGame(); const failure = businessFailureFromResult(result, 'Failed to leave the active game.'); if (failure) throw leaveFailureError(failure); } else if (this.currentStage === 'room') { const result = await this.client.leaveRoom(); const failure = businessFailureFromResult(result, 'Failed to leave the room.'); if (failure) throw leaveFailureError(failure); } else { const result = await this.client.leaveQueue('clawclaw'); const outcome = classifyLeaveQueueResult(result); if (!outcome.remoteLeft) throw leaveFailureError(outcome.failure!); } } catch (error) { this.leaveRequested = false; const message = error instanceof Error ? error.message : String(error); await this.submitCurrentState( 'control', CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId, this.activeGameConnectionId ?? this.activeRoomConnectionId ?? 'local-control', [{ type: 'quit_failed', error: { message }, stage: this.currentStage, transport: this.currentTransport, }], ); throw error; } } private requireTrainingRoomStage(operation: string): void { const roomType = this.currentRoom?.room?.room_type; if (this.currentStage !== 'room' || !isTrainingRoomMode(roomType)) { throw new Error(`${operation} requires an active training room.`); } } private async acceptTrainingRoomControlResult( result: Record, options: { roleConfigCleared?: boolean } = {}, ): Promise { const update = unwrapData(result); if (!update || typeof update !== 'object' || Array.isArray(update)) return; const current = this.currentRoom?.room; const base = current && typeof current === 'object' && !Array.isArray(current) ? current as Record : {}; const { member_count: _memberCount, is_owner: _isOwner, ready_to_start: _readyToStart, role_lock_character_id: _roleLockCharacterId, role_lock: _roleLock, ...baseSnapshot } = base; const snapshot: RoomSnapshot = { ...baseSnapshot, ...update, ...(options.roleConfigCleared ? { role_config: null } : {}), ...(baseSnapshot.my_seat !== undefined && update.my_seat === undefined ? { my_seat: baseSnapshot.my_seat } : {}), }; if (options.roleConfigCleared) this.trainingRoomControlOverlay.role_config = null; for (const key of ['room_type', 'role_config'] as const) { if (Object.prototype.hasOwnProperty.call(update, key)) { this.trainingRoomControlOverlay[key] = update[key] === undefined ? undefined : structuredClone(update[key]); } } const roomMode = isTrainingRoomMode(snapshot.room_type) ? snapshot.room_type : undefined; if (roomMode) { this.participationMode = roomMode; this.requireRuntime().updateMode(roomMode); } this.currentQueue = undefined; this.currentRoom = projectClawclawRoomState(snapshot, { profileName: this.profile.agentName, receivedAt: new Date().toISOString(), }); await this.submitCurrentState( 'control', CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId, this.activeRoomConnectionId ?? 'local-control', ); } private async reconcileBackoff( transport: ReconciledTransport, reason: string, ): Promise { const attempt = this.reconcileAttempts[transport] + 1; this.reconcileAttempts[transport] = attempt; const exponent = Math.min(20, attempt - 1); const delayMs = Math.min( this.reconcileMaxDelayMs, this.reconcileBaseDelayMs * (2 ** exponent), ); this.diagnostic('runtime.source.reconcile_backoff', { transport, reason, attempt, delay_ms: delayMs, queue_status: queueStatus(this.currentQueue), }, 'warn'); if (delayMs > 0) await this.sleep(delayMs, this.abortController.signal); } private resetReconcileBackoff(transport: ReconciledTransport): void { const attempts = this.reconcileAttempts[transport]; if (attempts > 0) { this.diagnostic('runtime.source.reconcile_recovered', { transport, attempts, }, 'info'); } this.reconcileAttempts[transport] = 0; } private async submitControlState(intent: ClawclawSourceControlIntent): Promise { if (!this.runtime || this.finished) return; if (intent.kind === 'stop') { this.currentStage = 'ended'; this.currentConnection = 'disconnected'; } const sourceSeq = ++this.localSourceSeq; const connectionId = this.activeGameConnectionId ?? this.activeRoomConnectionId ?? 'local-control'; const eventValues = intent.kind === 'stop' ? [{ type: 'stop_requested' }] : intent.kind === 'leave' ? [{ type: 'quit_requested' }] : []; const receivedAt = new Date().toISOString(); await this.submit({ scope: this.runtime.currentSegment().scope, sourceId: CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId, connectionId, sourceKey: `control:${this.sourceInstanceId}:${sourceSeq}`, sourceSeq, state: { ...this.runtimeState(intent.kind === 'stop' ? 'ending' : 'control'), control: { type: intent.kind }, }, events: this.localEvents(eventValues, sourceSeq, receivedAt), completeness: 'complete', receivedAt, }); } private sourceEvents( values: readonly unknown[], meta: Pick & { replayed?: boolean }, sourceId: string, transform?: ( event: RuntimeSourceEvent>, sourceEventIndex: number, ) => RuntimeSourceEvent>, recipientSummary?: Record | null, ): RuntimeSourceEvent>[] { const events: RuntimeSourceEvent>[] = []; const normalizedValues = normalizeGameSyncEventsSafely(values); for (const warning of normalizedValues.warnings ?? []) { this.diagnostic('runtime.source.event_field_preserved', { source_id: sourceId, source_seq: meta.sourceSeq, event_index: warning.index, field: warning.field, reason: warning.reason, }, 'warn'); } normalizedValues.rejected.forEach(({ index, error }) => { const value = values[index]; const raw = value && typeof value === 'object' && !Array.isArray(value) ? value as Record : undefined; const sourceEventId = raw ? eventSourceId(raw) : undefined; this.diagnostic('runtime.source.event_rejected', { source_id: sourceId, source_seq: meta.sourceSeq, event_index: index, error_code: 'GAME_SYNC_EVENT_NORMALIZATION_FAILED', error_name: error instanceof Error ? error.name : 'Error', error: serializeError(error), ...(typeof raw?.type === 'string' ? { event_type: raw.type } : {}), ...(sourceEventId === undefined ? {} : { source_event_id: sourceEventId }), }, 'error'); }); normalizedValues.events.forEach(({ event: normalized, index }) => { if (isSelfKillerMurderWitnessed(normalized, recipientSummary)) { this.diagnostic('runtime.source.event_downgraded', { source_id: sourceId, source_seq: meta.sourceSeq, event_index: index, event_type: normalized.type, error_code: 'MURDER_WITNESSED_SELF_KILLER', killer_seat: normalized.killer_seat, self_seat: recipientSummary?.you?.player?.seat ?? recipientSummary?.you?.seat ?? recipientSummary?.my_seat, }, 'warn'); return; } const value = values[index]; const sourceEventId = eventSourceId(value as Record); const event = ( ( normalized.type === 'game_started' || normalized.type === 'game_over' || normalized.type === 'exile_game_over' ) && normalized.game_mode == null && this.participationMode ) ? { ...normalized, game_mode: this.participationMode } : normalized; const { type, ...payload } = event; const sequence = eventSourceSequence(event) ?? meta.sourceSeq; const sourceEvent: RuntimeSourceEvent> = { type, producer: 'backend_push', payload, sourceEventId: sourceEventId ?? (values.length === 1 ? meta.sourceEventId : undefined), sourceSeq: sequence === undefined ? undefined : values.length === 1 ? sequence : `${String(sequence)}:${index}`, receivedAt: meta.receivedAt, replayed: meta.replayed === true, }; events.push(transform ? transform(sourceEvent, index) : sourceEvent); }); return events; } private applyGameRoute(value: Record | ClawclawRoomGameStarted): void { const data = normalizeClawclawQueueState(value); if (typeof data.ws_url === 'string' && data.ws_url.length > 0) { this.client.setGameServerUrl(data.ws_url); } if (typeof data.game_server_name === 'string' && data.game_server_name.length > 0) { this.client.setRoomGameServer(data.game_server_name); } } private async ensureSegment(kind: string, identity?: string): Promise { const runtime = this.requireRuntime(); const current = runtime.currentSegment(); if (current.kind === kind && current.identity === identity) return current.scope; const next = await runtime.activateSegment(kind, identity); this.activeGameConnectionId = undefined; this.activeRoomConnectionId = undefined; this.gameConnectionsWithState.clear(); this.roomConnectionsWithSnapshot.clear(); this.hasFreshGameSnapshot = false; this.latestFreshGameState = undefined; this.latestFreshGameTick = undefined; this.sourceCoalescingBoundaryState = undefined; this.actionSafetyGeneration = 0; return next; } private requireConnectionScope(sourceId: string, connectionId: string): RuntimeScope { const runtime = this.requireRuntime(); const scope = runtime.connectionScope(sourceId, connectionId); if (!scope || !runtime.isActiveConnection(sourceId, connectionId)) { throw new Error('stale_connection'); } if (!sameScope(scope, runtime.currentSegment().scope)) throw new Error('stale_connection'); return scope; } private async submitCurrentState( cause: ClawclawRuntimeCause, sourceId: string, connectionId: string, eventValues: readonly Record[] = [], backendEventValues: readonly Record[] = [], ): Promise { const sourceSeq = ++this.localSourceSeq; const receivedAt = new Date().toISOString(); await this.submit({ scope: this.requireRuntime().currentSegment().scope, sourceId, connectionId, sourceKey: `source-state:${this.sourceInstanceId}:${sourceSeq}`, sourceSeq, state: this.runtimeState(cause), events: [ ...this.localEvents(eventValues, sourceSeq, receivedAt), ...this.sourceEvents(backendEventValues, { receivedAt, sourceSeq }, sourceId), ], completeness: 'complete', receivedAt, }); } private localEvents( values: readonly Record[], sourceSeq: number | string, receivedAt: string, ): RuntimeSourceEvent>[] { return values.map((value, index) => { const normalized = normalizeBackendEvent(value); const { type, ...payload } = normalized; const localSequence = `local:${this.sourceInstanceId}:${String(sourceSeq)}`; return { type, producer: 'local_synth', payload, sourceEventId: `${localSequence}:${index}`, sourceSeq: values.length === 1 ? localSequence : `${localSequence}:${index}`, receivedAt, }; }); } private runtimeState( cause: ClawclawRuntimeCause, gameSnapshot?: ClawclawRuntimeState['game_snapshot'], ): ClawclawRuntimeState { return { schema: 'clawclaw.runtime-state.v1', stage: this.currentStage, transport: this.currentTransport, connection: this.currentConnection, cause, ...(this.currentQueue ? { queue: structuredClone(this.currentQueue) } : {}), ...(this.currentRoom ? { room: structuredClone(this.currentRoom) } : {}), game_snapshot: gameSnapshot ?? (this.hasFreshGameSnapshot ? { status: 'not_updated' } : { status: 'unavailable' }), }; } private gameRuntimeState( stage: ClawclawRuntimeStage, cause: ClawclawRuntimeCause, gameSnapshot: ClawclawRuntimeState['game_snapshot'], ): ClawclawRuntimeState { return { schema: 'clawclaw.runtime-state.v1', stage, transport: this.currentTransport, connection: this.currentConnection, cause, game_snapshot: gameSnapshot, }; } private physicalSourceKey( transport: 'game' | 'room', meta: Pick, ): string { // A message sequence identifies the physical frame. Envelope Event IDs // are only a fallback because one backend Event can accompany multiple // distinct State frames on the same connection. const identity = meta.sourceSeq ?? meta.sourceEventId ?? `${meta.receivedAt}:${++this.localSourceSeq}`; return `${transport}:${meta.connectionId}:${String(identity)}`; } private async submit( batch: RuntimeInputBatch, Record>, afterAccepted?: ( acceptance: RuntimeInputAcceptance, Record>, ) => void, ): Promise, Record>> { return this.enqueueInput(() => batch, afterAccepted); } private async enqueueInput( createBatch: () => ( RuntimeInputBatch, Record> | Promise, Record>> ), afterAccepted?: ( acceptance: RuntimeInputAcceptance, Record>, ) => void, ): Promise, Record>> { const acceptance = await this.enqueueInputIf(createBatch, afterAccepted); if (!acceptance) throw new Error('Runtime Source input was unexpectedly skipped.'); return acceptance; } private async enqueueInputIf( createBatch: () => ( RuntimeInputBatch, Record> | null | Promise, Record> | null> ), afterAccepted?: ( acceptance: RuntimeInputAcceptance, Record>, ) => void, ): Promise, Record> | null> { const operation = this.inputTail.then(async () => { const batch = await createBatch(); if (!batch) return null; const nextBoundaryState = nextSourceCoalescingBoundaryState( batch.state, this.sourceCoalescingBoundaryState, ); const crossedActionSafetyBoundary = crossesSourceCoalescingBoundary( this.sourceCoalescingBoundaryState, nextBoundaryState, ); const actionSafetyGeneration = this.actionSafetyGeneration + (crossedActionSafetyBoundary ? 1 : 0); const acceptedBatch = { ...batch, state: isClawclawRuntimeState(batch.state) ? { ...batch.state, action_safety_generation: actionSafetyGeneration } : batch.state, ...(crossedActionSafetyBoundary ? { coalescing: 'forbidden' as const } : {}), }; const acceptance = await this.requireRuntime().acceptInputBatch(acceptedBatch); if (isClawclawRuntimeState(acceptedBatch.state) && acceptedBatch.state.stage === 'ended') { this.requireRuntime().closeActionScope( acceptedBatch.scope, acceptedBatch.sourceId === CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId ? 'ACTION_SCOPE_ENDED' : 'GAME_ENDED', ); } this.sourceCoalescingBoundaryState = nextBoundaryState; this.actionSafetyGeneration = actionSafetyGeneration; if (acceptedBatch.state.stage === 'ended') { this.terminalStateSubmitted = true; } afterAccepted?.(acceptance); return acceptance; }); this.inputTail = operation.then(() => undefined, () => undefined); return operation; } private async stopGameTransport(reason: ClawclawGameTransportStopReason): Promise { const transport = this.gameTransport; if (!transport) return; this.gameTransport = undefined; await transport.stop(reason); } private async stopRoomTransport(reason: 'manual' | 'shutdown'): Promise { const transport = this.roomTransport; if (!transport) return; this.roomTransport = undefined; await transport.stop(reason); } private diagnostic( name: string, attributes: Readonly> = {}, severity: 'debug' | 'info' | 'warn' | 'error' = 'debug', ): void { this.runtime?.diagnostic(name, attributes, severity); } private requireRuntime(): RuntimeSourceContext, Record> { if (!this.runtime) throw new Error('ClawClaw Source is not started.'); return this.runtime; } private finish(completion: ClawclawSourceCompletion): void { if (this.finished) return; this.finished = true; this.resolveCompletion(completion); } private async completeLifecycle(completion: ClawclawSourceCompletion): Promise { if (completion.reason === 'error') { this.diagnostic('runtime.source.failed', { error: completion.error instanceof Error ? completion.error.message : String(completion.error ?? 'unknown source error'), }, 'error'); } let finalCompletion = completion; if (!this.terminalStateSubmitted && this.runtime && !this.finished) { this.currentStage = 'ended'; this.currentConnection = 'disconnected'; const sourceSeq = ++this.localSourceSeq; const receivedAt = new Date().toISOString(); const errorMessage = completion.error instanceof Error ? completion.error.message : String(completion.error ?? 'Unknown Source error.'); try { await this.submit({ scope: this.runtime.currentSegment().scope, sourceId: CLAWCLAW_LOCAL_CONTROL_SOURCE.sourceId, connectionId: 'source-lifecycle', sourceKey: `source-terminal:${this.sourceInstanceId}:${sourceSeq}`, sourceSeq, state: { ...this.runtimeState('ending'), control: { type: 'source_completed', reason: completion.reason }, }, events: completion.reason === 'error' ? this.localEvents([{ type: 'error', code: isInvalidHostContextError(completion.error) ? 'INVALID_HOST_CONTEXT' : 'SOURCE_FAILED', phase: 'runtime', message: errorMessage, ...(this.participationMode ? { game_mode: this.participationMode } : {}), }], sourceSeq, receivedAt) : [], completeness: 'complete', receivedAt, }); } catch (error) { this.diagnostic('runtime.source.terminal_state_failed', { completion_reason: completion.reason, error: error instanceof Error ? error.message : String(error), }, 'error'); finalCompletion = { reason: 'error', error }; } } this.finish(finalCompletion); } }