@myclaw163/clawclaw-cli 0.6.70 → 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 (212) hide show
  1. package/README.md +377 -427
  2. package/package.json +48 -48
  3. package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +23 -23
  4. package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +22 -22
  5. package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +22 -22
  6. package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +22 -22
  7. package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +23 -23
  8. package/scripts/check-skill-command-surface.mjs +116 -0
  9. package/scripts/find-hide-spots.py +157 -157
  10. package/scripts/postinstall.mjs +20 -20
  11. package/scripts/sync-bundled-skill.mjs +244 -244
  12. package/scripts/sync-bundled-skill.test.mjs +152 -152
  13. package/skills/clawclaw/SKILL.md +246 -244
  14. package/skills/clawclaw/references/CHATTERBOX.md +141 -142
  15. package/skills/clawclaw/references/COMMANDS.md +155 -148
  16. package/skills/clawclaw/references/GAME-MECHANICS.md +188 -188
  17. package/skills/clawclaw/references/HUB.md +48 -48
  18. package/skills/clawclaw/references/KNOWLEDGE.md +42 -45
  19. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  20. package/skills/clawclaw/references/STREAM.md +93 -91
  21. package/skills/clawclaw/references/TACTICS.md +65 -65
  22. package/src/assets/clawclaw-ascii-map.txt +40 -40
  23. package/src/cli.ts +110 -110
  24. package/src/commands/_schema.ts +124 -109
  25. package/src/commands/account.ts +209 -209
  26. package/src/commands/config.ts +30 -30
  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 -1042
  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/setup/hermes.test.ts +96 -96
  48. package/src/commands/setup/hermes.ts +76 -76
  49. package/src/commands/setup/index.ts +13 -13
  50. package/src/commands/setup/openclaw.test.ts +114 -114
  51. package/src/commands/setup/openclaw.ts +147 -147
  52. package/src/commands/skill.ts +128 -128
  53. package/src/commands/state.ts +46 -46
  54. package/src/commands/strategy.test.ts +145 -145
  55. package/src/commands/strategy.ts +181 -181
  56. package/src/commands/tts.ts +128 -128
  57. package/src/commands/upgrade.test.ts +82 -82
  58. package/src/commands/upgrade.ts +148 -148
  59. package/src/commands/watch.test.ts +999 -977
  60. package/src/commands/watch.ts +660 -658
  61. package/src/lib/auth.test.ts +74 -74
  62. package/src/lib/auth.ts +186 -186
  63. package/src/lib/command-meta.ts +37 -37
  64. package/src/lib/game-client.ts +403 -391
  65. package/src/lib/game-context.ts +92 -0
  66. package/src/lib/host-config-patcher.test.ts +130 -130
  67. package/src/lib/host-config-patcher.ts +151 -151
  68. package/src/lib/http-keepalive.ts +15 -15
  69. package/src/lib/http-transport.test.ts +42 -42
  70. package/src/lib/http-transport.ts +113 -113
  71. package/src/lib/hub-client.test.ts +56 -56
  72. package/src/lib/hub-client.ts +88 -88
  73. package/src/lib/hub-install.test.ts +98 -98
  74. package/src/lib/hub-install.ts +121 -121
  75. package/src/lib/hub-reminder.ts +56 -56
  76. package/src/lib/hub-unzip.test.ts +69 -69
  77. package/src/lib/hub-unzip.ts +62 -62
  78. package/src/lib/init-command.test.ts +75 -75
  79. package/src/lib/init-command.ts +120 -120
  80. package/src/lib/knowledge-store.test.ts +170 -170
  81. package/src/lib/knowledge-store.ts +369 -369
  82. package/src/lib/load-context.test.ts +52 -52
  83. package/src/lib/load-context.ts +52 -52
  84. package/src/lib/match-state.test.ts +134 -134
  85. package/src/lib/match-state.ts +94 -94
  86. package/src/lib/netease-tts.ts +83 -83
  87. package/src/lib/normalize.ts +42 -42
  88. package/src/lib/persona.test.ts +41 -41
  89. package/src/lib/persona.ts +72 -72
  90. package/src/lib/server-registry.ts +152 -152
  91. package/src/lib/skill-version.test.ts +48 -48
  92. package/src/lib/skill-version.ts +19 -19
  93. package/src/lib/strategy-export.test.ts +232 -232
  94. package/src/lib/strategy-export.ts +242 -242
  95. package/src/lib/tts-keys.ts +7 -7
  96. package/src/lib/tts-speech.test.ts +63 -63
  97. package/src/lib/tts-speech.ts +76 -76
  98. package/src/lib/workspace-argv.test.ts +49 -49
  99. package/src/lib/workspace-argv.ts +44 -44
  100. package/src/perception/player-history-store.test.ts +87 -87
  101. package/src/perception/player-history-store.ts +194 -194
  102. package/src/pipeline/event-format.test.ts +243 -215
  103. package/src/pipeline/event-format.ts +501 -485
  104. package/src/pipeline/event-hints.ts +195 -190
  105. package/src/pipeline/event-store.test.ts +28 -28
  106. package/src/pipeline/event-store.ts +193 -193
  107. package/src/pipeline/pipeline.ts +35 -35
  108. package/src/pipeline/player-projection.test.ts +119 -0
  109. package/src/pipeline/player-projection.ts +380 -0
  110. package/src/runtime/auto-upgrade.test.ts +66 -66
  111. package/src/runtime/auto-upgrade.ts +31 -31
  112. package/src/runtime/event-daemon.test.ts +209 -141
  113. package/src/runtime/event-daemon.ts +519 -457
  114. package/src/runtime/owner-control.ts +150 -150
  115. package/src/runtime/raw-ws-log.test.ts +33 -33
  116. package/src/runtime/raw-ws-log.ts +32 -32
  117. package/src/runtime/runtime-logger.ts +107 -107
  118. package/src/runtime/ws-client.test.ts +125 -104
  119. package/src/runtime/ws-client.ts +287 -272
  120. package/src/sdk/action.ts +166 -166
  121. package/src/sdk/index.ts +110 -110
  122. package/src/sdk/types.ts +161 -161
  123. package/src/strategies/avoid-lone.ts +12 -12
  124. package/src/strategies/avoid-players.knowledge.md +19 -19
  125. package/src/strategies/avoid-players.ts +16 -16
  126. package/src/strategies/corpse-patrol.ts +23 -23
  127. package/src/strategies/crab-sabotage.ts +22 -22
  128. package/src/strategies/custom-module.test.ts +270 -270
  129. package/src/strategies/find-player.ts +17 -17
  130. package/src/strategies/game-utils.test.ts +242 -242
  131. package/src/strategies/game-utils.ts +846 -846
  132. package/src/strategies/goals/anchor-linger.ts +77 -77
  133. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  134. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  135. package/src/strategies/goals/avoid-players-top.ts +121 -121
  136. package/src/strategies/goals/conversation-goal.ts +51 -51
  137. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  138. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  139. package/src/strategies/goals/crab-sabotage-top.ts +197 -197
  140. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  141. package/src/strategies/goals/find-player-top.ts +93 -93
  142. package/src/strategies/goals/flee-players-goal.ts +53 -53
  143. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  144. package/src/strategies/goals/goal-manager.ts +41 -41
  145. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  146. package/src/strategies/goals/goal.ts +28 -28
  147. package/src/strategies/goals/hide-top.ts +197 -197
  148. package/src/strategies/goals/keep-away-goal.ts +221 -221
  149. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  150. package/src/strategies/goals/kill-lone-top.ts +160 -160
  151. package/src/strategies/goals/kill-target-goal.ts +59 -59
  152. package/src/strategies/goals/kill-target-top.ts +109 -109
  153. package/src/strategies/goals/leaf-goal.ts +27 -27
  154. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  155. package/src/strategies/goals/lone-kill-core.ts +82 -82
  156. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  157. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  158. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  159. package/src/strategies/goals/move-room-goal.ts +60 -60
  160. package/src/strategies/goals/normal-shrimp-top.test.ts +80 -80
  161. package/src/strategies/goals/normal-shrimp-top.ts +242 -242
  162. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  163. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  164. package/src/strategies/goals/patrol-top.ts +57 -57
  165. package/src/strategies/goals/report-patrol-top.ts +80 -80
  166. package/src/strategies/goals/safe-task-goal.ts +102 -102
  167. package/src/strategies/goals/social-task-top.ts +161 -161
  168. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  169. package/src/strategies/goals/task-only-top.ts +57 -57
  170. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  171. package/src/strategies/goals/task-report-top.ts +57 -57
  172. package/src/strategies/goals/wander-task-goal.ts +33 -33
  173. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  174. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  175. package/src/strategies/greeting.ts +53 -53
  176. package/src/strategies/hide-spots.ts +59 -59
  177. package/src/strategies/hide.ts +24 -24
  178. package/src/strategies/kill-frenzy.ts +13 -13
  179. package/src/strategies/kill-lone.knowledge.md +17 -17
  180. package/src/strategies/kill-lone.ts +14 -14
  181. package/src/strategies/kill-target.ts +19 -19
  182. package/src/strategies/loader.test.ts +678 -678
  183. package/src/strategies/loader.ts +179 -179
  184. package/src/strategies/lone-kill-task.ts +22 -22
  185. package/src/strategies/meeting-gate.test.ts +59 -59
  186. package/src/strategies/meeting-gate.ts +23 -23
  187. package/src/strategies/move-room.ts +16 -16
  188. package/src/strategies/new-events-backfill.ts +98 -98
  189. package/src/strategies/off-route-points.ts +105 -105
  190. package/src/strategies/paradise-fish.knowledge.md +19 -19
  191. package/src/strategies/paradise-fish.ts +26 -26
  192. package/src/strategies/pathfind/distance-field.ts +150 -150
  193. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  194. package/src/strategies/pathfind/escape-planner.ts +355 -355
  195. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  196. package/src/strategies/patrol.ts +12 -12
  197. package/src/strategies/player-targets.ts +13 -13
  198. package/src/strategies/report-patrol.ts +12 -12
  199. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  200. package/src/strategies/shrimp-memory.ts +26 -26
  201. package/src/strategies/social-task.test.ts +28 -28
  202. package/src/strategies/social-task.ts +50 -50
  203. package/src/strategies/spawn.ts +82 -82
  204. package/src/strategies/speech-module.ts +123 -123
  205. package/src/strategies/strategy-loop.test.ts +15 -0
  206. package/src/strategies/strategy-loop.ts +776 -771
  207. package/src/strategies/task-kill-report.ts +18 -18
  208. package/src/strategies/task-only.ts +12 -12
  209. package/src/strategies/task-report.ts +23 -23
  210. package/src/strategies/types.ts +109 -109
  211. package/src/strategies/warrior-memory.knowledge.md +21 -21
  212. package/src/strategies/warrior-memory.ts +17 -17
