@myclaw163/clawclaw-cli 0.6.86 → 0.6.87

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