@myclaw163/clawclaw-cli 0.6.82 → 0.6.83

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.
Files changed (214) hide show
  1. package/README.md +385 -385
  2. package/bin/clawclaw-cli.mjs +3 -3
  3. package/package.json +48 -48
  4. package/personas//346/227/240/344/272/272/350/256/276.md +3 -3
  5. package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +23 -23
  6. package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +22 -22
  7. package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +22 -22
  8. package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +22 -22
  9. package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +23 -23
  10. package/scripts/check-skill-command-surface.mjs +118 -118
  11. package/scripts/enable_monitor.cjs +677 -677
  12. package/scripts/enable_monitor.test.mjs +201 -201
  13. package/scripts/find-hide-spots.py +157 -157
  14. package/scripts/postinstall.mjs +20 -20
  15. package/scripts/sync-bundled-skill.mjs +254 -254
  16. package/scripts/sync-bundled-skill.test.mjs +152 -152
  17. package/skills/clawclaw/.gitkeep +0 -0
  18. package/skills/clawclaw/SKILL.md +258 -256
  19. package/skills/clawclaw/references/CHATTERBOX.md +141 -141
  20. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  21. package/skills/clawclaw/references/COMMANDS.md +158 -158
  22. package/skills/clawclaw/references/GAME-MECHANICS.md +188 -188
  23. package/skills/clawclaw/references/HUB.md +48 -48
  24. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  25. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  26. package/skills/clawclaw/references/STREAM.md +84 -84
  27. package/skills/clawclaw/references/TACTICS.md +65 -65
  28. package/src/assets/clawclaw-ascii-map.txt +40 -40
  29. package/src/cli.ts +113 -113
  30. package/src/commands/_schema.ts +124 -124
  31. package/src/commands/account.ts +266 -266
  32. package/src/commands/competition.ts +42 -42
  33. package/src/commands/data.test.ts +33 -33
  34. package/src/commands/data.ts +22 -22
  35. package/src/commands/do.test.ts +40 -40
  36. package/src/commands/do.ts +93 -93
  37. package/src/commands/events.test.ts +100 -100
  38. package/src/commands/events.ts +250 -250
  39. package/src/commands/game-map.test.ts +28 -28
  40. package/src/commands/game-start-plan.test.ts +84 -84
  41. package/src/commands/game.ts +1237 -1235
  42. package/src/commands/history-player.test.ts +102 -102
  43. package/src/commands/history.ts +573 -573
  44. package/src/commands/hub.test.ts +113 -96
  45. package/src/commands/hub.ts +244 -234
  46. package/src/commands/knowledge.test.ts +13 -13
  47. package/src/commands/knowledge.ts +139 -139
  48. package/src/commands/load.test.ts +65 -65
  49. package/src/commands/load.ts +22 -22
  50. package/src/commands/meeting-history.test.ts +106 -106
  51. package/src/commands/memory.ts +40 -40
  52. package/src/commands/peek.ts +45 -45
  53. package/src/commands/persona.ts +62 -57
  54. package/src/commands/setup/codex.ts +266 -266
  55. package/src/commands/skill.ts +128 -128
  56. package/src/commands/state.ts +46 -46
  57. package/src/commands/strategy.test.ts +153 -153
  58. package/src/commands/strategy.ts +183 -183
  59. package/src/commands/upgrade.test.ts +82 -82
  60. package/src/commands/upgrade.ts +148 -148
  61. package/src/commands/watch.test.ts +999 -999
  62. package/src/commands/watch.ts +660 -660
  63. package/src/lib/account-guidance.test.ts +32 -32
  64. package/src/lib/account-guidance.ts +62 -62
  65. package/src/lib/auth.test.ts +72 -72
  66. package/src/lib/auth.ts +153 -153
  67. package/src/lib/command-meta.ts +37 -37
  68. package/src/lib/competition.ts +79 -79
  69. package/src/lib/game-client.test.ts +44 -0
  70. package/src/lib/game-client.ts +375 -370
  71. package/src/lib/game-context.ts +92 -92
  72. package/src/lib/http-keepalive.ts +15 -15
  73. package/src/lib/http-transport.test.ts +61 -42
  74. package/src/lib/http-transport.ts +118 -113
  75. package/src/lib/hub-client.test.ts +57 -56
  76. package/src/lib/hub-client.ts +88 -88
  77. package/src/lib/hub-install.test.ts +136 -98
  78. package/src/lib/hub-install.ts +198 -160
  79. package/src/lib/hub-reminder.ts +78 -78
  80. package/src/lib/hub-unzip.test.ts +69 -69
  81. package/src/lib/hub-unzip.ts +62 -62
  82. package/src/lib/init-command.test.ts +75 -75
  83. package/src/lib/init-command.ts +130 -130
  84. package/src/lib/knowledge-store.test.ts +170 -170
  85. package/src/lib/knowledge-store.ts +369 -369
  86. package/src/lib/load-context.test.ts +52 -52
  87. package/src/lib/load-context.ts +54 -54
  88. package/src/lib/match-state.test.ts +134 -134
  89. package/src/lib/match-state.ts +94 -94
  90. package/src/lib/normalize.ts +42 -42
  91. package/src/lib/persona.test.ts +84 -84
  92. package/src/lib/persona.ts +120 -89
  93. package/src/lib/server-registry.ts +152 -152
  94. package/src/lib/skill-version.test.ts +48 -48
  95. package/src/lib/skill-version.ts +19 -19
  96. package/src/lib/strategy-export.test.ts +240 -240
  97. package/src/lib/strategy-export.ts +247 -247
  98. package/src/lib/user-data.test.ts +97 -97
  99. package/src/lib/user-data.ts +374 -374
  100. package/src/lib/workspace-argv.test.ts +49 -49
  101. package/src/lib/workspace-argv.ts +44 -44
  102. package/src/perception/player-history-store.test.ts +87 -87
  103. package/src/perception/player-history-store.ts +194 -194
  104. package/src/pipeline/event-format.test.ts +243 -243
  105. package/src/pipeline/event-format.ts +501 -501
  106. package/src/pipeline/event-hints.ts +195 -195
  107. package/src/pipeline/event-store.test.ts +28 -28
  108. package/src/pipeline/event-store.ts +193 -193
  109. package/src/pipeline/pipeline.ts +35 -35
  110. package/src/pipeline/player-projection.test.ts +168 -168
  111. package/src/pipeline/player-projection.ts +370 -370
  112. package/src/runtime/auto-upgrade.test.ts +66 -66
  113. package/src/runtime/auto-upgrade.ts +31 -31
  114. package/src/runtime/event-daemon.test.ts +209 -209
  115. package/src/runtime/event-daemon.ts +519 -519
  116. package/src/runtime/owner-control.ts +150 -150
  117. package/src/runtime/raw-ws-log.test.ts +33 -33
  118. package/src/runtime/raw-ws-log.ts +32 -32
  119. package/src/runtime/runtime-logger.ts +107 -107
  120. package/src/runtime/ws-client.test.ts +169 -169
  121. package/src/runtime/ws-client.ts +280 -280
  122. package/src/sdk/action.ts +153 -153
  123. package/src/sdk/index.ts +107 -107
  124. package/src/sdk/types.ts +161 -161
  125. package/src/strategies/avoid-lone.ts +12 -12
  126. package/src/strategies/avoid-players.knowledge.md +19 -19
  127. package/src/strategies/avoid-players.ts +16 -16
  128. package/src/strategies/corpse-patrol.ts +19 -19
  129. package/src/strategies/crab-sabotage.ts +22 -22
  130. package/src/strategies/custom-module.test.ts +270 -270
  131. package/src/strategies/find-player.ts +17 -17
  132. package/src/strategies/game-utils.test.ts +242 -242
  133. package/src/strategies/game-utils.ts +846 -846
  134. package/src/strategies/goals/anchor-linger.ts +77 -77
  135. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  136. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  137. package/src/strategies/goals/avoid-players-top.ts +121 -121
  138. package/src/strategies/goals/conversation-goal.ts +51 -51
  139. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  140. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  141. package/src/strategies/goals/crab-sabotage-top.ts +197 -197
  142. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  143. package/src/strategies/goals/find-player-top.ts +93 -93
  144. package/src/strategies/goals/flee-players-goal.ts +53 -53
  145. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  146. package/src/strategies/goals/goal-manager.ts +41 -41
  147. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  148. package/src/strategies/goals/goal.ts +28 -28
  149. package/src/strategies/goals/hide-top.ts +197 -197
  150. package/src/strategies/goals/keep-away-goal.ts +221 -221
  151. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  152. package/src/strategies/goals/kill-lone-top.ts +160 -160
  153. package/src/strategies/goals/kill-target-goal.ts +59 -59
  154. package/src/strategies/goals/kill-target-top.ts +109 -109
  155. package/src/strategies/goals/leaf-goal.ts +27 -27
  156. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  157. package/src/strategies/goals/lone-kill-core.ts +82 -82
  158. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  159. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  160. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  161. package/src/strategies/goals/move-room-goal.ts +60 -60
  162. package/src/strategies/goals/normal-shrimp-top.test.ts +80 -80
  163. package/src/strategies/goals/normal-shrimp-top.ts +242 -242
  164. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  165. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  166. package/src/strategies/goals/patrol-top.ts +57 -57
  167. package/src/strategies/goals/report-patrol-top.ts +80 -80
  168. package/src/strategies/goals/safe-task-goal.ts +102 -102
  169. package/src/strategies/goals/social-task-top.ts +161 -161
  170. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  171. package/src/strategies/goals/task-only-top.ts +57 -57
  172. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  173. package/src/strategies/goals/task-report-top.ts +57 -57
  174. package/src/strategies/goals/wander-task-goal.ts +33 -33
  175. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  176. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  177. package/src/strategies/greeting.ts +53 -53
  178. package/src/strategies/hide-spots.ts +59 -59
  179. package/src/strategies/hide.ts +24 -24
  180. package/src/strategies/kill-frenzy.ts +13 -13
  181. package/src/strategies/kill-lone.knowledge.md +17 -17
  182. package/src/strategies/kill-lone.ts +14 -14
  183. package/src/strategies/kill-target.ts +19 -19
  184. package/src/strategies/loader.test.ts +678 -678
  185. package/src/strategies/loader.ts +181 -181
  186. package/src/strategies/lone-kill-task.ts +22 -22
  187. package/src/strategies/meeting-gate.test.ts +59 -59
  188. package/src/strategies/meeting-gate.ts +23 -23
  189. package/src/strategies/move-room.ts +16 -16
  190. package/src/strategies/new-events-backfill.ts +98 -98
  191. package/src/strategies/off-route-points.ts +105 -105
  192. package/src/strategies/paradise-fish.knowledge.md +19 -19
  193. package/src/strategies/paradise-fish.ts +22 -22
  194. package/src/strategies/pathfind/distance-field.ts +150 -150
  195. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  196. package/src/strategies/pathfind/escape-planner.ts +355 -355
  197. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  198. package/src/strategies/patrol.ts +12 -12
  199. package/src/strategies/player-targets.ts +13 -13
  200. package/src/strategies/report-patrol.ts +12 -12
  201. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  202. package/src/strategies/shrimp-memory.ts +22 -22
  203. package/src/strategies/social-task.test.ts +28 -28
  204. package/src/strategies/social-task.ts +50 -50
  205. package/src/strategies/spawn.ts +82 -82
  206. package/src/strategies/speech-module.ts +123 -123
  207. package/src/strategies/strategy-loop.test.ts +15 -15
  208. package/src/strategies/strategy-loop.ts +716 -716
  209. package/src/strategies/task-kill-report.ts +18 -18
  210. package/src/strategies/task-only.ts +12 -12
  211. package/src/strategies/task-report.ts +19 -19
  212. package/src/strategies/types.ts +107 -107
  213. package/src/strategies/warrior-memory.knowledge.md +21 -21
  214. package/src/strategies/warrior-memory.ts +17 -17
