@myclaw163/clawclaw-cli 0.6.83 → 0.6.84

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 (217) 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//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -0
  5. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -0
  6. package/personas//346/227/240/344/272/272/350/256/276.md +3 -3
  7. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -0
  8. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -0
  9. package/scripts/check-skill-command-surface.mjs +118 -118
  10. package/scripts/enable_monitor.cjs +677 -677
  11. package/scripts/enable_monitor.test.mjs +201 -201
  12. package/scripts/find-hide-spots.py +157 -157
  13. package/scripts/postinstall.mjs +20 -20
  14. package/scripts/sync-bundled-skill.mjs +254 -254
  15. package/scripts/sync-bundled-skill.test.mjs +152 -152
  16. package/skills/clawclaw/SKILL.md +257 -258
  17. package/skills/clawclaw/references/CHATTERBOX.md +141 -141
  18. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  19. package/skills/clawclaw/references/COMMANDS.md +157 -158
  20. package/skills/clawclaw/references/GAME-MECHANICS.md +188 -188
  21. package/skills/clawclaw/references/HUB.md +48 -48
  22. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  23. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  24. package/skills/clawclaw/references/STREAM.md +84 -84
  25. package/skills/clawclaw/references/TACTICS.md +65 -65
  26. package/src/assets/clawclaw-ascii-map.txt +40 -40
  27. package/src/cli.ts +113 -113
  28. package/src/commands/_schema.ts +124 -124
  29. package/src/commands/account.ts +266 -266
  30. package/src/commands/competition.ts +42 -42
  31. package/src/commands/data.test.ts +33 -33
  32. package/src/commands/data.ts +22 -22
  33. package/src/commands/do.test.ts +40 -40
  34. package/src/commands/do.ts +93 -93
  35. package/src/commands/events.test.ts +100 -100
  36. package/src/commands/events.ts +250 -250
  37. package/src/commands/game-map.test.ts +28 -28
  38. package/src/commands/game-start-plan.test.ts +94 -84
  39. package/src/commands/game.ts +1243 -1237
  40. package/src/commands/history-player.test.ts +102 -102
  41. package/src/commands/history.ts +573 -573
  42. package/src/commands/hub.test.ts +113 -113
  43. package/src/commands/hub.ts +244 -244
  44. package/src/commands/knowledge.test.ts +13 -13
  45. package/src/commands/knowledge.ts +139 -139
  46. package/src/commands/load.test.ts +65 -65
  47. package/src/commands/load.ts +22 -22
  48. package/src/commands/meeting-history.test.ts +106 -106
  49. package/src/commands/memory.ts +40 -40
  50. package/src/commands/peek.ts +45 -45
  51. package/src/commands/persona.ts +62 -62
  52. package/src/commands/setup/codex.ts +266 -266
  53. package/src/commands/skill.ts +128 -128
  54. package/src/commands/state.ts +46 -46
  55. package/src/commands/strategy.test.ts +153 -153
  56. package/src/commands/strategy.ts +183 -183
  57. package/src/commands/upgrade.test.ts +82 -82
  58. package/src/commands/upgrade.ts +148 -148
  59. package/src/commands/watch.test.ts +1041 -999
  60. package/src/commands/watch.ts +664 -660
  61. package/src/lib/account-guidance.test.ts +32 -32
  62. package/src/lib/account-guidance.ts +62 -62
  63. package/src/lib/auth.test.ts +72 -72
  64. package/src/lib/auth.ts +153 -153
  65. package/src/lib/command-meta.ts +37 -37
  66. package/src/lib/competition.ts +79 -79
  67. package/src/lib/game-client.test.ts +44 -44
  68. package/src/lib/game-client.ts +375 -375
  69. package/src/lib/game-context.ts +92 -92
  70. package/src/lib/http-keepalive.ts +15 -15
  71. package/src/lib/http-transport.test.ts +61 -61
  72. package/src/lib/http-transport.ts +118 -118
  73. package/src/lib/hub-client.test.ts +57 -57
  74. package/src/lib/hub-client.ts +88 -88
  75. package/src/lib/hub-install.test.ts +136 -136
  76. package/src/lib/hub-install.ts +198 -198
  77. package/src/lib/hub-reminder.ts +78 -78
  78. package/src/lib/hub-unzip.test.ts +69 -69
  79. package/src/lib/hub-unzip.ts +62 -62
  80. package/src/lib/init-command.test.ts +75 -75
  81. package/src/lib/init-command.ts +130 -130
  82. package/src/lib/knowledge-store.test.ts +170 -170
  83. package/src/lib/knowledge-store.ts +369 -369
  84. package/src/lib/load-context.test.ts +52 -52
  85. package/src/lib/load-context.ts +54 -54
  86. package/src/lib/match-state.test.ts +134 -134
  87. package/src/lib/match-state.ts +94 -94
  88. package/src/lib/normalize.ts +42 -42
  89. package/src/lib/persona.test.ts +84 -84
  90. package/src/lib/persona.ts +120 -120
  91. package/src/lib/server-registry.ts +152 -152
  92. package/src/lib/skill-version.test.ts +48 -48
  93. package/src/lib/skill-version.ts +19 -19
  94. package/src/lib/strategy-export.test.ts +240 -240
  95. package/src/lib/strategy-export.ts +247 -247
  96. package/src/lib/user-data.test.ts +97 -97
  97. package/src/lib/user-data.ts +374 -374
  98. package/src/lib/workspace-argv.test.ts +49 -49
  99. package/src/lib/workspace-argv.ts +44 -44
  100. package/src/perception/player-history-store.test.ts +87 -87
  101. package/src/perception/player-history-store.ts +194 -194
  102. package/src/pipeline/event-format.test.ts +247 -243
  103. package/src/pipeline/event-format.ts +507 -501
  104. package/src/pipeline/event-hints.ts +195 -195
  105. package/src/pipeline/event-store.test.ts +28 -28
  106. package/src/pipeline/event-store.ts +193 -193
  107. package/src/pipeline/pipeline.ts +35 -35
  108. package/src/pipeline/player-projection.test.ts +168 -168
  109. package/src/pipeline/player-projection.ts +370 -370
  110. package/src/runtime/auto-upgrade.test.ts +66 -66
  111. package/src/runtime/auto-upgrade.ts +31 -31
  112. package/src/runtime/event-daemon.test.ts +225 -209
  113. package/src/runtime/event-daemon.ts +527 -519
  114. package/src/runtime/owner-control.ts +150 -150
  115. package/src/runtime/raw-ws-log.test.ts +33 -33
  116. package/src/runtime/raw-ws-log.ts +32 -32
  117. package/src/runtime/runtime-logger.ts +107 -107
  118. package/src/runtime/ws-client.test.ts +169 -169
  119. package/src/runtime/ws-client.ts +280 -280
  120. package/src/sdk/action.ts +153 -153
  121. package/src/sdk/index.ts +107 -107
  122. package/src/sdk/types.ts +161 -161
  123. package/src/strategies/avoid-lone.ts +12 -12
  124. package/src/strategies/avoid-players.knowledge.md +19 -19
  125. package/src/strategies/avoid-players.ts +16 -16
  126. package/src/strategies/corpse-patrol.ts +19 -19
  127. package/src/strategies/crab-sabotage.ts +22 -22
  128. package/src/strategies/custom-module.test.ts +270 -270
  129. package/src/strategies/find-player.ts +17 -17
  130. package/src/strategies/game-utils.test.ts +242 -242
  131. package/src/strategies/game-utils.ts +846 -846
  132. package/src/strategies/goals/anchor-linger.ts +77 -77
  133. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  134. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  135. package/src/strategies/goals/avoid-players-top.ts +121 -121
  136. package/src/strategies/goals/conversation-goal.ts +51 -51
  137. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  138. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  139. package/src/strategies/goals/crab-sabotage-top.ts +197 -197
  140. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  141. package/src/strategies/goals/find-player-top.ts +93 -93
  142. package/src/strategies/goals/flee-players-goal.ts +53 -53
  143. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  144. package/src/strategies/goals/goal-manager.ts +41 -41
  145. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  146. package/src/strategies/goals/goal.ts +28 -28
  147. package/src/strategies/goals/hide-top.ts +197 -197
  148. package/src/strategies/goals/keep-away-goal.ts +221 -221
  149. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  150. package/src/strategies/goals/kill-lone-top.ts +160 -160
  151. package/src/strategies/goals/kill-target-goal.ts +59 -59
  152. package/src/strategies/goals/kill-target-top.ts +109 -109
  153. package/src/strategies/goals/leaf-goal.ts +27 -27
  154. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  155. package/src/strategies/goals/lone-kill-core.ts +82 -82
  156. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  157. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  158. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  159. package/src/strategies/goals/move-room-goal.ts +60 -60
  160. package/src/strategies/goals/normal-shrimp-top.test.ts +80 -80
  161. package/src/strategies/goals/normal-shrimp-top.ts +242 -242
  162. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  163. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  164. package/src/strategies/goals/patrol-top.ts +57 -57
  165. package/src/strategies/goals/report-patrol-top.ts +80 -80
  166. package/src/strategies/goals/safe-task-goal.ts +102 -102
  167. package/src/strategies/goals/social-task-top.ts +161 -161
  168. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  169. package/src/strategies/goals/task-only-top.ts +57 -57
  170. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  171. package/src/strategies/goals/task-report-top.ts +57 -57
  172. package/src/strategies/goals/wander-task-goal.ts +33 -33
  173. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  174. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  175. package/src/strategies/greeting.ts +53 -53
  176. package/src/strategies/hide-spots.ts +59 -59
  177. package/src/strategies/hide.ts +24 -24
  178. package/src/strategies/kill-frenzy.ts +13 -13
  179. package/src/strategies/kill-lone.knowledge.md +17 -17
  180. package/src/strategies/kill-lone.ts +14 -14
  181. package/src/strategies/kill-target.ts +19 -19
  182. package/src/strategies/loader.test.ts +678 -678
  183. package/src/strategies/loader.ts +181 -181
  184. package/src/strategies/lone-kill-task.ts +22 -22
  185. package/src/strategies/meeting-gate.test.ts +59 -59
  186. package/src/strategies/meeting-gate.ts +23 -23
  187. package/src/strategies/move-room.ts +16 -16
  188. package/src/strategies/new-events-backfill.ts +98 -98
  189. package/src/strategies/off-route-points.ts +105 -105
  190. package/src/strategies/paradise-fish.knowledge.md +19 -19
  191. package/src/strategies/paradise-fish.ts +22 -22
  192. package/src/strategies/pathfind/distance-field.ts +150 -150
  193. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  194. package/src/strategies/pathfind/escape-planner.ts +355 -355
  195. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  196. package/src/strategies/patrol.ts +12 -12
  197. package/src/strategies/player-targets.ts +13 -13
  198. package/src/strategies/report-patrol.ts +12 -12
  199. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  200. package/src/strategies/shrimp-memory.ts +22 -22
  201. package/src/strategies/social-task.test.ts +28 -28
  202. package/src/strategies/social-task.ts +50 -50
  203. package/src/strategies/spawn.ts +82 -82
  204. package/src/strategies/speech-module.ts +123 -123
  205. package/src/strategies/strategy-loop.test.ts +15 -15
  206. package/src/strategies/strategy-loop.ts +716 -716
  207. package/src/strategies/task-kill-report.ts +18 -18
  208. package/src/strategies/task-only.ts +12 -12
  209. package/src/strategies/task-report.ts +19 -19
  210. package/src/strategies/types.ts +107 -107
  211. package/src/strategies/warrior-memory.knowledge.md +21 -21
  212. package/src/strategies/warrior-memory.ts +17 -17
  213. package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +0 -23
  214. package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +0 -22
  215. package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +0 -22
  216. package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +0 -22
  217. package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +0 -23
