@myclaw163/clawclaw-cli 0.6.83 → 0.6.86

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 (220) hide show
  1. package/README.md +385 -385
  2. package/bin/clawclaw-cli.mjs +3 -3
  3. package/package.json +48 -48
  4. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -0
  5. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -0
  6. package/personas//346/227/240/344/272/272/350/256/276.md +1 -3
  7. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -0
  8. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -0
  9. package/scripts/check-skill-command-surface.mjs +118 -118
  10. package/scripts/enable_ccl_permissions.cjs +147 -0
  11. package/scripts/enable_ccl_permissions.test.mjs +132 -0
  12. package/scripts/enable_monitor.cjs +677 -677
  13. package/scripts/enable_monitor.test.mjs +201 -201
  14. package/scripts/find-hide-spots.py +157 -157
  15. package/scripts/postinstall.mjs +20 -20
  16. package/scripts/sync-bundled-skill.mjs +254 -254
  17. package/scripts/sync-bundled-skill.test.mjs +152 -152
  18. package/skills/clawclaw/SKILL.md +259 -258
  19. package/skills/clawclaw/references/CHATTERBOX.md +142 -141
  20. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  21. package/skills/clawclaw/references/COMMANDS.md +165 -158
  22. package/skills/clawclaw/references/GAME-MECHANICS.md +190 -188
  23. package/skills/clawclaw/references/HUB.md +48 -48
  24. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  25. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  26. package/skills/clawclaw/references/STREAM.md +74 -84
  27. package/skills/clawclaw/references/TACTICS.md +65 -65
  28. package/src/assets/clawclaw-ascii-map.txt +40 -40
  29. package/src/cli.ts +113 -113
  30. package/src/commands/_schema.ts +124 -124
  31. package/src/commands/account.test.ts +149 -0
  32. package/src/commands/account.ts +287 -266
  33. package/src/commands/competition.ts +42 -42
  34. package/src/commands/data.test.ts +33 -33
  35. package/src/commands/data.ts +22 -22
  36. package/src/commands/do.test.ts +40 -40
  37. package/src/commands/do.ts +93 -93
  38. package/src/commands/events.test.ts +124 -100
  39. package/src/commands/events.ts +262 -250
  40. package/src/commands/game-map.test.ts +28 -28
  41. package/src/commands/game-start-plan.test.ts +94 -84
  42. package/src/commands/game.ts +1243 -1237
  43. package/src/commands/history-player.test.ts +102 -102
  44. package/src/commands/history.ts +573 -573
  45. package/src/commands/hub.test.ts +113 -113
  46. package/src/commands/hub.ts +244 -244
  47. package/src/commands/knowledge.test.ts +13 -13
  48. package/src/commands/knowledge.ts +139 -139
  49. package/src/commands/load.test.ts +65 -65
  50. package/src/commands/load.ts +22 -22
  51. package/src/commands/meeting-history.test.ts +106 -106
  52. package/src/commands/memory.ts +40 -40
  53. package/src/commands/peek.ts +45 -45
  54. package/src/commands/persona.ts +62 -62
  55. package/src/commands/setup/codex.ts +266 -266
  56. package/src/commands/skill.ts +128 -128
  57. package/src/commands/state.ts +46 -46
  58. package/src/commands/strategy.test.ts +153 -153
  59. package/src/commands/strategy.ts +183 -183
  60. package/src/commands/upgrade.test.ts +82 -82
  61. package/src/commands/upgrade.ts +148 -148
  62. package/src/commands/watch.test.ts +1041 -999
  63. package/src/commands/watch.ts +664 -660
  64. package/src/lib/account-guidance.test.ts +32 -32
  65. package/src/lib/account-guidance.ts +62 -62
  66. package/src/lib/auth.test.ts +116 -72
  67. package/src/lib/auth.ts +189 -153
  68. package/src/lib/command-meta.ts +37 -37
  69. package/src/lib/competition.ts +79 -79
  70. package/src/lib/game-client.test.ts +44 -44
  71. package/src/lib/game-client.ts +375 -375
  72. package/src/lib/game-context.ts +92 -92
  73. package/src/lib/http-keepalive.ts +15 -15
  74. package/src/lib/http-transport.test.ts +61 -61
  75. package/src/lib/http-transport.ts +118 -118
  76. package/src/lib/hub-client.test.ts +57 -57
  77. package/src/lib/hub-client.ts +88 -88
  78. package/src/lib/hub-install.test.ts +136 -136
  79. package/src/lib/hub-install.ts +198 -198
  80. package/src/lib/hub-reminder.ts +78 -78
  81. package/src/lib/hub-unzip.test.ts +69 -69
  82. package/src/lib/hub-unzip.ts +62 -62
  83. package/src/lib/init-command.test.ts +75 -75
  84. package/src/lib/init-command.ts +130 -130
  85. package/src/lib/knowledge-store.test.ts +170 -170
  86. package/src/lib/knowledge-store.ts +369 -369
  87. package/src/lib/load-context.test.ts +62 -52
  88. package/src/lib/load-context.ts +49 -54
  89. package/src/lib/match-state.test.ts +134 -134
  90. package/src/lib/match-state.ts +94 -94
  91. package/src/lib/normalize.ts +42 -42
  92. package/src/lib/persona.test.ts +84 -84
  93. package/src/lib/persona.ts +120 -120
  94. package/src/lib/server-registry.ts +152 -152
  95. package/src/lib/skill-version.test.ts +48 -48
  96. package/src/lib/skill-version.ts +19 -19
  97. package/src/lib/strategy-export.test.ts +240 -240
  98. package/src/lib/strategy-export.ts +247 -247
  99. package/src/lib/user-data.test.ts +97 -97
  100. package/src/lib/user-data.ts +374 -374
  101. package/src/lib/workspace-argv.test.ts +49 -49
  102. package/src/lib/workspace-argv.ts +44 -44
  103. package/src/perception/player-history-store.test.ts +87 -87
  104. package/src/perception/player-history-store.ts +194 -194
  105. package/src/pipeline/event-format.test.ts +247 -243
  106. package/src/pipeline/event-format.ts +507 -501
  107. package/src/pipeline/event-hints.ts +195 -195
  108. package/src/pipeline/event-store.test.ts +28 -28
  109. package/src/pipeline/event-store.ts +193 -193
  110. package/src/pipeline/pipeline.ts +35 -35
  111. package/src/pipeline/player-projection.test.ts +168 -168
  112. package/src/pipeline/player-projection.ts +370 -370
  113. package/src/runtime/auto-upgrade.test.ts +66 -66
  114. package/src/runtime/auto-upgrade.ts +31 -31
  115. package/src/runtime/event-daemon.test.ts +225 -209
  116. package/src/runtime/event-daemon.ts +527 -519
  117. package/src/runtime/owner-control.ts +150 -150
  118. package/src/runtime/raw-ws-log.test.ts +33 -33
  119. package/src/runtime/raw-ws-log.ts +32 -32
  120. package/src/runtime/runtime-logger.ts +107 -107
  121. package/src/runtime/ws-client.test.ts +169 -169
  122. package/src/runtime/ws-client.ts +280 -280
  123. package/src/sdk/action.ts +153 -153
  124. package/src/sdk/index.ts +107 -107
  125. package/src/sdk/types.ts +161 -161
  126. package/src/strategies/avoid-lone.ts +12 -12
  127. package/src/strategies/avoid-players.knowledge.md +19 -19
  128. package/src/strategies/avoid-players.ts +16 -16
  129. package/src/strategies/corpse-patrol.ts +19 -19
  130. package/src/strategies/crab-sabotage.ts +22 -22
  131. package/src/strategies/custom-module.test.ts +270 -270
  132. package/src/strategies/find-player.ts +17 -17
  133. package/src/strategies/game-utils.test.ts +242 -242
  134. package/src/strategies/game-utils.ts +846 -846
  135. package/src/strategies/goals/anchor-linger.ts +77 -77
  136. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  137. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  138. package/src/strategies/goals/avoid-players-top.ts +121 -121
  139. package/src/strategies/goals/conversation-goal.ts +51 -51
  140. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  141. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  142. package/src/strategies/goals/crab-sabotage-top.ts +197 -197
  143. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  144. package/src/strategies/goals/find-player-top.ts +93 -93
  145. package/src/strategies/goals/flee-players-goal.ts +53 -53
  146. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  147. package/src/strategies/goals/goal-manager.ts +41 -41
  148. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  149. package/src/strategies/goals/goal.ts +28 -28
  150. package/src/strategies/goals/hide-top.ts +197 -197
  151. package/src/strategies/goals/keep-away-goal.ts +221 -221
  152. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  153. package/src/strategies/goals/kill-lone-top.ts +160 -160
  154. package/src/strategies/goals/kill-target-goal.ts +59 -59
  155. package/src/strategies/goals/kill-target-top.ts +109 -109
  156. package/src/strategies/goals/leaf-goal.ts +27 -27
  157. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  158. package/src/strategies/goals/lone-kill-core.ts +82 -82
  159. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  160. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  161. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  162. package/src/strategies/goals/move-room-goal.ts +60 -60
  163. package/src/strategies/goals/normal-shrimp-top.test.ts +80 -80
  164. package/src/strategies/goals/normal-shrimp-top.ts +242 -242
  165. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  166. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  167. package/src/strategies/goals/patrol-top.ts +57 -57
  168. package/src/strategies/goals/report-patrol-top.ts +80 -80
  169. package/src/strategies/goals/safe-task-goal.ts +102 -102
  170. package/src/strategies/goals/social-task-top.ts +161 -161
  171. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  172. package/src/strategies/goals/task-only-top.ts +57 -57
  173. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  174. package/src/strategies/goals/task-report-top.ts +57 -57
  175. package/src/strategies/goals/wander-task-goal.ts +33 -33
  176. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  177. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  178. package/src/strategies/greeting.ts +53 -53
  179. package/src/strategies/hide-spots.ts +59 -59
  180. package/src/strategies/hide.ts +24 -24
  181. package/src/strategies/kill-frenzy.ts +13 -13
  182. package/src/strategies/kill-lone.knowledge.md +17 -17
  183. package/src/strategies/kill-lone.ts +14 -14
  184. package/src/strategies/kill-target.ts +19 -19
  185. package/src/strategies/loader.test.ts +678 -678
  186. package/src/strategies/loader.ts +181 -181
  187. package/src/strategies/lone-kill-task.ts +22 -22
  188. package/src/strategies/meeting-gate.test.ts +59 -59
  189. package/src/strategies/meeting-gate.ts +23 -23
  190. package/src/strategies/move-room.ts +16 -16
  191. package/src/strategies/new-events-backfill.ts +98 -98
  192. package/src/strategies/off-route-points.ts +105 -105
  193. package/src/strategies/paradise-fish.knowledge.md +19 -19
  194. package/src/strategies/paradise-fish.ts +22 -22
  195. package/src/strategies/pathfind/distance-field.ts +150 -150
  196. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  197. package/src/strategies/pathfind/escape-planner.ts +355 -355
  198. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  199. package/src/strategies/patrol.ts +12 -12
  200. package/src/strategies/player-targets.ts +13 -13
  201. package/src/strategies/report-patrol.ts +12 -12
  202. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  203. package/src/strategies/shrimp-memory.ts +22 -22
  204. package/src/strategies/social-task.test.ts +28 -28
  205. package/src/strategies/social-task.ts +50 -50
  206. package/src/strategies/spawn.ts +82 -82
  207. package/src/strategies/speech-module.ts +123 -123
  208. package/src/strategies/strategy-loop.test.ts +15 -15
  209. package/src/strategies/strategy-loop.ts +716 -716
  210. package/src/strategies/task-kill-report.ts +18 -18
  211. package/src/strategies/task-only.ts +12 -12
  212. package/src/strategies/task-report.ts +19 -19
  213. package/src/strategies/types.ts +107 -107
  214. package/src/strategies/warrior-memory.knowledge.md +21 -21
  215. package/src/strategies/warrior-memory.ts +17 -17
  216. package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +0 -23
  217. package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +0 -22
  218. package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +0 -22
  219. package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +0 -22
  220. package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +0 -23