@@ -1,1235 +1,1237 @@
1
- import { Command } from 'commander';
2
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
3
- import { join } from 'path';
4
- import { spawn, spawnSync, type ChildProcess } from 'child_process';
5
- import { AuthStore } from '../lib/auth.js';
6
- import { ApiError, GameClient } from '../lib/game-client.js';
7
- import { getProfileStateDir } from '../lib/init-command.js';
8
- import { EventStore } from '../pipeline/event-store.js';
9
- import { spawnStrategyLoop } from '../strategies/spawn.js';
10
- import { stopStrategyIfRunning } from '../strategies/strategy-loop.js';
11
- import { setMeta } from '../lib/command-meta.js';
12
- import { runStreaming, buildErrorLine, summarizeFeed, nextStepFor } from './watch.js';
13
- import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
14
- import { noAccountMessage } from '../lib/account-guidance.js';
15
- import { EventRuntime } from '../runtime/event-daemon.js';
16
- import {
17
- apiErrorCode,
18
- apiErrorMessage,
19
- normalizeCompetitionStatusResponse,
20
- queueModeFrom,
21
- serializeError as serializeCompetitionError,
22
- type QueueMode,
23
- } from '../lib/competition.js';
24
- import {
25
- briefGameMap,
26
- summarizeGameMap,
27
- } from '../lib/game-context.js';
28
- import {
29
- gameStartRuntimePath,
30
- readGameStartRuntime,
31
- sendOwnerControlRequest,
32
- startOwnerControlServer,
33
- type OwnerControlInfo,
34
- type OwnerControlServer,
35
- } from '../runtime/owner-control.js';
36
- import {
37
- startMatch,
38
- endMatch,
39
- readMatchState,
40
- shouldEmitWaiting,
41
- markWaitingEmitted,
42
- getWaitedSecs,
43
- hasMatchTimedOut,
44
- } from '../lib/match-state.js';
45
-
46
- export { summarizeGameMap } from '../lib/game-context.js';
47
-
48
- function sleep(ms: number): Promise<void> {
49
- return new Promise(r => setTimeout(r, ms));
50
- }
51
-
52
- function positiveNumber(value: string, fallback: number): number {
53
- const parsed = Number(value);
54
- return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
55
- }
56
-
57
- function queueStatus(result: any): string | undefined {
58
- return (result?.data ?? result)?.status;
59
- }
60
-
61
- function queueMode(result: any): QueueMode | undefined {
62
- return queueModeFrom(result);
63
- }
64
-
65
- const DEFAULT_QUEUE_WAIT_TIMEOUT_SECS = 30;
66
-
67
- function clearCachedGameServerUrl(authStore: AuthStore, profileName?: string): void {
68
- try {
69
- authStore.updateGameServerUrl(undefined, profileName);
70
- } catch {
71
- // Cache cleanup is best-effort; queue status will discover the current server.
72
- }
73
- }
74
-
75
- function isLeaveGameSuccess(result: any): boolean {
76
- const data = result?.data ?? result;
77
- return data?.ok === true || data?.message === 'left_game';
78
- }
79
-
80
- function isPidAlive(pid: number): boolean {
81
- if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return false;
82
- try { process.kill(pid, 0); return true; } catch { return false; }
83
- }
84
-
85
- function getRunningGameStartPid(stateDir: string): number | null {
86
- const info = readGameStartRuntime(stateDir);
87
- if (!info) return null;
88
- const pid = Number(info?.owner_pid ?? info?.pid);
89
- if (isPidAlive(pid)) return pid;
90
- try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
91
- return null;
92
- }
93
-
94
- function writeGameStartRuntime(
95
- stateDir: string,
96
- mode: GameStartPlanKind,
97
- phase?: string,
98
- controlOverride?: { control: OwnerControlInfo; token: string },
99
- ): void {
100
- mkdirSync(stateDir, { recursive: true });
101
- let startedAt = new Date().toISOString();
102
- let existingControl: OwnerControlInfo | undefined;
103
- let existingToken: string | undefined;
104
- try {
105
- const existing = JSON.parse(readFileSync(gameStartRuntimePath(stateDir), 'utf8'));
106
- const existingPid = Number(existing?.owner_pid ?? existing?.pid);
107
- if (existingPid === process.pid && typeof existing?.started_at === 'string') {
108
- startedAt = existing.started_at;
109
- if (existing?.control?.path) existingControl = existing.control;
110
- if (typeof existing?.control_token === 'string') existingToken = existing.control_token;
111
- }
112
- } catch {}
113
- const control = controlOverride?.control ?? existingControl;
114
- const controlToken = controlOverride?.token ?? existingToken;
115
- writeFileSync(gameStartRuntimePath(stateDir), JSON.stringify({
116
- schema: 3,
117
- owner_pid: process.pid,
118
- pid: process.pid,
119
- started_at: startedAt,
120
- heartbeat_at: new Date().toISOString(),
121
- mode,
122
- ...(control ? { control } : {}),
123
- ...(controlToken ? { control_token: controlToken } : {}),
124
- ...(phase ? { phase } : {}),
125
- }, null, 2));
126
- }
127
-
128
- function startGameStartHeartbeat(stateDir: string, mode: GameStartPlanKind): ReturnType<typeof setInterval> {
129
- return setInterval(() => {
130
- try {
131
- writeGameStartRuntime(stateDir, mode);
132
- } catch {}
133
- }, 5000);
134
- }
135
-
136
- function cleanupGameStartRuntime(stateDir: string, opts: { removeFeed?: boolean; controlPath?: string } = {}): void {
137
- const runtimePath = gameStartRuntimePath(stateDir);
138
- try {
139
- const info = JSON.parse(readFileSync(runtimePath, 'utf8'));
140
- const pid = Number(info?.owner_pid ?? info?.pid);
141
- if (pid !== process.pid) return;
142
- } catch {}
143
- try { unlinkSync(runtimePath); } catch {}
144
- if (opts.removeFeed) {
145
- try { unlinkSync(join(stateDir, 'feed.json')); } catch {}
146
- }
147
- if (opts.controlPath && process.platform !== 'win32') {
148
- try { unlinkSync(opts.controlPath); } catch {}
149
- }
150
- }
151
-
152
- function terminateProcessTree(pid: number, signal: NodeJS.Signals = 'SIGTERM'): boolean {
153
- if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return false;
154
- if (process.platform === 'win32') {
155
- const result = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' });
156
- return result.status === 0;
157
- }
158
- const pkillSignal = signal === 'SIGKILL' ? '-KILL' : '-TERM';
159
- try { spawnSync('pkill', [pkillSignal, '-P', String(pid)], { stdio: 'ignore' }); } catch {}
160
- try {
161
- process.kill(pid, signal);
162
- return true;
163
- } catch {
164
- return false;
165
- }
166
- }
167
-
168
- async function waitPidExit(pid: number, timeoutMs = 5000): Promise<boolean> {
169
- const deadline = Date.now() + timeoutMs;
170
- while (Date.now() < deadline) {
171
- if (!isPidAlive(pid)) return true;
172
- await sleep(200);
173
- }
174
- return !isPidAlive(pid);
175
- }
176
-
177
- async function stopOwnerIfRunning(stateDir: string, timeoutMs = 5000): Promise<{ pid: number | null; stopped: boolean }> {
178
- return stopOwnerWithCommand(stateDir, 'stop', timeoutMs);
179
- }
180
-
181
- async function stopOwnerWithCommand(
182
- stateDir: string,
183
- command: 'stop' | 'quit' | 'leave',
184
- timeoutMs = 5000,
185
- ): Promise<{ pid: number | null; stopped: boolean }> {
186
- const pid = getRunningGameStartPid(stateDir);
187
- if (!pid) {
188
- try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
189
- try { unlinkSync(join(stateDir, 'feed.json')); } catch {}
190
- return { pid: null, stopped: false };
191
- }
192
- try {
193
- const response = await sendOwnerControlRequest(stateDir, command);
194
- if (response?.ok) {
195
- const exited = await waitPidExit(pid, timeoutMs);
196
- if (exited) return { pid, stopped: true };
197
- }
198
- } catch {}
199
- terminateProcessTree(pid, 'SIGTERM');
200
- const exited = await waitPidExit(pid, timeoutMs);
201
- if (!exited) {
202
- terminateProcessTree(pid, 'SIGKILL');
203
- await waitPidExit(pid, 2000);
204
- }
205
- try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
206
- try { unlinkSync(join(stateDir, 'feed.json')); } catch {}
207
- return { pid, stopped: true };
208
- }
209
-
210
- type QueueStatus = 'allocated' | 'queued' | 'not_in_queue' | string | undefined;
211
-
212
- export type GameStartPlan =
213
- | { kind: 'already_running'; pid: number }
214
- | { kind: 'resume_queue' }
215
- | { kind: 'resume_allocated' }
216
- | { kind: 'fresh_start' };
217
-
218
- type GameStartPlanKind = GameStartPlan['kind'];
219
-
220
- export function planGameStartAction(input: {
221
- gameStartPid?: number | null;
222
- hasMatchState: boolean;
223
- queueStatus?: QueueStatus;
224
- }): GameStartPlan {
225
- if (input.gameStartPid) return { kind: 'already_running', pid: input.gameStartPid };
226
-
227
- if (input.queueStatus === 'allocated') return { kind: 'resume_allocated' };
228
- if (input.queueStatus === 'queued' || input.queueStatus === 'already_in_queue') return { kind: 'resume_queue' };
229
- if (input.hasMatchState && input.queueStatus !== 'not_in_queue') return { kind: 'resume_queue' };
230
- return { kind: 'fresh_start' };
231
- }
232
-
233
- function isAlreadyInGameError(err: unknown): boolean {
234
- return err instanceof ApiError && err.body.includes('ALREADY_IN_GAME');
235
- }
236
-
237
- function apiErrorBody(err: unknown): string {
238
- if (err instanceof ApiError) return err.body;
239
- if (err instanceof Error) return err.message;
240
- return String(err);
241
- }
242
-
243
- function isStillAliveError(err: unknown): boolean {
244
- return /STILL_ALIVE/i.test(apiErrorBody(err));
245
- }
246
-
247
- function serializeError(err: unknown): Record<string, any> {
248
- if (err instanceof ApiError) {
249
- return { status: err.status, body: err.body };
250
- }
251
- return { message: err instanceof Error ? err.message : String(err) };
252
- }
253
-
254
- function competitionExitReason(code: string | undefined): string {
255
- switch (code) {
256
- case 'NO_ACTIVE_COMPETITION': return 'no_active_competition';
257
- case 'COMPETITION_NOT_OPEN': return 'competition_not_open';
258
- case 'ALREADY_IN_GAME': return 'already_in_game';
259
- case 'INVALID_MODE': return 'invalid_mode';
260
- default: return 'request_failed';
261
- }
262
- }
263
-
264
- function competitionNextStep(code: string | undefined): string {
265
- switch (code) {
266
- case 'NO_ACTIVE_COMPETITION':
267
- return 'Tell the user there is no active competition. Do not start normal matchmaking unless the user asks.';
268
- case 'COMPETITION_NOT_OPEN':
269
- return 'Tell the user competition is not open now and use competition.daily_windows for the opening windows. Do not start normal matchmaking unless the user asks.';
270
- case 'ALREADY_IN_GAME':
271
- return 'Tell the user this account is already in a game. Reconnect or continue the existing game instead of starting another match.';
272
- default:
273
- return 'Tell the user competition matchmaking failed. Do not start normal matchmaking unless the user asks.';
274
- }
275
- }
276
-
277
- type GamePresence = 'in_game' | 'matching' | 'none' | 'unknown';
278
-
279
- interface GamePresenceInfo {
280
- presence: GamePresence;
281
- game_state?: any;
282
- queue_status?: any;
283
- owner_pid: number | null;
284
- errors?: Array<{ source: string; error: Record<string, any> }>;
285
- }
286
-
287
- function isMatchingQueueStatus(status: QueueStatus): boolean {
288
- return status === 'queued'
289
- || status === 'already_in_queue'
290
- || status === 'allocating'
291
- || status === 'allocated';
292
- }
293
-
294
- async function detectGamePresence(client: GameClient, stateDir: string): Promise<GamePresenceInfo> {
295
- const errors: Array<{ source: string; error: Record<string, any> }> = [];
296
- const ownerPid = getRunningGameStartPid(stateDir);
297
- let gameState: any | null = null;
298
- try {
299
- await client.discoverGameServer();
300
- gameState = await client.getGameState();
301
- } catch (err) {
302
- errors.push({ source: 'game_current', error: serializeError(err) });
303
- }
304
- if (gameState) {
305
- return {
306
- presence: 'in_game',
307
- game_state: gameState,
308
- owner_pid: ownerPid,
309
- ...(errors.length ? { errors } : {}),
310
- };
311
- }
312
-
313
- let queue: any;
314
- try {
315
- queue = await client.getQueueStatus('clawclaw');
316
- } catch (err) {
317
- errors.push({ source: 'queue_status', error: serializeError(err) });
318
- }
319
- const status = queueStatus(queue);
320
- if (isMatchingQueueStatus(status)) {
321
- return {
322
- presence: 'matching',
323
- queue_status: queue,
324
- owner_pid: ownerPid,
325
- ...(errors.length ? { errors } : {}),
326
- };
327
- }
328
- if (status === 'not_in_queue') {
329
- return {
330
- presence: 'none',
331
- queue_status: queue,
332
- owner_pid: ownerPid,
333
- ...(errors.length ? { errors } : {}),
334
- };
335
- }
336
- return {
337
- presence: errors.length >= 2 ? 'unknown' : 'none',
338
- ...(queue ? { queue_status: queue } : {}),
339
- owner_pid: ownerPid,
340
- ...(errors.length ? { errors } : {}),
341
- };
342
- }
343
-
344
- function ensureEventSession(source: string): EventStore {
345
- const existing = EventStore.latestSessionPath();
346
- if (existing) {
347
- const events = EventStore.forActiveAccount();
348
- events.append({ type: 'session_resumed', source });
349
- return events;
350
- }
351
- const events = EventStore.createSessionForActiveAccount();
352
- events.append({ type: 'session_started', source });
353
- return events;
354
- }
355
-
356
- function nonEmptyString(value: unknown): string | undefined {
357
- return typeof value === 'string' && value.length > 0 ? value : undefined;
358
- }
359
-
360
- function unwrapData(value: any): any {
361
- return value?.data ?? value;
362
- }
363
-
364
- function cleanObject<T extends Record<string, any>>(obj: T): T {
365
- for (const key of Object.keys(obj)) {
366
- if (obj[key] === undefined) delete obj[key];
367
- }
368
- return obj;
369
- }
370
-
371
- export interface GameStrategyIdentity {
372
- gameId?: string;
373
- role?: string;
374
- alive: boolean | null;
375
- }
376
-
377
- export function gameStrategyIdentity(stateData: any, roleData: any): GameStrategyIdentity {
378
- const state = unwrapData(stateData);
379
- const role = unwrapData(roleData);
380
- const you = state?.you ?? {};
381
- const aliveRaw = you?.is_alive ?? you?.alive;
382
- return {
383
- gameId: nonEmptyString(state?.game_id) ?? nonEmptyString(state?.game?.id) ?? nonEmptyString(state?.game?.game_id),
384
- role: nonEmptyString(role?.role) ?? nonEmptyString(you?.role),
385
- alive: typeof aliveRaw === 'boolean' ? aliveRaw : null,
386
- };
387
- }
388
-
389
- function commandError(command: string, err: unknown): { command: string; error: string } {
390
- const message = err instanceof ApiError
391
- ? `${err.status}: ${err.body}`
392
- : err instanceof Error
393
- ? err.message
394
- : String(err);
395
- return { command, error: message };
396
- }
397
-
398
- async function fetchInitialGameContext(client: GameClient): Promise<{
399
- state: any | null;
400
- role: any | null;
401
- map: any | null;
402
- tasks: any[] | null;
403
- errors?: Array<{ command: string; error: string }>;
404
- }> {
405
- await sleep(500);
406
- const [stateResult, roleResult, mapResult] = await Promise.allSettled([
407
- client.getGameState(),
408
- client.getRoleInfo(),
409
- client.getMap(),
410
- ]);
411
-
412
- const errors: Array<{ command: string; error: string }> = [];
413
- if (stateResult.status === 'rejected') errors.push(commandError('state', stateResult.reason));
414
- if (roleResult.status === 'rejected') errors.push(commandError('game role', roleResult.reason));
415
- if (mapResult.status === 'rejected') errors.push(commandError('game map', mapResult.reason));
416
-
417
- const mapData = mapResult.status === 'fulfilled' ? mapResult.value : null;
418
- const context = {
419
- state: stateResult.status === 'fulfilled' ? stateResult.value : null,
420
- role: roleResult.status === 'fulfilled' ? roleResult.value : null,
421
- map: briefGameMap(mapData),
422
- tasks: mapData?.your_tasks ?? null,
423
- ...(errors.length ? { errors } : {}),
424
- };
425
- return context;
426
- }
427
-
428
- const ROLE_DEFAULT_STRATEGY: Record<string, string> = {
429
- 'shrimp_generic': 'task-report',
430
- 'shrimp_warrior': 'task-report',
431
- 'shrimp_pistol': 'task-report',
432
- 'crab_generic': 'crab-sabotage',
433
- 'neutral_paradise_fish': 'corpse-patrol',
434
- 'neutral_octopus': 'lone-kill-task',
435
- };
436
-
437
- function autoStartStrategy(roleData: any, stateData?: any, gameId?: string): { strategy: string; pid: number | undefined; child: ChildProcess } | null {
438
- const roleId: string | undefined = roleData?.data?.role ?? roleData?.role;
439
- if (!roleId) return null;
440
- const strategyId = ROLE_DEFAULT_STRATEGY[roleId];
441
- if (!strategyId) return null;
442
- const child = spawnStrategyLoop(strategyId, [roleId], {
443
- source: 'auto_start',
444
- gameId: gameId ?? gameStrategyIdentity(stateData, roleData).gameId,
445
- role: roleId,
446
- detached: false,
447
- writeRuntimeFiles: false,
448
- });
449
- return { strategy: strategyId, pid: child.pid, child };
450
- }
451
-
452
- async function runGameQuit(invokedAs = 'game quit'): Promise<void> {
453
- const authStore = new AuthStore();
454
- const profile = authStore.getActive();
455
- if (!profile) throw new Error('Not logged in.');
456
-
457
- const stateDir = getProfileStateDir(profile);
458
- const client = GameClient.fromAuth();
459
- const presence = await detectGamePresence(client, stateDir);
460
- let left: 'game' | 'queue' | 'local_runtime' | 'none' = presence.owner_pid ? 'local_runtime' : 'none';
461
- let gameResult: any;
462
- let queueResult: any;
463
- let leaveError: Record<string, any> | undefined;
464
-
465
- if (presence.presence === 'in_game') {
466
- try {
467
- gameResult = await client.leaveGame();
468
- if (isLeaveGameSuccess(gameResult)) clearCachedGameServerUrl(authStore, profile.agentName);
469
- left = 'game';
470
- } catch (err) {
471
- leaveError = {
472
- ...serializeError(err),
473
- still_alive: isStillAliveError(err),
474
- };
475
- left = 'local_runtime';
476
- }
477
- } else if (presence.presence === 'matching') {
478
- try {
479
- queueResult = await client.leaveQueue('clawclaw');
480
- left = 'queue';
481
- } catch (err) {
482
- leaveError = serializeError(err);
483
- }
484
- }
485
-
486
- endMatch(stateDir);
487
- const owner = await stopOwnerWithCommand(stateDir, 'quit');
488
- stopStrategyIfRunning();
489
-
490
- const reminder = hubReminder(readCachedGamesPlayed());
491
- const out: Record<string, any> = cleanObject({
492
- ok: true,
493
- command: invokedAs,
494
- left,
495
- presence: presence.presence,
496
- game_result: gameResult,
497
- queue_result: queueResult,
498
- leave_error: leaveError,
499
- detection_errors: presence.errors,
500
- queue_status: presence.queue_status,
501
- owner_pid: owner.pid ?? presence.owner_pid ?? undefined,
502
- owner_stopped: owner.stopped,
503
- hub_reminder: reminder,
504
- next_step: reminder ? `Stopped local runtime. ${reminder}` : undefined,
505
- });
506
- if (presence.presence === 'in_game' && leaveError?.still_alive) {
507
- out.message = 'The server rejected leaving the active game because you are still alive; local runtime was stopped only.';
508
- }
509
- console.log(JSON.stringify(out, null, 2));
510
- }
511
-
512
- async function runGameStart(opts: { force?: boolean; channelUrl?: string; competition?: boolean }): Promise<void> {
513
- if (process.env.CLAWCLAW_REQUIRE_STREAM_TOOL === '1' && process.env.CLAWCLAW_STREAMED !== '1') {
514
- process.stderr.write(
515
- 'In OpenClaw, start the game via the clawclaw_game_start tool - do not exec `ccl game start` directly.\n' +
516
- 'When run raw, the event NDJSON only fills an unconsumed buffer, so you never receive speech_your_turn and stay silent.\n',
517
- );
518
- process.exit(2);
519
- }
520
-
521
- // Channel 模式硬兜底:带 --channel-url 时,把真正的长流逻辑 fork 到 detached 后台进程,
522
- // 父进程立即返回。这样即使 agent 误用 Powershell/前台直接执行,也不会阻塞——事件仍通过
523
- // --channel-url 的 HTTP POST 推送给 channel,后台进程的 PID 写入 runtime 文件,
524
- // `ccl game quit` 依旧能正确清理。CLAWCLAW_CHANNEL_DETACHED 防止子进程再次 fork。
525
- if (opts.channelUrl && process.env.CLAWCLAW_CHANNEL_DETACHED !== '1') {
526
- // 先做本地登录校验,保证前台调用能立即看到未登录错误(detach 后 stdout 被丢弃)。
527
- const detachProfile = new AuthStore().getActive();
528
- if (!detachProfile) throw new Error(noAccountMessage('gameStart'));
529
- // 已有运行中的 stream 时不重复 fork:detach 的瞬间返回容易诱发 agent 误重试,
530
- // 在父进程同步拦截顺序重试,避免拉起第二个注定 already_running 的后台进程。
531
- const existingPid = getRunningGameStartPid(getProfileStateDir(detachProfile));
532
- if (existingPid && !opts.force) {
533
- process.stdout.write(JSON.stringify({
534
- exit_reason: ['already_running'],
535
- next_step: `已有 ccl game start 后台进程在运行(pid ${existingPid}),事件正通过 channel 推送。不要重复启动;如需重启加 --force,或先 ccl game quit。`,
536
- events: [{ type: 'already_running', pid: existingPid }],
537
- summary: { phase: 'matching' },
538
- }) + '\n');
539
- return;
540
- }
541
- const child = spawn(process.execPath, process.argv.slice(1), {
542
- detached: true,
543
- stdio: 'ignore',
544
- env: { ...process.env, CLAWCLAW_CHANNEL_DETACHED: '1' },
545
- });
546
- child.unref();
547
- process.stdout.write(JSON.stringify({
548
- exit_reason: ['channel_detached'],
549
- next_step: 'ccl game start 已在后台启动,事件将通过 channel 实时推送。不要在前台等待此进程;结束本局用 ccl game quit。',
550
- events: [{ type: 'channel_detached', pid: child.pid }],
551
- summary: { phase: 'matching' },
552
- }) + '\n');
553
- return;
554
- }
555
-
556
- const authStore = new AuthStore();
557
- const profile = authStore.getActive();
558
- if (!profile) throw new Error(noAccountMessage('gameStart'));
559
-
560
- const stateDir = getProfileStateDir(profile);
561
- const feedPath = join(stateDir, 'feed.json');
562
- clearCachedGameServerUrl(authStore, profile.agentName);
563
- const client = GameClient.fromAuth();
564
- const requestedMode: QueueMode = opts.competition ? 'competition' : 'match';
565
- let currentGameMode: QueueMode | undefined = requestedMode;
566
- let eventRuntime: EventRuntime | undefined;
567
- let streamAbortController: AbortController | null = null;
568
- let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
569
- let ownerControl: OwnerControlServer | null = null;
570
- let ownerFeed: any = {
571
- ts: new Date().toISOString(),
572
- phase: 'matching',
573
- terminal: false,
574
- you: { name: profile.agentName },
575
- game: {},
576
- urgent: {},
577
- meeting: null,
578
- recent_events: [],
579
- };
580
- let strategyChild: ChildProcess | null = null;
581
- let currentStrategy: string | null = null;
582
- const currentAutomationSummary = (): Record<string, any> | undefined => {
583
- if (!currentStrategy) return undefined;
584
- const pid = strategyChild?.pid;
585
- return { strategy: currentStrategy, running: !!(pid && isPidAlive(pid)) };
586
- };
587
- const updateGameMode = (mode: QueueMode | undefined): void => {
588
- if (!mode) return;
589
- currentGameMode = mode;
590
- };
591
- const withCurrentMode = (payload: Record<string, any>): Record<string, any> => {
592
- return currentGameMode ? { ...payload, mode: currentGameMode } : payload;
593
- };
594
- const currentSummary = (): any | null => {
595
- const runtimeFeed = eventRuntime?.snapshot();
596
- const feed = runtimeFeed && runtimeFeed.phase !== 'lobby' ? runtimeFeed : ownerFeed;
597
- const automation = currentAutomationSummary();
598
- return summarizeFeed(automation ? { ...feed, automation } : feed);
599
- };
600
- let manualExitEmitted = false;
601
- let ownerExitRequested = false;
602
- const stopOwnedStrategy = (): void => {
603
- const child = strategyChild;
604
- strategyChild = null;
605
- currentStrategy = null;
606
- if (child?.pid && isPidAlive(child.pid)) {
607
- try { child.kill('SIGTERM'); } catch {}
608
- setTimeout(() => {
609
- if (child.pid && isPidAlive(child.pid)) {
610
- try { child.kill('SIGKILL'); } catch {}
611
- }
612
- }, 1000).unref();
613
- }
614
- eventRuntime?.refreshFeed();
615
- };
616
- const onOwnerSignal = (): void => {
617
- streamAbortController?.abort();
618
- eventRuntime?.stop('SIGTERM');
619
- stopOwnedStrategy();
620
- cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
621
- process.exit(130);
622
- };
623
- process.on('SIGINT', onOwnerSignal);
624
- process.on('SIGTERM', onOwnerSignal);
625
- const emit = (obj: Record<string, any>): void => {
626
- const line = JSON.stringify(obj) + '\n';
627
- process.stdout.write(line);
628
- if (opts.channelUrl) {
629
- fetch(opts.channelUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: line }).catch(() => {});
630
- }
631
- };
632
- const emitLifecycle = (
633
- reason: string,
634
- payload: Record<string, any>,
635
- nextStepOverride?: string,
636
- ): void => {
637
- const event = { ...payload, type: reason };
638
- emit({
639
- exit_reason: [reason],
640
- next_step: nextStepOverride ?? nextStepFor(reason),
641
- events: [event],
642
- summary: currentSummary(),
643
- });
644
- };
645
- const emitOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
646
- if (manualExitEmitted) return;
647
- manualExitEmitted = true;
648
- const eventType = kind === 'leave' ? 'stop' : kind;
649
- emit({
650
- exit_reason: [eventType],
651
- next_step: `Received ${command}. The current ccl game start process is exiting now.`,
652
- events: [{ type: eventType, command }],
653
- summary: { phase: 'stopped' },
654
- });
655
- };
656
- const requestOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
657
- ownerExitRequested = true;
658
- emitOwnerExit(kind, command);
659
- streamAbortController?.abort();
660
- eventRuntime?.stop('manual');
661
- stopOwnedStrategy();
662
- };
663
- const emitMatchEvent = (evt: Record<string, any>): void => {
664
- try {
665
- const store = EventStore.forActiveAccount();
666
- store.append({ ts: new Date().toISOString(), ...evt });
667
- } catch {}
668
- };
669
- const ensureEventRuntime = async (): Promise<void> => {
670
- if (eventRuntime) return;
671
- eventRuntime = new EventRuntime({
672
- authStore,
673
- getAutomation: currentAutomationSummary,
674
- onStop: (stop) => {
675
- if (stop.reason === 'game_over' || stop.reason === 'user_left_game') return;
676
- streamAbortController?.abort();
677
- },
678
- });
679
- await eventRuntime.start();
680
- };
681
- const streamGame = async (): Promise<void> => {
682
- const sessionPath = EventStore.latestSessionPath();
683
- const ctrl = new AbortController();
684
- streamAbortController = ctrl;
685
- const onSignal = (): void => {
686
- ctrl.abort();
687
- eventRuntime?.stop('SIGTERM');
688
- };
689
- process.on('SIGINT', onSignal);
690
- process.on('SIGTERM', onSignal);
691
- try {
692
- await runStreaming({
693
- feedPath,
694
- sessionPath,
695
- getSessionPath: () => EventStore.latestSessionPath(),
696
- stdout: (s) => { process.stdout.write(s); if (opts.channelUrl) { fetch(opts.channelUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: s }).catch(() => {}); } },
697
- signal: ctrl.signal,
698
- skipFeedWait: true,
699
- readSummary: currentSummary,
700
- skipBacklogTypes: ['match_waiting', 'match_timeout'],
701
- emitGameStart: true,
702
- hubReminder: hubReminder(readCachedGamesPlayed()),
703
- });
704
- } catch (err: any) {
705
- process.stdout.write(buildErrorLine(err));
706
- process.exitCode = 1;
707
- } finally {
708
- process.off('SIGINT', onSignal);
709
- process.off('SIGTERM', onSignal);
710
- streamAbortController = null;
711
- }
712
- };
713
- const handleAllocated = async (queue: any, preserveStrategy: boolean): Promise<void> => {
714
- updateGameMode(queueMode(queue));
715
- const finalState = readMatchState(stateDir);
716
- const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
717
- endMatch(stateDir);
718
- const context = await fetchInitialGameContext(client);
719
- const identity = gameStrategyIdentity(context.state, context.role);
720
- // Supplement game_id from queue response when /game/current doesn't carry it yet.
721
- const queueGameId = nonEmptyString(queue?.game_id) ?? nonEmptyString(queue?.data?.game_id);
722
- if (!identity.gameId && queueGameId) {
723
- identity.gameId = queueGameId;
724
- }
725
- const role = unwrapData(context.role);
726
- ownerFeed = {
727
- ...ownerFeed,
728
- ts: new Date().toISOString(),
729
- phase: 'allocated',
730
- you: {
731
- ...ownerFeed.you,
732
- role: nonEmptyString(role?.role) ?? identity.role,
733
- role_display: nonEmptyString(role?.role_display_name) ?? nonEmptyString(role?.role_display),
734
- faction: nonEmptyString(role?.faction),
735
- alive: identity.alive,
736
- },
737
- game: {
738
- ...ownerFeed.game,
739
- game_id: identity.gameId,
740
- },
741
- };
742
- let strategyInfo: { strategy: string; pid: number | undefined } | null = null;
743
- if (identity.alive !== false) {
744
- stopOwnedStrategy();
745
- const started = autoStartStrategy(context.role, context.state, identity.gameId);
746
- if (started) {
747
- strategyChild = started.child;
748
- currentStrategy = started.strategy;
749
- strategyInfo = { strategy: started.strategy, pid: started.pid };
750
- }
751
- }
752
- const allocationPayload = {
753
- queue,
754
- waited_secs: waitedSecs,
755
- game_id: identity.gameId || undefined,
756
- ...context,
757
- ...(strategyInfo ? { default_strategy: strategyInfo } : {}),
758
- };
759
- ownerFeed = { ...ownerFeed, allocation: allocationPayload };
760
- await ensureEventRuntime();
761
- await streamGame();
762
- };
763
- const pollQueue = async (preserveStrategy: boolean): Promise<void> => {
764
- const intervalMs = 2000;
765
- const QUEUE_POLL_HEARTBEAT_MS = 60_000;
766
- const MAX_CONSECUTIVE_FAILURES = 3;
767
- let lastHeartbeat = Date.now();
768
- let consecutiveFailures = 0;
769
-
770
- while (!ownerExitRequested) {
771
- let queue: any;
772
- try {
773
- queue = await client.getQueueStatus('clawclaw');
774
- updateGameMode(queueMode(queue));
775
- consecutiveFailures = 0;
776
- } catch (err: any) {
777
- consecutiveFailures++;
778
- const msg = err?.message ?? String(err);
779
- if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
780
- emitLifecycle('error', {
781
- error: msg,
782
- consecutive_failures: consecutiveFailures,
783
- message: `Queue status polling failed ${consecutiveFailures} times consecutively.`,
784
- }, 'Queue polling has failed repeatedly. Check network, then launch a fresh `ccl game start` to retry.');
785
- return;
786
- }
787
- emitLifecycle('poll_error', {
788
- error: msg,
789
- consecutive_failures: consecutiveFailures,
790
- message: `Queue poll failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}). Retrying...`,
791
- }, 'Temporary polling failure. The stream will keep retrying - stay attached.');
792
- await sleep(intervalMs);
793
- continue;
794
- }
795
-
796
- if (queueStatus(queue) === 'allocated') {
797
- await handleAllocated(queue, preserveStrategy);
798
- return;
799
- }
800
- if (queueStatus(queue) === 'not_in_queue') {
801
- endMatch(stateDir);
802
- emitLifecycle('not_in_queue', { queue, message: 'Left or dropped from queue.' },
803
- 'No longer in matchmaking queue. The stream will exit; launch a fresh `ccl game start` to retry if the user wants to continue.');
804
- return;
805
- }
806
-
807
- const cur = readMatchState(stateDir);
808
- if (cur && shouldEmitWaiting(cur)) {
809
- const waitedSecs = getWaitedSecs(cur);
810
- emitMatchEvent(withCurrentMode({ type: 'match_waiting', waited_secs: waitedSecs }));
811
- emitLifecycle('match_waiting', withCurrentMode({ waited_secs: waitedSecs }));
812
- markWaitingEmitted(stateDir);
813
- lastHeartbeat = Date.now();
814
- }
815
- if (cur && hasMatchTimedOut(cur)) {
816
- const waitedSecs = getWaitedSecs(cur);
817
- emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
818
- emitLifecycle('match_timeout', {
819
- waited_secs: waitedSecs,
820
- queue,
821
- ...(currentGameMode ? { mode: currentGameMode } : {}),
822
- message: `No match after ${waitedSecs}s.`,
823
- });
824
- return;
825
- }
826
-
827
- if (Date.now() - lastHeartbeat >= QUEUE_POLL_HEARTBEAT_MS) {
828
- lastHeartbeat = Date.now();
829
- const waitedSecs = cur ? getWaitedSecs(cur) : 0;
830
- emitLifecycle('heartbeat', withCurrentMode({ waited_secs: waitedSecs }),
831
- 'Stream is alive; still waiting for match allocation. Keep chatting with the user.');
832
- }
833
-
834
- await sleep(intervalMs);
835
- }
836
- };
837
- const resumeQueue = async (source: string): Promise<void> => {
838
- ensureEventSession(source);
839
- if (!readMatchState(stateDir)) startMatch(stateDir);
840
- await ensureEventRuntime();
841
- await pollQueue(true);
842
- };
843
- const recoverAlreadyInGame = async (): Promise<boolean> => {
844
- let queue: any;
845
- try {
846
- queue = await client.getQueueStatus('clawclaw');
847
- updateGameMode(queueMode(queue));
848
- } catch {
849
- return false;
850
- }
851
- const status = queueStatus(queue);
852
- if (status === 'allocated') {
853
- ensureEventSession('game_start_already_in_game');
854
- await ensureEventRuntime();
855
- await handleAllocated(queue, true);
856
- return true;
857
- }
858
- if (status === 'queued' || status === 'already_in_queue') {
859
- await resumeQueue('game_start_already_in_game_queue');
860
- return true;
861
- }
862
- return false;
863
- };
864
-
865
- const runningGameStartPid = getRunningGameStartPid(stateDir);
866
- if (runningGameStartPid) {
867
- if (opts.force) {
868
- terminateProcessTree(runningGameStartPid, 'SIGKILL');
869
- try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
870
- try { unlinkSync(feedPath); } catch {}
871
- } else {
872
- emitLifecycle('already_running', { pid: runningGameStartPid },
873
- `A ccl game start stream is already running (pid ${runningGameStartPid}). To replace it, re-run with --force or stop it manually: taskkill /F /PID ${runningGameStartPid}`);
874
- return;
875
- }
876
- }
877
- let initialQueue: any;
878
- try {
879
- initialQueue = await client.getQueueStatus('clawclaw');
880
- updateGameMode(queueMode(initialQueue));
881
- } catch {}
882
- const plan = planGameStartAction({
883
- gameStartPid: null,
884
- hasMatchState: readMatchState(stateDir) !== null,
885
- queueStatus: queueStatus(initialQueue),
886
- });
887
-
888
- ownerFeed = {
889
- ...ownerFeed,
890
- ts: new Date().toISOString(),
891
- phase: plan.kind === 'resume_allocated' ? 'allocated' : 'matching',
892
- };
893
- if (plan.kind !== 'fresh_start' && !queueMode(initialQueue)) currentGameMode = undefined;
894
- ownerControl = await startOwnerControlServer(stateDir, async (request) => {
895
- if (request.type === 'snapshot') {
896
- return { ok: true, type: 'snapshot', summary: currentSummary() };
897
- }
898
- if (request.type === 'stop') {
899
- requestOwnerExit('stop', 'ccl game stop');
900
- return { ok: true, type: 'stop' };
901
- }
902
- if (request.type === 'quit') {
903
- requestOwnerExit('quit', 'ccl game quit');
904
- return { ok: true, type: 'quit' };
905
- }
906
- if (request.type === 'leave') {
907
- requestOwnerExit('leave', 'ccl game leave');
908
- return { ok: true, type: 'leave' };
909
- }
910
- if (request.type === 'stop_strategy') {
911
- stopOwnedStrategy();
912
- return { ok: true, type: 'stop_strategy' };
913
- }
914
- if (request.type === 'switch_strategy') {
915
- if (!request.strategy) return { ok: false, error: 'missing_strategy' };
916
- stopOwnedStrategy();
917
- const child = spawnStrategyLoop(request.strategy, request.args, {
918
- source: 'manual',
919
- detached: false,
920
- writeRuntimeFiles: false,
921
- });
922
- strategyChild = child;
923
- currentStrategy = request.strategy;
924
- eventRuntime?.refreshFeed();
925
- return { ok: true, type: 'switch_strategy', strategy: request.strategy, pid: child.pid };
926
- }
927
- return { ok: false, error: 'unsupported_owner_control_request' };
928
- });
929
- writeGameStartRuntime(stateDir, plan.kind, undefined, {
930
- control: ownerControl.control,
931
- token: ownerControl.token,
932
- });
933
- heartbeatTimer = startGameStartHeartbeat(stateDir, plan.kind);
934
- try {
935
- if (plan.kind === 'resume_queue') {
936
- await resumeQueue('game_start_resume_queue');
937
- return;
938
- }
939
-
940
- if (plan.kind === 'resume_allocated') {
941
- ensureEventSession('game_start_resume_allocated');
942
- await ensureEventRuntime();
943
- await handleAllocated(initialQueue, true);
944
- return;
945
- }
946
-
947
- let joinResult: any;
948
- try {
949
- updateGameMode(requestedMode);
950
- joinResult = await client.joinQueue({ gameType: 'clawclaw', mode: requestedMode });
951
- updateGameMode(queueMode(joinResult) ?? requestedMode);
952
- } catch (err) {
953
- if (isAlreadyInGameError(err) && await recoverAlreadyInGame()) return;
954
- if (requestedMode === 'competition') {
955
- const code = apiErrorCode(err);
956
- let competition: Record<string, any> = { status: 'unavailable', active: null, is_open: null };
957
- try {
958
- competition = normalizeCompetitionStatusResponse(await client.getCompetitionStatus());
959
- } catch (statusErr) {
960
- competition = {
961
- status: 'unavailable',
962
- active: null,
963
- is_open: null,
964
- error: serializeCompetitionError(statusErr),
965
- };
966
- }
967
- emit({
968
- exit_reason: [competitionExitReason(code)],
969
- next_step: competitionNextStep(code),
970
- events: [{
971
- type: 'game_start_failed',
972
- mode: 'competition',
973
- exit_reason: competitionExitReason(code),
974
- error: {
975
- code: code ?? 'REQUEST_FAILED',
976
- message: apiErrorMessage(err),
977
- },
978
- competition,
979
- }],
980
- summary: currentSummary(),
981
- });
982
- process.exitCode = 1;
983
- return;
984
- }
985
- throw err;
986
- }
987
- const joinedStatus = queueStatus(joinResult);
988
- if (joinedStatus === 'already_in_queue') {
989
- await resumeQueue('game_start_already_in_queue');
990
- return;
991
- }
992
- if (joinedStatus && joinedStatus !== 'queued') {
993
- emitLifecycle('error', { queue: joinResult, message: `Unexpected queue status: ${joinedStatus}.` },
994
- 'Queue join did not enter the clawclaw queue. Check queue status before launching another `ccl game start`.');
995
- return;
996
- }
997
-
998
- stopOwnedStrategy();
999
-
1000
- const events = EventStore.createSessionForActiveAccount();
1001
- events.append({ type: 'session_started', source: 'game_start' });
1002
- emitLifecycle('joined', joinResult,
1003
- requestedMode === 'competition'
1004
- ? 'Competition join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Game runtime is attached.'
1005
- : 'Match join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Game runtime is attached.');
1006
- startMatch(stateDir);
1007
- await ensureEventRuntime();
1008
- await pollQueue(false);
1009
- } finally {
1010
- if (heartbeatTimer) clearInterval(heartbeatTimer);
1011
- process.off('SIGINT', onOwnerSignal);
1012
- process.off('SIGTERM', onOwnerSignal);
1013
- eventRuntime?.stop('manual');
1014
- stopOwnedStrategy();
1015
- if (ownerControl) await ownerControl.close();
1016
- cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
1017
- }
1018
- }
1019
-
1020
- export function createGameCommand(): Command {
1021
- const game = new Command('game');
1022
- game.description('Game matchmaking & session');
1023
-
1024
- game
1025
- .command('join', { hidden: true })
1026
- .alias('j')
1027
- .description('Join matchmaking queue')
1028
- .action(async () => {
1029
- const authStore = new AuthStore();
1030
- const profile = authStore.getActive();
1031
- if (!profile) throw new Error('Not logged in.');
1032
- stopStrategyIfRunning();
1033
-
1034
- const client = GameClient.fromAuth();
1035
- const result = await client.joinQueue('clawclaw');
1036
- const events = EventStore.createSessionForActiveAccount();
1037
- events.append({ type: 'session_started', source: 'game_join' });
1038
- console.log(JSON.stringify(result, null, 2));
1039
- const stateDir = getProfileStateDir(profile);
1040
- // Reset match-state: a fresh queue session starts here so `ccl game queue`
1041
- // can compute `waited_secs` from a known anchor and emit the
1042
- // match_waiting / match_timeout synthetic events.
1043
- startMatch(stateDir);
1044
- });
1045
-
1046
- game
1047
- .command('start')
1048
- .alias('s')
1049
- .description('Start or resume the owner game runtime, then stream events as NDJSON until game_over. Pass --force to replace an orphaned game-start runtime.')
1050
- .option('--force', 'force restart: kill any lingering game-start stream process and start fresh')
1051
- .option('--competition', 'enter competition matchmaking instead of normal matchmaking')
1052
- .option('--channel-url <url>', 'forward each NDJSON line via HTTP POST to this URL')
1053
- .action(runGameStart);
1054
-
1055
- game
1056
- .command('queue', { hidden: true })
1057
- .alias('q')
1058
- .description('Wait for matchmaking allocation. Always run as a background bash task (run_in_background: true) — never block on it. Returns when allocated, queue is missing, or timeout (default 30s).')
1059
- .option('-w, --wait', '(no-op, kept for backwards compatibility — wait mode is now the default)')
1060
- .option('--interval <secs>', 'Polling interval', '2')
1061
- .option('--timeout <secs>', 'Max seconds to wait, 0 means forever', String(DEFAULT_QUEUE_WAIT_TIMEOUT_SECS))
1062
- .action(async (opts) => {
1063
- const authStore = new AuthStore();
1064
- const profile = authStore.getActive();
1065
- if (!profile) throw new Error('Not logged in.');
1066
- const stateDir = getProfileStateDir(profile);
1067
- const client = GameClient.fromAuth();
1068
-
1069
- const intervalMs = positiveNumber(opts.interval, 2) * 1000;
1070
- const timeoutSecs = Number(opts.timeout);
1071
- const deadline = Number.isFinite(timeoutSecs) && timeoutSecs > 0
1072
- ? Date.now() + timeoutSecs * 1000
1073
- : 0;
1074
-
1075
- // Synthetic matchmaking events feed the game start stream so the agent can
1076
- // observe match progress through the same channel as in-game events.
1077
- // Concurrency note: the agent typically keeps a 30s `ccl game queue`
1078
- // background chain running, so two queue invocations may observe the
1079
- // same `allocated` server state. That is
1080
- // intentionally fine — stream dedups via `eventKey` (type+tick+actor),
1081
- // so consumers only see one notification.
1082
- const emitMatchEvent = (evt: Record<string, any>): void => {
1083
- try {
1084
- const store = EventStore.forActiveAccount();
1085
- store.append({ ts: new Date().toISOString(), ...evt });
1086
- } catch {
1087
- // No active session (user ran queue without join) — skip silently;
1088
- // queue's own JSON return still informs the caller.
1089
- }
1090
- };
1091
-
1092
- // On entry: emit match_waiting if state exists and heartbeat is due.
1093
- const initialState = readMatchState(stateDir);
1094
- if (initialState && shouldEmitWaiting(initialState)) {
1095
- const waitedSecs = getWaitedSecs(initialState);
1096
- emitMatchEvent({ type: 'match_waiting', waited_secs: waitedSecs });
1097
- markWaitingEmitted(stateDir);
1098
- }
1099
-
1100
- while (true) {
1101
- const queue = await client.getQueueStatus('clawclaw');
1102
- if (queueStatus(queue) === 'allocated') {
1103
- const finalState = readMatchState(stateDir);
1104
- const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
1105
- endMatch(stateDir);
1106
- const context = await fetchInitialGameContext(client);
1107
- console.log(JSON.stringify({
1108
- status: 'active_game',
1109
- queue,
1110
- waited_secs: waitedSecs,
1111
- ...context,
1112
- next_step: 'Game allocated. Launch `ccl game start` to attach the owner stream if it is not already running, then narrate the role / map / opening plan to the user.',
1113
- }, null, 2));
1114
- return;
1115
- }
1116
- if (queueStatus(queue) === 'not_in_queue') {
1117
- // Queue session is gone (user manually left or server expired it):
1118
- // clean the match-state so next `game join` starts fresh.
1119
- endMatch(stateDir);
1120
- console.log(JSON.stringify({
1121
- status: 'not_in_queue',
1122
- queue,
1123
- message: 'You are not in the matchmaking queue. Did you forget to run `ccl game join` first?',
1124
- next_step: 'Run `ccl game join` to re-enter the queue, then launch the next `ccl game queue` background task.',
1125
- }, null, 2));
1126
- return;
1127
- }
1128
- if (deadline > 0 && Date.now() >= deadline) {
1129
- const cur = readMatchState(stateDir);
1130
- const waitedSecs = cur ? getWaitedSecs(cur) : timeoutSecs;
1131
- // Total-wait timeout (>=10 min by default) gets its own synthetic
1132
- // event so the agent can prompt the user to keep waiting / leave /
1133
- // retry later. Single 30s queue-attempt timeouts do NOT emit anything
1134
- // — they are an internal polling boundary, not a user-visible event.
1135
- if (cur && hasMatchTimedOut(cur)) {
1136
- emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
1137
- }
1138
- console.log(JSON.stringify({
1139
- status: 'timeout',
1140
- waited_secs: waitedSecs,
1141
- queue,
1142
- message: `No match after ${timeoutSecs} seconds (total wait ${waitedSecs}s).`,
1143
- next_step: 'ZERO-GAP PROTOCOL: (1) Launch the next `ccl game queue` background task IMMEDIATELY. (2) While it runs, chat with the user — share strategy, persona, banter — never go silent.',
1144
- }, null, 2));
1145
- return;
1146
- }
1147
- await sleep(intervalMs);
1148
- }
1149
- });
1150
-
1151
- game
1152
- .command('leave', { hidden: true })
1153
- .alias('l')
1154
- .description('Deprecated alias for quit')
1155
- .action(async () => runGameQuit('game leave'));
1156
-
1157
-
1158
- game
1159
- .command('stop', { hidden: true })
1160
- .alias('x')
1161
- .description('Stop local game runtime')
1162
- .action(async () => {
1163
- const authStore = new AuthStore();
1164
- const profile = authStore.getActive();
1165
- if (!profile) throw new Error('Not logged in.');
1166
- const stateDir = getProfileStateDir(profile);
1167
- const owner = await stopOwnerIfRunning(stateDir);
1168
- stopStrategyIfRunning();
1169
- if (!owner.stopped) {
1170
- console.log(JSON.stringify({ message: 'No game runtime running.' }, null, 2));
1171
- return;
1172
- }
1173
- console.log(JSON.stringify({
1174
- message: 'Game runtime stopped.',
1175
- ...(owner.pid ? { owner_pid: owner.pid } : {}),
1176
- }, null, 2));
1177
- });
1178
-
1179
- game
1180
- .command('quit')
1181
- .description('Leave active game and stop local runtime')
1182
- .action(async () => runGameQuit('game quit'));
1183
-
1184
- game
1185
- .command('map', { hidden: true })
1186
- .alias('m')
1187
- .description('Show game map')
1188
- .option('--ascii', 'Include packaged ASCII topology map')
1189
- .action(async (opts) => {
1190
- const client = GameClient.fromAuth();
1191
- await client.discoverGameServer();
1192
- const result = await client.getMap();
1193
- console.log(JSON.stringify(summarizeGameMap(result, { ascii: opts.ascii === true }), null, 2));
1194
- });
1195
-
1196
- game
1197
- .command('tasks', { hidden: true })
1198
- .alias('t')
1199
- .description('Show my tasks')
1200
- .action(async () => {
1201
- const client = GameClient.fromAuth();
1202
- await client.discoverGameServer();
1203
- const result = await client.getMap();
1204
- console.log(JSON.stringify(result?.your_tasks ?? [], null, 2));
1205
- });
1206
-
1207
- game
1208
- .command('role', { hidden: true })
1209
- .alias('r')
1210
- .description('Show my role info')
1211
- .action(async () => {
1212
- const client = GameClient.fromAuth();
1213
- const result = await client.getRoleInfo();
1214
- console.log(JSON.stringify(result, null, 2));
1215
- });
1216
-
1217
- game
1218
- .command('watch')
1219
- .alias('w')
1220
- .description('Get spectating URL')
1221
- .action(() => {
1222
- const authStore = new AuthStore();
1223
- const profile = authStore.getActive();
1224
- if (!profile) throw new Error('Not logged in.');
1225
- const origin = new URL(profile.serverUrl).origin.replace(/^http:\/\//, 'https://');
1226
- const url = `${origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`;
1227
- console.log(JSON.stringify({ url, message: 'Open in browser to spectate.' }, null, 2));
1228
- });
1229
-
1230
- // ── Adapter metadata: queue blocks up to --timeout secs (default 30); cap L2 spawn at 60s ──
1231
- setMeta(game.commands.find((c) => c.name() === 'queue')!, { longRunning: true, timeoutMs: 60_000 });
1232
- setMeta(game.commands.find((c) => c.name() === 'start')!, { longRunning: true, timeoutMs: 1_800_000 });
1233
-
1234
- return game;
1235
- }
1
+ import { Command } from 'commander';
2
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { spawn, spawnSync, type ChildProcess } from 'child_process';
5
+ import { AuthStore } from '../lib/auth.js';
6
+ import { ApiError, GameClient } from '../lib/game-client.js';
7
+ import { getProfileStateDir } from '../lib/init-command.js';
8
+ import { EventStore } from '../pipeline/event-store.js';
9
+ import { spawnStrategyLoop } from '../strategies/spawn.js';
10
+ import { stopStrategyIfRunning } from '../strategies/strategy-loop.js';
11
+ import { setMeta } from '../lib/command-meta.js';
12
+ import { runStreaming, buildErrorLine, summarizeFeed, nextStepFor } from './watch.js';
13
+ import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
14
+ import { noAccountMessage } from '../lib/account-guidance.js';
15
+ import { EventRuntime } from '../runtime/event-daemon.js';
16
+ import {
17
+ apiErrorCode,
18
+ apiErrorMessage,
19
+ normalizeCompetitionStatusResponse,
20
+ queueModeFrom,
21
+ serializeError as serializeCompetitionError,
22
+ type QueueMode,
23
+ } from '../lib/competition.js';
24
+ import {
25
+ briefGameMap,
26
+ summarizeGameMap,
27
+ } from '../lib/game-context.js';
28
+ import {
29
+ gameStartRuntimePath,
30
+ readGameStartRuntime,
31
+ sendOwnerControlRequest,
32
+ startOwnerControlServer,
33
+ type OwnerControlInfo,
34
+ type OwnerControlServer,
35
+ } from '../runtime/owner-control.js';
36
+ import {
37
+ startMatch,
38
+ endMatch,
39
+ readMatchState,
40
+ shouldEmitWaiting,
41
+ markWaitingEmitted,
42
+ getWaitedSecs,
43
+ hasMatchTimedOut,
44
+ } from '../lib/match-state.js';
45
+
46
+ export { summarizeGameMap } from '../lib/game-context.js';
47
+
48
+ function sleep(ms: number): Promise<void> {
49
+ return new Promise(r => setTimeout(r, ms));
50
+ }
51
+
52
+ function positiveNumber(value: string, fallback: number): number {
53
+ const parsed = Number(value);
54
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
55
+ }
56
+
57
+ function queueStatus(result: any): string | undefined {
58
+ return (result?.data ?? result)?.status;
59
+ }
60
+
61
+ function queueMode(result: any): QueueMode | undefined {
62
+ return queueModeFrom(result);
63
+ }
64
+
65
+ const DEFAULT_QUEUE_WAIT_TIMEOUT_SECS = 30;
66
+
67
+ function clearCachedGameServerUrl(authStore: AuthStore, profileName?: string): void {
68
+ try {
69
+ authStore.updateGameServerUrl(undefined, profileName);
70
+ } catch {
71
+ // Cache cleanup is best-effort; queue status will discover the current server.
72
+ }
73
+ }
74
+
75
+ function isLeaveGameSuccess(result: any): boolean {
76
+ const data = result?.data ?? result;
77
+ return data?.ok === true || data?.message === 'left_game';
78
+ }
79
+
80
+ function isPidAlive(pid: number): boolean {
81
+ if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return false;
82
+ try { process.kill(pid, 0); return true; } catch { return false; }
83
+ }
84
+
85
+ function getRunningGameStartPid(stateDir: string): number | null {
86
+ const info = readGameStartRuntime(stateDir);
87
+ if (!info) return null;
88
+ const pid = Number(info?.owner_pid ?? info?.pid);
89
+ if (isPidAlive(pid)) return pid;
90
+ try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
91
+ return null;
92
+ }
93
+
94
+ function writeGameStartRuntime(
95
+ stateDir: string,
96
+ mode: GameStartPlanKind,
97
+ phase?: string,
98
+ controlOverride?: { control: OwnerControlInfo; token: string },
99
+ ): void {
100
+ mkdirSync(stateDir, { recursive: true });
101
+ let startedAt = new Date().toISOString();
102
+ let existingControl: OwnerControlInfo | undefined;
103
+ let existingToken: string | undefined;
104
+ try {
105
+ const existing = JSON.parse(readFileSync(gameStartRuntimePath(stateDir), 'utf8'));
106
+ const existingPid = Number(existing?.owner_pid ?? existing?.pid);
107
+ if (existingPid === process.pid && typeof existing?.started_at === 'string') {
108
+ startedAt = existing.started_at;
109
+ if (existing?.control?.path) existingControl = existing.control;
110
+ if (typeof existing?.control_token === 'string') existingToken = existing.control_token;
111
+ }
112
+ } catch {}
113
+ const control = controlOverride?.control ?? existingControl;
114
+ const controlToken = controlOverride?.token ?? existingToken;
115
+ writeFileSync(gameStartRuntimePath(stateDir), JSON.stringify({
116
+ schema: 3,
117
+ owner_pid: process.pid,
118
+ pid: process.pid,
119
+ started_at: startedAt,
120
+ heartbeat_at: new Date().toISOString(),
121
+ mode,
122
+ ...(control ? { control } : {}),
123
+ ...(controlToken ? { control_token: controlToken } : {}),
124
+ ...(phase ? { phase } : {}),
125
+ }, null, 2));
126
+ }
127
+
128
+ function startGameStartHeartbeat(stateDir: string, mode: GameStartPlanKind): ReturnType<typeof setInterval> {
129
+ return setInterval(() => {
130
+ try {
131
+ writeGameStartRuntime(stateDir, mode);
132
+ } catch {}
133
+ }, 5000);
134
+ }
135
+
136
+ function cleanupGameStartRuntime(stateDir: string, opts: { removeFeed?: boolean; controlPath?: string } = {}): void {
137
+ const runtimePath = gameStartRuntimePath(stateDir);
138
+ try {
139
+ const info = JSON.parse(readFileSync(runtimePath, 'utf8'));
140
+ const pid = Number(info?.owner_pid ?? info?.pid);
141
+ if (pid !== process.pid) return;
142
+ } catch {}
143
+ try { unlinkSync(runtimePath); } catch {}
144
+ if (opts.removeFeed) {
145
+ try { unlinkSync(join(stateDir, 'feed.json')); } catch {}
146
+ }
147
+ if (opts.controlPath && process.platform !== 'win32') {
148
+ try { unlinkSync(opts.controlPath); } catch {}
149
+ }
150
+ }
151
+
152
+ function terminateProcessTree(pid: number, signal: NodeJS.Signals = 'SIGTERM'): boolean {
153
+ if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return false;
154
+ if (process.platform === 'win32') {
155
+ const result = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' });
156
+ return result.status === 0;
157
+ }
158
+ const pkillSignal = signal === 'SIGKILL' ? '-KILL' : '-TERM';
159
+ try { spawnSync('pkill', [pkillSignal, '-P', String(pid)], { stdio: 'ignore' }); } catch {}
160
+ try {
161
+ process.kill(pid, signal);
162
+ return true;
163
+ } catch {
164
+ return false;
165
+ }
166
+ }
167
+
168
+ async function waitPidExit(pid: number, timeoutMs = 5000): Promise<boolean> {
169
+ const deadline = Date.now() + timeoutMs;
170
+ while (Date.now() < deadline) {
171
+ if (!isPidAlive(pid)) return true;
172
+ await sleep(200);
173
+ }
174
+ return !isPidAlive(pid);
175
+ }
176
+
177
+ async function stopOwnerIfRunning(stateDir: string, timeoutMs = 5000): Promise<{ pid: number | null; stopped: boolean }> {
178
+ return stopOwnerWithCommand(stateDir, 'stop', timeoutMs);
179
+ }
180
+
181
+ async function stopOwnerWithCommand(
182
+ stateDir: string,
183
+ command: 'stop' | 'quit' | 'leave',
184
+ timeoutMs = 5000,
185
+ ): Promise<{ pid: number | null; stopped: boolean }> {
186
+ const pid = getRunningGameStartPid(stateDir);
187
+ if (!pid) {
188
+ try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
189
+ try { unlinkSync(join(stateDir, 'feed.json')); } catch {}
190
+ return { pid: null, stopped: false };
191
+ }
192
+ try {
193
+ const response = await sendOwnerControlRequest(stateDir, command);
194
+ if (response?.ok) {
195
+ const exited = await waitPidExit(pid, timeoutMs);
196
+ if (exited) return { pid, stopped: true };
197
+ }
198
+ } catch {}
199
+ terminateProcessTree(pid, 'SIGTERM');
200
+ const exited = await waitPidExit(pid, timeoutMs);
201
+ if (!exited) {
202
+ terminateProcessTree(pid, 'SIGKILL');
203
+ await waitPidExit(pid, 2000);
204
+ }
205
+ try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
206
+ try { unlinkSync(join(stateDir, 'feed.json')); } catch {}
207
+ return { pid, stopped: true };
208
+ }
209
+
210
+ type QueueStatus = 'allocated' | 'queued' | 'not_in_queue' | string | undefined;
211
+
212
+ export type GameStartPlan =
213
+ | { kind: 'already_running'; pid: number }
214
+ | { kind: 'resume_queue' }
215
+ | { kind: 'resume_allocated' }
216
+ | { kind: 'fresh_start' };
217
+
218
+ type GameStartPlanKind = GameStartPlan['kind'];
219
+
220
+ export function planGameStartAction(input: {
221
+ gameStartPid?: number | null;
222
+ hasMatchState: boolean;
223
+ queueStatus?: QueueStatus;
224
+ }): GameStartPlan {
225
+ if (input.gameStartPid) return { kind: 'already_running', pid: input.gameStartPid };
226
+
227
+ if (input.queueStatus === 'allocated') return { kind: 'resume_allocated' };
228
+ if (input.queueStatus === 'queued' || input.queueStatus === 'already_in_queue') return { kind: 'resume_queue' };
229
+ if (input.hasMatchState && input.queueStatus !== 'not_in_queue') return { kind: 'resume_queue' };
230
+ return { kind: 'fresh_start' };
231
+ }
232
+
233
+ function isAlreadyInGameError(err: unknown): boolean {
234
+ return err instanceof ApiError && err.body.includes('ALREADY_IN_GAME');
235
+ }
236
+
237
+ function apiErrorBody(err: unknown): string {
238
+ if (err instanceof ApiError) return err.body;
239
+ if (err instanceof Error) return err.message;
240
+ return String(err);
241
+ }
242
+
243
+ function isStillAliveError(err: unknown): boolean {
244
+ return /STILL_ALIVE/i.test(apiErrorBody(err));
245
+ }
246
+
247
+ function serializeError(err: unknown): Record<string, any> {
248
+ if (err instanceof ApiError) {
249
+ return { status: err.status, body: err.body };
250
+ }
251
+ return { message: err instanceof Error ? err.message : String(err) };
252
+ }
253
+
254
+ function competitionExitReason(code: string | undefined): string {
255
+ switch (code) {
256
+ case 'NO_ACTIVE_COMPETITION': return 'no_active_competition';
257
+ case 'COMPETITION_NOT_OPEN': return 'competition_not_open';
258
+ case 'ALREADY_IN_GAME': return 'already_in_game';
259
+ case 'INVALID_MODE': return 'invalid_mode';
260
+ default: return 'request_failed';
261
+ }
262
+ }
263
+
264
+ function competitionNextStep(code: string | undefined): string {
265
+ switch (code) {
266
+ case 'NO_ACTIVE_COMPETITION':
267
+ return 'Tell the user there is no active competition. Do not start normal matchmaking unless the user asks.';
268
+ case 'COMPETITION_NOT_OPEN':
269
+ return 'Tell the user competition is not open now and use competition.daily_windows for the opening windows. Do not start normal matchmaking unless the user asks.';
270
+ case 'ALREADY_IN_GAME':
271
+ return 'Tell the user this account is already in a game. Reconnect or continue the existing game instead of starting another match.';
272
+ default:
273
+ return 'Tell the user competition matchmaking failed. Do not start normal matchmaking unless the user asks.';
274
+ }
275
+ }
276
+
277
+ type GamePresence = 'in_game' | 'matching' | 'none' | 'unknown';
278
+
279
+ interface GamePresenceInfo {
280
+ presence: GamePresence;
281
+ game_state?: any;
282
+ queue_status?: any;
283
+ owner_pid: number | null;
284
+ errors?: Array<{ source: string; error: Record<string, any> }>;
285
+ }
286
+
287
+ function isMatchingQueueStatus(status: QueueStatus): boolean {
288
+ return status === 'queued'
289
+ || status === 'already_in_queue'
290
+ || status === 'allocating'
291
+ || status === 'allocated';
292
+ }
293
+
294
+ async function detectGamePresence(client: GameClient, stateDir: string): Promise<GamePresenceInfo> {
295
+ const errors: Array<{ source: string; error: Record<string, any> }> = [];
296
+ const ownerPid = getRunningGameStartPid(stateDir);
297
+ let gameState: any | null = null;
298
+ try {
299
+ await client.discoverGameServer();
300
+ gameState = await client.getGameState();
301
+ } catch (err) {
302
+ errors.push({ source: 'game_current', error: serializeError(err) });
303
+ }
304
+ if (gameState) {
305
+ return {
306
+ presence: 'in_game',
307
+ game_state: gameState,
308
+ owner_pid: ownerPid,
309
+ ...(errors.length ? { errors } : {}),
310
+ };
311
+ }
312
+
313
+ let queue: any;
314
+ try {
315
+ queue = await client.getQueueStatus('clawclaw');
316
+ } catch (err) {
317
+ errors.push({ source: 'queue_status', error: serializeError(err) });
318
+ }
319
+ const status = queueStatus(queue);
320
+ if (isMatchingQueueStatus(status)) {
321
+ return {
322
+ presence: 'matching',
323
+ queue_status: queue,
324
+ owner_pid: ownerPid,
325
+ ...(errors.length ? { errors } : {}),
326
+ };
327
+ }
328
+ if (status === 'not_in_queue') {
329
+ return {
330
+ presence: 'none',
331
+ queue_status: queue,
332
+ owner_pid: ownerPid,
333
+ ...(errors.length ? { errors } : {}),
334
+ };
335
+ }
336
+ return {
337
+ presence: errors.length >= 2 ? 'unknown' : 'none',
338
+ ...(queue ? { queue_status: queue } : {}),
339
+ owner_pid: ownerPid,
340
+ ...(errors.length ? { errors } : {}),
341
+ };
342
+ }
343
+
344
+ function ensureEventSession(source: string): EventStore {
345
+ const existing = EventStore.latestSessionPath();
346
+ if (existing) {
347
+ const events = EventStore.forActiveAccount();
348
+ events.append({ type: 'session_resumed', source });
349
+ return events;
350
+ }
351
+ const events = EventStore.createSessionForActiveAccount();
352
+ events.append({ type: 'session_started', source });
353
+ return events;
354
+ }
355
+
356
+ function nonEmptyString(value: unknown): string | undefined {
357
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
358
+ }
359
+
360
+ function unwrapData(value: any): any {
361
+ return value?.data ?? value;
362
+ }
363
+
364
+ function cleanObject<T extends Record<string, any>>(obj: T): T {
365
+ for (const key of Object.keys(obj)) {
366
+ if (obj[key] === undefined) delete obj[key];
367
+ }
368
+ return obj;
369
+ }
370
+
371
+ export interface GameStrategyIdentity {
372
+ gameId?: string;
373
+ role?: string;
374
+ alive: boolean | null;
375
+ }
376
+
377
+ export function gameStrategyIdentity(stateData: any, roleData: any): GameStrategyIdentity {
378
+ const state = unwrapData(stateData);
379
+ const role = unwrapData(roleData);
380
+ const you = state?.you ?? {};
381
+ const aliveRaw = you?.is_alive ?? you?.alive;
382
+ return {
383
+ gameId: nonEmptyString(state?.game_id) ?? nonEmptyString(state?.game?.id) ?? nonEmptyString(state?.game?.game_id),
384
+ role: nonEmptyString(role?.role) ?? nonEmptyString(you?.role),
385
+ alive: typeof aliveRaw === 'boolean' ? aliveRaw : null,
386
+ };
387
+ }
388
+
389
+ function commandError(command: string, err: unknown): { command: string; error: string } {
390
+ const message = err instanceof ApiError
391
+ ? `${err.status}: ${err.body}`
392
+ : err instanceof Error
393
+ ? err.message
394
+ : String(err);
395
+ return { command, error: message };
396
+ }
397
+
398
+ async function fetchInitialGameContext(client: GameClient): Promise<{
399
+ state: any | null;
400
+ role: any | null;
401
+ map: any | null;
402
+ tasks: any[] | null;
403
+ errors?: Array<{ command: string; error: string }>;
404
+ }> {
405
+ await sleep(500);
406
+ const [stateResult, roleResult, mapResult] = await Promise.allSettled([
407
+ client.getGameState(),
408
+ client.getRoleInfo(),
409
+ client.getMap(),
410
+ ]);
411
+
412
+ const errors: Array<{ command: string; error: string }> = [];
413
+ if (stateResult.status === 'rejected') errors.push(commandError('state', stateResult.reason));
414
+ if (roleResult.status === 'rejected') errors.push(commandError('game role', roleResult.reason));
415
+ if (mapResult.status === 'rejected') errors.push(commandError('game map', mapResult.reason));
416
+
417
+ const mapData = mapResult.status === 'fulfilled' ? mapResult.value : null;
418
+ const context = {
419
+ state: stateResult.status === 'fulfilled' ? stateResult.value : null,
420
+ role: roleResult.status === 'fulfilled' ? roleResult.value : null,
421
+ map: briefGameMap(mapData),
422
+ tasks: mapData?.your_tasks ?? null,
423
+ ...(errors.length ? { errors } : {}),
424
+ };
425
+ return context;
426
+ }
427
+
428
+ const ROLE_DEFAULT_STRATEGY: Record<string, string> = {
429
+ 'shrimp_generic': 'task-report',
430
+ 'shrimp_warrior': 'task-report',
431
+ 'shrimp_pistol': 'task-report',
432
+ 'crab_generic': 'crab-sabotage',
433
+ 'neutral_paradise_fish': 'corpse-patrol',
434
+ 'neutral_octopus': 'lone-kill-task',
435
+ };
436
+
437
+ function autoStartStrategy(roleData: any, stateData?: any, gameId?: string): { strategy: string; pid: number | undefined; child: ChildProcess } | null {
438
+ const roleId: string | undefined = roleData?.data?.role ?? roleData?.role;
439
+ if (!roleId) return null;
440
+ const strategyId = ROLE_DEFAULT_STRATEGY[roleId];
441
+ if (!strategyId) return null;
442
+ const child = spawnStrategyLoop(strategyId, [roleId], {
443
+ source: 'auto_start',
444
+ gameId: gameId ?? gameStrategyIdentity(stateData, roleData).gameId,
445
+ role: roleId,
446
+ detached: false,
447
+ writeRuntimeFiles: false,
448
+ });
449
+ return { strategy: strategyId, pid: child.pid, child };
450
+ }
451
+
452
+ async function runGameQuit(invokedAs = 'game quit'): Promise<void> {
453
+ const authStore = new AuthStore();
454
+ const profile = authStore.getActive();
455
+ if (!profile) throw new Error('Not logged in.');
456
+
457
+ const stateDir = getProfileStateDir(profile);
458
+ const client = GameClient.fromAuth();
459
+ const presence = await detectGamePresence(client, stateDir);
460
+ let left: 'game' | 'queue' | 'local_runtime' | 'none' = presence.owner_pid ? 'local_runtime' : 'none';
461
+ let gameResult: any;
462
+ let queueResult: any;
463
+ let leaveError: Record<string, any> | undefined;
464
+
465
+ if (presence.presence === 'in_game') {
466
+ try {
467
+ gameResult = await client.leaveGame();
468
+ if (isLeaveGameSuccess(gameResult)) clearCachedGameServerUrl(authStore, profile.agentName);
469
+ left = 'game';
470
+ } catch (err) {
471
+ leaveError = {
472
+ ...serializeError(err),
473
+ still_alive: isStillAliveError(err),
474
+ };
475
+ left = 'local_runtime';
476
+ }
477
+ } else if (presence.presence === 'matching') {
478
+ try {
479
+ queueResult = await client.leaveQueue('clawclaw');
480
+ left = 'queue';
481
+ } catch (err) {
482
+ leaveError = serializeError(err);
483
+ }
484
+ }
485
+
486
+ endMatch(stateDir);
487
+ const owner = await stopOwnerWithCommand(stateDir, 'quit');
488
+ stopStrategyIfRunning();
489
+
490
+ const reminder = hubReminder(readCachedGamesPlayed());
491
+ const out: Record<string, any> = cleanObject({
492
+ ok: true,
493
+ command: invokedAs,
494
+ left,
495
+ presence: presence.presence,
496
+ game_result: gameResult,
497
+ queue_result: queueResult,
498
+ leave_error: leaveError,
499
+ detection_errors: presence.errors,
500
+ queue_status: presence.queue_status,
501
+ owner_pid: owner.pid ?? presence.owner_pid ?? undefined,
502
+ owner_stopped: owner.stopped,
503
+ hub_reminder: reminder,
504
+ next_step: reminder ? `Stopped local runtime. ${reminder}` : undefined,
505
+ });
506
+ if (presence.presence === 'in_game' && leaveError?.still_alive) {
507
+ out.message = 'The server rejected leaving the active game because you are still alive; local runtime was stopped only.';
508
+ }
509
+ console.log(JSON.stringify(out, null, 2));
510
+ }
511
+
512
+ async function runGameStart(opts: { force?: boolean; channelUrl?: string; competition?: boolean; agentType?: string }): Promise<void> {
513
+ if (process.env.CLAWCLAW_REQUIRE_STREAM_TOOL === '1' && process.env.CLAWCLAW_STREAMED !== '1') {
514
+ process.stderr.write(
515
+ 'In OpenClaw, start the game via the clawclaw_game_start tool - do not exec `ccl game start` directly.\n' +
516
+ 'When run raw, the event NDJSON only fills an unconsumed buffer, so you never receive speech_your_turn and stay silent.\n',
517
+ );
518
+ process.exit(2);
519
+ }
520
+
521
+ // Channel 模式硬兜底:带 --channel-url 时,把真正的长流逻辑 fork 到 detached 后台进程,
522
+ // 父进程立即返回。这样即使 agent 误用 Powershell/前台直接执行,也不会阻塞——事件仍通过
523
+ // --channel-url 的 HTTP POST 推送给 channel,后台进程的 PID 写入 runtime 文件,
524
+ // `ccl game quit` 依旧能正确清理。CLAWCLAW_CHANNEL_DETACHED 防止子进程再次 fork。
525
+ if (opts.channelUrl && process.env.CLAWCLAW_CHANNEL_DETACHED !== '1') {
526
+ // 先做本地登录校验,保证前台调用能立即看到未登录错误(detach 后 stdout 被丢弃)。
527
+ const detachProfile = new AuthStore().getActive();
528
+ if (!detachProfile) throw new Error(noAccountMessage('gameStart'));
529
+ // 已有运行中的 stream 时不重复 fork:detach 的瞬间返回容易诱发 agent 误重试,
530
+ // 在父进程同步拦截顺序重试,避免拉起第二个注定 already_running 的后台进程。
531
+ const existingPid = getRunningGameStartPid(getProfileStateDir(detachProfile));
532
+ if (existingPid && !opts.force) {
533
+ process.stdout.write(JSON.stringify({
534
+ exit_reason: ['already_running'],
535
+ next_step: `已有 ccl game start 后台进程在运行(pid ${existingPid}),事件正通过 channel 推送。不要重复启动;如需重启加 --force,或先 ccl game quit。`,
536
+ events: [{ type: 'already_running', pid: existingPid }],
537
+ summary: { phase: 'matching' },
538
+ }) + '\n');
539
+ return;
540
+ }
541
+ const child = spawn(process.execPath, process.argv.slice(1), {
542
+ detached: true,
543
+ stdio: 'ignore',
544
+ env: { ...process.env, CLAWCLAW_CHANNEL_DETACHED: '1' },
545
+ });
546
+ child.unref();
547
+ process.stdout.write(JSON.stringify({
548
+ exit_reason: ['channel_detached'],
549
+ next_step: 'ccl game start 已在后台启动,事件将通过 channel 实时推送。不要在前台等待此进程;结束本局用 ccl game quit。',
550
+ events: [{ type: 'channel_detached', pid: child.pid }],
551
+ summary: { phase: 'matching' },
552
+ }) + '\n');
553
+ return;
554
+ }
555
+
556
+ const authStore = new AuthStore();
557
+ const profile = authStore.getActive();
558
+ if (!profile) throw new Error(noAccountMessage('gameStart'));
559
+
560
+ const stateDir = getProfileStateDir(profile);
561
+ const feedPath = join(stateDir, 'feed.json');
562
+ clearCachedGameServerUrl(authStore, profile.agentName);
563
+ const client = GameClient.fromAuth();
564
+ const requestedMode: QueueMode = opts.competition ? 'competition' : 'match';
565
+ let currentGameMode: QueueMode | undefined = requestedMode;
566
+ let eventRuntime: EventRuntime | undefined;
567
+ let streamAbortController: AbortController | null = null;
568
+ let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
569
+ let ownerControl: OwnerControlServer | null = null;
570
+ let ownerFeed: any = {
571
+ ts: new Date().toISOString(),
572
+ phase: 'matching',
573
+ terminal: false,
574
+ you: { name: profile.agentName },
575
+ game: {},
576
+ urgent: {},
577
+ meeting: null,
578
+ recent_events: [],
579
+ };
580
+ let strategyChild: ChildProcess | null = null;
581
+ let currentStrategy: string | null = null;
582
+ const currentAutomationSummary = (): Record<string, any> | undefined => {
583
+ if (!currentStrategy) return undefined;
584
+ const pid = strategyChild?.pid;
585
+ return { strategy: currentStrategy, running: !!(pid && isPidAlive(pid)) };
586
+ };
587
+ const updateGameMode = (mode: QueueMode | undefined): void => {
588
+ if (!mode) return;
589
+ currentGameMode = mode;
590
+ };
591
+ const withCurrentMode = (payload: Record<string, any>): Record<string, any> => {
592
+ return currentGameMode ? { ...payload, mode: currentGameMode } : payload;
593
+ };
594
+ const currentSummary = (): any | null => {
595
+ const runtimeFeed = eventRuntime?.snapshot();
596
+ const feed = runtimeFeed && runtimeFeed.phase !== 'lobby' ? runtimeFeed : ownerFeed;
597
+ const automation = currentAutomationSummary();
598
+ return summarizeFeed(automation ? { ...feed, automation } : feed);
599
+ };
600
+ let manualExitEmitted = false;
601
+ let ownerExitRequested = false;
602
+ const stopOwnedStrategy = (): void => {
603
+ const child = strategyChild;
604
+ strategyChild = null;
605
+ currentStrategy = null;
606
+ if (child?.pid && isPidAlive(child.pid)) {
607
+ try { child.kill('SIGTERM'); } catch {}
608
+ setTimeout(() => {
609
+ if (child.pid && isPidAlive(child.pid)) {
610
+ try { child.kill('SIGKILL'); } catch {}
611
+ }
612
+ }, 1000).unref();
613
+ }
614
+ eventRuntime?.refreshFeed();
615
+ };
616
+ const onOwnerSignal = (): void => {
617
+ streamAbortController?.abort();
618
+ eventRuntime?.stop('SIGTERM');
619
+ stopOwnedStrategy();
620
+ cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
621
+ process.exit(130);
622
+ };
623
+ process.on('SIGINT', onOwnerSignal);
624
+ process.on('SIGTERM', onOwnerSignal);
625
+ const emit = (obj: Record<string, any>): void => {
626
+ const line = JSON.stringify(obj) + '\n';
627
+ process.stdout.write(line);
628
+ if (opts.channelUrl) {
629
+ fetch(opts.channelUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: line }).catch(() => {});
630
+ }
631
+ };
632
+ const emitLifecycle = (
633
+ reason: string,
634
+ payload: Record<string, any>,
635
+ nextStepOverride?: string,
636
+ ): void => {
637
+ const event = { ...payload, type: reason };
638
+ emit({
639
+ exit_reason: [reason],
640
+ next_step: nextStepOverride ?? nextStepFor(reason),
641
+ events: [event],
642
+ summary: currentSummary(),
643
+ });
644
+ };
645
+ const emitOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
646
+ if (manualExitEmitted) return;
647
+ manualExitEmitted = true;
648
+ const eventType = kind === 'leave' ? 'stop' : kind;
649
+ emit({
650
+ exit_reason: [eventType],
651
+ next_step: `Received ${command}. The current ccl game start process is exiting now.`,
652
+ events: [{ type: eventType, command }],
653
+ summary: { phase: 'stopped' },
654
+ });
655
+ };
656
+ const requestOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
657
+ ownerExitRequested = true;
658
+ emitOwnerExit(kind, command);
659
+ streamAbortController?.abort();
660
+ eventRuntime?.stop('manual');
661
+ stopOwnedStrategy();
662
+ };
663
+ const emitMatchEvent = (evt: Record<string, any>): void => {
664
+ try {
665
+ const store = EventStore.forActiveAccount();
666
+ store.append({ ts: new Date().toISOString(), ...evt });
667
+ } catch {}
668
+ };
669
+ const ensureEventRuntime = async (): Promise<void> => {
670
+ if (eventRuntime) return;
671
+ eventRuntime = new EventRuntime({
672
+ authStore,
673
+ getAutomation: currentAutomationSummary,
674
+ onStop: (stop) => {
675
+ if (stop.reason === 'game_over' || stop.reason === 'user_left_game') return;
676
+ streamAbortController?.abort();
677
+ },
678
+ });
679
+ await eventRuntime.start();
680
+ };
681
+ const streamGame = async (): Promise<void> => {
682
+ const sessionPath = EventStore.latestSessionPath();
683
+ const ctrl = new AbortController();
684
+ streamAbortController = ctrl;
685
+ const onSignal = (): void => {
686
+ ctrl.abort();
687
+ eventRuntime?.stop('SIGTERM');
688
+ };
689
+ process.on('SIGINT', onSignal);
690
+ process.on('SIGTERM', onSignal);
691
+ try {
692
+ await runStreaming({
693
+ feedPath,
694
+ sessionPath,
695
+ getSessionPath: () => EventStore.latestSessionPath(),
696
+ stdout: (s) => { process.stdout.write(s); if (opts.channelUrl) { fetch(opts.channelUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: s }).catch(() => {}); } },
697
+ signal: ctrl.signal,
698
+ skipFeedWait: true,
699
+ readSummary: currentSummary,
700
+ skipBacklogTypes: ['match_waiting', 'match_timeout'],
701
+ emitGameStart: true,
702
+ hubReminder: hubReminder(readCachedGamesPlayed()),
703
+ });
704
+ } catch (err: any) {
705
+ process.stdout.write(buildErrorLine(err));
706
+ process.exitCode = 1;
707
+ } finally {
708
+ process.off('SIGINT', onSignal);
709
+ process.off('SIGTERM', onSignal);
710
+ streamAbortController = null;
711
+ }
712
+ };
713
+ const handleAllocated = async (queue: any, preserveStrategy: boolean): Promise<void> => {
714
+ updateGameMode(queueMode(queue));
715
+ const finalState = readMatchState(stateDir);
716
+ const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
717
+ endMatch(stateDir);
718
+ const context = await fetchInitialGameContext(client);
719
+ const identity = gameStrategyIdentity(context.state, context.role);
720
+ // Supplement game_id from queue response when /game/current doesn't carry it yet.
721
+ const queueGameId = nonEmptyString(queue?.game_id) ?? nonEmptyString(queue?.data?.game_id);
722
+ if (!identity.gameId && queueGameId) {
723
+ identity.gameId = queueGameId;
724
+ }
725
+ const role = unwrapData(context.role);
726
+ ownerFeed = {
727
+ ...ownerFeed,
728
+ ts: new Date().toISOString(),
729
+ phase: 'allocated',
730
+ you: {
731
+ ...ownerFeed.you,
732
+ role: nonEmptyString(role?.role) ?? identity.role,
733
+ role_display: nonEmptyString(role?.role_display_name) ?? nonEmptyString(role?.role_display),
734
+ faction: nonEmptyString(role?.faction),
735
+ alive: identity.alive,
736
+ },
737
+ game: {
738
+ ...ownerFeed.game,
739
+ game_id: identity.gameId,
740
+ },
741
+ };
742
+ let strategyInfo: { strategy: string; pid: number | undefined } | null = null;
743
+ if (identity.alive !== false) {
744
+ stopOwnedStrategy();
745
+ const started = autoStartStrategy(context.role, context.state, identity.gameId);
746
+ if (started) {
747
+ strategyChild = started.child;
748
+ currentStrategy = started.strategy;
749
+ strategyInfo = { strategy: started.strategy, pid: started.pid };
750
+ }
751
+ }
752
+ const allocationPayload = {
753
+ queue,
754
+ waited_secs: waitedSecs,
755
+ game_id: identity.gameId || undefined,
756
+ ...context,
757
+ ...(strategyInfo ? { default_strategy: strategyInfo } : {}),
758
+ };
759
+ ownerFeed = { ...ownerFeed, allocation: allocationPayload };
760
+ await ensureEventRuntime();
761
+ await streamGame();
762
+ };
763
+ const pollQueue = async (preserveStrategy: boolean): Promise<void> => {
764
+ const intervalMs = 2000;
765
+ const QUEUE_POLL_HEARTBEAT_MS = 60_000;
766
+ const MAX_CONSECUTIVE_FAILURES = 3;
767
+ let lastHeartbeat = Date.now();
768
+ let consecutiveFailures = 0;
769
+
770
+ while (!ownerExitRequested) {
771
+ let queue: any;
772
+ try {
773
+ queue = await client.getQueueStatus('clawclaw');
774
+ updateGameMode(queueMode(queue));
775
+ consecutiveFailures = 0;
776
+ } catch (err: any) {
777
+ consecutiveFailures++;
778
+ const msg = err?.message ?? String(err);
779
+ if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
780
+ emitLifecycle('error', {
781
+ error: msg,
782
+ consecutive_failures: consecutiveFailures,
783
+ message: `Queue status polling failed ${consecutiveFailures} times consecutively.`,
784
+ }, 'Queue polling has failed repeatedly. Check network, then launch a fresh `ccl game start` to retry.');
785
+ return;
786
+ }
787
+ emitLifecycle('poll_error', {
788
+ error: msg,
789
+ consecutive_failures: consecutiveFailures,
790
+ message: `Queue poll failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}). Retrying...`,
791
+ }, 'Temporary polling failure. The stream will keep retrying - stay attached.');
792
+ await sleep(intervalMs);
793
+ continue;
794
+ }
795
+
796
+ if (queueStatus(queue) === 'allocated') {
797
+ await handleAllocated(queue, preserveStrategy);
798
+ return;
799
+ }
800
+ if (queueStatus(queue) === 'not_in_queue') {
801
+ endMatch(stateDir);
802
+ emitLifecycle('not_in_queue', { queue, message: 'Left or dropped from queue.' },
803
+ 'No longer in matchmaking queue. The stream will exit; launch a fresh `ccl game start` to retry if the user wants to continue.');
804
+ return;
805
+ }
806
+
807
+ const cur = readMatchState(stateDir);
808
+ if (cur && shouldEmitWaiting(cur)) {
809
+ const waitedSecs = getWaitedSecs(cur);
810
+ emitMatchEvent(withCurrentMode({ type: 'match_waiting', waited_secs: waitedSecs }));
811
+ emitLifecycle('match_waiting', withCurrentMode({ waited_secs: waitedSecs }));
812
+ markWaitingEmitted(stateDir);
813
+ lastHeartbeat = Date.now();
814
+ }
815
+ if (cur && hasMatchTimedOut(cur)) {
816
+ const waitedSecs = getWaitedSecs(cur);
817
+ emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
818
+ emitLifecycle('match_timeout', {
819
+ waited_secs: waitedSecs,
820
+ queue,
821
+ ...(currentGameMode ? { mode: currentGameMode } : {}),
822
+ message: `No match after ${waitedSecs}s.`,
823
+ });
824
+ return;
825
+ }
826
+
827
+ if (Date.now() - lastHeartbeat >= QUEUE_POLL_HEARTBEAT_MS) {
828
+ lastHeartbeat = Date.now();
829
+ const waitedSecs = cur ? getWaitedSecs(cur) : 0;
830
+ emitLifecycle('heartbeat', withCurrentMode({ waited_secs: waitedSecs }),
831
+ 'Stream is alive; still waiting for match allocation. Keep chatting with the user.');
832
+ }
833
+
834
+ await sleep(intervalMs);
835
+ }
836
+ };
837
+ const resumeQueue = async (source: string): Promise<void> => {
838
+ ensureEventSession(source);
839
+ if (!readMatchState(stateDir)) startMatch(stateDir);
840
+ await ensureEventRuntime();
841
+ await pollQueue(true);
842
+ };
843
+ const recoverAlreadyInGame = async (): Promise<boolean> => {
844
+ let queue: any;
845
+ try {
846
+ queue = await client.getQueueStatus('clawclaw');
847
+ updateGameMode(queueMode(queue));
848
+ } catch {
849
+ return false;
850
+ }
851
+ const status = queueStatus(queue);
852
+ if (status === 'allocated') {
853
+ ensureEventSession('game_start_already_in_game');
854
+ await ensureEventRuntime();
855
+ await handleAllocated(queue, true);
856
+ return true;
857
+ }
858
+ if (status === 'queued' || status === 'already_in_queue') {
859
+ await resumeQueue('game_start_already_in_game_queue');
860
+ return true;
861
+ }
862
+ return false;
863
+ };
864
+
865
+ const runningGameStartPid = getRunningGameStartPid(stateDir);
866
+ if (runningGameStartPid) {
867
+ if (opts.force) {
868
+ terminateProcessTree(runningGameStartPid, 'SIGKILL');
869
+ try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
870
+ try { unlinkSync(feedPath); } catch {}
871
+ } else {
872
+ emitLifecycle('already_running', { pid: runningGameStartPid },
873
+ `A ccl game start stream is already running (pid ${runningGameStartPid}). To replace it, re-run with --force or stop it manually: taskkill /F /PID ${runningGameStartPid}`);
874
+ return;
875
+ }
876
+ }
877
+ let initialQueue: any;
878
+ try {
879
+ initialQueue = await client.getQueueStatus('clawclaw');
880
+ updateGameMode(queueMode(initialQueue));
881
+ } catch {}
882
+ const plan = planGameStartAction({
883
+ gameStartPid: null,
884
+ hasMatchState: readMatchState(stateDir) !== null,
885
+ queueStatus: queueStatus(initialQueue),
886
+ });
887
+
888
+ ownerFeed = {
889
+ ...ownerFeed,
890
+ ts: new Date().toISOString(),
891
+ phase: plan.kind === 'resume_allocated' ? 'allocated' : 'matching',
892
+ };
893
+ if (plan.kind !== 'fresh_start' && !queueMode(initialQueue)) currentGameMode = undefined;
894
+ ownerControl = await startOwnerControlServer(stateDir, async (request) => {
895
+ if (request.type === 'snapshot') {
896
+ return { ok: true, type: 'snapshot', summary: currentSummary() };
897
+ }
898
+ if (request.type === 'stop') {
899
+ requestOwnerExit('stop', 'ccl game stop');
900
+ return { ok: true, type: 'stop' };
901
+ }
902
+ if (request.type === 'quit') {
903
+ requestOwnerExit('quit', 'ccl game quit');
904
+ return { ok: true, type: 'quit' };
905
+ }
906
+ if (request.type === 'leave') {
907
+ requestOwnerExit('leave', 'ccl game leave');
908
+ return { ok: true, type: 'leave' };
909
+ }
910
+ if (request.type === 'stop_strategy') {
911
+ stopOwnedStrategy();
912
+ return { ok: true, type: 'stop_strategy' };
913
+ }
914
+ if (request.type === 'switch_strategy') {
915
+ if (!request.strategy) return { ok: false, error: 'missing_strategy' };
916
+ stopOwnedStrategy();
917
+ const child = spawnStrategyLoop(request.strategy, request.args, {
918
+ source: 'manual',
919
+ detached: false,
920
+ writeRuntimeFiles: false,
921
+ });
922
+ strategyChild = child;
923
+ currentStrategy = request.strategy;
924
+ eventRuntime?.refreshFeed();
925
+ return { ok: true, type: 'switch_strategy', strategy: request.strategy, pid: child.pid };
926
+ }
927
+ return { ok: false, error: 'unsupported_owner_control_request' };
928
+ });
929
+ writeGameStartRuntime(stateDir, plan.kind, undefined, {
930
+ control: ownerControl.control,
931
+ token: ownerControl.token,
932
+ });
933
+ heartbeatTimer = startGameStartHeartbeat(stateDir, plan.kind);
934
+ try {
935
+ if (plan.kind === 'resume_queue') {
936
+ await resumeQueue('game_start_resume_queue');
937
+ return;
938
+ }
939
+
940
+ if (plan.kind === 'resume_allocated') {
941
+ ensureEventSession('game_start_resume_allocated');
942
+ await ensureEventRuntime();
943
+ await handleAllocated(initialQueue, true);
944
+ return;
945
+ }
946
+
947
+ let joinResult: any;
948
+ try {
949
+ updateGameMode(requestedMode);
950
+ joinResult = await client.joinQueue({ gameType: 'clawclaw', mode: requestedMode, agentType: opts.agentType });
951
+ updateGameMode(queueMode(joinResult) ?? requestedMode);
952
+ } catch (err) {
953
+ if (isAlreadyInGameError(err) && await recoverAlreadyInGame()) return;
954
+ if (requestedMode === 'competition') {
955
+ const code = apiErrorCode(err);
956
+ let competition: Record<string, any> = { status: 'unavailable', active: null, is_open: null };
957
+ try {
958
+ competition = normalizeCompetitionStatusResponse(await client.getCompetitionStatus());
959
+ } catch (statusErr) {
960
+ competition = {
961
+ status: 'unavailable',
962
+ active: null,
963
+ is_open: null,
964
+ error: serializeCompetitionError(statusErr),
965
+ };
966
+ }
967
+ emit({
968
+ exit_reason: [competitionExitReason(code)],
969
+ next_step: competitionNextStep(code),
970
+ events: [{
971
+ type: 'game_start_failed',
972
+ mode: 'competition',
973
+ exit_reason: competitionExitReason(code),
974
+ error: {
975
+ code: code ?? 'REQUEST_FAILED',
976
+ message: apiErrorMessage(err),
977
+ },
978
+ competition,
979
+ }],
980
+ summary: currentSummary(),
981
+ });
982
+ process.exitCode = 1;
983
+ return;
984
+ }
985
+ throw err;
986
+ }
987
+ const joinedStatus = queueStatus(joinResult);
988
+ if (joinedStatus === 'already_in_queue') {
989
+ await resumeQueue('game_start_already_in_queue');
990
+ return;
991
+ }
992
+ if (joinedStatus && joinedStatus !== 'queued') {
993
+ emitLifecycle('error', { queue: joinResult, message: `Unexpected queue status: ${joinedStatus}.` },
994
+ 'Queue join did not enter the clawclaw queue. Check queue status before launching another `ccl game start`.');
995
+ return;
996
+ }
997
+
998
+ stopOwnedStrategy();
999
+
1000
+ const events = EventStore.createSessionForActiveAccount();
1001
+ events.append({ type: 'session_started', source: 'game_start' });
1002
+ emitLifecycle('joined', joinResult,
1003
+ requestedMode === 'competition'
1004
+ ? 'Competition join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Game runtime is attached.'
1005
+ : 'Match join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Game runtime is attached.');
1006
+ startMatch(stateDir);
1007
+ await ensureEventRuntime();
1008
+ await pollQueue(false);
1009
+ } finally {
1010
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
1011
+ process.off('SIGINT', onOwnerSignal);
1012
+ process.off('SIGTERM', onOwnerSignal);
1013
+ eventRuntime?.stop('manual');
1014
+ stopOwnedStrategy();
1015
+ if (ownerControl) await ownerControl.close();
1016
+ cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
1017
+ }
1018
+ }
1019
+
1020
+ export function createGameCommand(): Command {
1021
+ const game = new Command('game');
1022
+ game.description('Game matchmaking & session');
1023
+
1024
+ game
1025
+ .command('join', { hidden: true })
1026
+ .alias('j')
1027
+ .description('Join matchmaking queue')
1028
+ .option('--agent-type <platform>', 'the agent platform you are running on (e.g. claude-code, openclaw, hermes); reported to the server via the X-Agent-Type header on queue join')
1029
+ .action(async (opts: { agentType?: string }) => {
1030
+ const authStore = new AuthStore();
1031
+ const profile = authStore.getActive();
1032
+ if (!profile) throw new Error('Not logged in.');
1033
+ stopStrategyIfRunning();
1034
+
1035
+ const client = GameClient.fromAuth();
1036
+ const result = await client.joinQueue({ gameType: 'clawclaw', agentType: opts.agentType });
1037
+ const events = EventStore.createSessionForActiveAccount();
1038
+ events.append({ type: 'session_started', source: 'game_join' });
1039
+ console.log(JSON.stringify(result, null, 2));
1040
+ const stateDir = getProfileStateDir(profile);
1041
+ // Reset match-state: a fresh queue session starts here so `ccl game queue`
1042
+ // can compute `waited_secs` from a known anchor and emit the
1043
+ // match_waiting / match_timeout synthetic events.
1044
+ startMatch(stateDir);
1045
+ });
1046
+
1047
+ game
1048
+ .command('start')
1049
+ .alias('s')
1050
+ .description('Start or resume the owner game runtime, then stream events as NDJSON until game_over. Pass --force to replace an orphaned game-start runtime.')
1051
+ .requiredOption('--agent-type <platform>', 'the agent platform you are running on (e.g. claude-code, openclaw, hermes); reported to the server via the X-Agent-Type header on queue join')
1052
+ .option('--force', 'force restart: kill any lingering game-start stream process and start fresh')
1053
+ .option('--competition', 'enter competition matchmaking instead of normal matchmaking')
1054
+ .option('--channel-url <url>', 'forward each NDJSON line via HTTP POST to this URL')
1055
+ .action(runGameStart);
1056
+
1057
+ game
1058
+ .command('queue', { hidden: true })
1059
+ .alias('q')
1060
+ .description('Wait for matchmaking allocation. Always run as a background bash task (run_in_background: true) — never block on it. Returns when allocated, queue is missing, or timeout (default 30s).')
1061
+ .option('-w, --wait', '(no-op, kept for backwards compatibility — wait mode is now the default)')
1062
+ .option('--interval <secs>', 'Polling interval', '2')
1063
+ .option('--timeout <secs>', 'Max seconds to wait, 0 means forever', String(DEFAULT_QUEUE_WAIT_TIMEOUT_SECS))
1064
+ .action(async (opts) => {
1065
+ const authStore = new AuthStore();
1066
+ const profile = authStore.getActive();
1067
+ if (!profile) throw new Error('Not logged in.');
1068
+ const stateDir = getProfileStateDir(profile);
1069
+ const client = GameClient.fromAuth();
1070
+
1071
+ const intervalMs = positiveNumber(opts.interval, 2) * 1000;
1072
+ const timeoutSecs = Number(opts.timeout);
1073
+ const deadline = Number.isFinite(timeoutSecs) && timeoutSecs > 0
1074
+ ? Date.now() + timeoutSecs * 1000
1075
+ : 0;
1076
+
1077
+ // Synthetic matchmaking events feed the game start stream so the agent can
1078
+ // observe match progress through the same channel as in-game events.
1079
+ // Concurrency note: the agent typically keeps a 30s `ccl game queue`
1080
+ // background chain running, so two queue invocations may observe the
1081
+ // same `allocated` server state. That is
1082
+ // intentionally fine — stream dedups via `eventKey` (type+tick+actor),
1083
+ // so consumers only see one notification.
1084
+ const emitMatchEvent = (evt: Record<string, any>): void => {
1085
+ try {
1086
+ const store = EventStore.forActiveAccount();
1087
+ store.append({ ts: new Date().toISOString(), ...evt });
1088
+ } catch {
1089
+ // No active session (user ran queue without join) — skip silently;
1090
+ // queue's own JSON return still informs the caller.
1091
+ }
1092
+ };
1093
+
1094
+ // On entry: emit match_waiting if state exists and heartbeat is due.
1095
+ const initialState = readMatchState(stateDir);
1096
+ if (initialState && shouldEmitWaiting(initialState)) {
1097
+ const waitedSecs = getWaitedSecs(initialState);
1098
+ emitMatchEvent({ type: 'match_waiting', waited_secs: waitedSecs });
1099
+ markWaitingEmitted(stateDir);
1100
+ }
1101
+
1102
+ while (true) {
1103
+ const queue = await client.getQueueStatus('clawclaw');
1104
+ if (queueStatus(queue) === 'allocated') {
1105
+ const finalState = readMatchState(stateDir);
1106
+ const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
1107
+ endMatch(stateDir);
1108
+ const context = await fetchInitialGameContext(client);
1109
+ console.log(JSON.stringify({
1110
+ status: 'active_game',
1111
+ queue,
1112
+ waited_secs: waitedSecs,
1113
+ ...context,
1114
+ next_step: 'Game allocated. Launch `ccl game start` to attach the owner stream if it is not already running, then narrate the role / map / opening plan to the user.',
1115
+ }, null, 2));
1116
+ return;
1117
+ }
1118
+ if (queueStatus(queue) === 'not_in_queue') {
1119
+ // Queue session is gone (user manually left or server expired it):
1120
+ // clean the match-state so next `game join` starts fresh.
1121
+ endMatch(stateDir);
1122
+ console.log(JSON.stringify({
1123
+ status: 'not_in_queue',
1124
+ queue,
1125
+ message: 'You are not in the matchmaking queue. Did you forget to run `ccl game join` first?',
1126
+ next_step: 'Run `ccl game join` to re-enter the queue, then launch the next `ccl game queue` background task.',
1127
+ }, null, 2));
1128
+ return;
1129
+ }
1130
+ if (deadline > 0 && Date.now() >= deadline) {
1131
+ const cur = readMatchState(stateDir);
1132
+ const waitedSecs = cur ? getWaitedSecs(cur) : timeoutSecs;
1133
+ // Total-wait timeout (>=10 min by default) gets its own synthetic
1134
+ // event so the agent can prompt the user to keep waiting / leave /
1135
+ // retry later. Single 30s queue-attempt timeouts do NOT emit anything
1136
+ // — they are an internal polling boundary, not a user-visible event.
1137
+ if (cur && hasMatchTimedOut(cur)) {
1138
+ emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
1139
+ }
1140
+ console.log(JSON.stringify({
1141
+ status: 'timeout',
1142
+ waited_secs: waitedSecs,
1143
+ queue,
1144
+ message: `No match after ${timeoutSecs} seconds (total wait ${waitedSecs}s).`,
1145
+ next_step: 'ZERO-GAP PROTOCOL: (1) Launch the next `ccl game queue` background task IMMEDIATELY. (2) While it runs, chat with the user — share strategy, persona, banter — never go silent.',
1146
+ }, null, 2));
1147
+ return;
1148
+ }
1149
+ await sleep(intervalMs);
1150
+ }
1151
+ });
1152
+
1153
+ game
1154
+ .command('leave', { hidden: true })
1155
+ .alias('l')
1156
+ .description('Deprecated alias for quit')
1157
+ .action(async () => runGameQuit('game leave'));
1158
+
1159
+
1160
+ game
1161
+ .command('stop', { hidden: true })
1162
+ .alias('x')
1163
+ .description('Stop local game runtime')
1164
+ .action(async () => {
1165
+ const authStore = new AuthStore();
1166
+ const profile = authStore.getActive();
1167
+ if (!profile) throw new Error('Not logged in.');
1168
+ const stateDir = getProfileStateDir(profile);
1169
+ const owner = await stopOwnerIfRunning(stateDir);
1170
+ stopStrategyIfRunning();
1171
+ if (!owner.stopped) {
1172
+ console.log(JSON.stringify({ message: 'No game runtime running.' }, null, 2));
1173
+ return;
1174
+ }
1175
+ console.log(JSON.stringify({
1176
+ message: 'Game runtime stopped.',
1177
+ ...(owner.pid ? { owner_pid: owner.pid } : {}),
1178
+ }, null, 2));
1179
+ });
1180
+
1181
+ game
1182
+ .command('quit')
1183
+ .description('Leave active game and stop local runtime')
1184
+ .action(async () => runGameQuit('game quit'));
1185
+
1186
+ game
1187
+ .command('map', { hidden: true })
1188
+ .alias('m')
1189
+ .description('Show game map')
1190
+ .option('--ascii', 'Include packaged ASCII topology map')
1191
+ .action(async (opts) => {
1192
+ const client = GameClient.fromAuth();
1193
+ await client.discoverGameServer();
1194
+ const result = await client.getMap();
1195
+ console.log(JSON.stringify(summarizeGameMap(result, { ascii: opts.ascii === true }), null, 2));
1196
+ });
1197
+
1198
+ game
1199
+ .command('tasks', { hidden: true })
1200
+ .alias('t')
1201
+ .description('Show my tasks')
1202
+ .action(async () => {
1203
+ const client = GameClient.fromAuth();
1204
+ await client.discoverGameServer();
1205
+ const result = await client.getMap();
1206
+ console.log(JSON.stringify(result?.your_tasks ?? [], null, 2));
1207
+ });
1208
+
1209
+ game
1210
+ .command('role', { hidden: true })
1211
+ .alias('r')
1212
+ .description('Show my role info')
1213
+ .action(async () => {
1214
+ const client = GameClient.fromAuth();
1215
+ const result = await client.getRoleInfo();
1216
+ console.log(JSON.stringify(result, null, 2));
1217
+ });
1218
+
1219
+ game
1220
+ .command('watch')
1221
+ .alias('w')
1222
+ .description('Get spectating URL')
1223
+ .action(() => {
1224
+ const authStore = new AuthStore();
1225
+ const profile = authStore.getActive();
1226
+ if (!profile) throw new Error('Not logged in.');
1227
+ const origin = new URL(profile.serverUrl).origin.replace(/^http:\/\//, 'https://');
1228
+ const url = `${origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`;
1229
+ console.log(JSON.stringify({ url, message: 'Open in browser to spectate.' }, null, 2));
1230
+ });
1231
+
1232
+ // ── Adapter metadata: queue blocks up to --timeout secs (default 30); cap L2 spawn at 60s ──
1233
+ setMeta(game.commands.find((c) => c.name() === 'queue')!, { longRunning: true, timeoutMs: 60_000 });
1234
+ setMeta(game.commands.find((c) => c.name() === 'start')!, { longRunning: true, timeoutMs: 1_800_000 });
1235
+
1236
+ return game;
1237
+ }