import { startupMark, timeStartup } from '../../../bin/startup-trace.mjs'; import { Command, InvalidArgumentError, Option } from 'commander'; import { AuthStore, type AuthProfile } from '../../lib/auth.js'; import { ApiError, GameClient } from '../../lib/game-client.js'; import { noAccountMessage } from '../../lib/account-guidance.js'; import { CLAWCLAW_ROLE_IDS, type ClawclawRoleId } from '../../lib/gameplay-config.js'; import { isTrainingRole } from '../../lib/training-role.js'; import { summarizeLocalClawclawMap } from '../../lib/game-context.js'; import { businessFailureFromResult, classifyLeaveQueueResult, type ParticipationLeaveFailure, } from '../../lib/participation-leave.js'; import { isRoomMode, isTrainingRoomMode, queueMode, queueStatus, unwrapData, type TrainingRoomType, } from '../../lib/room.js'; import { queryGameParticipationStatus, type GameParticipationStatus, } from '../../lib/participation-status.js'; import { setMeta } from '../../lib/command-meta.js'; import { ShortCommandRunner } from '../../short-command/runner.js'; import type { ClawclawOwnerOptions } from '../../runtime/clawclaw/owner.js'; import { normalizeDesktopEventSocketPath, validateDesktopEventToken, type DesktopEventSocketConfig, } from '../../runtime/clawclaw/plugins/mailbox/desktop-event-socket.js'; import { sendProfileOwnerControlRequest } from '../../runtime/owner-control.js'; type GameCommandClient = Pick< GameClient, 'getQueueStatus' | 'getRoomStatus' | 'leaveGame' | 'leaveRoom' | 'leaveQueue' | 'startRoom' >; type GameOwnerIntent = ClawclawOwnerOptions['intent']; type GameOwnerRunOptions = { forceExistingRuntime?: boolean; desktopEvents?: DesktopEventSocketConfig; channelDelivery?: boolean; resolveStartupIntent?: ClawclawOwnerOptions['resolveStartupIntent']; }; export const CLAWCLAW_ENABLE_CLAUDE_CHANNELS = 'CLAWCLAW_ENABLE_CLAUDE_CHANNELS'; interface DesktopEventCliOptions { desktopEventSocket?: string; desktopEventToken?: string; } interface OwnerCliOptions extends DesktopEventCliOptions { agentType: string; llmModel?: string; force?: boolean; } interface ResumeCliOptions extends DesktopEventCliOptions { force?: boolean; } interface JoinCliOptions extends ResumeCliOptions { agentType?: string; llmModel?: string; } type ParticipationKind = 'match' | 'room' | TrainingRoomType; interface GameCommandIo { writeStdout(text: string): void; setExitCode(code: number): void; } export interface GameCommandDependencies { activeProfile?: () => AuthProfile; clientFactory?: () => GameCommandClient; stopRuntime?: (profile: AuthProfile) => Promise; ownerControl?: typeof sendProfileOwnerControlRequest; ownerRunner?: ( intent: GameOwnerIntent, options?: GameOwnerRunOptions, ) => Promise; io?: GameCommandIo; env?: NodeJS.ProcessEnv; } function trainingRoomType(value: string): TrainingRoomType { if (value === 'simulation' || value === 'training_simulation') return 'training_simulation'; if (value === 'dummy' || value === 'training_dummy') return 'training_dummy'; throw new InvalidArgumentError('Training mode must be simulation or dummy.'); } function trainingRole(value: string): ClawclawRoleId { if (!isTrainingRole(value)) { throw new InvalidArgumentError(`role must be one of: ${CLAWCLAW_ROLE_IDS.join(', ')}.`); } return value; } function addDesktopEventOptions(command: Command): Command { return command .addOption(new Option('--desktop-event-socket ').hideHelp()) .addOption(new Option('--desktop-event-token ').hideHelp()); } function desktopEventConfig( options: DesktopEventCliOptions, ): DesktopEventSocketConfig | undefined { const hasSocket = typeof options.desktopEventSocket === 'string'; const hasToken = typeof options.desktopEventToken === 'string'; if (hasSocket !== hasToken) { throw new InvalidArgumentError( '--desktop-event-socket and --desktop-event-token must be provided together.', ); } if (!hasSocket || !hasToken) return undefined; try { return { socketPath: normalizeDesktopEventSocketPath(options.desktopEventSocket!), token: validateDesktopEventToken(options.desktopEventToken!), }; } catch (error) { throw new InvalidArgumentError(error instanceof Error ? error.message : String(error)); } } async function runTrainingControl( type: 'training_mode' | 'training_role_lock' | 'training_role_clear', payload: Record, dependencies: GameCommandDependencies, ): Promise { const profile = (dependencies.activeProfile ?? activeProfile)(); const io = dependencies.io ?? processGameCommandIo; const response = await (dependencies.ownerControl ?? sendProfileOwnerControlRequest)( profile, type, payload, ); if (!response) { const command = type === 'training_mode' ? 'ccl game training mode' : type === 'training_role_lock' ? 'ccl game training role-lock' : 'ccl game training role-unlock'; writeQuitResult(io, { ok: false, command, error: 'runtime_not_running', message: 'Training configuration requires the foreground training-room runtime.', next_step: 'Start one with `ccl game training create --mode simulation|dummy`.', }, 1); return; } writeQuitResult(io, response, response.ok ? 0 : 1); } function activeProfile(): AuthProfile { const profile = new AuthStore().getActive(); if (!profile) throw new Error(noAccountMessage('gameStart')); return profile; } function backendSpectateUrl(result: any): string | undefined { const data = unwrapData(result); const value = data?.spectate_url ?? data?.url; return typeof value === 'string' && value.length > 0 ? value : undefined; } function lobbyWatchUrl(profile: Pick): string { return `${new URL(profile.serverUrl).origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`; } async function runOwner( intent: GameOwnerIntent, options: GameOwnerRunOptions = {}, ): Promise { const [{ runClawclawOwner }, { ClawclawHostNotificationRoute }, { createProcessCanonicalEventEmitter }] = await Promise.all([ import('../../runtime/clawclaw/owner.js'), import('../../runtime/clawclaw/notifications.js'), import('../../runtime/canonical-event-emitter.js'), ]); startupMark('cli.owner_modules_loaded'); const emitter = createProcessCanonicalEventEmitter(); const notifications = new ClawclawHostNotificationRoute( (payload) => emitter.emit(payload), ); let profile: AuthProfile | undefined; try { profile = activeProfile(); const completion = await runClawclawOwner({ profile, intent, forceExistingRuntime: options.forceExistingRuntime, resolveStartupIntent: options.resolveStartupIntent, ...(options.desktopEvents ? { desktopEvents: options.desktopEvents } : {}), ...(options.channelDelivery ? { channelDelivery: true } : {}), ...(!options.desktopEvents && !options.channelDelivery ? { notificationHost: notifications } : {}), }); if (completion.reason === 'error' || completion.reason === 'maintenance') process.exitCode = 1; } catch (error) { try { await notifications.reportBootstrapFailure( error, profile ? [profile.apiKey] : [], ); } catch {} throw error; } } function ownerRunOptions( forceExistingRuntime: boolean, desktopEvents?: DesktopEventSocketConfig, agentType?: string, env: NodeJS.ProcessEnv = process.env, ): GameOwnerRunOptions { const channelDelivery = agentType === 'claude-code' && env[CLAWCLAW_ENABLE_CLAUDE_CHANNELS] === '1'; return { forceExistingRuntime, ...(desktopEvents ? { desktopEvents } : {}), ...(channelDelivery ? { channelDelivery: true } : {}), }; } const processGameCommandIo: GameCommandIo = { writeStdout: (text) => process.stdout.write(text), setExitCode: (code) => { process.exitCode = code; }, }; async function requestRuntimeStop(profile: AuthProfile): Promise { try { return (await sendProfileOwnerControlRequest(profile, 'stop'))?.ok === true; } catch { return false; } } function writeQuitResult( io: GameCommandIo, value: Record, exitCode: number, ): void { io.writeStdout(`${JSON.stringify(value, null, 2)}\n`); io.setExitCode(exitCode); } function objectRoot(value: unknown): Record | undefined { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record : undefined; } function apiErrorRoot(error: ApiError): Record | undefined { if (error.response?.body.kind === 'json') { const root = objectRoot(error.response.body.value); if (root) return root; } try { return objectRoot(JSON.parse(error.body)); } catch { return undefined; } } async function writeStartRoomFailure( io: GameCommandIo, root: Record, httpStatus: number, requestId?: string, command = 'ccl game start-room', ): Promise { await new ShortCommandRunner().run({ descriptor: { command, service: 'clawclaw-lobby', operation: 'start_room', }, io, operation: () => ({ kind: 'backend_outcome', status: 'failure', value: root, response: { status: httpStatus, ...(requestId ? { requestId } : {}), }, }), }); } async function startCurrentRoom( dependencies: GameCommandDependencies = {}, command = 'ccl game start-room', ): Promise { (dependencies.activeProfile ?? activeProfile)(); const client = (dependencies.clientFactory ?? (() => GameClient.fromAuth()))(); const io = dependencies.io ?? processGameCommandIo; try { const result = await client.startRoom(); const root = objectRoot(result); if (root?.success === false) { await writeStartRoomFailure(io, root, 200, undefined, command); return; } io.writeStdout(`${JSON.stringify(result, null, 2)}\n`); io.setExitCode(0); } catch (error) { if (!(error instanceof ApiError)) throw error; const root = apiErrorRoot(error) ?? { success: false, error: { code: `HTTP_${error.status}`, message: error.body || error.message, }, }; await writeStartRoomFailure( io, root, error.status, error.response?.requestId, command, ); } } function quitFailure( status: string, presence: string | undefined, failure: ParticipationLeaveFailure, runtimeStopRequested: boolean, extra: Record = {}, ): Record { return { ok: false, command: 'game quit', status, left: runtimeStopRequested ? 'local_runtime' : 'none', remote_left: false, presence, leave_error: failure, runtime_stop_requested: runtimeStopRequested, ...extra, }; } async function quitParticipation(dependencies: GameCommandDependencies = {}): Promise { const profile = (dependencies.activeProfile ?? activeProfile)(); const client = (dependencies.clientFactory ?? (() => GameClient.fromAuth()))(); const stopRuntime = dependencies.stopRuntime ?? requestRuntimeStop; const io = dependencies.io ?? processGameCommandIo; const queue = await client.getQueueStatus('clawclaw'); const status = queueStatus(queue); if (status === 'allocated') { const game = await client.leaveGame(); const failure = businessFailureFromResult(game, 'Failed to leave the active game.'); if (failure) { const runtimeStopRequested = await stopRuntime(profile); const stillAliveDetails = failure.still_alive ? { partial: runtimeStopRequested, backend_participation: 'active_game', local_runtime: runtimeStopRequested ? 'stopping' : 'stop_not_confirmed', message: runtimeStopRequested ? 'The local runtime accepted a stop request, but the backend rejected leaving the game. The player still exists in the active game on the server.' : 'The backend rejected leaving the game, so the player still exists in the active game on the server. No local runtime acknowledged a stop request.', next_step: 'Tell the user that the local runtime and the server-side player now have different states; do not claim that the player left the game.', } : {}; writeQuitResult(io, quitFailure( 'leave_game_failed', 'in_game', failure, runtimeStopRequested, { game_result: game, queue_status: unwrapData(queue), ...stillAliveDetails, }, ), 1); return; } if (isRoomMode(queueMode(queue))) { writeQuitResult(io, { ok: true, command: 'game quit', status: 'game_returned_room', left: 'game_returned_room', remote_left: true, presence: 'in_game', game_result: game, queue_status: unwrapData(queue), runtime_stop_requested: false, next_step: 'Left the current room game. The running runtime will return to the room lobby.', }, 0); return; } const runtimeStopRequested = await stopRuntime(profile); writeQuitResult(io, { ok: true, command: 'game quit', status: 'left_game', left: 'game', remote_left: true, presence: 'in_game', game_result: game, queue_status: unwrapData(queue), runtime_stop_requested: runtimeStopRequested, }, 0); return; } if (status === 'in_room') { const room = await client.leaveRoom(); const failure = businessFailureFromResult(room, 'Failed to leave the room.'); const runtimeStopRequested = await stopRuntime(profile); if (failure) { writeQuitResult(io, quitFailure( 'leave_room_failed', 'in_room', failure, runtimeStopRequested, { room_result: room, queue_status: unwrapData(queue) }, ), 1); return; } writeQuitResult(io, { ok: true, command: 'game quit', status: 'left_room', left: 'room', remote_left: true, presence: 'in_room', room_result: room, queue_status: unwrapData(queue), runtime_stop_requested: runtimeStopRequested, }, 0); return; } if (status === 'queued' || status === 'already_in_queue' || status === 'allocating') { const matching = await client.leaveQueue('clawclaw'); const outcome = classifyLeaveQueueResult(matching); if (!outcome.remoteLeft) { writeQuitResult(io, quitFailure( outcome.status === 'allocating' ? 'leave_queue_allocating' : 'leave_queue_failed', 'matching', outcome.failure!, false, { queue_result: matching, queue_status: unwrapData(queue) }, ), 1); return; } const runtimeStopRequested = await stopRuntime(profile); writeQuitResult(io, { ok: true, command: 'game quit', status: outcome.status, left: 'queue', remote_left: true, presence: 'matching', queue_result: matching, queue_status: unwrapData(queue), runtime_stop_requested: runtimeStopRequested, }, 0); return; } if (status === 'not_in_queue') { const runtimeStopRequested = await stopRuntime(profile); writeQuitResult(io, { ok: true, command: 'game quit', status: 'not_participating', left: runtimeStopRequested ? 'local_runtime' : 'none', remote_left: true, presence: status, queue_status: unwrapData(queue), runtime_stop_requested: runtimeStopRequested, }, 0); return; } writeQuitResult(io, quitFailure( 'unknown_participation_status', status, { code: 'UNEXPECTED_QUEUE_STATUS', message: 'The server returned an unknown participation status, so no leave action was attempted.', retryable: true, }, false, { queue_status: unwrapData(queue) }, ), 1); } async function showParticipationStatus( dependencies: GameCommandDependencies = {}, ): Promise { const io = dependencies.io ?? processGameCommandIo; const status = await readParticipationStatus(dependencies); io.writeStdout(`${JSON.stringify(status, null, 2)}\n`); io.setExitCode(status.status === 'unknown' ? 1 : 0); } async function readParticipationStatus( dependencies: GameCommandDependencies, ): Promise { (dependencies.activeProfile ?? activeProfile)(); const client = (dependencies.clientFactory ?? (() => GameClient.fromAuth()))(); return queryGameParticipationStatus(client); } function participationKind(status: GameParticipationStatus): ParticipationKind | undefined { if (status.status === 'matching') { return status.mode === 'match' ? 'match' : undefined; } if (status.status === 'friend_room') return 'room'; if (status.status === 'training_room') { const roomType = status.room_type ?? status.mode; return isTrainingRoomMode(roomType) ? roomType : undefined; } if (status.status === 'room') { const roomType = status.room_type ?? status.mode; return isTrainingRoomMode(roomType) ? roomType : 'room'; } if (status.status === 'in_game') { if (isTrainingRoomMode(status.mode)) return status.mode; if (isRoomMode(status.mode)) return 'room'; return status.mode === 'match' ? 'match' : undefined; } return undefined; } function participationLabel(status: GameParticipationStatus): string { const fields = [ `status=${status.status}`, status.mode ? `mode=${status.mode}` : undefined, status.room_type ? `room_type=${status.room_type}` : undefined, status.room_code ? `room_code=${status.room_code}` : undefined, ].filter((value): value is string => value !== undefined); return fields.join(', '); } function participationConflict(operation: string, status: GameParticipationStatus): Error { return new Error( `Cannot ${operation} while another backend participation is active (${participationLabel(status)}). Run ccl join to continue it, or quit it before switching.`, ); } async function resolveStartIntent( target: ParticipationKind, createIntent: GameOwnerIntent, dependencies: GameCommandDependencies, ): Promise { const status = await timeStartup('start.participation_preflight', () => readParticipationStatus(dependencies)); return resolveStartStatus(target, createIntent, status); } function resolveStartStatus(target: ParticipationKind, createIntent: GameOwnerIntent, status: GameParticipationStatus): GameOwnerIntent { if (status.status === 'idle') return createIntent; if (status.status === 'unknown') { throw new Error('Cannot start because the backend participation status is unknown.'); } if (participationKind(status) === target) return { kind: 'resume' }; throw participationConflict(`start ${target}`, status); } async function resolveResumeIntent( dependencies: GameCommandDependencies, ): Promise { const status = await readParticipationStatus(dependencies); if (status.status === 'idle') { throw new Error('No active backend participation to join.'); } if (status.status === 'unknown') { throw new Error('Cannot join because the backend participation status is unknown.'); } return { kind: 'resume' }; } async function resolveJoinRoomIntent( roomCode: string, metadata: { agentType: string; llmModel?: string }, dependencies: GameCommandDependencies, ): Promise { const status = await readParticipationStatus(dependencies); if (status.status === 'idle') { return { kind: 'join_room', roomCode, agentType: metadata.agentType, llmModel: metadata.llmModel, }; } if (status.status === 'unknown') { throw new Error('Cannot join a room because the backend participation status is unknown.'); } const currentKind = participationKind(status); if ( (currentKind === 'room' || isTrainingRoomMode(currentKind)) && status.room_code === roomCode ) { return { kind: 'resume' }; } throw participationConflict(`join room ${roomCode}`, status); } async function runTopLevelOwner( intent: GameOwnerIntent, options: JoinCliOptions, dependencies: GameCommandDependencies, ): Promise { const ownerRunner = dependencies.ownerRunner ?? runOwner; const env = dependencies.env ?? process.env; const channelAgentType = options.agentType ?? (env[CLAWCLAW_ENABLE_CLAUDE_CHANNELS] === '1' ? 'claude-code' : undefined); await ownerRunner(intent, ownerRunOptions( options.force === true, desktopEventConfig(options), channelAgentType, env, )); } export function createStartCommand( dependencies: GameCommandDependencies = {}, ): Command { const start = new Command('start').description('Create or resume a ClawClaw participation'); addDesktopEventOptions(start .command('match') .description('Start ordinary matchmaking, or resume an existing ordinary match') .requiredOption('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before starting')) .action(async (options: OwnerCliOptions) => { const intent: GameOwnerIntent = { kind: 'match', mode: 'match', agentType: options.agentType, llmModel: options.llmModel, }; if (options.force || dependencies.ownerRunner || dependencies.clientFactory || dependencies.activeProfile) { await runTopLevelOwner(await resolveStartIntent('match', intent, dependencies), options, dependencies); return; } await runOwner(intent, { ...ownerRunOptions(false, desktopEventConfig(options), options.agentType, dependencies.env), async resolveStartupIntent(client, queue) { const status = await queryGameParticipationStatus({ getQueueStatus: async () => queue, getRoomStatus: () => client.getRoomStatus(), }); return resolveStartStatus('match', intent, status); }, }); }); addDesktopEventOptions(start .command('room') .description('Create a friend room, or resume an existing friend-room participation') .requiredOption('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before starting')) .action(async (options: OwnerCliOptions) => { const intent = await resolveStartIntent('room', { kind: 'create_room', agentType: options.agentType, llmModel: options.llmModel, }, dependencies); await runTopLevelOwner(intent, options, dependencies); }); addDesktopEventOptions(start .command('training') .description('Create a training room, or resume the same training mode') .argument('[simulation|dummy]', 'training ruleset', trainingRoomType, 'training_simulation') .requiredOption('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before starting')) .action(async (roomType: TrainingRoomType, options: OwnerCliOptions) => { const intent = await resolveStartIntent(roomType, { kind: 'create_room', roomType, agentType: options.agentType, llmModel: options.llmModel, }, dependencies); await runTopLevelOwner(intent, options, dependencies); }); for (const command of start.commands) { setMeta(command, { longRunning: true, timeoutMs: 1_800_000 }); } return start; } export function createJoinCommand( dependencies: GameCommandDependencies = {}, ): Command { const join = addDesktopEventOptions(new Command('join') .description('Resume the current participation, or join a specific friend room') .argument('[target]', 'omit to resume, or use "room" to join a friend room') .argument('[room_code]', 'friend room code when target is "room"') .option('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before joining')) .action(async ( target: string | undefined, roomCode: string | undefined, options: JoinCliOptions, ) => { if (target === undefined) { const intent = await resolveResumeIntent(dependencies); await runTopLevelOwner(intent, options, dependencies); return; } if (target !== 'room') { throw new InvalidArgumentError('Join target must be "room", or omitted to resume.'); } if (!roomCode) { throw new InvalidArgumentError('A room code is required for `ccl join room`.'); } if (!options.agentType) { throw new InvalidArgumentError('--agent-type is required when joining a room.'); } const intent = await resolveJoinRoomIntent(roomCode, { agentType: options.agentType, llmModel: options.llmModel, }, dependencies); await runTopLevelOwner(intent, options, dependencies); }); setMeta(join, { longRunning: true, timeoutMs: 1_800_000 }); return join; } export function createGameCommand(dependencies: GameCommandDependencies = {}): Command { const game = new Command('game').description('Game participation and inspection'); const ownerRunner = dependencies.ownerRunner ?? runOwner; const start = addDesktopEventOptions(game .command('start') .alias('s') .description('Run the ClawClaw Source until the current participation ends.') .requiredOption('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before starting') .addOption(new Option('--competition').hideHelp())) .action(async (opts: { agentType: string; llmModel?: string; competition?: boolean; force?: boolean; desktopEventSocket?: string; desktopEventToken?: string; }) => { const desktopEvents = desktopEventConfig(opts); await ownerRunner({ kind: 'match', mode: opts.competition ? 'competition' : 'match', agentType: opts.agentType, llmModel: opts.llmModel, }, ownerRunOptions( opts.force === true, desktopEvents, opts.agentType, dependencies.env ?? process.env, )); }); const createRoom = addDesktopEventOptions(game .command('create-room') .description('Create a room and run its Source lifecycle.') .requiredOption('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before starting')) .action(async (opts: { agentType: string; llmModel?: string; force?: boolean; desktopEventSocket?: string; desktopEventToken?: string; }) => { const desktopEvents = desktopEventConfig(opts); return ownerRunner({ kind: 'create_room', agentType: opts.agentType, llmModel: opts.llmModel, }, ownerRunOptions( opts.force === true, desktopEvents, opts.agentType, dependencies.env ?? process.env, )); }); const joinRoom = addDesktopEventOptions(game .command('join-room') .description('Join a room and run its Source lifecycle.') .argument('') .requiredOption('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before starting')) .action(async (roomCode: string, opts: { agentType: string; llmModel?: string; force?: boolean; desktopEventSocket?: string; desktopEventToken?: string; }) => { const desktopEvents = desktopEventConfig(opts); return ownerRunner({ kind: 'join_room', roomCode, agentType: opts.agentType, llmModel: opts.llmModel, }, ownerRunOptions( opts.force === true, desktopEvents, opts.agentType, dependencies.env ?? process.env, )); }); const training = game .command('training') .description('Create and configure a bot-filled training room.'); const trainingCreate = addDesktopEventOptions(training .command('create') .description('Create a training room and run its Source lifecycle.') .requiredOption('--mode ', 'training ruleset', trainingRoomType) .requiredOption('--agent-type ') .option('--llm-model ') .option('--force', 'replace an existing local runtime process before starting')) .action(async (opts: { mode: TrainingRoomType; agentType: string; llmModel?: string; force?: boolean; desktopEventSocket?: string; desktopEventToken?: string; }) => { const desktopEvents = desktopEventConfig(opts); return ownerRunner({ kind: 'create_room', roomType: opts.mode, agentType: opts.agentType, llmModel: opts.llmModel, }, ownerRunOptions( opts.force === true, desktopEvents, opts.agentType, dependencies.env ?? process.env, )); }); training .command('mode') .description('Switch the current training room ruleset.') .argument('', 'training ruleset', trainingRoomType) .action((roomType: TrainingRoomType) => runTrainingControl( 'training_mode', { room_type: roomType }, dependencies, )); training .command('role-lock') .description('Lock the player role for future training rounds.') .argument('', `English role: ${CLAWCLAW_ROLE_IDS.join(', ')}`, trainingRole) .action((role: ClawclawRoleId) => runTrainingControl( 'training_role_lock', { role }, dependencies, )); training .command('role-unlock') .description('Clear the player character lock for future training rounds.') .action(() => runTrainingControl('training_role_clear', {}, dependencies)); training .command('start') .description('Start a round in the current training room.') .action(() => startCurrentRoom(dependencies, 'ccl game training start')); game .command('status') .description('Show the current backend participation status.') .action(() => showParticipationStatus(dependencies)); game .command('quit') .description('Leave the active queue, room, or game.') .action(() => quitParticipation(dependencies)); game .command('start-room') .description('Start the current room.') .action(() => startCurrentRoom(dependencies)); game .command('map', { hidden: true }) .description('Show the current game map.') .option('--ascii') .action(async (opts: { ascii?: boolean }) => { process.stdout.write(`${JSON.stringify(summarizeLocalClawclawMap({ ascii: opts.ascii === true, }), null, 2)}\n`); }); game .command('watch') .alias('w') .description('Get the current spectating URL.') .action(async () => { const profile = activeProfile(); const queue = await GameClient.fromAuth().getQueueStatus('clawclaw'); process.stdout.write(`${JSON.stringify({ ...unwrapData(queue), url: backendSpectateUrl(queue) ?? lobbyWatchUrl(profile), }, null, 2)}\n`); }); setMeta(start, { longRunning: true, timeoutMs: 1_800_000 }); setMeta(createRoom, { longRunning: true, timeoutMs: 1_800_000 }); setMeta(joinRoom, { longRunning: true, timeoutMs: 1_800_000 }); setMeta(trainingCreate, { longRunning: true, timeoutMs: 1_800_000 }); return game; }