@@ -1,1237 +1,1243 @@
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
- }
1
+ import { Command, Option } 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
+ let currentGameMode: QueueMode | undefined;
565
+ let eventRuntime: EventRuntime | undefined;
566
+ let streamAbortController: AbortController | null = null;
567
+ let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
568
+ let ownerControl: OwnerControlServer | null = null;
569
+ let ownerFeed: any = {
570
+ ts: new Date().toISOString(),
571
+ phase: 'matching',
572
+ terminal: false,
573
+ you: { name: profile.agentName },
574
+ game: {},
575
+ urgent: {},
576
+ meeting: null,
577
+ recent_events: [],
578
+ };
579
+ let strategyChild: ChildProcess | null = null;
580
+ let currentStrategy: string | null = null;
581
+ const currentAutomationSummary = (): Record<string, any> | undefined => {
582
+ if (!currentStrategy) return undefined;
583
+ const pid = strategyChild?.pid;
584
+ return { strategy: currentStrategy, running: !!(pid && isPidAlive(pid)) };
585
+ };
586
+ const updateGameMode = (mode: QueueMode | undefined): void => {
587
+ if (!mode) return;
588
+ currentGameMode = mode;
589
+ };
590
+ const withCurrentGameMode = (payload: Record<string, any>): Record<string, any> => {
591
+ return currentGameMode ? { ...payload, game_mode: currentGameMode } : payload;
592
+ };
593
+ const currentSummary = (): any | null => {
594
+ const runtimeFeed = eventRuntime?.snapshot();
595
+ const feed = runtimeFeed && runtimeFeed.phase !== 'lobby' ? runtimeFeed : ownerFeed;
596
+ const automation = currentAutomationSummary();
597
+ return summarizeFeed(automation ? { ...feed, automation } : feed);
598
+ };
599
+ let manualExitEmitted = false;
600
+ let ownerExitRequested = false;
601
+ const stopOwnedStrategy = (): void => {
602
+ const child = strategyChild;
603
+ strategyChild = null;
604
+ currentStrategy = null;
605
+ if (child?.pid && isPidAlive(child.pid)) {
606
+ try { child.kill('SIGTERM'); } catch {}
607
+ setTimeout(() => {
608
+ if (child.pid && isPidAlive(child.pid)) {
609
+ try { child.kill('SIGKILL'); } catch {}
610
+ }
611
+ }, 1000).unref();
612
+ }
613
+ eventRuntime?.refreshFeed();
614
+ };
615
+ const onOwnerSignal = (): void => {
616
+ streamAbortController?.abort();
617
+ eventRuntime?.stop('SIGTERM');
618
+ stopOwnedStrategy();
619
+ cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
620
+ process.exit(130);
621
+ };
622
+ process.on('SIGINT', onOwnerSignal);
623
+ process.on('SIGTERM', onOwnerSignal);
624
+ const emit = (obj: Record<string, any>): void => {
625
+ const line = JSON.stringify(obj) + '\n';
626
+ process.stdout.write(line);
627
+ if (opts.channelUrl) {
628
+ fetch(opts.channelUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: line }).catch(() => {});
629
+ }
630
+ };
631
+ const emitLifecycle = (
632
+ reason: string,
633
+ payload: Record<string, any>,
634
+ nextStepOverride?: string,
635
+ ): void => {
636
+ const event = { ...payload, type: reason };
637
+ emit({
638
+ exit_reason: [reason],
639
+ next_step: nextStepOverride ?? nextStepFor(reason),
640
+ events: [event],
641
+ summary: currentSummary(),
642
+ });
643
+ };
644
+ const emitOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
645
+ if (manualExitEmitted) return;
646
+ manualExitEmitted = true;
647
+ const eventType = kind === 'leave' ? 'stop' : kind;
648
+ emit({
649
+ exit_reason: [eventType],
650
+ next_step: `Received ${command}. The current ccl game start process is exiting now.`,
651
+ events: [{ type: eventType, command }],
652
+ summary: { phase: 'stopped' },
653
+ });
654
+ };
655
+ const requestOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
656
+ ownerExitRequested = true;
657
+ emitOwnerExit(kind, command);
658
+ streamAbortController?.abort();
659
+ eventRuntime?.stop('manual');
660
+ stopOwnedStrategy();
661
+ };
662
+ const emitMatchEvent = (evt: Record<string, any>): void => {
663
+ try {
664
+ const store = EventStore.forActiveAccount();
665
+ store.append({ ts: new Date().toISOString(), ...evt });
666
+ } catch {}
667
+ };
668
+ const ensureEventRuntime = async (): Promise<void> => {
669
+ if (eventRuntime) return;
670
+ eventRuntime = new EventRuntime({
671
+ authStore,
672
+ getAutomation: currentAutomationSummary,
673
+ getGameMode: () => currentGameMode,
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(withCurrentGameMode({ type: 'match_waiting', waited_secs: waitedSecs }));
811
+ emitLifecycle('match_waiting', withCurrentGameMode({ waited_secs: waitedSecs }));
812
+ markWaitingEmitted(stateDir);
813
+ lastHeartbeat = Date.now();
814
+ }
815
+ if (cur && hasMatchTimedOut(cur)) {
816
+ const waitedSecs = getWaitedSecs(cur);
817
+ emitMatchEvent(withCurrentGameMode({ type: 'match_timeout', waited_secs: waitedSecs }));
818
+ emitLifecycle('match_timeout', withCurrentGameMode({
819
+ waited_secs: waitedSecs,
820
+ queue,
821
+ message: `No match after ${waitedSecs}s.`,
822
+ }));
823
+ return;
824
+ }
825
+
826
+ if (Date.now() - lastHeartbeat >= QUEUE_POLL_HEARTBEAT_MS) {
827
+ lastHeartbeat = Date.now();
828
+ const waitedSecs = cur ? getWaitedSecs(cur) : 0;
829
+ emitLifecycle('heartbeat', withCurrentGameMode({ waited_secs: waitedSecs }),
830
+ 'Stream is alive; still waiting for match allocation. Keep chatting with the user.');
831
+ }
832
+
833
+ await sleep(intervalMs);
834
+ }
835
+ };
836
+ const resumeQueue = async (source: string): Promise<void> => {
837
+ ensureEventSession(source);
838
+ if (!readMatchState(stateDir)) startMatch(stateDir);
839
+ await ensureEventRuntime();
840
+ await pollQueue(true);
841
+ };
842
+ const recoverAlreadyInGame = async (): Promise<boolean> => {
843
+ let queue: any;
844
+ try {
845
+ queue = await client.getQueueStatus('clawclaw');
846
+ updateGameMode(queueMode(queue));
847
+ } catch {
848
+ return false;
849
+ }
850
+ const status = queueStatus(queue);
851
+ if (status === 'allocated') {
852
+ ensureEventSession('game_start_already_in_game');
853
+ await ensureEventRuntime();
854
+ await handleAllocated(queue, true);
855
+ return true;
856
+ }
857
+ if (status === 'queued' || status === 'already_in_queue') {
858
+ await resumeQueue('game_start_already_in_game_queue');
859
+ return true;
860
+ }
861
+ return false;
862
+ };
863
+
864
+ const runningGameStartPid = getRunningGameStartPid(stateDir);
865
+ if (runningGameStartPid) {
866
+ if (opts.force) {
867
+ terminateProcessTree(runningGameStartPid, 'SIGKILL');
868
+ try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
869
+ try { unlinkSync(feedPath); } catch {}
870
+ } else {
871
+ emitLifecycle('already_running', { pid: runningGameStartPid },
872
+ `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}`);
873
+ return;
874
+ }
875
+ }
876
+ let initialQueue: any;
877
+ try {
878
+ initialQueue = await client.getQueueStatus('clawclaw');
879
+ updateGameMode(queueMode(initialQueue));
880
+ } catch {}
881
+ const plan = planGameStartAction({
882
+ gameStartPid: null,
883
+ hasMatchState: readMatchState(stateDir) !== null,
884
+ queueStatus: queueStatus(initialQueue),
885
+ });
886
+
887
+ ownerFeed = {
888
+ ...ownerFeed,
889
+ ts: new Date().toISOString(),
890
+ phase: plan.kind === 'resume_allocated' ? 'allocated' : 'matching',
891
+ };
892
+ if (plan.kind !== 'fresh_start' && !queueMode(initialQueue)) currentGameMode = undefined;
893
+ ownerControl = await startOwnerControlServer(stateDir, async (request) => {
894
+ if (request.type === 'snapshot') {
895
+ return { ok: true, type: 'snapshot', summary: currentSummary() };
896
+ }
897
+ if (request.type === 'stop') {
898
+ requestOwnerExit('stop', 'ccl game stop');
899
+ return { ok: true, type: 'stop' };
900
+ }
901
+ if (request.type === 'quit') {
902
+ requestOwnerExit('quit', 'ccl game quit');
903
+ return { ok: true, type: 'quit' };
904
+ }
905
+ if (request.type === 'leave') {
906
+ requestOwnerExit('leave', 'ccl game leave');
907
+ return { ok: true, type: 'leave' };
908
+ }
909
+ if (request.type === 'stop_strategy') {
910
+ stopOwnedStrategy();
911
+ return { ok: true, type: 'stop_strategy' };
912
+ }
913
+ if (request.type === 'switch_strategy') {
914
+ if (!request.strategy) return { ok: false, error: 'missing_strategy' };
915
+ stopOwnedStrategy();
916
+ const child = spawnStrategyLoop(request.strategy, request.args, {
917
+ source: 'manual',
918
+ detached: false,
919
+ writeRuntimeFiles: false,
920
+ });
921
+ strategyChild = child;
922
+ currentStrategy = request.strategy;
923
+ eventRuntime?.refreshFeed();
924
+ return { ok: true, type: 'switch_strategy', strategy: request.strategy, pid: child.pid };
925
+ }
926
+ return { ok: false, error: 'unsupported_owner_control_request' };
927
+ });
928
+ writeGameStartRuntime(stateDir, plan.kind, undefined, {
929
+ control: ownerControl.control,
930
+ token: ownerControl.token,
931
+ });
932
+ heartbeatTimer = startGameStartHeartbeat(stateDir, plan.kind);
933
+ try {
934
+ if (plan.kind === 'resume_queue') {
935
+ await resumeQueue('game_start_resume_queue');
936
+ return;
937
+ }
938
+
939
+ if (plan.kind === 'resume_allocated') {
940
+ ensureEventSession('game_start_resume_allocated');
941
+ await ensureEventRuntime();
942
+ await handleAllocated(initialQueue, true);
943
+ return;
944
+ }
945
+
946
+ let joinResult: any;
947
+ try {
948
+ joinResult = await client.joinQueue({
949
+ gameType: 'clawclaw',
950
+ mode: opts.competition ? 'competition' : 'match',
951
+ agentType: opts.agentType,
952
+ });
953
+ updateGameMode(queueMode(joinResult));
954
+ } catch (err) {
955
+ if (isAlreadyInGameError(err) && await recoverAlreadyInGame()) return;
956
+ if (opts.competition) {
957
+ const code = apiErrorCode(err);
958
+ let competition: Record<string, any> = { status: 'unavailable', active: null, is_open: null };
959
+ try {
960
+ competition = normalizeCompetitionStatusResponse(await client.getCompetitionStatus());
961
+ } catch (statusErr) {
962
+ competition = {
963
+ status: 'unavailable',
964
+ active: null,
965
+ is_open: null,
966
+ error: serializeCompetitionError(statusErr),
967
+ };
968
+ }
969
+ emit({
970
+ exit_reason: [competitionExitReason(code)],
971
+ next_step: competitionNextStep(code),
972
+ events: [{
973
+ type: 'game_start_failed',
974
+ game_mode: 'competition',
975
+ exit_reason: competitionExitReason(code),
976
+ error: {
977
+ code: code ?? 'REQUEST_FAILED',
978
+ message: apiErrorMessage(err),
979
+ },
980
+ competition,
981
+ }],
982
+ summary: currentSummary(),
983
+ });
984
+ process.exitCode = 1;
985
+ return;
986
+ }
987
+ throw err;
988
+ }
989
+ const joinedStatus = queueStatus(joinResult);
990
+ if (joinedStatus === 'already_in_queue') {
991
+ await resumeQueue('game_start_already_in_queue');
992
+ return;
993
+ }
994
+ if (joinedStatus && joinedStatus !== 'queued') {
995
+ emitLifecycle('error', { queue: joinResult, message: `Unexpected queue status: ${joinedStatus}.` },
996
+ 'Queue join did not enter the clawclaw queue. Check queue status before launching another `ccl game start`.');
997
+ return;
998
+ }
999
+
1000
+ let joinedQueue = joinResult;
1001
+ try {
1002
+ joinedQueue = await client.getQueueStatus('clawclaw');
1003
+ updateGameMode(queueMode(joinedQueue));
1004
+ } catch {}
1005
+
1006
+ stopOwnedStrategy();
1007
+
1008
+ const events = EventStore.createSessionForActiveAccount();
1009
+ events.append({ type: 'session_started', source: 'game_start' });
1010
+ emitLifecycle('joined', withCurrentGameMode({ ...joinResult, queue: joinedQueue }),
1011
+ 'Join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Game runtime is attached.');
1012
+ startMatch(stateDir);
1013
+ await ensureEventRuntime();
1014
+ await pollQueue(false);
1015
+ } finally {
1016
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
1017
+ process.off('SIGINT', onOwnerSignal);
1018
+ process.off('SIGTERM', onOwnerSignal);
1019
+ eventRuntime?.stop('manual');
1020
+ stopOwnedStrategy();
1021
+ if (ownerControl) await ownerControl.close();
1022
+ cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
1023
+ }
1024
+ }
1025
+
1026
+ export function createGameCommand(): Command {
1027
+ const game = new Command('game');
1028
+ game.description('Game matchmaking & session');
1029
+
1030
+ game
1031
+ .command('join', { hidden: true })
1032
+ .alias('j')
1033
+ .description('Join matchmaking queue')
1034
+ .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')
1035
+ .action(async (opts: { agentType?: string }) => {
1036
+ const authStore = new AuthStore();
1037
+ const profile = authStore.getActive();
1038
+ if (!profile) throw new Error('Not logged in.');
1039
+ stopStrategyIfRunning();
1040
+
1041
+ const client = GameClient.fromAuth();
1042
+ const result = await client.joinQueue({ gameType: 'clawclaw', agentType: opts.agentType });
1043
+ const events = EventStore.createSessionForActiveAccount();
1044
+ events.append({ type: 'session_started', source: 'game_join' });
1045
+ console.log(JSON.stringify(result, null, 2));
1046
+ const stateDir = getProfileStateDir(profile);
1047
+ // Reset match-state: a fresh queue session starts here so `ccl game queue`
1048
+ // can compute `waited_secs` from a known anchor and emit the
1049
+ // match_waiting / match_timeout synthetic events.
1050
+ startMatch(stateDir);
1051
+ });
1052
+
1053
+ game
1054
+ .command('start')
1055
+ .alias('s')
1056
+ .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.')
1057
+ .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')
1058
+ .option('--force', 'force restart: kill any lingering game-start stream process and start fresh')
1059
+ .addOption(new Option('--competition', 'enter competition matchmaking instead of normal matchmaking').hideHelp())
1060
+ .option('--channel-url <url>', 'forward each NDJSON line via HTTP POST to this URL')
1061
+ .action(runGameStart);
1062
+
1063
+ game
1064
+ .command('queue', { hidden: true })
1065
+ .alias('q')
1066
+ .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).')
1067
+ .option('-w, --wait', '(no-op, kept for backwards compatibility — wait mode is now the default)')
1068
+ .option('--interval <secs>', 'Polling interval', '2')
1069
+ .option('--timeout <secs>', 'Max seconds to wait, 0 means forever', String(DEFAULT_QUEUE_WAIT_TIMEOUT_SECS))
1070
+ .action(async (opts) => {
1071
+ const authStore = new AuthStore();
1072
+ const profile = authStore.getActive();
1073
+ if (!profile) throw new Error('Not logged in.');
1074
+ const stateDir = getProfileStateDir(profile);
1075
+ const client = GameClient.fromAuth();
1076
+
1077
+ const intervalMs = positiveNumber(opts.interval, 2) * 1000;
1078
+ const timeoutSecs = Number(opts.timeout);
1079
+ const deadline = Number.isFinite(timeoutSecs) && timeoutSecs > 0
1080
+ ? Date.now() + timeoutSecs * 1000
1081
+ : 0;
1082
+
1083
+ // Synthetic matchmaking events feed the game start stream so the agent can
1084
+ // observe match progress through the same channel as in-game events.
1085
+ // Concurrency note: the agent typically keeps a 30s `ccl game queue`
1086
+ // background chain running, so two queue invocations may observe the
1087
+ // same `allocated` server state. That is
1088
+ // intentionally fine — stream dedups via `eventKey` (type+tick+actor),
1089
+ // so consumers only see one notification.
1090
+ const emitMatchEvent = (evt: Record<string, any>): void => {
1091
+ try {
1092
+ const store = EventStore.forActiveAccount();
1093
+ store.append({ ts: new Date().toISOString(), ...evt });
1094
+ } catch {
1095
+ // No active session (user ran queue without join) — skip silently;
1096
+ // queue's own JSON return still informs the caller.
1097
+ }
1098
+ };
1099
+
1100
+ // On entry: emit match_waiting if state exists and heartbeat is due.
1101
+ const initialState = readMatchState(stateDir);
1102
+ if (initialState && shouldEmitWaiting(initialState)) {
1103
+ const waitedSecs = getWaitedSecs(initialState);
1104
+ emitMatchEvent({ type: 'match_waiting', waited_secs: waitedSecs });
1105
+ markWaitingEmitted(stateDir);
1106
+ }
1107
+
1108
+ while (true) {
1109
+ const queue = await client.getQueueStatus('clawclaw');
1110
+ if (queueStatus(queue) === 'allocated') {
1111
+ const finalState = readMatchState(stateDir);
1112
+ const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
1113
+ endMatch(stateDir);
1114
+ const context = await fetchInitialGameContext(client);
1115
+ console.log(JSON.stringify({
1116
+ status: 'active_game',
1117
+ queue,
1118
+ waited_secs: waitedSecs,
1119
+ ...context,
1120
+ 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.',
1121
+ }, null, 2));
1122
+ return;
1123
+ }
1124
+ if (queueStatus(queue) === 'not_in_queue') {
1125
+ // Queue session is gone (user manually left or server expired it):
1126
+ // clean the match-state so next `game join` starts fresh.
1127
+ endMatch(stateDir);
1128
+ console.log(JSON.stringify({
1129
+ status: 'not_in_queue',
1130
+ queue,
1131
+ message: 'You are not in the matchmaking queue. Did you forget to run `ccl game join` first?',
1132
+ next_step: 'Run `ccl game join` to re-enter the queue, then launch the next `ccl game queue` background task.',
1133
+ }, null, 2));
1134
+ return;
1135
+ }
1136
+ if (deadline > 0 && Date.now() >= deadline) {
1137
+ const cur = readMatchState(stateDir);
1138
+ const waitedSecs = cur ? getWaitedSecs(cur) : timeoutSecs;
1139
+ // Total-wait timeout (>=10 min by default) gets its own synthetic
1140
+ // event so the agent can prompt the user to keep waiting / leave /
1141
+ // retry later. Single 30s queue-attempt timeouts do NOT emit anything
1142
+ // — they are an internal polling boundary, not a user-visible event.
1143
+ if (cur && hasMatchTimedOut(cur)) {
1144
+ emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
1145
+ }
1146
+ console.log(JSON.stringify({
1147
+ status: 'timeout',
1148
+ waited_secs: waitedSecs,
1149
+ queue,
1150
+ message: `No match after ${timeoutSecs} seconds (total wait ${waitedSecs}s).`,
1151
+ 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.',
1152
+ }, null, 2));
1153
+ return;
1154
+ }
1155
+ await sleep(intervalMs);
1156
+ }
1157
+ });
1158
+
1159
+ game
1160
+ .command('leave', { hidden: true })
1161
+ .alias('l')
1162
+ .description('Deprecated alias for quit')
1163
+ .action(async () => runGameQuit('game leave'));
1164
+
1165
+
1166
+ game
1167
+ .command('stop', { hidden: true })
1168
+ .alias('x')
1169
+ .description('Stop local game runtime')
1170
+ .action(async () => {
1171
+ const authStore = new AuthStore();
1172
+ const profile = authStore.getActive();
1173
+ if (!profile) throw new Error('Not logged in.');
1174
+ const stateDir = getProfileStateDir(profile);
1175
+ const owner = await stopOwnerIfRunning(stateDir);
1176
+ stopStrategyIfRunning();
1177
+ if (!owner.stopped) {
1178
+ console.log(JSON.stringify({ message: 'No game runtime running.' }, null, 2));
1179
+ return;
1180
+ }
1181
+ console.log(JSON.stringify({
1182
+ message: 'Game runtime stopped.',
1183
+ ...(owner.pid ? { owner_pid: owner.pid } : {}),
1184
+ }, null, 2));
1185
+ });
1186
+
1187
+ game
1188
+ .command('quit')
1189
+ .description('Leave active game and stop local runtime')
1190
+ .action(async () => runGameQuit('game quit'));
1191
+
1192
+ game
1193
+ .command('map', { hidden: true })
1194
+ .alias('m')
1195
+ .description('Show game map')
1196
+ .option('--ascii', 'Include packaged ASCII topology map')
1197
+ .action(async (opts) => {
1198
+ const client = GameClient.fromAuth();
1199
+ await client.discoverGameServer();
1200
+ const result = await client.getMap();
1201
+ console.log(JSON.stringify(summarizeGameMap(result, { ascii: opts.ascii === true }), null, 2));
1202
+ });
1203
+
1204
+ game
1205
+ .command('tasks', { hidden: true })
1206
+ .alias('t')
1207
+ .description('Show my tasks')
1208
+ .action(async () => {
1209
+ const client = GameClient.fromAuth();
1210
+ await client.discoverGameServer();
1211
+ const result = await client.getMap();
1212
+ console.log(JSON.stringify(result?.your_tasks ?? [], null, 2));
1213
+ });
1214
+
1215
+ game
1216
+ .command('role', { hidden: true })
1217
+ .alias('r')
1218
+ .description('Show my role info')
1219
+ .action(async () => {
1220
+ const client = GameClient.fromAuth();
1221
+ const result = await client.getRoleInfo();
1222
+ console.log(JSON.stringify(result, null, 2));
1223
+ });
1224
+
1225
+ game
1226
+ .command('watch')
1227
+ .alias('w')
1228
+ .description('Get spectating URL')
1229
+ .action(() => {
1230
+ const authStore = new AuthStore();
1231
+ const profile = authStore.getActive();
1232
+ if (!profile) throw new Error('Not logged in.');
1233
+ const origin = new URL(profile.serverUrl).origin.replace(/^http:\/\//, 'https://');
1234
+ const url = `${origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`;
1235
+ console.log(JSON.stringify({ url, message: 'Open in browser to spectate.' }, null, 2));
1236
+ });
1237
+
1238
+ // ── Adapter metadata: queue blocks up to --timeout secs (default 30); cap L2 spawn at 60s ──
1239
+ setMeta(game.commands.find((c) => c.name() === 'queue')!, { longRunning: true, timeoutMs: 60_000 });
1240
+ setMeta(game.commands.find((c) => c.name() === 'start')!, { longRunning: true, timeoutMs: 1_800_000 });
1241
+
1242
+ return game;
1243
+ }