@@ -1,660 +1,664 @@
1
- import { Command } from 'commander';
2
- import { existsSync, readFileSync, openSync, readSync, closeSync, statSync } from 'fs';
3
- import { join } from 'path';
4
- import { AuthStore } from '../lib/auth.js';
5
- import { getProfileStateDir } from '../lib/init-command.js';
6
- import { setMeta } from '../lib/command-meta.js';
7
- import { EventStore, extractNewEvents, isLocalControlEvent } from '../pipeline/event-store.js';
8
- import { compactEventForEvents, formatEventMessage, shortStateText } from '../pipeline/event-format.js';
9
- import { PlayerHistoryStore } from '../perception/player-history-store.js';
10
- import { DEFAULT_MATCH_TIMEOUT_MS } from '../lib/match-state.js';
11
- import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
12
- import { sendOwnerControlRequest } from '../runtime/owner-control.js';
13
-
14
- export const POLL_INTERVAL_MS = 220;
15
- const HEARTBEAT_INTERVAL_MS = 60_000;
16
- const RUNTIME_WAIT_MS = 30_000;
17
-
18
- export class WatchNotReadyError extends Error {
19
- constructor(message: string) {
20
- super(message);
21
- this.name = 'WatchNotReadyError';
22
- }
23
- }
24
-
25
- /** Legacy helper for tests and explicit file-backed attaches. Owner paths use control socket snapshots. */
26
- export async function waitForFeed(
27
- feedPath: string,
28
- opts?: { signal?: AbortSignal; timeoutMs?: number; pollMs?: number },
29
- ): Promise<boolean> {
30
- const timeoutMs = opts?.timeoutMs ?? RUNTIME_WAIT_MS;
31
- const pollMs = opts?.pollMs ?? POLL_INTERVAL_MS;
32
- const deadline = Date.now() + timeoutMs;
33
- while (Date.now() < deadline) {
34
- if (existsSync(feedPath)) return true;
35
- if (opts?.signal?.aborted) return false;
36
- await new Promise((r) => setTimeout(r, pollMs));
37
- }
38
- return existsSync(feedPath);
39
- }
40
-
41
- const DEFAULT_MONITOR_EVENT_PRIORITY = 50;
42
-
43
- export interface MonitorEventConfig {
44
- priority: number;
45
- }
46
-
47
- export const MONITOR_EVENT_CONFIG: Record<string, MonitorEventConfig> = {
48
- kill: { priority: 50 },
49
- killed: { priority: 99 },
50
- murder_witnessed: { priority: 50 },
51
- warrior_shrimp_self_destruct: { priority: 50 },
52
-
53
- task_completed: { priority: 50 },
54
- task_sabotaged: { priority: 50 },
55
-
56
- corpse_spotted: { priority: 50 },
57
- octopus_time_start: { priority: 50 },
58
-
59
- emergency_started: { priority: 50 },
60
- emergency_resolved: { priority: 50 },
61
-
62
- exile: { priority: 50 },
63
- no_exile: { priority: 50 },
64
-
65
- vote_speech_phase_ended: { priority: 50 },
66
- death_speech: { priority: 50 },
67
- wandering_speech: { priority: 50 },
68
- crab_teammates: { priority: 50 },
69
-
70
- meeting_briefing: { priority: 50 },
71
- speech: { priority: 50 },
72
- speech_skipped: { priority: 50 },
73
- speech_your_turn: { priority: 99 },
74
-
75
- vote_phase_start: { priority: 99 },
76
-
77
- game_over: { priority: 50 },
78
- user_left_game: { priority: 50 },
79
- game_started: { priority: 50 },
80
- role_assigned: { priority: 50 },
81
-
82
- // #region: Matchmaking-phase synthetic events
83
- match_waiting: { priority: 50 },
84
- match_timeout: { priority: 50 },
85
- robot_speak_rule: { priority: 50 },
86
- // #endregion
87
-
88
- // Strategy → agent real-time briefing (the automation explaining a decisive
89
- // autonomous move, e.g. self-reporting its own kill). Ranked above ambient
90
- // wander events so it leads the events[] list.
91
- strategy_alert: { priority: 60 },
92
- };
93
-
94
- export const NOTABLE_EVENT_TYPES = new Set(Object.keys(MONITOR_EVENT_CONFIG));
95
-
96
- /** Events whose trigger should be delayed to allow merging with nearby events.
97
- * Key = event type, Value = delay in milliseconds.
98
- * During the delay window, all incoming events (both delayable and non-delayable)
99
- * are buffered and emitted together when the timer expires.
100
- * Only one delay runs at a time — subsequent delayable events do NOT reset the timer. */
101
- export const DELAYABLE_EVENT_CONFIG: Record<string, number> = {
102
- kill: 2000,
103
- emergency_started: 2000,
104
- corpse_spotted: 2000,
105
- };
106
-
107
- export interface GameEvent {
108
- type: string;
109
- tick?: number;
110
- ts?: string;
111
- [key: string]: any;
112
- }
113
-
114
- export function eventKey(evt: GameEvent): string {
115
- const type = evt.type ?? '?';
116
- const tick = evt.tick ?? 0;
117
- const parts = [
118
- evt.actor_name,
119
- evt.spotted_name,
120
- evt.killer_name,
121
- evt.result_target,
122
- evt.target_name,
123
- evt.corpse_name,
124
- evt.task_name,
125
- ].filter(Boolean);
126
- const disc = parts.length > 0 ? parts.join('|') : '';
127
- return `${type}@${tick}#${disc}`;
128
- }
129
-
130
- export interface EventClassification {
131
- notable: boolean;
132
- }
133
-
134
- export function classifyEvent(evt: GameEvent, _youName: string | null = null): EventClassification {
135
- const notable = !!(evt.type && NOTABLE_EVENT_TYPES.has(evt.type));
136
- return { notable };
137
- }
138
-
139
- function monitorEventPriority(event: GameEvent): number {
140
- return MONITOR_EVENT_CONFIG[event.type]?.priority ?? DEFAULT_MONITOR_EVENT_PRIORITY;
141
- }
142
-
143
- interface RouteRule {
144
- reason: string;
145
- match: (triggers: string[]) => boolean;
146
- nextStep: string;
147
- }
148
-
149
- const ROUTING_RULES: RouteRule[] = [
150
- { reason: 'speech_your_turn', match: (t) => t.includes('speech_your_turn'), nextStep: 'It is YOUR turn to speak. Submit `ccl do -s "<draft>"` immediately. Server skips you after 45s.' },
151
- { reason: 'role_assigned', match: (t) => t.includes('role_assigned'), nextStep: 'Tell user your role, faction, win condition, and first plan.' },
152
- { reason: 'game_started', match: (t) => t.includes('game_started'), nextStep: 'Game started. Use `ccl events game_started` for opening map/seat context and `ccl events role_assigned` for role/tasks if needed. Do not relaunch.' },
153
- { reason: 'crab_teammates', match: (t) => t.includes('crab_teammates'), nextStep: 'Crab teammate list is available. Keep teammate identities private, coordinate cover stories, and avoid voting or killing into them.' },
154
- { reason: 'match_start', match: (t) => t.includes('match_start'), nextStep: 'Matchmaking queue entered. The game runtime is live and the stream is attached. Chat with the user while waiting for allocation.' },
155
- { reason: 'match_waiting', match: (t) => t.includes('match_waiting'), nextStep: 'Still in queue (see `events[].waited_secs`). Keep chatting with the user; no tactical action required.' },
156
- { reason: 'match_timeout', match: (t) => t.includes('match_timeout'), nextStep: `Cumulative wait reached ${Math.round(DEFAULT_MATCH_TIMEOUT_MS / 60_000)} min (see \`events[].waited_secs\`). The stream will exit — discuss with the user: launch a fresh \`ccl game start\` to retry, or call it a session.` },
157
- { reason: 'game_over', match: (t) => t.includes('game_over'), nextStep: 'Game ended. The current ccl game start process is exiting automatically. Review the result with the user; start another match only if the user asks.' },
158
- { reason: 'strategy_alert', match: (t) => t.includes('strategy_alert'), nextStep: 'Your automation just made a decisive autonomous move and is briefing you (read events[].message). Lock your story to it before you next speak or vote — e.g. if it reported a corpse that is likely your own kill, present yourself as the proactive reporter, steer suspicion onto the bystanders, and do NOT confess.' },
159
- ];
160
-
161
- const DEFAULT_NEXT_STEP = 'React to summary fields. No relaunch needed — the stream stays attached.';
162
-
163
- function routeTriggers(triggers: string[]): { exitReason: string; nextStep: string } {
164
- const rule = ROUTING_RULES.find((r) => r.match(triggers));
165
- return {
166
- exitReason: rule?.reason ?? triggers[0],
167
- nextStep: rule?.nextStep ?? DEFAULT_NEXT_STEP,
168
- };
169
- }
170
-
171
- export function nextStepFor(reason: string): string {
172
- return routeTriggers([reason]).nextStep;
173
- }
174
-
175
- export function nextStepForTriggers(triggers: string[]): string {
176
- return routeTriggers(triggers).nextStep;
177
- }
178
-
179
- export function sortEventsForMonitor(events: GameEvent[]): GameEvent[] {
180
- return events
181
- .map((event, index) => ({
182
- event,
183
- index,
184
- priority: monitorEventPriority(event),
185
- }))
186
- .sort((a, b) => (b.priority - a.priority) || (a.index - b.index))
187
- .map(({ event }) => event);
188
- }
189
-
190
- function readSeatMapForMonitor(sessionPath: string | null): Record<string, number> {
191
- if (!sessionPath) return {};
192
- try {
193
- return PlayerHistoryStore.forSession(sessionPath).read()?.seats ?? {};
194
- } catch {
195
- return {};
196
- }
197
- }
198
-
199
- function cleanObject<T extends Record<string, any>>(obj: T): T {
200
- for (const key of Object.keys(obj)) {
201
- if (obj[key] === undefined) delete obj[key];
202
- }
203
- return obj;
204
- }
205
-
206
- export function compactEventForMonitor(event: GameEvent): Record<string, any> {
207
- return compactEventForEvents(event);
208
- }
209
-
210
- export function summarizeFeed(feed: any): any | null {
211
- if (!feed || typeof feed !== 'object') return null;
212
- const summary: any = {
213
- phase: feed.phase,
214
- you: {
215
- name: feed.you?.name,
216
- seat: feed.you?.seat,
217
- role: feed.you?.role,
218
- role_display: feed.you?.role_display,
219
- faction: feed.you?.faction,
220
- alive: feed.you?.alive,
221
- x: feed.you?.x,
222
- y: feed.you?.y,
223
- currently_moving: feed.you?.currently_moving,
224
- doing_task: feed.you?.doing_task,
225
- kill_cooldown_secs: feed.you?.kill_cooldown_secs,
226
- kills_remaining: feed.you?.kills_remaining,
227
- },
228
- game: feed.game,
229
- urgent: feed.urgent,
230
- meeting: feed.meeting,
231
- };
232
- if (feed.automation) summary.automation = feed.automation;
233
- return summary;
234
- }
235
-
236
- export function readFeedSummary(feedPath: string): any | null {
237
- try {
238
- const feed = JSON.parse(readFileSync(feedPath, 'utf8'));
239
- return summarizeFeed(feed);
240
- } catch {
241
- return null;
242
- }
243
- }
244
-
245
- export function compactSummaryForMonitor(summary: any | null, triggers: string[]): any | null {
246
- if (!summary || summary.phase !== 'meeting') return summary;
247
- const oldMeeting = summary.meeting ?? {};
248
- const oldYou = summary.you ?? {};
249
- const isVotePhase = triggers.includes('vote_phase_start')
250
- || (!triggers.includes('speech_your_turn') && oldMeeting.sub_phase === 'vote');
251
- const meeting: Record<string, any> = {
252
- caller: oldMeeting.caller,
253
- sub_phase: triggers.includes('vote_phase_start') ? 'vote' : oldMeeting.sub_phase,
254
- alive_players: oldMeeting.alive_players,
255
- };
256
- if (triggers.includes('speech_your_turn')) {
257
- meeting.sub_phase = 'speech';
258
- meeting.current_speaker = oldYou.name;
259
- meeting.is_my_turn = true;
260
- } else if (!isVotePhase) {
261
- meeting.current_speaker = oldMeeting.current_speaker;
262
- meeting.is_my_turn = oldMeeting.is_my_turn;
263
- }
264
- if (isVotePhase) {
265
- meeting.votes_submitted_count = Array.isArray(oldMeeting.votes_submitted)
266
- ? oldMeeting.votes_submitted.length
267
- : 0;
268
- }
269
- return cleanObject({
270
- phase: summary.phase,
271
- you: cleanObject({
272
- name: oldYou.name,
273
- role: oldYou.role,
274
- faction: oldYou.faction,
275
- }),
276
- game: summary.game,
277
- meeting: cleanObject(meeting),
278
- automation: summary.automation,
279
- });
280
- }
281
-
282
- export interface RunStreamingOptions {
283
- feedPath: string;
284
- sessionPath: string | null;
285
- readSummary?: () => any | null;
286
- /** Optional dynamic resolver — called each poll so the stream can follow session rotation across games. */
287
- getSessionPath?: () => string | null;
288
- stdout: (line: string) => void;
289
- signal?: AbortSignal;
290
- skipFeedWait?: boolean;
291
- pollIntervalMs?: number;
292
- /** Emit a `heartbeat` NDJSON line after this many ms of silence so consumers don't see the stream as hung. Default 30s. Pass 0 to disable. */
293
- heartbeatIntervalMs?: number;
294
- /** Max ms to wait for feed.json when launching alongside `game start`. Default 30s. */
295
- runtimeWaitMs?: number;
296
- /**
297
- * Per-event-type delay overrides for the delay buffer (see DELAYABLE_EVENT_CONFIG).
298
- * Pass `{ kill: 0 }` to disable the kill delay in tests.
299
- * Values from DELAYABLE_EVENT_CONFIG are used for any type not overridden here.
300
- */
301
- delayableEventMs?: Record<string, number>;
302
- /**
303
- * Event types to exclude from the initial `caught_up` backlog (useful when the
304
- * caller already emitted them live before chaining into runStreaming, e.g.
305
- * `ccl game start` emits `match_waiting` / `match_timeout` during its polling
306
- * phase). Does NOT affect ongoing event tailing — only the one-time pre-attach
307
- * backlog drain.
308
- */
309
- skipBacklogTypes?: string[];
310
- /**
311
- * Emit a first `game_start` beat even when no backlog is present. `ccl game start`
312
- * uses this to tell the agent the stream is attached without carrying a huge
313
- * `initial_payload`.
314
- */
315
- emitGameStart?: boolean;
316
- /**
317
- * When set, attached to the `game_over` emission (as a `hub_reminder` field
318
- * and appended to `next_step`) so the agent sees the nudge in the same beat it
319
- * starts the post-game debrief. Callers compute it via `hubReminder()`; pass
320
- * nothing once the account has adopted a hub or custom strategy.
321
- */
322
- hubReminder?: string;
323
- }
324
-
325
- export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
326
- if (!opts.skipFeedWait) {
327
- const feedReady = await waitForFeed(opts.feedPath, {
328
- signal: opts.signal,
329
- timeoutMs: opts.runtimeWaitMs ?? RUNTIME_WAIT_MS,
330
- pollMs: opts.pollIntervalMs ?? POLL_INTERVAL_MS,
331
- });
332
- if (!feedReady) {
333
- throw new WatchNotReadyError(
334
- 'Game runtime not ready (no feed.json). Run `ccl game start` to start or recover the game stream.',
335
- );
336
- }
337
- }
338
- const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;
339
- const heartbeatInterval = opts.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
340
- const resolvedDelays: Record<string, number> = { ...DELAYABLE_EVENT_CONFIG, ...(opts.delayableEventMs ?? {}) };
341
- let lastEmitMs = Date.now();
342
- const emit = (obj: any): void => {
343
- opts.stdout(JSON.stringify(obj) + '\n');
344
- lastEmitMs = Date.now();
345
- };
346
-
347
- // Initial player name from owner snapshot or legacy feed file (best-effort).
348
- let youName: string | null = null;
349
- try {
350
- youName = opts.readSummary?.()?.you?.name
351
- ?? JSON.parse(readFileSync(opts.feedPath, 'utf8'))?.you?.name
352
- ?? null;
353
- } catch {}
354
-
355
- // Tail state for the .jsonl
356
- const seenKeys = new Set<string>();
357
- let filePos = 0;
358
- let fileIno = 0;
359
- let lineBuffer = '';
360
- let currentSessionPath: string | null = opts.sessionPath;
361
-
362
- if (currentSessionPath && existsSync(currentSessionPath)) {
363
- filePos = 0;
364
- fileIno = statSync(currentSessionPath).ino;
365
- }
366
-
367
- // Cross-game session rotation: the runtime may create a new events.jsonl when a new
368
- // game starts. If the caller provided a dynamic resolver, poll it and switch
369
- // tail state to the new file. Without this, the stream would silently follow the
370
- // previous game's file forever and look like a huge event delay.
371
- const refreshSessionPath = (): void => {
372
- if (!opts.getSessionPath) return;
373
- const latest = opts.getSessionPath();
374
- if (!latest || latest === currentSessionPath) return;
375
- currentSessionPath = latest;
376
- filePos = 0;
377
- lineBuffer = '';
378
- try { fileIno = existsSync(latest) ? statSync(latest).ino : 0; } catch { fileIno = 0; }
379
- };
380
-
381
- const drainNewEvents = (): GameEvent[] => {
382
- if (!currentSessionPath || !existsSync(currentSessionPath)) return [];
383
- let stat;
384
- try { stat = statSync(currentSessionPath); } catch { return []; }
385
- if (stat.ino !== fileIno || stat.size < filePos) {
386
- filePos = 0; fileIno = stat.ino; lineBuffer = '';
387
- }
388
- if (stat.size <= filePos) return [];
389
- let fd: number;
390
- try { fd = openSync(currentSessionPath, 'r'); } catch { return []; }
391
- const buf = Buffer.alloc(stat.size - filePos);
392
- readSync(fd, buf, 0, buf.length, filePos);
393
- closeSync(fd);
394
- filePos = stat.size;
395
- lineBuffer += buf.toString('utf8');
396
- const lastNl = lineBuffer.lastIndexOf('\n');
397
- if (lastNl < 0) return [];
398
- const chunk = lineBuffer.slice(0, lastNl);
399
- lineBuffer = lineBuffer.slice(lastNl + 1);
400
- const events: GameEvent[] = [];
401
- for (const line of chunk.split('\n')) {
402
- if (!line) continue;
403
- try {
404
- const evt = JSON.parse(line);
405
- if (!isLocalControlEvent(evt)) events.push(evt);
406
- for (const nested of extractNewEvents(evt) as GameEvent[]) {
407
- if (!isLocalControlEvent(nested)) events.push(nested);
408
- }
409
- } catch {}
410
- }
411
- return events;
412
- };
413
-
414
- // Pre-attach backlog: drain once, classify, hold for first emit.
415
- const backlogEvents = drainNewEvents();
416
- const skipSet = new Set(opts.skipBacklogTypes ?? []);
417
- const backlogNotable = backlogEvents.filter((e) => {
418
- if (e.type && skipSet.has(e.type as string)) return false;
419
- return classifyEvent(e, youName).notable;
420
- });
421
- let caughtUpEvents: GameEvent[] = backlogNotable.slice(-20);
422
- for (const e of backlogEvents) seenKeys.add(eventKey(e));
423
-
424
- const buildOut = (
425
- triggers: string[],
426
- _nextStep: string,
427
- events: GameEvent[] = [],
428
- ): any => {
429
- const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
430
- const summary = compactSummaryForMonitor(rawSummary, triggers);
431
- // Server pushes `meeting_briefing` without `speech_order` (that field only lives in
432
- // meeting state, which the runtime projects onto the owner snapshot).
433
- // Inject it onto the briefing event here so consumers can read it from events[]
434
- // directly. Guarded by caller match so a stale speech_order from a previous
435
- // meeting isn't ever attached.
436
- const enrichMeetingBriefing = (e: GameEvent): GameEvent => {
437
- if (e.type !== 'meeting_briefing') return e;
438
- if (e.speech_order) return e;
439
- const so = rawSummary?.meeting?.speech_order;
440
- if (!Array.isArray(so)) return e;
441
- const sumCaller = rawSummary?.meeting?.caller;
442
- if (sumCaller && e.caller && sumCaller !== e.caller) return e;
443
- return { ...e, speech_order: so };
444
- };
445
- const sourceEvents = events.length > 0
446
- ? sortEventsForMonitor(events).map(enrichMeetingBriefing)
447
- : triggers.map((type) => ({ type }));
448
- const context = {
449
- summary,
450
- seats: readSeatMapForMonitor(currentSessionPath),
451
- maxTextLength: 90,
452
- };
453
- return {
454
- events: sourceEvents.map((event) => event.type),
455
- messages: sourceEvents.map((event) => formatEventMessage(event, context)),
456
- state: shortStateText(summary),
457
- };
458
- };
459
-
460
- const fireTrigger = (
461
- triggers: string[],
462
- triggeredEvents: GameEvent[],
463
- ): void => {
464
- if (triggers.length === 0) return;
465
- const { nextStep } = routeTriggers(triggers);
466
- const out = buildOut(triggers, nextStep, triggeredEvents.slice(-10));
467
- if (opts.hubReminder && triggers.includes('game_over')) {
468
- out.hub_reminder = opts.hubReminder;
469
- }
470
- emit(out);
471
- };
472
-
473
- // Always emit an attached first beat when there is a pre-attach backlog OR
474
- // the caller explicitly requests one.
475
- if (caughtUpEvents.length > 0 || opts.emitGameStart) {
476
- const hasBacklog = caughtUpEvents.length > 0;
477
- const nextStep = opts.emitGameStart
478
- ? hasBacklog
479
- ? 'Game stream attached. Read summary and caught_up.notable_events for opening events; current strategy appears in summary.automation.strategy.'
480
- : 'Game stream attached. Read summary and wait for role_assigned; current strategy appears in summary.automation.strategy.'
481
- : 'Catch-up complete. Read summary, then continue play.';
482
- const attachedEvents = hasBacklog ? caughtUpEvents : [{ type: 'game_start' }];
483
- const attachedOut = buildOut(attachedEvents.map((event) => event.type), nextStep, attachedEvents);
484
- caughtUpEvents = [];
485
- emit(attachedOut);
486
- }
487
-
488
- // Delay buffer: merge rapid-fire wandering-phase events into one notification
489
- let delayActive = false;
490
- let delayDeadline = 0;
491
- const delayBuffer: { triggers: Set<string>; events: GameEvent[] } = {
492
- triggers: new Set(),
493
- events: [],
494
- };
495
-
496
- while (!opts.signal?.aborted) {
497
- refreshSessionPath();
498
-
499
- const triggers: string[] = [];
500
- const triggeredEvents: GameEvent[] = [];
501
-
502
- const newEvents = drainNewEvents();
503
- for (const evt of newEvents) {
504
- const cls = classifyEvent(evt, youName);
505
- if (!cls.notable) continue;
506
- const key = eventKey(evt);
507
- if (seenKeys.has(key)) continue;
508
- seenKeys.add(key);
509
- triggeredEvents.push(evt);
510
- if (evt.type && !triggers.includes(evt.type)) {
511
- triggers.push(evt.type);
512
- }
513
- }
514
-
515
- // ── Delay buffer: merge rapid-fire wandering-phase events ──
516
- // Only active during wandering; meeting-phase events (my_turn, speech, etc.)
517
- // are not in DELAYABLE_EVENT_CONFIG and won't start a delay.
518
- if (delayActive) {
519
- if (Date.now() < delayDeadline) {
520
- // Still within delay window — buffer everything and wait
521
- for (const t of triggers) delayBuffer.triggers.add(t);
522
- for (const e of triggeredEvents) delayBuffer.events.push(e);
523
- triggers.length = 0;
524
- triggeredEvents.length = 0;
525
- } else {
526
- // Delay expired — flush buffer in front of current batch
527
- for (const t of delayBuffer.triggers) {
528
- if (!triggers.includes(t)) triggers.unshift(t);
529
- }
530
- triggeredEvents.unshift(...delayBuffer.events);
531
- delayBuffer.triggers.clear();
532
- delayBuffer.events.length = 0;
533
- delayActive = false;
534
- }
535
- } else if (triggers.length > 0) {
536
- // Check if any trigger is delayable; start a delay if so
537
- let delayMs = 0;
538
- for (const t of triggers) {
539
- const ms = resolvedDelays[t];
540
- if (ms !== undefined && ms > delayMs) delayMs = ms;
541
- }
542
- if (delayMs > 0) {
543
- delayActive = true;
544
- delayDeadline = Date.now() + delayMs;
545
- for (const t of triggers) delayBuffer.triggers.add(t);
546
- for (const e of triggeredEvents) delayBuffer.events.push(e);
547
- triggers.length = 0;
548
- triggeredEvents.length = 0;
549
- }
550
- }
551
-
552
- if (triggers.length > 0) {
553
- fireTrigger(triggers, triggeredEvents);
554
- if (triggers.includes('game_over') || triggers.includes('user_left_game')) return;
555
- } else if (!delayActive && heartbeatInterval > 0 && Date.now() - lastEmitMs >= heartbeatInterval) {
556
- // Idle keepalive — prevents downstream adapters from interpreting a quiet
557
- // wandering/transit period as a hung subprocess and killing it on their
558
- // own default timeout (commonly 60s).
559
- emit(buildOut(
560
- ['heartbeat'],
561
- 'Stream is alive; no notable events. Continue waiting — no action required.',
562
- ));
563
- }
564
-
565
- if (opts.signal?.aborted) break;
566
- await new Promise((r) => setTimeout(r, interval));
567
- }
568
- }
569
-
570
- export interface SnapshotOnceOptions {
571
- feedPath: string;
572
- stdout: (line: string) => void;
573
- }
574
-
575
- export function snapshotOnce(opts: SnapshotOnceOptions): void {
576
- if (!existsSync(opts.feedPath)) {
577
- throw new Error('ccl game runtime is not running. Start it first with `ccl game start`.');
578
- }
579
- const summary = readFeedSummary(opts.feedPath);
580
- opts.stdout(JSON.stringify({
581
- events: ['snapshot'],
582
- messages: [formatEventMessage({ type: 'snapshot' })],
583
- state: shortStateText(summary),
584
- }) + '\n');
585
- }
586
-
587
- export function buildErrorLine(err: any, opts?: { notReadyNextStep?: string }): string {
588
- const msg = err?.message ?? String(err);
589
- const notReady = err?.name === 'WatchNotReadyError' || /not ready|feed\.json/i.test(msg);
590
- const reason = notReady ? 'not_ready' : 'error';
591
- const event = {
592
- type: reason,
593
- message: notReady
594
- ? (opts?.notReadyNextStep ?? 'Game runtime not running. Run `ccl game start` to begin a new session.')
595
- : msg,
596
- };
597
- return JSON.stringify({
598
- events: [reason],
599
- messages: [formatEventMessage(event)],
600
- state: 'state unavailable',
601
- error: msg,
602
- }) + '\n';
603
- }
604
-
605
- export function createWatchCommand(): Command {
606
- const cmd = new Command('watch')
607
- .description('Stream notable game events as NDJSON. Exits on game_over. For a one-shot snapshot use `ccl peek`.')
608
- .action(async () => {
609
- const store = new AuthStore();
610
- const profile = store.getActive();
611
- if (!profile) {
612
- process.stdout.write(JSON.stringify({ exit_reason: ['not_logged_in'], error: 'Not logged in' }) + '\n');
613
- return;
614
- }
615
- const stateDir = getProfileStateDir(profile);
616
- const feedPath = join(stateDir, 'feed.json');
617
- const sessionPath = EventStore.latestSessionPath();
618
- const ctrl = new AbortController();
619
- process.on('SIGINT', () => ctrl.abort());
620
- process.on('SIGTERM', () => ctrl.abort());
621
- let summaryCache: any | null = null;
622
- let summaryPoll: ReturnType<typeof setInterval> | null = null;
623
- try {
624
- const snapshot = await sendOwnerControlRequest(stateDir, 'snapshot');
625
- if (!snapshot?.ok) {
626
- throw new WatchNotReadyError(
627
- 'Game runtime not ready (no active ccl game start owner). Run `ccl game start` to start or recover the game stream.',
628
- );
629
- }
630
- summaryCache = snapshot.summary ?? null;
631
- summaryPoll = setInterval(() => {
632
- void sendOwnerControlRequest(stateDir, 'snapshot')
633
- .then((response) => {
634
- if (response?.ok) summaryCache = response.summary ?? null;
635
- })
636
- .catch(() => {});
637
- }, 1000);
638
- await runStreaming({
639
- feedPath,
640
- sessionPath,
641
- getSessionPath: () => EventStore.latestSessionPath(),
642
- stdout: (s) => process.stdout.write(s),
643
- signal: ctrl.signal,
644
- skipFeedWait: true,
645
- readSummary: () => summaryCache,
646
- hubReminder: hubReminder(readCachedGamesPlayed()),
647
- });
648
- } catch (err: any) {
649
- process.stdout.write(buildErrorLine(err, {
650
- notReadyNextStep: 'Run `ccl game start` to start or recover the game stream.',
651
- }));
652
- process.exit(1);
653
- } finally {
654
- if (summaryPoll) clearInterval(summaryPoll);
655
- }
656
- });
657
- // ── Adapter metadata: streaming mode blocks until game_over; cap at 30min for stuck-process safety ──
658
- setMeta(cmd, { longRunning: true, timeoutMs: 1_800_000 });
659
- return cmd;
660
- }
1
+ import { Command } from 'commander';
2
+ import { existsSync, readFileSync, openSync, readSync, closeSync, statSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { AuthStore } from '../lib/auth.js';
5
+ import { getProfileStateDir } from '../lib/init-command.js';
6
+ import { setMeta } from '../lib/command-meta.js';
7
+ import { EventStore, extractNewEvents, isLocalControlEvent } from '../pipeline/event-store.js';
8
+ import { compactEventForEvents, formatEventMessage, shortStateText } from '../pipeline/event-format.js';
9
+ import { PlayerHistoryStore } from '../perception/player-history-store.js';
10
+ import { DEFAULT_MATCH_TIMEOUT_MS } from '../lib/match-state.js';
11
+ import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
12
+ import { sendOwnerControlRequest } from '../runtime/owner-control.js';
13
+
14
+ export const POLL_INTERVAL_MS = 220;
15
+ const HEARTBEAT_INTERVAL_MS = 60_000;
16
+ const RUNTIME_WAIT_MS = 30_000;
17
+
18
+ export class WatchNotReadyError extends Error {
19
+ constructor(message: string) {
20
+ super(message);
21
+ this.name = 'WatchNotReadyError';
22
+ }
23
+ }
24
+
25
+ /** Legacy helper for tests and explicit file-backed attaches. Owner paths use control socket snapshots. */
26
+ export async function waitForFeed(
27
+ feedPath: string,
28
+ opts?: { signal?: AbortSignal; timeoutMs?: number; pollMs?: number },
29
+ ): Promise<boolean> {
30
+ const timeoutMs = opts?.timeoutMs ?? RUNTIME_WAIT_MS;
31
+ const pollMs = opts?.pollMs ?? POLL_INTERVAL_MS;
32
+ const deadline = Date.now() + timeoutMs;
33
+ while (Date.now() < deadline) {
34
+ if (existsSync(feedPath)) return true;
35
+ if (opts?.signal?.aborted) return false;
36
+ await new Promise((r) => setTimeout(r, pollMs));
37
+ }
38
+ return existsSync(feedPath);
39
+ }
40
+
41
+ const DEFAULT_MONITOR_EVENT_PRIORITY = 50;
42
+
43
+ export interface MonitorEventConfig {
44
+ priority: number;
45
+ }
46
+
47
+ export const MONITOR_EVENT_CONFIG: Record<string, MonitorEventConfig> = {
48
+ kill: { priority: 50 },
49
+ killed: { priority: 99 },
50
+ murder_witnessed: { priority: 50 },
51
+ warrior_shrimp_self_destruct: { priority: 50 },
52
+
53
+ task_completed: { priority: 50 },
54
+ task_sabotaged: { priority: 50 },
55
+
56
+ corpse_spotted: { priority: 50 },
57
+ octopus_time_start: { priority: 50 },
58
+
59
+ emergency_started: { priority: 50 },
60
+ emergency_resolved: { priority: 50 },
61
+
62
+ exile: { priority: 50 },
63
+ no_exile: { priority: 50 },
64
+
65
+ vote_speech_phase_ended: { priority: 50 },
66
+ death_speech: { priority: 50 },
67
+ wandering_speech: { priority: 50 },
68
+ crab_teammates: { priority: 50 },
69
+
70
+ meeting_briefing: { priority: 50 },
71
+ speech: { priority: 50 },
72
+ speech_skipped: { priority: 50 },
73
+ speech_your_turn: { priority: 99 },
74
+
75
+ vote_phase_start: { priority: 99 },
76
+
77
+ game_over: { priority: 50 },
78
+ user_left_game: { priority: 50 },
79
+ game_started: { priority: 50 },
80
+ role_assigned: { priority: 50 },
81
+
82
+ // #region: Matchmaking-phase synthetic events
83
+ match_waiting: { priority: 50 },
84
+ match_timeout: { priority: 50 },
85
+ robot_speak_rule: { priority: 50 },
86
+ // #endregion
87
+
88
+ // Strategy → agent real-time briefing (the automation explaining a decisive
89
+ // autonomous move, e.g. self-reporting its own kill). Ranked above ambient
90
+ // wander events so it leads the events[] list.
91
+ strategy_alert: { priority: 60 },
92
+ };
93
+
94
+ export const NOTABLE_EVENT_TYPES = new Set(Object.keys(MONITOR_EVENT_CONFIG));
95
+
96
+ /** Events whose trigger should be delayed to allow merging with nearby events.
97
+ * Key = event type, Value = delay in milliseconds.
98
+ * During the delay window, all incoming events (both delayable and non-delayable)
99
+ * are buffered and emitted together when the timer expires.
100
+ * Only one delay runs at a time — subsequent delayable events do NOT reset the timer. */
101
+ export const DELAYABLE_EVENT_CONFIG: Record<string, number> = {
102
+ kill: 2000,
103
+ emergency_started: 2000,
104
+ corpse_spotted: 2000,
105
+ };
106
+
107
+ export interface GameEvent {
108
+ type: string;
109
+ tick?: number;
110
+ ts?: string;
111
+ [key: string]: any;
112
+ }
113
+
114
+ export function eventKey(evt: GameEvent): string {
115
+ const type = evt.type ?? '?';
116
+ const tick = evt.tick ?? 0;
117
+ const parts = [
118
+ evt.actor_name,
119
+ evt.spotted_name,
120
+ evt.killer_name,
121
+ evt.result_target,
122
+ evt.target_name,
123
+ evt.corpse_name,
124
+ evt.task_name,
125
+ ].filter(Boolean);
126
+ const disc = parts.length > 0 ? parts.join('|') : '';
127
+ return `${type}@${tick}#${disc}`;
128
+ }
129
+
130
+ export interface EventClassification {
131
+ notable: boolean;
132
+ }
133
+
134
+ export function classifyEvent(evt: GameEvent, _youName: string | null = null): EventClassification {
135
+ const notable = !!(evt.type && NOTABLE_EVENT_TYPES.has(evt.type));
136
+ return { notable };
137
+ }
138
+
139
+ function monitorEventPriority(event: GameEvent): number {
140
+ return MONITOR_EVENT_CONFIG[event.type]?.priority ?? DEFAULT_MONITOR_EVENT_PRIORITY;
141
+ }
142
+
143
+ interface RouteRule {
144
+ reason: string;
145
+ match: (triggers: string[]) => boolean;
146
+ nextStep: string;
147
+ }
148
+
149
+ const ROUTING_RULES: RouteRule[] = [
150
+ { reason: 'speech_your_turn', match: (t) => t.includes('speech_your_turn'), nextStep: 'It is YOUR turn to speak. Submit `ccl do -s "<draft>"` immediately. Server skips you after 45s.' },
151
+ { reason: 'role_assigned', match: (t) => t.includes('role_assigned'), nextStep: 'Tell user your role, faction, win condition, and first plan.' },
152
+ { reason: 'game_started', match: (t) => t.includes('game_started'), nextStep: 'Game started. Use `ccl events game_started` for opening map/seat context and `ccl events role_assigned` for role/tasks if needed. Do not relaunch.' },
153
+ { reason: 'crab_teammates', match: (t) => t.includes('crab_teammates'), nextStep: 'Crab teammate list is available. Keep teammate identities private, coordinate cover stories, and avoid voting or killing into them.' },
154
+ { reason: 'match_start', match: (t) => t.includes('match_start'), nextStep: 'Matchmaking queue entered. The game runtime is live and the stream is attached. Chat with the user while waiting for allocation.' },
155
+ { reason: 'match_waiting', match: (t) => t.includes('match_waiting'), nextStep: 'Still in queue (see `events[].waited_secs`). Keep chatting with the user; no tactical action required.' },
156
+ { reason: 'match_timeout', match: (t) => t.includes('match_timeout'), nextStep: `Cumulative wait reached ${Math.round(DEFAULT_MATCH_TIMEOUT_MS / 60_000)} min (see \`events[].waited_secs\`). The stream will exit — discuss with the user: launch a fresh \`ccl game start\` to retry, or call it a session.` },
157
+ { reason: 'game_over', match: (t) => t.includes('game_over'), nextStep: 'Game ended. The current ccl game start process is exiting automatically. Review the result with the user; start another match only if the user asks.' },
158
+ { reason: 'strategy_alert', match: (t) => t.includes('strategy_alert'), nextStep: 'Your automation just made a decisive autonomous move and is briefing you (read events[].message). Lock your story to it before you next speak or vote — e.g. if it reported a corpse that is likely your own kill, present yourself as the proactive reporter, steer suspicion onto the bystanders, and do NOT confess.' },
159
+ ];
160
+
161
+ const DEFAULT_NEXT_STEP = 'React to summary fields. No relaunch needed — the stream stays attached.';
162
+
163
+ function routeTriggers(triggers: string[]): { exitReason: string; nextStep: string } {
164
+ const rule = ROUTING_RULES.find((r) => r.match(triggers));
165
+ return {
166
+ exitReason: rule?.reason ?? triggers[0],
167
+ nextStep: rule?.nextStep ?? DEFAULT_NEXT_STEP,
168
+ };
169
+ }
170
+
171
+ export function nextStepFor(reason: string): string {
172
+ return routeTriggers([reason]).nextStep;
173
+ }
174
+
175
+ export function nextStepForTriggers(triggers: string[]): string {
176
+ return routeTriggers(triggers).nextStep;
177
+ }
178
+
179
+ export function sortEventsForMonitor(events: GameEvent[]): GameEvent[] {
180
+ return events
181
+ .map((event, index) => ({
182
+ event,
183
+ index,
184
+ priority: monitorEventPriority(event),
185
+ }))
186
+ .sort((a, b) => (b.priority - a.priority) || (a.index - b.index))
187
+ .map(({ event }) => event);
188
+ }
189
+
190
+ function readSeatMapForMonitor(sessionPath: string | null): Record<string, number> {
191
+ if (!sessionPath) return {};
192
+ try {
193
+ return PlayerHistoryStore.forSession(sessionPath).read()?.seats ?? {};
194
+ } catch {
195
+ return {};
196
+ }
197
+ }
198
+
199
+ function cleanObject<T extends Record<string, any>>(obj: T): T {
200
+ for (const key of Object.keys(obj)) {
201
+ if (obj[key] === undefined) delete obj[key];
202
+ }
203
+ return obj;
204
+ }
205
+
206
+ export function compactEventForMonitor(event: GameEvent): Record<string, any> {
207
+ return compactEventForEvents(event);
208
+ }
209
+
210
+ export function summarizeFeed(feed: any): any | null {
211
+ if (!feed || typeof feed !== 'object') return null;
212
+ const summary: any = {
213
+ phase: feed.phase,
214
+ you: {
215
+ name: feed.you?.name,
216
+ seat: feed.you?.seat,
217
+ role: feed.you?.role,
218
+ role_display: feed.you?.role_display,
219
+ faction: feed.you?.faction,
220
+ alive: feed.you?.alive,
221
+ x: feed.you?.x,
222
+ y: feed.you?.y,
223
+ currently_moving: feed.you?.currently_moving,
224
+ doing_task: feed.you?.doing_task,
225
+ kill_cooldown_secs: feed.you?.kill_cooldown_secs,
226
+ kills_remaining: feed.you?.kills_remaining,
227
+ },
228
+ game: feed.game,
229
+ urgent: feed.urgent,
230
+ meeting: feed.meeting,
231
+ };
232
+ if (feed.automation) summary.automation = feed.automation;
233
+ return summary;
234
+ }
235
+
236
+ export function readFeedSummary(feedPath: string): any | null {
237
+ try {
238
+ const feed = JSON.parse(readFileSync(feedPath, 'utf8'));
239
+ return summarizeFeed(feed);
240
+ } catch {
241
+ return null;
242
+ }
243
+ }
244
+
245
+ export function compactSummaryForMonitor(summary: any | null, triggers: string[]): any | null {
246
+ if (!summary || summary.phase !== 'meeting') return summary;
247
+ const oldMeeting = summary.meeting ?? {};
248
+ const oldYou = summary.you ?? {};
249
+ const isVotePhase = triggers.includes('vote_phase_start')
250
+ || (!triggers.includes('speech_your_turn') && oldMeeting.sub_phase === 'vote');
251
+ const meeting: Record<string, any> = {
252
+ caller: oldMeeting.caller,
253
+ sub_phase: triggers.includes('vote_phase_start') ? 'vote' : oldMeeting.sub_phase,
254
+ alive_players: oldMeeting.alive_players,
255
+ };
256
+ if (triggers.includes('speech_your_turn')) {
257
+ meeting.sub_phase = 'speech';
258
+ meeting.current_speaker = oldYou.name;
259
+ meeting.is_my_turn = true;
260
+ } else if (!isVotePhase) {
261
+ meeting.current_speaker = oldMeeting.current_speaker;
262
+ meeting.is_my_turn = oldMeeting.is_my_turn;
263
+ }
264
+ if (isVotePhase) {
265
+ meeting.votes_submitted_count = Array.isArray(oldMeeting.votes_submitted)
266
+ ? oldMeeting.votes_submitted.length
267
+ : 0;
268
+ }
269
+ return cleanObject({
270
+ phase: summary.phase,
271
+ you: cleanObject({
272
+ name: oldYou.name,
273
+ role: oldYou.role,
274
+ faction: oldYou.faction,
275
+ }),
276
+ game: summary.game,
277
+ meeting: cleanObject(meeting),
278
+ automation: summary.automation,
279
+ });
280
+ }
281
+
282
+ export interface RunStreamingOptions {
283
+ feedPath: string;
284
+ sessionPath: string | null;
285
+ readSummary?: () => any | null;
286
+ /** Optional dynamic resolver — called each poll so the stream can follow session rotation across games. */
287
+ getSessionPath?: () => string | null;
288
+ stdout: (line: string) => void;
289
+ signal?: AbortSignal;
290
+ skipFeedWait?: boolean;
291
+ pollIntervalMs?: number;
292
+ /** Emit a `heartbeat` NDJSON line after this many ms of silence so consumers don't see the stream as hung. Default 30s. Pass 0 to disable. */
293
+ heartbeatIntervalMs?: number;
294
+ /** Max ms to wait for feed.json when launching alongside `game start`. Default 30s. */
295
+ runtimeWaitMs?: number;
296
+ /**
297
+ * Per-event-type delay overrides for the delay buffer (see DELAYABLE_EVENT_CONFIG).
298
+ * Pass `{ kill: 0 }` to disable the kill delay in tests.
299
+ * Values from DELAYABLE_EVENT_CONFIG are used for any type not overridden here.
300
+ */
301
+ delayableEventMs?: Record<string, number>;
302
+ /**
303
+ * Event types to exclude from the initial `caught_up` backlog (useful when the
304
+ * caller already emitted them live before chaining into runStreaming, e.g.
305
+ * `ccl game start` emits `match_waiting` / `match_timeout` during its polling
306
+ * phase). Does NOT affect ongoing event tailing — only the one-time pre-attach
307
+ * backlog drain.
308
+ */
309
+ skipBacklogTypes?: string[];
310
+ /**
311
+ * Emit a first `game_start` beat even when no backlog is present. `ccl game start`
312
+ * uses this to tell the agent the stream is attached without carrying a huge
313
+ * `initial_payload`.
314
+ */
315
+ emitGameStart?: boolean;
316
+ /**
317
+ * When set, attached to the `game_over` emission (as a `hub_reminder` field
318
+ * and appended to `next_step`) so the agent sees the nudge in the same beat it
319
+ * starts the post-game debrief. Callers compute it via `hubReminder()`; pass
320
+ * nothing once the account has adopted a hub or custom strategy.
321
+ */
322
+ hubReminder?: string;
323
+ }
324
+
325
+ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
326
+ if (!opts.skipFeedWait) {
327
+ const feedReady = await waitForFeed(opts.feedPath, {
328
+ signal: opts.signal,
329
+ timeoutMs: opts.runtimeWaitMs ?? RUNTIME_WAIT_MS,
330
+ pollMs: opts.pollIntervalMs ?? POLL_INTERVAL_MS,
331
+ });
332
+ if (!feedReady) {
333
+ throw new WatchNotReadyError(
334
+ 'Game runtime not ready (no feed.json). Run `ccl game start` to start or recover the game stream.',
335
+ );
336
+ }
337
+ }
338
+ const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;
339
+ const heartbeatInterval = opts.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
340
+ const resolvedDelays: Record<string, number> = { ...DELAYABLE_EVENT_CONFIG, ...(opts.delayableEventMs ?? {}) };
341
+ let lastEmitMs = Date.now();
342
+ const emit = (obj: any): void => {
343
+ opts.stdout(JSON.stringify(obj) + '\n');
344
+ lastEmitMs = Date.now();
345
+ };
346
+
347
+ // Initial player name from owner snapshot or legacy feed file (best-effort).
348
+ let youName: string | null = null;
349
+ try {
350
+ youName = opts.readSummary?.()?.you?.name
351
+ ?? JSON.parse(readFileSync(opts.feedPath, 'utf8'))?.you?.name
352
+ ?? null;
353
+ } catch {}
354
+
355
+ // Tail state for the .jsonl
356
+ const seenKeys = new Set<string>();
357
+ let filePos = 0;
358
+ let fileIno = 0;
359
+ let lineBuffer = '';
360
+ let currentSessionPath: string | null = opts.sessionPath;
361
+
362
+ if (currentSessionPath && existsSync(currentSessionPath)) {
363
+ filePos = 0;
364
+ fileIno = statSync(currentSessionPath).ino;
365
+ }
366
+
367
+ // Cross-game session rotation: the runtime may create a new events.jsonl when a new
368
+ // game starts. If the caller provided a dynamic resolver, poll it and switch
369
+ // tail state to the new file. Without this, the stream would silently follow the
370
+ // previous game's file forever and look like a huge event delay.
371
+ const refreshSessionPath = (): void => {
372
+ if (!opts.getSessionPath) return;
373
+ const latest = opts.getSessionPath();
374
+ if (!latest || latest === currentSessionPath) return;
375
+ currentSessionPath = latest;
376
+ filePos = 0;
377
+ lineBuffer = '';
378
+ try { fileIno = existsSync(latest) ? statSync(latest).ino : 0; } catch { fileIno = 0; }
379
+ };
380
+
381
+ const drainNewEvents = (): GameEvent[] => {
382
+ if (!currentSessionPath || !existsSync(currentSessionPath)) return [];
383
+ let stat;
384
+ try { stat = statSync(currentSessionPath); } catch { return []; }
385
+ if (stat.ino !== fileIno || stat.size < filePos) {
386
+ filePos = 0; fileIno = stat.ino; lineBuffer = '';
387
+ }
388
+ if (stat.size <= filePos) return [];
389
+ let fd: number;
390
+ try { fd = openSync(currentSessionPath, 'r'); } catch { return []; }
391
+ const buf = Buffer.alloc(stat.size - filePos);
392
+ readSync(fd, buf, 0, buf.length, filePos);
393
+ closeSync(fd);
394
+ filePos = stat.size;
395
+ lineBuffer += buf.toString('utf8');
396
+ const lastNl = lineBuffer.lastIndexOf('\n');
397
+ if (lastNl < 0) return [];
398
+ const chunk = lineBuffer.slice(0, lastNl);
399
+ lineBuffer = lineBuffer.slice(lastNl + 1);
400
+ const events: GameEvent[] = [];
401
+ for (const line of chunk.split('\n')) {
402
+ if (!line) continue;
403
+ try {
404
+ const evt = JSON.parse(line);
405
+ if (!isLocalControlEvent(evt)) events.push(evt);
406
+ for (const nested of extractNewEvents(evt) as GameEvent[]) {
407
+ if (!isLocalControlEvent(nested)) events.push(nested);
408
+ }
409
+ } catch {}
410
+ }
411
+ return events;
412
+ };
413
+
414
+ // Pre-attach backlog: drain once, classify, hold for first emit.
415
+ const backlogEvents = drainNewEvents();
416
+ const skipSet = new Set(opts.skipBacklogTypes ?? []);
417
+ const backlogNotable = backlogEvents.filter((e) => {
418
+ if (e.type && skipSet.has(e.type as string)) return false;
419
+ return classifyEvent(e, youName).notable;
420
+ });
421
+ let caughtUpEvents: GameEvent[] = backlogNotable.slice(-20);
422
+ for (const e of backlogEvents) seenKeys.add(eventKey(e));
423
+
424
+ const buildOut = (
425
+ triggers: string[],
426
+ _nextStep: string,
427
+ events: GameEvent[] = [],
428
+ ): any => {
429
+ const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
430
+ const summary = compactSummaryForMonitor(rawSummary, triggers);
431
+ // Server pushes `meeting_briefing` without `speech_order` (that field only lives in
432
+ // meeting state, which the runtime projects onto the owner snapshot).
433
+ // Inject it onto the briefing event here so consumers can read it from events[]
434
+ // directly. Guarded by caller match so a stale speech_order from a previous
435
+ // meeting isn't ever attached.
436
+ const enrichMeetingBriefing = (e: GameEvent): GameEvent => {
437
+ if (e.type !== 'meeting_briefing') return e;
438
+ if (e.speech_order) return e;
439
+ const so = rawSummary?.meeting?.speech_order;
440
+ if (!Array.isArray(so)) return e;
441
+ const sumCaller = rawSummary?.meeting?.caller;
442
+ if (sumCaller && e.caller && sumCaller !== e.caller) return e;
443
+ return { ...e, speech_order: so };
444
+ };
445
+ const sourceEvents: GameEvent[] = events.length > 0
446
+ ? sortEventsForMonitor(events).map(enrichMeetingBriefing)
447
+ : triggers.map((type) => ({ type }));
448
+ const gameMode = sourceEvents.find(
449
+ (event) => event.game_mode === 'match' || event.game_mode === 'competition',
450
+ )?.game_mode;
451
+ const context = {
452
+ summary,
453
+ seats: readSeatMapForMonitor(currentSessionPath),
454
+ maxTextLength: 90,
455
+ };
456
+ return {
457
+ events: sourceEvents.map((event) => event.type),
458
+ ...(gameMode ? { game_mode: gameMode } : {}),
459
+ messages: sourceEvents.map((event) => formatEventMessage(event, context)),
460
+ state: shortStateText(summary),
461
+ };
462
+ };
463
+
464
+ const fireTrigger = (
465
+ triggers: string[],
466
+ triggeredEvents: GameEvent[],
467
+ ): void => {
468
+ if (triggers.length === 0) return;
469
+ const { nextStep } = routeTriggers(triggers);
470
+ const out = buildOut(triggers, nextStep, triggeredEvents.slice(-10));
471
+ if (opts.hubReminder && triggers.includes('game_over')) {
472
+ out.hub_reminder = opts.hubReminder;
473
+ }
474
+ emit(out);
475
+ };
476
+
477
+ // Always emit an attached first beat when there is a pre-attach backlog OR
478
+ // the caller explicitly requests one.
479
+ if (caughtUpEvents.length > 0 || opts.emitGameStart) {
480
+ const hasBacklog = caughtUpEvents.length > 0;
481
+ const nextStep = opts.emitGameStart
482
+ ? hasBacklog
483
+ ? 'Game stream attached. Read summary and caught_up.notable_events for opening events; current strategy appears in summary.automation.strategy.'
484
+ : 'Game stream attached. Read summary and wait for role_assigned; current strategy appears in summary.automation.strategy.'
485
+ : 'Catch-up complete. Read summary, then continue play.';
486
+ const attachedEvents = hasBacklog ? caughtUpEvents : [{ type: 'game_start' }];
487
+ const attachedOut = buildOut(attachedEvents.map((event) => event.type), nextStep, attachedEvents);
488
+ caughtUpEvents = [];
489
+ emit(attachedOut);
490
+ }
491
+
492
+ // Delay buffer: merge rapid-fire wandering-phase events into one notification
493
+ let delayActive = false;
494
+ let delayDeadline = 0;
495
+ const delayBuffer: { triggers: Set<string>; events: GameEvent[] } = {
496
+ triggers: new Set(),
497
+ events: [],
498
+ };
499
+
500
+ while (!opts.signal?.aborted) {
501
+ refreshSessionPath();
502
+
503
+ const triggers: string[] = [];
504
+ const triggeredEvents: GameEvent[] = [];
505
+
506
+ const newEvents = drainNewEvents();
507
+ for (const evt of newEvents) {
508
+ const cls = classifyEvent(evt, youName);
509
+ if (!cls.notable) continue;
510
+ const key = eventKey(evt);
511
+ if (seenKeys.has(key)) continue;
512
+ seenKeys.add(key);
513
+ triggeredEvents.push(evt);
514
+ if (evt.type && !triggers.includes(evt.type)) {
515
+ triggers.push(evt.type);
516
+ }
517
+ }
518
+
519
+ // ── Delay buffer: merge rapid-fire wandering-phase events ──
520
+ // Only active during wandering; meeting-phase events (my_turn, speech, etc.)
521
+ // are not in DELAYABLE_EVENT_CONFIG and won't start a delay.
522
+ if (delayActive) {
523
+ if (Date.now() < delayDeadline) {
524
+ // Still within delay window — buffer everything and wait
525
+ for (const t of triggers) delayBuffer.triggers.add(t);
526
+ for (const e of triggeredEvents) delayBuffer.events.push(e);
527
+ triggers.length = 0;
528
+ triggeredEvents.length = 0;
529
+ } else {
530
+ // Delay expired — flush buffer in front of current batch
531
+ for (const t of delayBuffer.triggers) {
532
+ if (!triggers.includes(t)) triggers.unshift(t);
533
+ }
534
+ triggeredEvents.unshift(...delayBuffer.events);
535
+ delayBuffer.triggers.clear();
536
+ delayBuffer.events.length = 0;
537
+ delayActive = false;
538
+ }
539
+ } else if (triggers.length > 0) {
540
+ // Check if any trigger is delayable; start a delay if so
541
+ let delayMs = 0;
542
+ for (const t of triggers) {
543
+ const ms = resolvedDelays[t];
544
+ if (ms !== undefined && ms > delayMs) delayMs = ms;
545
+ }
546
+ if (delayMs > 0) {
547
+ delayActive = true;
548
+ delayDeadline = Date.now() + delayMs;
549
+ for (const t of triggers) delayBuffer.triggers.add(t);
550
+ for (const e of triggeredEvents) delayBuffer.events.push(e);
551
+ triggers.length = 0;
552
+ triggeredEvents.length = 0;
553
+ }
554
+ }
555
+
556
+ if (triggers.length > 0) {
557
+ fireTrigger(triggers, triggeredEvents);
558
+ if (triggers.includes('game_over') || triggers.includes('user_left_game')) return;
559
+ } else if (!delayActive && heartbeatInterval > 0 && Date.now() - lastEmitMs >= heartbeatInterval) {
560
+ // Idle keepalive — prevents downstream adapters from interpreting a quiet
561
+ // wandering/transit period as a hung subprocess and killing it on their
562
+ // own default timeout (commonly 60s).
563
+ emit(buildOut(
564
+ ['heartbeat'],
565
+ 'Stream is alive; no notable events. Continue waiting — no action required.',
566
+ ));
567
+ }
568
+
569
+ if (opts.signal?.aborted) break;
570
+ await new Promise((r) => setTimeout(r, interval));
571
+ }
572
+ }
573
+
574
+ export interface SnapshotOnceOptions {
575
+ feedPath: string;
576
+ stdout: (line: string) => void;
577
+ }
578
+
579
+ export function snapshotOnce(opts: SnapshotOnceOptions): void {
580
+ if (!existsSync(opts.feedPath)) {
581
+ throw new Error('ccl game runtime is not running. Start it first with `ccl game start`.');
582
+ }
583
+ const summary = readFeedSummary(opts.feedPath);
584
+ opts.stdout(JSON.stringify({
585
+ events: ['snapshot'],
586
+ messages: [formatEventMessage({ type: 'snapshot' })],
587
+ state: shortStateText(summary),
588
+ }) + '\n');
589
+ }
590
+
591
+ export function buildErrorLine(err: any, opts?: { notReadyNextStep?: string }): string {
592
+ const msg = err?.message ?? String(err);
593
+ const notReady = err?.name === 'WatchNotReadyError' || /not ready|feed\.json/i.test(msg);
594
+ const reason = notReady ? 'not_ready' : 'error';
595
+ const event = {
596
+ type: reason,
597
+ message: notReady
598
+ ? (opts?.notReadyNextStep ?? 'Game runtime not running. Run `ccl game start` to begin a new session.')
599
+ : msg,
600
+ };
601
+ return JSON.stringify({
602
+ events: [reason],
603
+ messages: [formatEventMessage(event)],
604
+ state: 'state unavailable',
605
+ error: msg,
606
+ }) + '\n';
607
+ }
608
+
609
+ export function createWatchCommand(): Command {
610
+ const cmd = new Command('watch')
611
+ .description('Stream notable game events as NDJSON. Exits on game_over. For a one-shot snapshot use `ccl peek`.')
612
+ .action(async () => {
613
+ const store = new AuthStore();
614
+ const profile = store.getActive();
615
+ if (!profile) {
616
+ process.stdout.write(JSON.stringify({ exit_reason: ['not_logged_in'], error: 'Not logged in' }) + '\n');
617
+ return;
618
+ }
619
+ const stateDir = getProfileStateDir(profile);
620
+ const feedPath = join(stateDir, 'feed.json');
621
+ const sessionPath = EventStore.latestSessionPath();
622
+ const ctrl = new AbortController();
623
+ process.on('SIGINT', () => ctrl.abort());
624
+ process.on('SIGTERM', () => ctrl.abort());
625
+ let summaryCache: any | null = null;
626
+ let summaryPoll: ReturnType<typeof setInterval> | null = null;
627
+ try {
628
+ const snapshot = await sendOwnerControlRequest(stateDir, 'snapshot');
629
+ if (!snapshot?.ok) {
630
+ throw new WatchNotReadyError(
631
+ 'Game runtime not ready (no active ccl game start owner). Run `ccl game start` to start or recover the game stream.',
632
+ );
633
+ }
634
+ summaryCache = snapshot.summary ?? null;
635
+ summaryPoll = setInterval(() => {
636
+ void sendOwnerControlRequest(stateDir, 'snapshot')
637
+ .then((response) => {
638
+ if (response?.ok) summaryCache = response.summary ?? null;
639
+ })
640
+ .catch(() => {});
641
+ }, 1000);
642
+ await runStreaming({
643
+ feedPath,
644
+ sessionPath,
645
+ getSessionPath: () => EventStore.latestSessionPath(),
646
+ stdout: (s) => process.stdout.write(s),
647
+ signal: ctrl.signal,
648
+ skipFeedWait: true,
649
+ readSummary: () => summaryCache,
650
+ hubReminder: hubReminder(readCachedGamesPlayed()),
651
+ });
652
+ } catch (err: any) {
653
+ process.stdout.write(buildErrorLine(err, {
654
+ notReadyNextStep: 'Run `ccl game start` to start or recover the game stream.',
655
+ }));
656
+ process.exit(1);
657
+ } finally {
658
+ if (summaryPoll) clearInterval(summaryPoll);
659
+ }
660
+ });
661
+ // ── Adapter metadata: streaming mode blocks until game_over; cap at 30min for stuck-process safety ──
662
+ setMeta(cmd, { longRunning: true, timeoutMs: 1_800_000 });
663
+ return cmd;
664
+ }