@myclaw163/clawclaw-cli 0.6.71 → 0.6.74

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