@myclaw163/clawclaw-cli 0.6.96 → 0.6.101
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/clawclaw-cli.mjs +3 -3
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +26 -10
- package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +17 -5
- package/skills/clawclaw/references/STREAM.md +15 -12
- package/src/commands/config.ts +30 -30
- package/src/commands/do.test.ts +27 -1
- package/src/commands/do.ts +61 -0
- package/src/commands/events.test.ts +21 -3
- package/src/commands/events.ts +8 -2
- package/src/commands/game-start-plan.test.ts +158 -0
- package/src/commands/game.ts +670 -64
- package/src/commands/history-player.test.ts +3 -0
- package/src/commands/setup/hermes.test.ts +96 -96
- package/src/commands/setup/hermes.ts +76 -76
- package/src/commands/setup/index.ts +13 -13
- package/src/commands/setup/openclaw.test.ts +124 -114
- package/src/commands/setup/openclaw.ts +162 -147
- package/src/commands/watch.test.ts +272 -0
- package/src/commands/watch.ts +185 -25
- package/src/lib/game-client.ts +34 -0
- package/src/lib/host-config-patcher.test.ts +130 -130
- package/src/lib/host-config-patcher.ts +151 -151
- package/src/lib/room.test.ts +74 -0
- package/src/lib/room.ts +129 -0
- package/src/lib/server-registry.test.ts +54 -0
- package/src/lib/server-registry.ts +35 -2
- package/src/perception/player-history-store.test.ts +92 -2
- package/src/perception/player-history-store.ts +68 -0
- package/src/pipeline/event-format.test.ts +61 -1
- package/src/pipeline/event-format.ts +88 -0
- package/src/pipeline/event-hints.ts +10 -1
- package/src/runtime/event-daemon.test.ts +43 -0
- package/src/runtime/event-daemon.ts +8 -4
- package/src/runtime/room-lobby-runtime.test.ts +95 -0
- package/src/runtime/room-lobby-runtime.ts +367 -0
package/src/commands/game.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { runStreaming, buildErrorLine, summarizeFeed, nextStepFor } from './watc
|
|
|
14
14
|
import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
|
|
15
15
|
import { noAccountMessage } from '../lib/account-guidance.js';
|
|
16
16
|
import { EventRuntime } from '../runtime/event-daemon.js';
|
|
17
|
+
import { RoomLobbyRuntime, type RoomGameStarted } from '../runtime/room-lobby-runtime.js';
|
|
17
18
|
import {
|
|
18
19
|
apiErrorCode,
|
|
19
20
|
apiErrorMessage,
|
|
@@ -43,6 +44,16 @@ import {
|
|
|
43
44
|
getWaitedSecs,
|
|
44
45
|
hasMatchTimedOut,
|
|
45
46
|
} from '../lib/match-state.js';
|
|
47
|
+
import {
|
|
48
|
+
hasRoomQueueContext,
|
|
49
|
+
isAlreadyInRoomError,
|
|
50
|
+
isRoomAllocatedQueueStatus,
|
|
51
|
+
parseApiErrorBody,
|
|
52
|
+
queueRoomCode,
|
|
53
|
+
queueMode as roomQueueMode,
|
|
54
|
+
queueStatus as roomQueueStatus,
|
|
55
|
+
roomCodeFromAlreadyInRoomError,
|
|
56
|
+
} from '../lib/room.js';
|
|
46
57
|
|
|
47
58
|
export { summarizeGameMap } from '../lib/game-context.js';
|
|
48
59
|
|
|
@@ -63,6 +74,8 @@ function queueMode(result: any): QueueMode | undefined {
|
|
|
63
74
|
return queueModeFrom(result);
|
|
64
75
|
}
|
|
65
76
|
|
|
77
|
+
type RuntimeGameMode = QueueMode | 'room';
|
|
78
|
+
|
|
66
79
|
const DEFAULT_QUEUE_WAIT_TIMEOUT_SECS = 30;
|
|
67
80
|
|
|
68
81
|
function clearCachedGameServerUrl(authStore: AuthStore, profileName?: string): void {
|
|
@@ -75,7 +88,46 @@ function clearCachedGameServerUrl(authStore: AuthStore, profileName?: string): v
|
|
|
75
88
|
|
|
76
89
|
function isLeaveGameSuccess(result: any): boolean {
|
|
77
90
|
const data = result?.data ?? result;
|
|
78
|
-
return data?.ok === true || data?.message === 'left_game';
|
|
91
|
+
return result?.success === true || data?.success === true || data?.ok === true || data?.left === true || data?.message === 'left_game';
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function leaveGameFailureFromResult(result: any): Record<string, any> | undefined {
|
|
95
|
+
const data = result?.data ?? result;
|
|
96
|
+
const success = result?.success ?? data?.success;
|
|
97
|
+
if (success !== false) return undefined;
|
|
98
|
+
const error = result?.error ?? data?.error ?? {};
|
|
99
|
+
const code = typeof error?.code === 'string'
|
|
100
|
+
? error.code
|
|
101
|
+
: typeof data?.code === 'string'
|
|
102
|
+
? data.code
|
|
103
|
+
: undefined;
|
|
104
|
+
const message = typeof error?.message === 'string'
|
|
105
|
+
? error.message
|
|
106
|
+
: typeof data?.message === 'string'
|
|
107
|
+
? data.message
|
|
108
|
+
: 'Leave game failed';
|
|
109
|
+
return cleanObject({
|
|
110
|
+
code,
|
|
111
|
+
message,
|
|
112
|
+
still_alive: /STILL_ALIVE/i.test(`${code ?? ''} ${message ?? ''}`),
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function roomStartFailureFromError(err: unknown, queue?: any): Record<string, any> | undefined {
|
|
117
|
+
if (!(err instanceof ApiError)) return undefined;
|
|
118
|
+
const parsed = parseApiErrorBody(err.body);
|
|
119
|
+
const error = parsed?.error ?? {};
|
|
120
|
+
if (error?.code !== 'NOT_ENOUGH_PLAYERS') return undefined;
|
|
121
|
+
|
|
122
|
+
return cleanObject({
|
|
123
|
+
ok: false,
|
|
124
|
+
command: 'game start-room',
|
|
125
|
+
error: 'NOT_ENOUGH_PLAYERS',
|
|
126
|
+
message: typeof error.message === 'string' ? error.message : 'Need 10 players to start the room match.',
|
|
127
|
+
shortage: error.shortage,
|
|
128
|
+
queue_status: queue === undefined ? undefined : unwrapData(queue),
|
|
129
|
+
next_step: 'The room is not full yet. Tell the user how many players are missing; do not leave the room or start normal matchmaking.',
|
|
130
|
+
});
|
|
79
131
|
}
|
|
80
132
|
|
|
81
133
|
function isPidAlive(pid: number): boolean {
|
|
@@ -212,6 +264,8 @@ type QueueStatus = 'allocated' | 'queued' | 'not_in_queue' | string | undefined;
|
|
|
212
264
|
|
|
213
265
|
export type GameStartPlan =
|
|
214
266
|
| { kind: 'already_running'; pid: number }
|
|
267
|
+
| { kind: 'resume_room' }
|
|
268
|
+
| { kind: 'resume_room_allocated' }
|
|
215
269
|
| { kind: 'resume_queue' }
|
|
216
270
|
| { kind: 'resume_allocated' }
|
|
217
271
|
| { kind: 'fresh_start' };
|
|
@@ -222,15 +276,68 @@ export function planGameStartAction(input: {
|
|
|
222
276
|
gameStartPid?: number | null;
|
|
223
277
|
hasMatchState: boolean;
|
|
224
278
|
queueStatus?: QueueStatus;
|
|
279
|
+
queueMode?: string;
|
|
225
280
|
}): GameStartPlan {
|
|
226
281
|
if (input.gameStartPid) return { kind: 'already_running', pid: input.gameStartPid };
|
|
227
282
|
|
|
283
|
+
if (input.queueStatus === 'in_room') return { kind: 'resume_room' };
|
|
284
|
+
if (input.queueStatus === 'allocated' && input.queueMode === 'room') return { kind: 'resume_room_allocated' };
|
|
228
285
|
if (input.queueStatus === 'allocated') return { kind: 'resume_allocated' };
|
|
229
286
|
if (input.queueStatus === 'queued' || input.queueStatus === 'already_in_queue') return { kind: 'resume_queue' };
|
|
230
287
|
if (input.hasMatchState && input.queueStatus !== 'not_in_queue') return { kind: 'resume_queue' };
|
|
231
288
|
return { kind: 'fresh_start' };
|
|
232
289
|
}
|
|
233
290
|
|
|
291
|
+
export type RoomJoinPlan =
|
|
292
|
+
| { kind: 'join' }
|
|
293
|
+
| { kind: 'resume_current_room'; roomCode: string }
|
|
294
|
+
| { kind: 'leave_then_join'; roomCode: string }
|
|
295
|
+
| { kind: 'refuse_room_allocated'; roomCode?: string };
|
|
296
|
+
|
|
297
|
+
export function planRoomJoinAction(input: {
|
|
298
|
+
targetRoomCode: string;
|
|
299
|
+
queueStatus?: QueueStatus;
|
|
300
|
+
queueMode?: string;
|
|
301
|
+
currentRoomCode?: string;
|
|
302
|
+
}): RoomJoinPlan {
|
|
303
|
+
if (input.queueStatus === 'allocated' && input.queueMode === 'room') {
|
|
304
|
+
return { kind: 'refuse_room_allocated', roomCode: input.currentRoomCode };
|
|
305
|
+
}
|
|
306
|
+
if (input.queueStatus !== 'in_room') return { kind: 'join' };
|
|
307
|
+
if (!input.currentRoomCode) return { kind: 'join' };
|
|
308
|
+
if (input.currentRoomCode === input.targetRoomCode) {
|
|
309
|
+
return { kind: 'resume_current_room', roomCode: input.currentRoomCode };
|
|
310
|
+
}
|
|
311
|
+
return { kind: 'leave_then_join', roomCode: input.currentRoomCode };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function roomJoinAlreadyRunningNextStep(pid: number): string {
|
|
315
|
+
return `A room/game stream is already running (pid ${pid}). To enter another room, run ccl game quit first, wait for the current stream to exit, then start ccl game join-room <room_code> with Monitor.`;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function planRoomEntryStreamGuard(input: {
|
|
319
|
+
runningPid?: number | null;
|
|
320
|
+
force?: boolean;
|
|
321
|
+
source: 'room_create' | 'room_join';
|
|
322
|
+
}): { kind: 'continue' } | { kind: 'already_running'; pid: number; nextStep: string } {
|
|
323
|
+
if (!input.runningPid || input.force) return { kind: 'continue' };
|
|
324
|
+
if (input.source === 'room_join') {
|
|
325
|
+
return {
|
|
326
|
+
kind: 'already_running',
|
|
327
|
+
pid: input.runningPid,
|
|
328
|
+
nextStep: roomJoinAlreadyRunningNextStep(input.runningPid),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
kind: 'already_running',
|
|
333
|
+
pid: input.runningPid,
|
|
334
|
+
nextStep: `A room/game stream is already running (pid ${input.runningPid}). Do not start another stream; run ccl game quit first, or pass --force explicitly.`,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const ROOM_SELF_LEFT_MESSAGE = 'The user left the room from the web page, or the current CLI quit command has left the room. Stop the room flow and do not create or join another room unless the user asks.';
|
|
339
|
+
const ROOM_SELF_LEFT_STREAM_MESSAGE = 'The user left the room from the web page, or the current CLI quit command has left the room. The room stream is exiting.';
|
|
340
|
+
|
|
234
341
|
function isAlreadyInGameError(err: unknown): boolean {
|
|
235
342
|
return err instanceof ApiError && err.body.includes('ALREADY_IN_GAME');
|
|
236
343
|
}
|
|
@@ -275,7 +382,7 @@ function competitionNextStep(code: string | undefined): string {
|
|
|
275
382
|
}
|
|
276
383
|
}
|
|
277
384
|
|
|
278
|
-
type GamePresence = 'in_game' | 'matching' | 'none' | 'unknown';
|
|
385
|
+
type GamePresence = 'in_game' | 'matching' | 'in_room' | 'none' | 'unknown';
|
|
279
386
|
|
|
280
387
|
interface GamePresenceInfo {
|
|
281
388
|
presence: GamePresence;
|
|
@@ -296,28 +403,37 @@ async function detectGamePresence(client: GameClient, stateDir: string): Promise
|
|
|
296
403
|
const errors: Array<{ source: string; error: Record<string, any> }> = [];
|
|
297
404
|
const ownerPid = getRunningGameStartPid(stateDir);
|
|
298
405
|
let gameState: any | null = null;
|
|
406
|
+
let queue: any;
|
|
299
407
|
try {
|
|
300
408
|
await client.discoverGameServer();
|
|
301
409
|
gameState = await client.getGameState();
|
|
302
410
|
} catch (err) {
|
|
303
411
|
errors.push({ source: 'game_current', error: serializeError(err) });
|
|
304
412
|
}
|
|
413
|
+
try {
|
|
414
|
+
queue = await client.getQueueStatus('clawclaw');
|
|
415
|
+
} catch (err) {
|
|
416
|
+
errors.push({ source: 'queue_status', error: serializeError(err) });
|
|
417
|
+
}
|
|
305
418
|
if (gameState) {
|
|
306
419
|
return {
|
|
307
420
|
presence: 'in_game',
|
|
308
421
|
game_state: gameState,
|
|
422
|
+
...(queue ? { queue_status: queue } : {}),
|
|
309
423
|
owner_pid: ownerPid,
|
|
310
424
|
...(errors.length ? { errors } : {}),
|
|
311
425
|
};
|
|
312
426
|
}
|
|
313
427
|
|
|
314
|
-
let queue: any;
|
|
315
|
-
try {
|
|
316
|
-
queue = await client.getQueueStatus('clawclaw');
|
|
317
|
-
} catch (err) {
|
|
318
|
-
errors.push({ source: 'queue_status', error: serializeError(err) });
|
|
319
|
-
}
|
|
320
428
|
const status = queueStatus(queue);
|
|
429
|
+
if (status === 'in_room') {
|
|
430
|
+
return {
|
|
431
|
+
presence: 'in_room',
|
|
432
|
+
queue_status: queue,
|
|
433
|
+
owner_pid: ownerPid,
|
|
434
|
+
...(errors.length ? { errors } : {}),
|
|
435
|
+
};
|
|
436
|
+
}
|
|
321
437
|
if (isMatchingQueueStatus(status)) {
|
|
322
438
|
return {
|
|
323
439
|
presence: 'matching',
|
|
@@ -349,8 +465,13 @@ function ensureEventSession(source: string): EventStore {
|
|
|
349
465
|
events.append({ type: 'session_resumed', source });
|
|
350
466
|
return events;
|
|
351
467
|
}
|
|
468
|
+
const events = startEventSession(source);
|
|
469
|
+
return events;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function startEventSession(source: string, extra: Record<string, any> = {}): EventStore {
|
|
352
473
|
const events = EventStore.createSessionForActiveAccount();
|
|
353
|
-
events.append({ type: 'session_started', source });
|
|
474
|
+
events.append({ type: 'session_started', source, ...extra });
|
|
354
475
|
return events;
|
|
355
476
|
}
|
|
356
477
|
|
|
@@ -362,6 +483,11 @@ function unwrapData(value: any): any {
|
|
|
362
483
|
return value?.data ?? value;
|
|
363
484
|
}
|
|
364
485
|
|
|
486
|
+
export function lobbyWatchUrl(profile: { serverUrl: string; apiKey: string }): string {
|
|
487
|
+
const origin = new URL(profile.serverUrl).origin;
|
|
488
|
+
return `${origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`;
|
|
489
|
+
}
|
|
490
|
+
|
|
365
491
|
function cleanObject<T extends Record<string, any>>(obj: T): T {
|
|
366
492
|
for (const key of Object.keys(obj)) {
|
|
367
493
|
if (obj[key] === undefined) delete obj[key];
|
|
@@ -369,12 +495,30 @@ function cleanObject<T extends Record<string, any>>(obj: T): T {
|
|
|
369
495
|
return obj;
|
|
370
496
|
}
|
|
371
497
|
|
|
498
|
+
function applyRoomGameServer(client: GameClient, event: RoomGameStarted): void {
|
|
499
|
+
if (event.ws_url && typeof event.ws_url === 'string') {
|
|
500
|
+
client.setGameServerUrl(event.ws_url.replace(/^wss:/, 'https:').replace(/^ws:/, 'http:'));
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (event.game_server_name) {
|
|
504
|
+
client.setRoomGameServer(event.game_server_name);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
372
508
|
export interface GameStrategyIdentity {
|
|
373
509
|
gameId?: string;
|
|
374
510
|
role?: string;
|
|
375
511
|
alive: boolean | null;
|
|
376
512
|
}
|
|
377
513
|
|
|
514
|
+
type InitialGameContext = {
|
|
515
|
+
state: any | null;
|
|
516
|
+
role: any | null;
|
|
517
|
+
map: any | null;
|
|
518
|
+
tasks: any[] | null;
|
|
519
|
+
errors?: Array<{ command: string; error: string }>;
|
|
520
|
+
};
|
|
521
|
+
|
|
378
522
|
export function gameStrategyIdentity(stateData: any, roleData: any): GameStrategyIdentity {
|
|
379
523
|
const state = unwrapData(stateData);
|
|
380
524
|
const role = unwrapData(roleData);
|
|
@@ -396,14 +540,8 @@ function commandError(command: string, err: unknown): { command: string; error:
|
|
|
396
540
|
return { command, error: message };
|
|
397
541
|
}
|
|
398
542
|
|
|
399
|
-
async function fetchInitialGameContext(client: GameClient): Promise<{
|
|
400
|
-
|
|
401
|
-
role: any | null;
|
|
402
|
-
map: any | null;
|
|
403
|
-
tasks: any[] | null;
|
|
404
|
-
errors?: Array<{ command: string; error: string }>;
|
|
405
|
-
}> {
|
|
406
|
-
await sleep(500);
|
|
543
|
+
async function fetchInitialGameContext(client: GameClient, delayMs = 500): Promise<InitialGameContext> {
|
|
544
|
+
if (delayMs > 0) await sleep(delayMs);
|
|
407
545
|
const [stateResult, roleResult, mapResult] = await Promise.allSettled([
|
|
408
546
|
client.getGameState(),
|
|
409
547
|
client.getRoleInfo(),
|
|
@@ -426,6 +564,54 @@ async function fetchInitialGameContext(client: GameClient): Promise<{
|
|
|
426
564
|
return context;
|
|
427
565
|
}
|
|
428
566
|
|
|
567
|
+
function roleIdFromRoleInfo(roleData: any): string | undefined {
|
|
568
|
+
return roleData?.data?.role ?? roleData?.role;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async function waitForRoleInfo(
|
|
572
|
+
client: GameClient,
|
|
573
|
+
timeoutMs = 30_000,
|
|
574
|
+
intervalMs = 500,
|
|
575
|
+
): Promise<{ role: any | null; errors?: Array<{ command: string; error: string }>; timedOut: boolean }> {
|
|
576
|
+
const deadline = Date.now() + timeoutMs;
|
|
577
|
+
let lastError: { command: string; error: string } | undefined;
|
|
578
|
+
|
|
579
|
+
while (true) {
|
|
580
|
+
try {
|
|
581
|
+
const role = await client.getRoleInfo();
|
|
582
|
+
if (roleIdFromRoleInfo(role)) return { role, timedOut: false };
|
|
583
|
+
lastError = { command: 'game role', error: 'Role info response did not include a role field.' };
|
|
584
|
+
} catch (err) {
|
|
585
|
+
lastError = commandError('game role', err);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
if (Date.now() >= deadline) {
|
|
589
|
+
return { role: null, ...(lastError ? { errors: [lastError] } : {}), timedOut: true };
|
|
590
|
+
}
|
|
591
|
+
await sleep(Math.min(intervalMs, Math.max(0, deadline - Date.now())));
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
async function fetchGameContextWithRole(client: GameClient, role: any): Promise<InitialGameContext> {
|
|
596
|
+
const [stateResult, mapResult] = await Promise.allSettled([
|
|
597
|
+
client.getGameState(),
|
|
598
|
+
client.getMap(),
|
|
599
|
+
]);
|
|
600
|
+
|
|
601
|
+
const errors: Array<{ command: string; error: string }> = [];
|
|
602
|
+
if (stateResult.status === 'rejected') errors.push(commandError('state', stateResult.reason));
|
|
603
|
+
if (mapResult.status === 'rejected') errors.push(commandError('game map', mapResult.reason));
|
|
604
|
+
|
|
605
|
+
const mapData = mapResult.status === 'fulfilled' ? mapResult.value : null;
|
|
606
|
+
return {
|
|
607
|
+
state: stateResult.status === 'fulfilled' ? stateResult.value : null,
|
|
608
|
+
role,
|
|
609
|
+
map: briefGameMap(mapData),
|
|
610
|
+
tasks: mapData?.your_tasks ?? null,
|
|
611
|
+
...(errors.length ? { errors } : {}),
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
429
615
|
const ROLE_DEFAULT_STRATEGY: Record<string, string> = {
|
|
430
616
|
'shrimp_generic': 'task-report',
|
|
431
617
|
'shrimp_warrior': 'task-report',
|
|
@@ -436,7 +622,7 @@ const ROLE_DEFAULT_STRATEGY: Record<string, string> = {
|
|
|
436
622
|
};
|
|
437
623
|
|
|
438
624
|
function autoStartStrategy(roleData: any, stateData?: any, gameId?: string): { strategy: string; pid: number | undefined; child: ChildProcess } | null {
|
|
439
|
-
const roleId
|
|
625
|
+
const roleId = roleIdFromRoleInfo(roleData);
|
|
440
626
|
if (!roleId) return null;
|
|
441
627
|
const strategyId = ROLE_DEFAULT_STRATEGY[roleId];
|
|
442
628
|
if (!strategyId) return null;
|
|
@@ -458,16 +644,24 @@ async function runGameQuit(invokedAs = 'game quit'): Promise<void> {
|
|
|
458
644
|
const stateDir = getProfileStateDir(profile);
|
|
459
645
|
const client = GameClient.fromAuth();
|
|
460
646
|
const presence = await detectGamePresence(client, stateDir);
|
|
461
|
-
let left: 'game' | 'queue' | 'local_runtime' | 'none' = presence.owner_pid ? 'local_runtime' : 'none';
|
|
647
|
+
let left: 'game' | 'game_returned_room' | 'room' | 'queue' | 'local_runtime' | 'none' = presence.owner_pid ? 'local_runtime' : 'none';
|
|
462
648
|
let gameResult: any;
|
|
463
649
|
let queueResult: any;
|
|
650
|
+
let roomResult: any;
|
|
464
651
|
let leaveError: Record<string, any> | undefined;
|
|
652
|
+
const roomGame = hasRoomQueueContext(presence.queue_status);
|
|
465
653
|
|
|
466
654
|
if (presence.presence === 'in_game') {
|
|
467
655
|
try {
|
|
468
656
|
gameResult = await client.leaveGame();
|
|
469
|
-
|
|
470
|
-
|
|
657
|
+
const gameFailure = leaveGameFailureFromResult(gameResult);
|
|
658
|
+
if (gameFailure) {
|
|
659
|
+
leaveError = gameFailure;
|
|
660
|
+
left = 'local_runtime';
|
|
661
|
+
} else {
|
|
662
|
+
if (isLeaveGameSuccess(gameResult)) clearCachedGameServerUrl(authStore, profile.agentName);
|
|
663
|
+
left = roomGame ? 'game_returned_room' : 'game';
|
|
664
|
+
}
|
|
471
665
|
} catch (err) {
|
|
472
666
|
leaveError = {
|
|
473
667
|
...serializeError(err),
|
|
@@ -475,6 +669,13 @@ async function runGameQuit(invokedAs = 'game quit'): Promise<void> {
|
|
|
475
669
|
};
|
|
476
670
|
left = 'local_runtime';
|
|
477
671
|
}
|
|
672
|
+
} else if (presence.presence === 'in_room') {
|
|
673
|
+
try {
|
|
674
|
+
roomResult = await client.leaveRoom();
|
|
675
|
+
left = 'room';
|
|
676
|
+
} catch (err) {
|
|
677
|
+
leaveError = serializeError(err);
|
|
678
|
+
}
|
|
478
679
|
} else if (presence.presence === 'matching') {
|
|
479
680
|
try {
|
|
480
681
|
queueResult = await client.leaveQueue('clawclaw');
|
|
@@ -485,7 +686,10 @@ async function runGameQuit(invokedAs = 'game quit'): Promise<void> {
|
|
|
485
686
|
}
|
|
486
687
|
|
|
487
688
|
endMatch(stateDir);
|
|
488
|
-
const
|
|
689
|
+
const keepOwnerForRoomReturn = left === 'game_returned_room' && presence.owner_pid !== null && !leaveError;
|
|
690
|
+
const owner = keepOwnerForRoomReturn
|
|
691
|
+
? { pid: presence.owner_pid, stopped: false }
|
|
692
|
+
: await stopOwnerWithCommand(stateDir, 'quit');
|
|
489
693
|
stopStrategyIfRunning();
|
|
490
694
|
|
|
491
695
|
const reminder = hubReminder(readCachedGamesPlayed());
|
|
@@ -496,13 +700,18 @@ async function runGameQuit(invokedAs = 'game quit'): Promise<void> {
|
|
|
496
700
|
presence: presence.presence,
|
|
497
701
|
game_result: gameResult,
|
|
498
702
|
queue_result: queueResult,
|
|
703
|
+
room_result: roomResult,
|
|
499
704
|
leave_error: leaveError,
|
|
500
705
|
detection_errors: presence.errors,
|
|
501
706
|
queue_status: presence.queue_status,
|
|
502
707
|
owner_pid: owner.pid ?? presence.owner_pid ?? undefined,
|
|
503
708
|
owner_stopped: owner.stopped,
|
|
504
|
-
hub_reminder: reminder,
|
|
505
|
-
next_step:
|
|
709
|
+
hub_reminder: left === 'game_returned_room' || left === 'room' ? undefined : reminder,
|
|
710
|
+
next_step: left === 'game_returned_room'
|
|
711
|
+
? 'Left the room match. The active stream will reconnect to the familiar room lobby.'
|
|
712
|
+
: left === 'room'
|
|
713
|
+
? 'Left the familiar room.'
|
|
714
|
+
: reminder ? `Stopped local runtime. ${reminder}` : undefined,
|
|
506
715
|
});
|
|
507
716
|
if (presence.presence === 'in_game' && leaveError?.still_alive) {
|
|
508
717
|
out.message = 'The server rejected leaving the active game because you are still alive; local runtime was stopped only.';
|
|
@@ -510,6 +719,188 @@ async function runGameQuit(invokedAs = 'game quit'): Promise<void> {
|
|
|
510
719
|
console.log(JSON.stringify(out, null, 2));
|
|
511
720
|
}
|
|
512
721
|
|
|
722
|
+
async function runEnterRoom(
|
|
723
|
+
source: 'room_create' | 'room_join',
|
|
724
|
+
enter: (client: GameClient) => Promise<any>,
|
|
725
|
+
opts: { force?: boolean; channelUrl?: string; agentType?: string; llmModel?: string },
|
|
726
|
+
targetRoomCode?: string,
|
|
727
|
+
): Promise<void> {
|
|
728
|
+
requireStreamTool(source === 'room_create' ? 'ccl game create-room' : 'ccl game join-room <room_code>');
|
|
729
|
+
const profile = new AuthStore().getActive();
|
|
730
|
+
if (!profile) throw new Error(noAccountMessage('gameStart'));
|
|
731
|
+
const events = startEventSession(source);
|
|
732
|
+
const client = GameClient.fromAuth();
|
|
733
|
+
const stateDir = getProfileStateDir(profile);
|
|
734
|
+
const streamGuard = planRoomEntryStreamGuard({
|
|
735
|
+
runningPid: getRunningGameStartPid(stateDir),
|
|
736
|
+
force: opts.force,
|
|
737
|
+
source,
|
|
738
|
+
});
|
|
739
|
+
if (streamGuard.kind === 'already_running') {
|
|
740
|
+
events.append({ type: 'already_running', pid: streamGuard.pid, source, target_room_code: targetRoomCode });
|
|
741
|
+
console.log(JSON.stringify({
|
|
742
|
+
exit_reason: ['already_running'],
|
|
743
|
+
next_step: streamGuard.nextStep,
|
|
744
|
+
events: [{ type: 'already_running', pid: streamGuard.pid }],
|
|
745
|
+
summary: { phase: 'matching', you: { name: profile.agentName }, game: {}, urgent: {}, meeting: null },
|
|
746
|
+
}));
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
let shouldEnter = true;
|
|
750
|
+
if (source === 'room_join' && targetRoomCode) {
|
|
751
|
+
let queue: any | undefined;
|
|
752
|
+
try {
|
|
753
|
+
queue = await client.getQueueStatus('clawclaw');
|
|
754
|
+
} catch (err) {
|
|
755
|
+
events.append({
|
|
756
|
+
type: 'room_join_preflight_failed',
|
|
757
|
+
target_room_code: targetRoomCode,
|
|
758
|
+
error: serializeError(err),
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
if (queue) {
|
|
762
|
+
const plan = planRoomJoinAction({
|
|
763
|
+
targetRoomCode,
|
|
764
|
+
queueStatus: roomQueueStatus(queue),
|
|
765
|
+
queueMode: roomQueueMode(queue),
|
|
766
|
+
currentRoomCode: queueRoomCode(queue),
|
|
767
|
+
});
|
|
768
|
+
events.append({
|
|
769
|
+
type: 'room_join_preflight',
|
|
770
|
+
target_room_code: targetRoomCode,
|
|
771
|
+
current_room_code: 'roomCode' in plan ? plan.roomCode : undefined,
|
|
772
|
+
action: plan.kind,
|
|
773
|
+
});
|
|
774
|
+
if (plan.kind === 'resume_current_room') {
|
|
775
|
+
shouldEnter = false;
|
|
776
|
+
} else if (plan.kind === 'leave_then_join') {
|
|
777
|
+
try {
|
|
778
|
+
const leaveResult = await client.leaveRoom();
|
|
779
|
+
events.append({
|
|
780
|
+
type: 'room_left_before_join',
|
|
781
|
+
room_code: plan.roomCode,
|
|
782
|
+
target_room_code: targetRoomCode,
|
|
783
|
+
result: leaveResult,
|
|
784
|
+
});
|
|
785
|
+
} catch (err) {
|
|
786
|
+
events.append({
|
|
787
|
+
type: 'room_leave_before_join_failed',
|
|
788
|
+
room_code: plan.roomCode,
|
|
789
|
+
target_room_code: targetRoomCode,
|
|
790
|
+
error: serializeError(err),
|
|
791
|
+
});
|
|
792
|
+
throw err;
|
|
793
|
+
}
|
|
794
|
+
} else if (plan.kind === 'refuse_room_allocated') {
|
|
795
|
+
const err = new Error('This account is already in a room match allocation; cannot switch rooms automatically.');
|
|
796
|
+
events.append({ type: 'room_join_refused', target_room_code: targetRoomCode, error: serializeError(err) });
|
|
797
|
+
throw err;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
stopStrategyIfRunning();
|
|
802
|
+
try {
|
|
803
|
+
if (shouldEnter) {
|
|
804
|
+
const result = await enter(client);
|
|
805
|
+
const data = unwrapData(result);
|
|
806
|
+
events.append({ type: `${source}_accepted`, ...data });
|
|
807
|
+
if (data?.spectate_url) {
|
|
808
|
+
const event = {
|
|
809
|
+
type: source === 'room_create' ? 'room_created' : 'room_joined',
|
|
810
|
+
source,
|
|
811
|
+
...data,
|
|
812
|
+
};
|
|
813
|
+
const line = JSON.stringify({
|
|
814
|
+
exit_reason: [event.type],
|
|
815
|
+
next_step: 'Room entered. Share events[0].spectate_url with the user as the room page link. Keep the room stream attached.',
|
|
816
|
+
events: [event],
|
|
817
|
+
summary: {
|
|
818
|
+
phase: 'room_waiting',
|
|
819
|
+
you: { name: profile.agentName, seat: data.seat, is_owner: data.is_owner },
|
|
820
|
+
room: { room_code: data.room_code, status: data.status },
|
|
821
|
+
},
|
|
822
|
+
}) + '\n';
|
|
823
|
+
process.stdout.write(line);
|
|
824
|
+
if (opts.channelUrl) {
|
|
825
|
+
fetch(opts.channelUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: line }).catch(() => {});
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
} else {
|
|
829
|
+
events.append({ type: `${source}_accepted`, room_code: targetRoomCode, already_in_room: true });
|
|
830
|
+
}
|
|
831
|
+
} catch (err) {
|
|
832
|
+
if (!isAlreadyInRoomError(err)) {
|
|
833
|
+
events.append({ type: `${source}_failed`, error: serializeError(err) });
|
|
834
|
+
throw err;
|
|
835
|
+
}
|
|
836
|
+
if (source === 'room_join') {
|
|
837
|
+
events.append({
|
|
838
|
+
type: `${source}_failed`,
|
|
839
|
+
room_code: targetRoomCode,
|
|
840
|
+
error: serializeError(err),
|
|
841
|
+
});
|
|
842
|
+
throw err;
|
|
843
|
+
}
|
|
844
|
+
events.append({
|
|
845
|
+
type: 'room_already_joined',
|
|
846
|
+
room_code: roomCodeFromAlreadyInRoomError(err),
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
await runGameStart({
|
|
850
|
+
force: opts.force,
|
|
851
|
+
channelUrl: opts.channelUrl,
|
|
852
|
+
agentType: opts.agentType,
|
|
853
|
+
llmModel: opts.llmModel ?? '',
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
async function runGameStartRoom(): Promise<void> {
|
|
858
|
+
const authStore = new AuthStore();
|
|
859
|
+
const profile = authStore.getActive();
|
|
860
|
+
if (!profile) throw new Error('Not logged in.');
|
|
861
|
+
const client = GameClient.fromAuth({ authStore });
|
|
862
|
+
const queue = await client.getQueueStatus('clawclaw');
|
|
863
|
+
if (roomQueueStatus(queue) !== 'in_room') {
|
|
864
|
+
console.log(JSON.stringify({
|
|
865
|
+
ok: false,
|
|
866
|
+
error: 'not_in_room',
|
|
867
|
+
queue_status: unwrapData(queue),
|
|
868
|
+
message: 'This account is not currently in a room.',
|
|
869
|
+
}, null, 2));
|
|
870
|
+
process.exitCode = 1;
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
try {
|
|
874
|
+
const store = EventStore.forActiveAccount();
|
|
875
|
+
store.append({
|
|
876
|
+
type: 'room_start_requested',
|
|
877
|
+
room_code: queueRoomCode(queue),
|
|
878
|
+
ts: new Date().toISOString(),
|
|
879
|
+
});
|
|
880
|
+
} catch {}
|
|
881
|
+
let result: any;
|
|
882
|
+
try {
|
|
883
|
+
result = await client.startRoom();
|
|
884
|
+
} catch (err) {
|
|
885
|
+
const failure = roomStartFailureFromError(err, queue);
|
|
886
|
+
if (failure) {
|
|
887
|
+
console.log(JSON.stringify(failure, null, 2));
|
|
888
|
+
process.exitCode = 1;
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
throw err;
|
|
892
|
+
}
|
|
893
|
+
try {
|
|
894
|
+
const store = EventStore.forActiveAccount();
|
|
895
|
+
store.append({ type: 'room_start_accepted', ts: new Date().toISOString(), ...unwrapData(result) });
|
|
896
|
+
} catch {}
|
|
897
|
+
console.log(JSON.stringify({
|
|
898
|
+
ok: true,
|
|
899
|
+
command: 'game start-room',
|
|
900
|
+
result,
|
|
901
|
+
}, null, 2));
|
|
902
|
+
}
|
|
903
|
+
|
|
513
904
|
/**
|
|
514
905
|
* Absolute path to the bundled read-only Monitor diagnostic. Resolved from this
|
|
515
906
|
* module's location — the package ships and runs straight from `src/` (see
|
|
@@ -542,14 +933,17 @@ export function detectMonitorStatus(scriptPath: string = MONITOR_CHECK_SCRIPT):
|
|
|
542
933
|
}
|
|
543
934
|
}
|
|
544
935
|
|
|
936
|
+
function requireStreamTool(command: string): void {
|
|
937
|
+
if (process.env.CLAWCLAW_REQUIRE_STREAM_TOOL !== '1' || process.env.CLAWCLAW_STREAMED === '1') return;
|
|
938
|
+
process.stderr.write(
|
|
939
|
+
`In OpenClaw, start the game via the clawclaw_game_start tool - do not exec \`${command}\` directly.\n` +
|
|
940
|
+
'When run raw, the event NDJSON only fills an unconsumed buffer, so you never receive speech_your_turn and stay silent.\n',
|
|
941
|
+
);
|
|
942
|
+
process.exit(2);
|
|
943
|
+
}
|
|
944
|
+
|
|
545
945
|
async function runGameStart(opts: { force?: boolean; channelUrl?: string; competition?: boolean; agentType?: string; llmModel: string }): Promise<void> {
|
|
546
|
-
|
|
547
|
-
process.stderr.write(
|
|
548
|
-
'In OpenClaw, start the game via the clawclaw_game_start tool - do not exec `ccl game start` directly.\n' +
|
|
549
|
-
'When run raw, the event NDJSON only fills an unconsumed buffer, so you never receive speech_your_turn and stay silent.\n',
|
|
550
|
-
);
|
|
551
|
-
process.exit(2);
|
|
552
|
-
}
|
|
946
|
+
requireStreamTool('ccl game start');
|
|
553
947
|
|
|
554
948
|
// Channel 模式硬兜底:带 --channel-url 时,把真正的长流逻辑 fork 到 detached 后台进程,
|
|
555
949
|
// 父进程立即返回。这样即使 agent 误用 Powershell/前台直接执行,也不会阻塞——事件仍通过
|
|
@@ -594,8 +988,10 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
594
988
|
const feedPath = join(stateDir, 'feed.json');
|
|
595
989
|
clearCachedGameServerUrl(authStore, profile.agentName);
|
|
596
990
|
const client = GameClient.fromAuth();
|
|
597
|
-
let currentGameMode:
|
|
991
|
+
let currentGameMode: RuntimeGameMode | undefined;
|
|
598
992
|
let eventRuntime: EventRuntime | undefined;
|
|
993
|
+
let roomRuntime: RoomLobbyRuntime | undefined;
|
|
994
|
+
let lastEventStopReason: string | null = null;
|
|
599
995
|
let streamAbortController: AbortController | null = null;
|
|
600
996
|
let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
601
997
|
let ownerControl: OwnerControlServer | null = null;
|
|
@@ -616,7 +1012,7 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
616
1012
|
const pid = strategyChild?.pid;
|
|
617
1013
|
return { strategy: currentStrategy, running: !!(pid && isPidAlive(pid)) };
|
|
618
1014
|
};
|
|
619
|
-
const updateGameMode = (mode:
|
|
1015
|
+
const updateGameMode = (mode: RuntimeGameMode | undefined): void => {
|
|
620
1016
|
if (!mode) return;
|
|
621
1017
|
currentGameMode = mode;
|
|
622
1018
|
};
|
|
@@ -625,7 +1021,10 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
625
1021
|
};
|
|
626
1022
|
const currentSummary = (): any | null => {
|
|
627
1023
|
const runtimeFeed = eventRuntime?.snapshot();
|
|
628
|
-
const
|
|
1024
|
+
const roomFeed = roomRuntime?.snapshot();
|
|
1025
|
+
const feed = runtimeFeed && runtimeFeed.phase !== 'lobby'
|
|
1026
|
+
? runtimeFeed
|
|
1027
|
+
: roomFeed ?? ownerFeed;
|
|
629
1028
|
const automation = currentAutomationSummary();
|
|
630
1029
|
return summarizeFeed(automation ? { ...feed, automation } : feed);
|
|
631
1030
|
};
|
|
@@ -648,6 +1047,7 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
648
1047
|
const onOwnerSignal = (): void => {
|
|
649
1048
|
streamAbortController?.abort();
|
|
650
1049
|
eventRuntime?.stop('SIGTERM');
|
|
1050
|
+
roomRuntime?.stop('SIGTERM');
|
|
651
1051
|
stopOwnedStrategy();
|
|
652
1052
|
cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
|
|
653
1053
|
process.exit(130);
|
|
@@ -690,6 +1090,7 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
690
1090
|
emitOwnerExit(kind, command);
|
|
691
1091
|
streamAbortController?.abort();
|
|
692
1092
|
eventRuntime?.stop('manual');
|
|
1093
|
+
roomRuntime?.stop('manual');
|
|
693
1094
|
stopOwnedStrategy();
|
|
694
1095
|
};
|
|
695
1096
|
const emitMatchEvent = (evt: Record<string, any>): void => {
|
|
@@ -700,18 +1101,24 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
700
1101
|
};
|
|
701
1102
|
const ensureEventRuntime = async (): Promise<void> => {
|
|
702
1103
|
if (eventRuntime) return;
|
|
1104
|
+
lastEventStopReason = null;
|
|
703
1105
|
eventRuntime = new EventRuntime({
|
|
704
1106
|
authStore,
|
|
705
1107
|
getAutomation: currentAutomationSummary,
|
|
706
1108
|
getGameMode: () => currentGameMode,
|
|
707
1109
|
onStop: (stop) => {
|
|
1110
|
+
lastEventStopReason = stop.reason;
|
|
708
1111
|
if (stop.reason === 'game_over' || stop.reason === 'user_left_game') return;
|
|
709
1112
|
streamAbortController?.abort();
|
|
710
1113
|
},
|
|
711
1114
|
});
|
|
712
1115
|
await eventRuntime.start();
|
|
713
1116
|
};
|
|
714
|
-
const streamGame = async (
|
|
1117
|
+
const streamGame = async (streamOpts: {
|
|
1118
|
+
emitGameStart?: boolean;
|
|
1119
|
+
finalDrainOnAbort?: boolean | (() => boolean);
|
|
1120
|
+
finalDrainTimeoutMs?: number;
|
|
1121
|
+
} = {}): Promise<void> => {
|
|
715
1122
|
const sessionPath = EventStore.latestSessionPath();
|
|
716
1123
|
const ctrl = new AbortController();
|
|
717
1124
|
streamAbortController = ctrl;
|
|
@@ -731,7 +1138,9 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
731
1138
|
skipFeedWait: true,
|
|
732
1139
|
readSummary: currentSummary,
|
|
733
1140
|
skipBacklogTypes: ['match_waiting', 'match_timeout'],
|
|
734
|
-
emitGameStart: true,
|
|
1141
|
+
emitGameStart: streamOpts.emitGameStart ?? true,
|
|
1142
|
+
finalDrainOnAbort: streamOpts.finalDrainOnAbort,
|
|
1143
|
+
finalDrainTimeoutMs: streamOpts.finalDrainTimeoutMs,
|
|
735
1144
|
hubReminder: hubReminder(readCachedGamesPlayed()),
|
|
736
1145
|
});
|
|
737
1146
|
} catch (err: any) {
|
|
@@ -743,18 +1152,71 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
743
1152
|
streamAbortController = null;
|
|
744
1153
|
}
|
|
745
1154
|
};
|
|
746
|
-
const handleAllocated = async (
|
|
747
|
-
|
|
1155
|
+
const handleAllocated = async (
|
|
1156
|
+
queue: any,
|
|
1157
|
+
preserveStrategy: boolean,
|
|
1158
|
+
sessionSource?: string,
|
|
1159
|
+
): Promise<void> => {
|
|
1160
|
+
let currentQueue = queue;
|
|
1161
|
+
updateGameMode(isRoomAllocatedQueueStatus(currentQueue) ? 'room' : queueMode(currentQueue));
|
|
1162
|
+
try {
|
|
1163
|
+
const refreshedQueue = await client.getQueueStatus('clawclaw');
|
|
1164
|
+
if (queueStatus(refreshedQueue) === 'allocated') {
|
|
1165
|
+
currentQueue = refreshedQueue;
|
|
1166
|
+
updateGameMode(isRoomAllocatedQueueStatus(currentQueue) ? 'room' : queueMode(currentQueue));
|
|
1167
|
+
}
|
|
1168
|
+
} catch {
|
|
1169
|
+
// Keep the original allocation; role polling below will report failures.
|
|
1170
|
+
}
|
|
748
1171
|
const finalState = readMatchState(stateDir);
|
|
749
1172
|
const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
|
|
750
1173
|
endMatch(stateDir);
|
|
751
|
-
|
|
752
|
-
|
|
1174
|
+
eventRuntime?.stop('manual');
|
|
1175
|
+
eventRuntime = undefined;
|
|
1176
|
+
startEventSession(sessionSource ?? (isRoomAllocatedQueueStatus(currentQueue) ? 'room_game' : 'game_start_allocated'), {
|
|
1177
|
+
game_id: nonEmptyString(currentQueue?.game_id) ?? nonEmptyString(currentQueue?.data?.game_id),
|
|
1178
|
+
});
|
|
1179
|
+
const roleResult = await waitForRoleInfo(client);
|
|
753
1180
|
// Supplement game_id from queue response when /game/current doesn't carry it yet.
|
|
754
|
-
const queueGameId = nonEmptyString(
|
|
1181
|
+
const queueGameId = nonEmptyString(currentQueue?.game_id) ?? nonEmptyString(currentQueue?.data?.game_id);
|
|
1182
|
+
if (roleResult.timedOut || !roleResult.role) {
|
|
1183
|
+
ownerFeed = {
|
|
1184
|
+
...ownerFeed,
|
|
1185
|
+
ts: new Date().toISOString(),
|
|
1186
|
+
phase: 'allocated',
|
|
1187
|
+
allocation: {
|
|
1188
|
+
queue: currentQueue,
|
|
1189
|
+
waited_secs: waitedSecs,
|
|
1190
|
+
game_id: queueGameId,
|
|
1191
|
+
errors: roleResult.errors,
|
|
1192
|
+
role_timeout_ms: 30_000,
|
|
1193
|
+
},
|
|
1194
|
+
};
|
|
1195
|
+
emitLifecycle('role_timeout', {
|
|
1196
|
+
queue: currentQueue,
|
|
1197
|
+
waited_secs: waitedSecs,
|
|
1198
|
+
game_id: queueGameId,
|
|
1199
|
+
errors: roleResult.errors,
|
|
1200
|
+
role_timeout_ms: 30_000,
|
|
1201
|
+
}, 'Timed out waiting for /api/v1/game/role_info. The stream is exiting; retry `ccl game start` after the GameServer is ready.');
|
|
1202
|
+
process.exitCode = 1;
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
const context = await fetchGameContextWithRole(client, roleResult.role);
|
|
1206
|
+
let identity = gameStrategyIdentity(context.state, context.role);
|
|
755
1207
|
if (!identity.gameId && queueGameId) {
|
|
756
1208
|
identity.gameId = queueGameId;
|
|
757
1209
|
}
|
|
1210
|
+
let strategyInfo: { strategy: string; pid: number | undefined } | null = null;
|
|
1211
|
+
if (identity.alive !== false) {
|
|
1212
|
+
stopOwnedStrategy();
|
|
1213
|
+
const started = autoStartStrategy(context.role, context.state, identity.gameId);
|
|
1214
|
+
if (started) {
|
|
1215
|
+
strategyChild = started.child;
|
|
1216
|
+
currentStrategy = started.strategy;
|
|
1217
|
+
strategyInfo = { strategy: started.strategy, pid: started.pid };
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
758
1220
|
const role = unwrapData(context.role);
|
|
759
1221
|
ownerFeed = {
|
|
760
1222
|
...ownerFeed,
|
|
@@ -772,18 +1234,8 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
772
1234
|
game_id: identity.gameId,
|
|
773
1235
|
},
|
|
774
1236
|
};
|
|
775
|
-
let strategyInfo: { strategy: string; pid: number | undefined } | null = null;
|
|
776
|
-
if (identity.alive !== false) {
|
|
777
|
-
stopOwnedStrategy();
|
|
778
|
-
const started = autoStartStrategy(context.role, context.state, identity.gameId);
|
|
779
|
-
if (started) {
|
|
780
|
-
strategyChild = started.child;
|
|
781
|
-
currentStrategy = started.strategy;
|
|
782
|
-
strategyInfo = { strategy: started.strategy, pid: started.pid };
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
1237
|
const allocationPayload = {
|
|
786
|
-
queue,
|
|
1238
|
+
queue: currentQueue,
|
|
787
1239
|
waited_secs: waitedSecs,
|
|
788
1240
|
game_id: identity.gameId || undefined,
|
|
789
1241
|
...context,
|
|
@@ -793,6 +1245,109 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
793
1245
|
await ensureEventRuntime();
|
|
794
1246
|
await streamGame();
|
|
795
1247
|
};
|
|
1248
|
+
const roomReturnSourceFor = (endedReason: string | null | undefined): string => {
|
|
1249
|
+
return endedReason === 'user_left_game' ? 'room_game_left_return_room' : 'room_game_over_return_room';
|
|
1250
|
+
};
|
|
1251
|
+
|
|
1252
|
+
const prepareRoomLobbyReturn = async (endedReason: string | null | undefined): Promise<string | null> => {
|
|
1253
|
+
eventRuntime?.stop('manual');
|
|
1254
|
+
eventRuntime = undefined;
|
|
1255
|
+
stopOwnedStrategy();
|
|
1256
|
+
clearCachedGameServerUrl(authStore, profile.agentName);
|
|
1257
|
+
if (ownerExitRequested) return null;
|
|
1258
|
+
|
|
1259
|
+
let queueAfterGame: any;
|
|
1260
|
+
try {
|
|
1261
|
+
queueAfterGame = await client.getQueueStatus('clawclaw');
|
|
1262
|
+
updateGameMode(queueMode(queueAfterGame));
|
|
1263
|
+
} catch (err) {
|
|
1264
|
+
emitLifecycle('room_lobby_reconnect_failed', {
|
|
1265
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1266
|
+
message: 'Room match ended, but Lobby queue status could not be confirmed.',
|
|
1267
|
+
}, 'Room match ended. Launch `ccl game start` to reattach, or ask the user whether to leave the room.');
|
|
1268
|
+
return null;
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
if (!hasRoomQueueContext(queueAfterGame)) {
|
|
1272
|
+
emitLifecycle('room_lobby_missing', {
|
|
1273
|
+
queue: queueAfterGame,
|
|
1274
|
+
message: 'Room match ended, but this account is no longer in a familiar room.',
|
|
1275
|
+
}, 'Room match ended and no room lobby was found. Do not auto-start another match; ask the user what to do next.');
|
|
1276
|
+
return null;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
emitMatchEvent({
|
|
1280
|
+
type: 'room_returning_to_lobby',
|
|
1281
|
+
reason: endedReason ?? 'game_over',
|
|
1282
|
+
queue: queueAfterGame,
|
|
1283
|
+
message: 'Room match ended; reconnecting to Lobby agent_ws for the room snapshot.',
|
|
1284
|
+
});
|
|
1285
|
+
return roomReturnSourceFor(endedReason);
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
const streamRoomLobby = async (source: string): Promise<void> => {
|
|
1289
|
+
let roomSource = source;
|
|
1290
|
+
while (!ownerExitRequested) {
|
|
1291
|
+
startEventSession(roomSource);
|
|
1292
|
+
const roomStartedRef: { value: RoomGameStarted | null } = { value: null };
|
|
1293
|
+
let roomStopReason: string | null = null;
|
|
1294
|
+
ownerFeed = {
|
|
1295
|
+
...ownerFeed,
|
|
1296
|
+
ts: new Date().toISOString(),
|
|
1297
|
+
phase: 'room_waiting',
|
|
1298
|
+
};
|
|
1299
|
+
roomRuntime = new RoomLobbyRuntime({
|
|
1300
|
+
authStore,
|
|
1301
|
+
onGameStarted: (event) => {
|
|
1302
|
+
roomStartedRef.value = event;
|
|
1303
|
+
streamAbortController?.abort();
|
|
1304
|
+
},
|
|
1305
|
+
onStop: (reason) => {
|
|
1306
|
+
roomStopReason = reason;
|
|
1307
|
+
if (reason === 'self_left') streamAbortController?.abort();
|
|
1308
|
+
},
|
|
1309
|
+
});
|
|
1310
|
+
await roomRuntime.start();
|
|
1311
|
+
if (!roomStartedRef.value) {
|
|
1312
|
+
await streamGame({
|
|
1313
|
+
emitGameStart: false,
|
|
1314
|
+
finalDrainOnAbort: () => !!roomStartedRef.value,
|
|
1315
|
+
finalDrainTimeoutMs: 500,
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
if (!roomStartedRef.value && ownerExitRequested) return;
|
|
1319
|
+
if (!roomStartedRef.value && roomStopReason === 'self_left') {
|
|
1320
|
+
emitLifecycle('room_self_left', {
|
|
1321
|
+
message: ROOM_SELF_LEFT_STREAM_MESSAGE,
|
|
1322
|
+
}, ROOM_SELF_LEFT_MESSAGE);
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
if (!roomStartedRef.value || ownerExitRequested) return;
|
|
1326
|
+
|
|
1327
|
+
const started = roomStartedRef.value;
|
|
1328
|
+
roomRuntime.stop('game_started');
|
|
1329
|
+
roomRuntime = undefined;
|
|
1330
|
+
applyRoomGameServer(client, started);
|
|
1331
|
+
await handleAllocated({
|
|
1332
|
+
status: 'allocated',
|
|
1333
|
+
game_id: started.game_id,
|
|
1334
|
+
game_server_name: started.game_server_name,
|
|
1335
|
+
ws_url: started.ws_url,
|
|
1336
|
+
}, true);
|
|
1337
|
+
|
|
1338
|
+
const endedReason = lastEventStopReason ?? eventRuntime?.snapshot()?.phase;
|
|
1339
|
+
const nextRoomSource = await prepareRoomLobbyReturn(endedReason);
|
|
1340
|
+
if (!nextRoomSource) return;
|
|
1341
|
+
roomSource = nextRoomSource;
|
|
1342
|
+
}
|
|
1343
|
+
};
|
|
1344
|
+
const streamRoomAllocated = async (queue: any, source: string): Promise<void> => {
|
|
1345
|
+
await handleAllocated(queue, true, source);
|
|
1346
|
+
const endedReason = lastEventStopReason ?? eventRuntime?.snapshot()?.phase;
|
|
1347
|
+
const nextRoomSource = await prepareRoomLobbyReturn(endedReason);
|
|
1348
|
+
if (!nextRoomSource) return;
|
|
1349
|
+
await streamRoomLobby(nextRoomSource);
|
|
1350
|
+
};
|
|
796
1351
|
const pollQueue = async (preserveStrategy: boolean): Promise<void> => {
|
|
797
1352
|
const intervalMs = 2000;
|
|
798
1353
|
const QUEUE_POLL_HEARTBEAT_MS = 60_000;
|
|
@@ -827,6 +1382,10 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
827
1382
|
}
|
|
828
1383
|
|
|
829
1384
|
if (queueStatus(queue) === 'allocated') {
|
|
1385
|
+
if (isRoomAllocatedQueueStatus(queue)) {
|
|
1386
|
+
await streamRoomAllocated(queue, 'game_start_room_allocated_from_queue');
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
830
1389
|
await handleAllocated(queue, preserveStrategy);
|
|
831
1390
|
return;
|
|
832
1391
|
}
|
|
@@ -882,9 +1441,11 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
882
1441
|
}
|
|
883
1442
|
const status = queueStatus(queue);
|
|
884
1443
|
if (status === 'allocated') {
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
1444
|
+
if (isRoomAllocatedQueueStatus(queue)) {
|
|
1445
|
+
await streamRoomAllocated(queue, 'game_start_already_in_room_game');
|
|
1446
|
+
} else {
|
|
1447
|
+
await handleAllocated(queue, true);
|
|
1448
|
+
}
|
|
888
1449
|
return true;
|
|
889
1450
|
}
|
|
890
1451
|
if (status === 'queued' || status === 'already_in_queue') {
|
|
@@ -915,12 +1476,13 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
915
1476
|
gameStartPid: null,
|
|
916
1477
|
hasMatchState: readMatchState(stateDir) !== null,
|
|
917
1478
|
queueStatus: queueStatus(initialQueue),
|
|
1479
|
+
queueMode: roomQueueMode(initialQueue),
|
|
918
1480
|
});
|
|
919
1481
|
|
|
920
1482
|
ownerFeed = {
|
|
921
1483
|
...ownerFeed,
|
|
922
1484
|
ts: new Date().toISOString(),
|
|
923
|
-
phase: plan.kind === 'resume_allocated' ? 'allocated' : 'matching',
|
|
1485
|
+
phase: (plan.kind === 'resume_allocated' || plan.kind === 'resume_room_allocated') ? 'allocated' : 'matching',
|
|
924
1486
|
};
|
|
925
1487
|
if (plan.kind !== 'fresh_start' && !queueMode(initialQueue)) currentGameMode = undefined;
|
|
926
1488
|
ownerControl = await startOwnerControlServer(stateDir, async (request) => {
|
|
@@ -970,12 +1532,20 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
970
1532
|
}
|
|
971
1533
|
|
|
972
1534
|
if (plan.kind === 'resume_allocated') {
|
|
973
|
-
ensureEventSession('game_start_resume_allocated');
|
|
974
|
-
await ensureEventRuntime();
|
|
975
1535
|
await handleAllocated(initialQueue, true);
|
|
976
1536
|
return;
|
|
977
1537
|
}
|
|
978
1538
|
|
|
1539
|
+
if (plan.kind === 'resume_room_allocated') {
|
|
1540
|
+
await streamRoomAllocated(initialQueue, 'game_start_resume_room_allocated');
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
if (plan.kind === 'resume_room') {
|
|
1545
|
+
await streamRoomLobby('game_start_resume_room');
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
|
|
979
1549
|
let joinResult: any;
|
|
980
1550
|
try {
|
|
981
1551
|
// The Monitor status is only meaningful for Claude Code hosts; for other
|
|
@@ -990,6 +1560,10 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
990
1560
|
});
|
|
991
1561
|
updateGameMode(queueMode(joinResult));
|
|
992
1562
|
} catch (err) {
|
|
1563
|
+
if (isAlreadyInRoomError(err)) {
|
|
1564
|
+
await streamRoomLobby('game_start_already_in_room');
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
993
1567
|
if (isAlreadyInGameError(err) && await recoverAlreadyInGame()) return;
|
|
994
1568
|
if (opts.competition) {
|
|
995
1569
|
const code = apiErrorCode(err);
|
|
@@ -1025,6 +1599,10 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
1025
1599
|
throw err;
|
|
1026
1600
|
}
|
|
1027
1601
|
const joinedStatus = queueStatus(joinResult);
|
|
1602
|
+
if (joinedStatus === 'in_room') {
|
|
1603
|
+
await streamRoomLobby('game_start_joined_room');
|
|
1604
|
+
return;
|
|
1605
|
+
}
|
|
1028
1606
|
if (joinedStatus === 'already_in_queue') {
|
|
1029
1607
|
await resumeQueue('game_start_already_in_queue');
|
|
1030
1608
|
return;
|
|
@@ -1043,8 +1621,7 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
1043
1621
|
|
|
1044
1622
|
stopOwnedStrategy();
|
|
1045
1623
|
|
|
1046
|
-
const events =
|
|
1047
|
-
events.append({ type: 'session_started', source: 'game_start' });
|
|
1624
|
+
const events = startEventSession('game_start');
|
|
1048
1625
|
emitLifecycle('joined', withCurrentGameMode({ ...joinResult, queue: joinedQueue }),
|
|
1049
1626
|
'Join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Game runtime is attached.');
|
|
1050
1627
|
startMatch(stateDir);
|
|
@@ -1055,6 +1632,7 @@ async function runGameStart(opts: { force?: boolean; channelUrl?: string; compet
|
|
|
1055
1632
|
process.off('SIGINT', onOwnerSignal);
|
|
1056
1633
|
process.off('SIGTERM', onOwnerSignal);
|
|
1057
1634
|
eventRuntime?.stop('manual');
|
|
1635
|
+
roomRuntime?.stop('manual');
|
|
1058
1636
|
stopOwnedStrategy();
|
|
1059
1637
|
if (ownerControl) await ownerControl.close();
|
|
1060
1638
|
cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
|
|
@@ -1082,8 +1660,7 @@ export function createGameCommand(): Command {
|
|
|
1082
1660
|
// off for other platforms (mirrors `game start`).
|
|
1083
1661
|
const monitorStatus = opts.agentType === 'claude-code' ? detectMonitorStatus() : undefined;
|
|
1084
1662
|
const result = await client.joinQueue({ gameType: 'clawclaw', agentType: opts.agentType, monitorStatus, llmModel: opts.llmModel });
|
|
1085
|
-
const events =
|
|
1086
|
-
events.append({ type: 'session_started', source: 'game_join' });
|
|
1663
|
+
const events = startEventSession('game_join');
|
|
1087
1664
|
console.log(JSON.stringify(result, null, 2));
|
|
1088
1665
|
const stateDir = getProfileStateDir(profile);
|
|
1089
1666
|
// Reset match-state: a fresh queue session starts here so `ccl game queue`
|
|
@@ -1103,6 +1680,34 @@ export function createGameCommand(): Command {
|
|
|
1103
1680
|
.option('--channel-url <url>', 'forward each NDJSON line via HTTP POST to this URL')
|
|
1104
1681
|
.action(runGameStart);
|
|
1105
1682
|
|
|
1683
|
+
game
|
|
1684
|
+
.command('create-room')
|
|
1685
|
+
.description('Create a familiar room, then attach the room lobby stream as NDJSON.')
|
|
1686
|
+
.option('--force', 'force restart: kill any lingering game-start stream process and start fresh')
|
|
1687
|
+
.option('--channel-url <url>', 'forward each NDJSON line via HTTP POST to this URL')
|
|
1688
|
+
.option('--agent-type <platform>', 'the agent platform you are running on (e.g. claude-code, openclaw, hermes)')
|
|
1689
|
+
.option('--llm-model <model>', 'the model the lobster side uses; stored only if the flow later enters matchmaking')
|
|
1690
|
+
.action(async (opts: { force?: boolean; channelUrl?: string; agentType?: string; llmModel?: string }) => {
|
|
1691
|
+
await runEnterRoom('room_create', (client) => client.createRoom(), opts);
|
|
1692
|
+
});
|
|
1693
|
+
|
|
1694
|
+
game
|
|
1695
|
+
.command('join-room')
|
|
1696
|
+
.description('Join a familiar room, then attach the room lobby stream as NDJSON.')
|
|
1697
|
+
.argument('<room_code>', 'six digit room code')
|
|
1698
|
+
.option('--force', 'force restart: kill any lingering game-start stream process and start fresh')
|
|
1699
|
+
.option('--channel-url <url>', 'forward each NDJSON line via HTTP POST to this URL')
|
|
1700
|
+
.option('--agent-type <platform>', 'the agent platform you are running on (e.g. claude-code, openclaw, hermes)')
|
|
1701
|
+
.option('--llm-model <model>', 'the model the lobster side uses; stored only if the flow later enters matchmaking')
|
|
1702
|
+
.action(async (roomCode: string, opts: { force?: boolean; channelUrl?: string; agentType?: string; llmModel?: string }) => {
|
|
1703
|
+
await runEnterRoom('room_join', (client) => client.joinRoom(roomCode), opts, roomCode);
|
|
1704
|
+
});
|
|
1705
|
+
|
|
1706
|
+
game
|
|
1707
|
+
.command('start-room')
|
|
1708
|
+
.description('Manually start the current familiar room if this agent is the room owner.')
|
|
1709
|
+
.action(runGameStartRoom);
|
|
1710
|
+
|
|
1106
1711
|
game
|
|
1107
1712
|
.command('queue', { hidden: true })
|
|
1108
1713
|
.alias('q')
|
|
@@ -1273,14 +1878,15 @@ export function createGameCommand(): Command {
|
|
|
1273
1878
|
const authStore = new AuthStore();
|
|
1274
1879
|
const profile = authStore.getActive();
|
|
1275
1880
|
if (!profile) throw new Error('Not logged in.');
|
|
1276
|
-
const
|
|
1277
|
-
const url = `${origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`;
|
|
1881
|
+
const url = lobbyWatchUrl(profile);
|
|
1278
1882
|
console.log(JSON.stringify({ url, message: 'Open in browser to spectate.' }, null, 2));
|
|
1279
1883
|
});
|
|
1280
1884
|
|
|
1281
1885
|
// ── Adapter metadata: queue blocks up to --timeout secs (default 30); cap L2 spawn at 60s ──
|
|
1282
1886
|
setMeta(game.commands.find((c) => c.name() === 'queue')!, { longRunning: true, timeoutMs: 60_000 });
|
|
1283
1887
|
setMeta(game.commands.find((c) => c.name() === 'start')!, { longRunning: true, timeoutMs: 1_800_000 });
|
|
1888
|
+
setMeta(game.commands.find((c) => c.name() === 'create-room')!, { longRunning: true, timeoutMs: 1_800_000 });
|
|
1889
|
+
setMeta(game.commands.find((c) => c.name() === 'join-room')!, { longRunning: true, timeoutMs: 1_800_000 });
|
|
1284
1890
|
|
|
1285
1891
|
return game;
|
|
1286
1892
|
}
|