@@ -1,1042 +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 }): 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
- process.stdout.write(JSON.stringify(obj) + '\n');
438
- };
439
- const emitLifecycle = (
440
- reason: string,
441
- payload: Record<string, any>,
442
- nextStepOverride?: string,
443
- ): void => {
444
- const event = { ...payload, type: reason };
445
- emit({
446
- exit_reason: [reason],
447
- next_step: nextStepOverride ?? nextStepFor(reason),
448
- events: [event],
449
- summary: currentSummary(),
450
- });
451
- };
452
- const emitOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
453
- if (manualExitEmitted) return;
454
- manualExitEmitted = true;
455
- const eventType = kind === 'leave' ? 'stop' : kind;
456
- emit({
457
- exit_reason: [eventType],
458
- next_step: `Received ${command}. The current ccl game start process is exiting now.`,
459
- events: [{ type: eventType, command }],
460
- summary: { phase: 'stopped' },
461
- });
462
- };
463
- const requestOwnerExit = (kind: 'stop' | 'quit' | 'leave', command: string): void => {
464
- ownerExitRequested = true;
465
- emitOwnerExit(kind, command);
466
- streamAbortController?.abort();
467
- eventRuntime?.stop('manual');
468
- stopOwnedStrategy();
469
- };
470
- const emitMatchEvent = (evt: Record<string, any>): void => {
471
- try {
472
- const store = EventStore.forActiveAccount();
473
- store.append({ ts: new Date().toISOString(), ...evt });
474
- } catch {}
475
- };
476
- const ensureEventRuntime = async (): Promise<void> => {
477
- if (eventRuntime) return;
478
- eventRuntime = new EventRuntime({
479
- authStore,
480
- getAutomation: currentAutomationSummary,
481
- onStop: (stop) => {
482
- if (stop.reason === 'game_over') return;
483
- streamAbortController?.abort();
484
- },
485
- });
486
- await eventRuntime.start();
487
- };
488
- const streamGame = async (): Promise<void> => {
489
- const sessionPath = EventStore.latestSessionPath();
490
- const ctrl = new AbortController();
491
- streamAbortController = ctrl;
492
- const onSignal = (): void => {
493
- ctrl.abort();
494
- eventRuntime?.stop('SIGTERM');
495
- };
496
- process.on('SIGINT', onSignal);
497
- process.on('SIGTERM', onSignal);
498
- try {
499
- await runStreaming({
500
- feedPath,
501
- sessionPath,
502
- getSessionPath: () => EventStore.latestSessionPath(),
503
- stdout: (s) => process.stdout.write(s),
504
- signal: ctrl.signal,
505
- skipFeedWait: true,
506
- readSummary: currentSummary,
507
- skipBacklogTypes: ['match_waiting', 'match_timeout'],
508
- emitGameStart: true,
509
- hubReminder: hubReminder(readCachedGamesPlayed()),
510
- });
511
- } catch (err: any) {
512
- process.stdout.write(buildErrorLine(err));
513
- process.exitCode = 1;
514
- } finally {
515
- process.off('SIGINT', onSignal);
516
- process.off('SIGTERM', onSignal);
517
- streamAbortController = null;
518
- }
519
- };
520
- const handleAllocated = async (queue: any, preserveStrategy: boolean): Promise<void> => {
521
- const finalState = readMatchState(stateDir);
522
- const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
523
- endMatch(stateDir);
524
- const context = await fetchInitialGameContext(client);
525
- const identity = gameStrategyIdentity(context.state, context.role);
526
- // Supplement game_id from queue response when /game/current doesn't carry it yet.
527
- const queueGameId = nonEmptyString(queue?.game_id) ?? nonEmptyString(queue?.data?.game_id);
528
- if (!identity.gameId && queueGameId) {
529
- identity.gameId = queueGameId;
530
- }
531
- const role = unwrapData(context.role);
532
- ownerFeed = {
533
- ...ownerFeed,
534
- ts: new Date().toISOString(),
535
- phase: 'allocated',
536
- you: {
537
- ...ownerFeed.you,
538
- role: nonEmptyString(role?.role) ?? identity.role,
539
- role_display: nonEmptyString(role?.role_display_name) ?? nonEmptyString(role?.role_display),
540
- faction: nonEmptyString(role?.faction),
541
- alive: identity.alive,
542
- },
543
- game: {
544
- ...ownerFeed.game,
545
- game_id: identity.gameId,
546
- },
547
- };
548
- let strategyInfo: { strategy: string; pid: number | undefined } | null = null;
549
- if (opts.watch && identity.alive !== false) {
550
- stopOwnedStrategy();
551
- const started = autoStartStrategy(context.role, context.state, identity.gameId);
552
- if (started) {
553
- strategyChild = started.child;
554
- currentStrategy = started.strategy;
555
- strategyInfo = { strategy: started.strategy, pid: started.pid };
556
- }
557
- }
558
- const allocationPayload = {
559
- queue,
560
- waited_secs: waitedSecs,
561
- game_id: identity.gameId || undefined,
562
- ...context,
563
- ...(strategyInfo ? { default_strategy: strategyInfo } : {}),
564
- };
565
- if (!opts.watch) {
566
- emitLifecycle('allocated', allocationPayload,
567
- 'Match secured. Read role/map/tasks from `events[0]`, then launch `ccl game start` without --no-watch to attach the owner stream and automation.');
568
- return;
569
- }
570
- await ensureEventRuntime();
571
- await streamGame();
572
- };
573
- const pollQueue = async (preserveStrategy: boolean): Promise<void> => {
574
- const intervalMs = 2000;
575
- const QUEUE_POLL_HEARTBEAT_MS = 60_000;
576
- const MAX_CONSECUTIVE_FAILURES = 3;
577
- let lastHeartbeat = Date.now();
578
- let consecutiveFailures = 0;
579
-
580
- while (!ownerExitRequested) {
581
- let queue: any;
582
- try {
583
- queue = await client.getQueueStatus('clawclaw');
584
- consecutiveFailures = 0;
585
- } catch (err: any) {
586
- consecutiveFailures++;
587
- const msg = err?.message ?? String(err);
588
- if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
589
- emitLifecycle('error', {
590
- error: msg,
591
- consecutive_failures: consecutiveFailures,
592
- message: `Queue status polling failed ${consecutiveFailures} times consecutively.`,
593
- }, 'Queue polling has failed repeatedly. Check network, then launch a fresh `ccl game start` to retry.');
594
- return;
595
- }
596
- emitLifecycle('poll_error', {
597
- error: msg,
598
- consecutive_failures: consecutiveFailures,
599
- message: `Queue poll failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}). Retrying...`,
600
- }, 'Temporary polling failure. The stream will keep retrying - stay attached.');
601
- await sleep(intervalMs);
602
- continue;
603
- }
604
-
605
- if (queueStatus(queue) === 'allocated') {
606
- await handleAllocated(queue, preserveStrategy);
607
- return;
608
- }
609
- if (queueStatus(queue) === 'not_in_queue') {
610
- endMatch(stateDir);
611
- emitLifecycle('not_in_queue', { queue, message: 'Left or dropped from queue.' },
612
- 'No longer in matchmaking queue. The stream will exit; launch a fresh `ccl game start` to retry if the user wants to continue.');
613
- return;
614
- }
615
-
616
- const cur = readMatchState(stateDir);
617
- if (cur && shouldEmitWaiting(cur)) {
618
- const waitedSecs = getWaitedSecs(cur);
619
- emitMatchEvent({ type: 'match_waiting', waited_secs: waitedSecs });
620
- emitLifecycle('match_waiting', { waited_secs: waitedSecs });
621
- markWaitingEmitted(stateDir);
622
- lastHeartbeat = Date.now();
623
- }
624
- if (cur && hasMatchTimedOut(cur)) {
625
- const waitedSecs = getWaitedSecs(cur);
626
- emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
627
- emitLifecycle('match_timeout', {
628
- waited_secs: waitedSecs,
629
- queue,
630
- message: `No match after ${waitedSecs}s.`,
631
- });
632
- return;
633
- }
634
-
635
- if (Date.now() - lastHeartbeat >= QUEUE_POLL_HEARTBEAT_MS) {
636
- lastHeartbeat = Date.now();
637
- const waitedSecs = cur ? getWaitedSecs(cur) : 0;
638
- emitLifecycle('heartbeat', { waited_secs: waitedSecs },
639
- 'Stream is alive; still waiting for match allocation. Keep chatting with the user.');
640
- }
641
-
642
- await sleep(intervalMs);
643
- }
644
- };
645
- const resumeQueue = async (source: string): Promise<void> => {
646
- ensureEventSession(source);
647
- if (!readMatchState(stateDir)) startMatch(stateDir);
648
- await ensureEventRuntime();
649
- await pollQueue(true);
650
- };
651
- const recoverAlreadyInGame = async (): Promise<boolean> => {
652
- let queue: any;
653
- try {
654
- queue = await client.getQueueStatus('clawclaw');
655
- } catch {
656
- return false;
657
- }
658
- const status = queueStatus(queue);
659
- if (status === 'allocated') {
660
- ensureEventSession('game_start_already_in_game');
661
- await ensureEventRuntime();
662
- await handleAllocated(queue, true);
663
- return true;
664
- }
665
- if (status === 'queued' || status === 'already_in_queue') {
666
- await resumeQueue('game_start_already_in_game_queue');
667
- return true;
668
- }
669
- return false;
670
- };
671
-
672
- const runningGameStartPid = getRunningGameStartPid(stateDir);
673
- if (runningGameStartPid) {
674
- if (opts.force) {
675
- terminateProcessTree(runningGameStartPid, 'SIGKILL');
676
- try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
677
- try { unlinkSync(feedPath); } catch {}
678
- } else {
679
- emitLifecycle('already_running', { pid: runningGameStartPid },
680
- `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}`);
681
- return;
682
- }
683
- }
684
- let initialQueue: any;
685
- try {
686
- initialQueue = await client.getQueueStatus('clawclaw');
687
- } catch {}
688
- const plan = planGameStartAction({
689
- gameStartPid: null,
690
- hasMatchState: readMatchState(stateDir) !== null,
691
- queueStatus: queueStatus(initialQueue),
692
- });
693
-
694
- ownerFeed = {
695
- ...ownerFeed,
696
- ts: new Date().toISOString(),
697
- phase: plan.kind === 'resume_allocated' ? 'allocated' : 'matching',
698
- };
699
- ownerControl = await startOwnerControlServer(stateDir, async (request) => {
700
- if (request.type === 'snapshot') {
701
- return { ok: true, type: 'snapshot', summary: currentSummary() };
702
- }
703
- if (request.type === 'stop') {
704
- requestOwnerExit('stop', 'ccl game stop');
705
- return { ok: true, type: 'stop' };
706
- }
707
- if (request.type === 'quit') {
708
- requestOwnerExit('quit', 'ccl game quit');
709
- return { ok: true, type: 'quit' };
710
- }
711
- if (request.type === 'leave') {
712
- requestOwnerExit('leave', 'ccl game leave');
713
- return { ok: true, type: 'leave' };
714
- }
715
- if (request.type === 'stop_strategy') {
716
- stopOwnedStrategy();
717
- return { ok: true, type: 'stop_strategy' };
718
- }
719
- if (request.type === 'switch_strategy') {
720
- if (!request.strategy) return { ok: false, error: 'missing_strategy' };
721
- stopOwnedStrategy();
722
- const child = spawnStrategyLoop(request.strategy, request.args, {
723
- source: 'manual',
724
- detached: false,
725
- writeRuntimeFiles: false,
726
- });
727
- strategyChild = child;
728
- currentStrategy = request.strategy;
729
- eventRuntime?.refreshFeed();
730
- return { ok: true, type: 'switch_strategy', strategy: request.strategy, pid: child.pid };
731
- }
732
- return { ok: false, error: 'unsupported_owner_control_request' };
733
- });
734
- writeGameStartRuntime(stateDir, plan.kind, undefined, {
735
- control: ownerControl.control,
736
- token: ownerControl.token,
737
- });
738
- heartbeatTimer = startGameStartHeartbeat(stateDir, plan.kind);
739
- try {
740
- if (plan.kind === 'resume_queue') {
741
- await resumeQueue('game_start_resume_queue');
742
- return;
743
- }
744
-
745
- if (plan.kind === 'resume_allocated') {
746
- ensureEventSession('game_start_resume_allocated');
747
- await ensureEventRuntime();
748
- await handleAllocated(initialQueue, true);
749
- return;
750
- }
751
-
752
- let joinResult: any;
753
- try {
754
- joinResult = await client.joinQueue('clawclaw');
755
- } catch (err) {
756
- if (isAlreadyInGameError(err) && await recoverAlreadyInGame()) return;
757
- throw err;
758
- }
759
- const joinedStatus = queueStatus(joinResult);
760
- if (joinedStatus === 'already_in_queue') {
761
- await resumeQueue('game_start_already_in_queue');
762
- return;
763
- }
764
- if (joinedStatus && joinedStatus !== 'queued') {
765
- emitLifecycle('error', { queue: joinResult, message: `Unexpected queue status: ${joinedStatus}.` },
766
- 'Queue join did not enter the clawclaw queue. Check queue status before launching another `ccl game start`.');
767
- return;
768
- }
769
-
770
- stopOwnedStrategy();
771
-
772
- const events = EventStore.createSessionForActiveAccount();
773
- events.append({ type: 'session_started', source: 'game_start' });
774
- emitLifecycle('joined', joinResult,
775
- 'Match join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Game runtime is attached.');
776
- startMatch(stateDir);
777
- await ensureEventRuntime();
778
- await pollQueue(false);
779
- } finally {
780
- if (heartbeatTimer) clearInterval(heartbeatTimer);
781
- process.off('SIGINT', onOwnerSignal);
782
- process.off('SIGTERM', onOwnerSignal);
783
- eventRuntime?.stop('manual');
784
- stopOwnedStrategy();
785
- if (ownerControl) await ownerControl.close();
786
- cleanupGameStartRuntime(stateDir, { removeFeed: true, controlPath: ownerControl?.control.path });
787
- }
788
- }
789
-
790
- export function createGameCommand(): Command {
791
- const game = new Command('game');
792
- game.description('Game matchmaking & session');
793
-
794
- game
795
- .command('join')
796
- .alias('j')
797
- .description('Join matchmaking queue')
798
- .action(async () => {
799
- const authStore = new AuthStore();
800
- const profile = authStore.getActive();
801
- if (!profile) throw new Error('Not logged in.');
802
- stopStrategyIfRunning();
803
-
804
- const client = GameClient.fromAuth();
805
- const result = await client.joinQueue('clawclaw');
806
- const events = EventStore.createSessionForActiveAccount();
807
- events.append({ type: 'session_started', source: 'game_join' });
808
- console.log(JSON.stringify(result, null, 2));
809
- const stateDir = getProfileStateDir(profile);
810
- // Reset match-state: a fresh queue session starts here so `ccl game queue`
811
- // can compute `waited_secs` from a known anchor and emit the
812
- // match_waiting / match_timeout synthetic events.
813
- startMatch(stateDir);
814
- });
815
-
816
- game
817
- .command('start')
818
- .alias('s')
819
- .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.')
820
- .option('--no-watch', 'exit after allocation instead of streaming events through game_over')
821
- .option('--force', 'force restart: kill any lingering game-start stream process and start fresh')
822
- .action(runGameStart);
823
-
824
- game
825
- .command('queue')
826
- .alias('q')
827
- .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).')
828
- .option('-w, --wait', '(no-op, kept for backwards compatibility — wait mode is now the default)')
829
- .option('--interval <secs>', 'Polling interval', '2')
830
- .option('--timeout <secs>', 'Max seconds to wait, 0 means forever', String(DEFAULT_QUEUE_WAIT_TIMEOUT_SECS))
831
- .action(async (opts) => {
832
- const authStore = new AuthStore();
833
- const profile = authStore.getActive();
834
- if (!profile) throw new Error('Not logged in.');
835
- const stateDir = getProfileStateDir(profile);
836
- const client = GameClient.fromAuth();
837
-
838
- const intervalMs = positiveNumber(opts.interval, 2) * 1000;
839
- const timeoutSecs = Number(opts.timeout);
840
- const deadline = Number.isFinite(timeoutSecs) && timeoutSecs > 0
841
- ? Date.now() + timeoutSecs * 1000
842
- : 0;
843
-
844
- // Synthetic matchmaking events feed the game start stream so the agent can
845
- // observe match progress through the same channel as in-game events.
846
- // Concurrency note: the agent typically keeps a 30s `ccl game queue`
847
- // background chain running, so two queue invocations may observe the
848
- // same `allocated` server state. That is
849
- // intentionally fine stream dedups via `eventKey` (type+tick+actor),
850
- // so consumers only see one notification.
851
- const emitMatchEvent = (evt: Record<string, any>): void => {
852
- try {
853
- const store = EventStore.forActiveAccount();
854
- store.append({ ts: new Date().toISOString(), ...evt });
855
- } catch {
856
- // No active session (user ran queue without join) — skip silently;
857
- // queue's own JSON return still informs the caller.
858
- }
859
- };
860
-
861
- // On entry: emit match_waiting if state exists and heartbeat is due.
862
- const initialState = readMatchState(stateDir);
863
- if (initialState && shouldEmitWaiting(initialState)) {
864
- const waitedSecs = getWaitedSecs(initialState);
865
- emitMatchEvent({ type: 'match_waiting', waited_secs: waitedSecs });
866
- markWaitingEmitted(stateDir);
867
- }
868
-
869
- while (true) {
870
- const queue = await client.getQueueStatus('clawclaw');
871
- if (queueStatus(queue) === 'allocated') {
872
- const finalState = readMatchState(stateDir);
873
- const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
874
- endMatch(stateDir);
875
- const context = await fetchInitialGameContext(client);
876
- console.log(JSON.stringify({
877
- status: 'active_game',
878
- queue,
879
- waited_secs: waitedSecs,
880
- ...context,
881
- 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.',
882
- }, null, 2));
883
- return;
884
- }
885
- if (queueStatus(queue) === 'not_in_queue') {
886
- // Queue session is gone (user manually left or server expired it):
887
- // clean the match-state so next `game join` starts fresh.
888
- endMatch(stateDir);
889
- console.log(JSON.stringify({
890
- status: 'not_in_queue',
891
- queue,
892
- message: 'You are not in the matchmaking queue. Did you forget to run `ccl game join` first?',
893
- next_step: 'Run `ccl game join` to re-enter the queue, then launch the next `ccl game queue` background task.',
894
- }, null, 2));
895
- return;
896
- }
897
- if (deadline > 0 && Date.now() >= deadline) {
898
- const cur = readMatchState(stateDir);
899
- const waitedSecs = cur ? getWaitedSecs(cur) : timeoutSecs;
900
- // Total-wait timeout (>=10 min by default) gets its own synthetic
901
- // event so the agent can prompt the user to keep waiting / leave /
902
- // retry later. Single 30s queue-attempt timeouts do NOT emit anything
903
- // — they are an internal polling boundary, not a user-visible event.
904
- if (cur && hasMatchTimedOut(cur)) {
905
- emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
906
- }
907
- console.log(JSON.stringify({
908
- status: 'timeout',
909
- waited_secs: waitedSecs,
910
- queue,
911
- message: `No match after ${timeoutSecs} seconds (total wait ${waitedSecs}s).`,
912
- 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.',
913
- }, null, 2));
914
- return;
915
- }
916
- await sleep(intervalMs);
917
- }
918
- });
919
-
920
- game
921
- .command('leave')
922
- .alias('l')
923
- .description('Leave queue')
924
- .action(async () => {
925
- const authStore = new AuthStore();
926
- const profile = authStore.getActive();
927
- if (profile) {
928
- const stateDir = getProfileStateDir(profile);
929
- endMatch(stateDir);
930
- await stopOwnerWithCommand(stateDir, 'leave');
931
- }
932
- stopStrategyIfRunning();
933
- const client = GameClient.fromAuth();
934
- const result = await client.leaveQueue('clawclaw');
935
- console.log(JSON.stringify(result, null, 2));
936
- });
937
-
938
-
939
- game
940
- .command('stop')
941
- .alias('x')
942
- .description('Stop local game runtime')
943
- .action(async () => {
944
- const authStore = new AuthStore();
945
- const profile = authStore.getActive();
946
- if (!profile) throw new Error('Not logged in.');
947
- const stateDir = getProfileStateDir(profile);
948
- const owner = await stopOwnerIfRunning(stateDir);
949
- stopStrategyIfRunning();
950
- if (!owner.stopped) {
951
- console.log(JSON.stringify({ message: 'No game runtime running.' }, null, 2));
952
- return;
953
- }
954
- console.log(JSON.stringify({
955
- message: 'Game runtime stopped.',
956
- ...(owner.pid ? { owner_pid: owner.pid } : {}),
957
- }, null, 2));
958
- });
959
-
960
- game
961
- .command('quit')
962
- .description('Leave active game and stop local runtime')
963
- .action(async () => {
964
- const authStore = new AuthStore();
965
- const profile = authStore.getActive();
966
- if (!profile) throw new Error('Not logged in.');
967
- const client = GameClient.fromAuth();
968
- let result: any;
969
- try {
970
- result = await client.leaveGame();
971
- } catch (err: any) {
972
- result = { error: err?.message ?? String(err) };
973
- }
974
- if (isLeaveGameSuccess(result)) clearCachedGameServerUrl(authStore, profile.agentName);
975
- const stateDir = getProfileStateDir(profile);
976
- endMatch(stateDir);
977
- const owner = await stopOwnerWithCommand(stateDir, 'quit');
978
- stopStrategyIfRunning();
979
- const reminder = hubReminder(readCachedGamesPlayed());
980
- const out: Record<string, any> = (result && typeof result === 'object' && !Array.isArray(result))
981
- ? { ...result }
982
- : { result };
983
- if (reminder) {
984
- out.hub_reminder = reminder;
985
- out.next_step = `Left the game. ${reminder}`;
986
- }
987
- if (owner.pid) out.owner_pid = owner.pid;
988
- console.log(JSON.stringify(out, null, 2));
989
- });
990
-
991
- game
992
- .command('map')
993
- .alias('m')
994
- .description('Show game map')
995
- .option('--ascii', 'Include packaged ASCII topology map')
996
- .action(async (opts) => {
997
- const client = GameClient.fromAuth();
998
- await client.discoverGameServer();
999
- const result = await client.getMap();
1000
- console.log(JSON.stringify(summarizeGameMap(result, { ascii: opts.ascii === true }), null, 2));
1001
- });
1002
-
1003
- game
1004
- .command('tasks')
1005
- .alias('t')
1006
- .description('Show my tasks')
1007
- .action(async () => {
1008
- const client = GameClient.fromAuth();
1009
- await client.discoverGameServer();
1010
- const result = await client.getMap();
1011
- console.log(JSON.stringify(result?.your_tasks ?? [], null, 2));
1012
- });
1013
-
1014
- game
1015
- .command('role')
1016
- .alias('r')
1017
- .description('Show my role info')
1018
- .action(async () => {
1019
- const client = GameClient.fromAuth();
1020
- const result = await client.getRoleInfo();
1021
- console.log(JSON.stringify(result, null, 2));
1022
- });
1023
-
1024
- game
1025
- .command('watch')
1026
- .alias('w')
1027
- .description('Get spectating URL')
1028
- .action(() => {
1029
- const authStore = new AuthStore();
1030
- const profile = authStore.getActive();
1031
- if (!profile) throw new Error('Not logged in.');
1032
- const origin = new URL(profile.serverUrl).origin.replace(/^http:\/\//, 'https://');
1033
- const url = `${origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`;
1034
- console.log(JSON.stringify({ url, message: 'Open in browser to spectate.' }, null, 2));
1035
- });
1036
-
1037
- // ── Adapter metadata: queue blocks up to --timeout secs (default 30); cap L2 spawn at 60s ──
1038
- setMeta(game.commands.find((c) => c.name() === 'queue')!, { longRunning: true, timeoutMs: 60_000 });
1039
- setMeta(game.commands.find((c) => c.name() === 'start')!, { longRunning: true, timeoutMs: 1_800_000 });
1040
-
1041
- return game;
1042
- }
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
+ }