@myclaw163/clawclaw-cli 0.6.96 → 0.6.100

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 (231) hide show
  1. package/README.md +385 -385
  2. package/package.json +48 -48
  3. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -50
  4. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -51
  5. package/personas//346/227/240/344/272/272/350/256/276.md +1 -1
  6. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -48
  7. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -51
  8. package/scripts/check-skill-command-surface.mjs +118 -118
  9. package/scripts/check_monitor.cjs +435 -435
  10. package/scripts/check_monitor.test.mjs +212 -212
  11. package/scripts/enable_ccl_permissions.cjs +147 -147
  12. package/scripts/enable_ccl_permissions.test.mjs +132 -132
  13. package/scripts/enable_monitor.cjs +677 -677
  14. package/scripts/enable_monitor.test.mjs +201 -201
  15. package/scripts/find-hide-spots.py +157 -157
  16. package/scripts/postinstall.mjs +20 -20
  17. package/scripts/sync-bundled-skill.mjs +254 -254
  18. package/scripts/sync-bundled-skill.test.mjs +152 -152
  19. package/skills/clawclaw/SKILL.md +290 -274
  20. package/skills/clawclaw/references/CHATTERBOX.md +142 -142
  21. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  22. package/skills/clawclaw/references/COMMANDS.md +177 -165
  23. package/skills/clawclaw/references/GAME-MECHANICS.md +190 -190
  24. package/skills/clawclaw/references/HUB.md +48 -48
  25. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  26. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  27. package/skills/clawclaw/references/STREAM.md +77 -74
  28. package/skills/clawclaw/references/TACTICS.md +65 -65
  29. package/src/assets/clawclaw-ascii-map.txt +40 -40
  30. package/src/cli.ts +113 -113
  31. package/src/commands/_schema.ts +124 -124
  32. package/src/commands/account.test.ts +332 -332
  33. package/src/commands/account.ts +315 -315
  34. package/src/commands/competition.ts +42 -42
  35. package/src/commands/config.ts +30 -30
  36. package/src/commands/data.test.ts +33 -33
  37. package/src/commands/data.ts +22 -22
  38. package/src/commands/do.test.ts +117 -91
  39. package/src/commands/do.ts +191 -130
  40. package/src/commands/events.test.ts +142 -124
  41. package/src/commands/events.ts +268 -262
  42. package/src/commands/game-map.test.ts +28 -28
  43. package/src/commands/game-monitor-status.test.ts +58 -58
  44. package/src/commands/game-start-plan.test.ts +252 -94
  45. package/src/commands/game.ts +1892 -1286
  46. package/src/commands/history-player.test.ts +105 -102
  47. package/src/commands/history.ts +573 -573
  48. package/src/commands/hub.test.ts +113 -113
  49. package/src/commands/hub.ts +244 -244
  50. package/src/commands/knowledge.test.ts +13 -13
  51. package/src/commands/knowledge.ts +176 -176
  52. package/src/commands/load.test.ts +65 -65
  53. package/src/commands/load.ts +22 -22
  54. package/src/commands/meeting-history.test.ts +106 -106
  55. package/src/commands/memory.ts +40 -40
  56. package/src/commands/peek.ts +45 -45
  57. package/src/commands/persona.ts +62 -62
  58. package/src/commands/setup/codex.ts +266 -266
  59. package/src/commands/setup/hermes.test.ts +96 -96
  60. package/src/commands/setup/hermes.ts +76 -76
  61. package/src/commands/setup/index.ts +13 -13
  62. package/src/commands/setup/openclaw.test.ts +114 -114
  63. package/src/commands/setup/openclaw.ts +147 -147
  64. package/src/commands/skill.ts +128 -128
  65. package/src/commands/state.ts +46 -46
  66. package/src/commands/strategy.test.ts +153 -153
  67. package/src/commands/strategy.ts +194 -194
  68. package/src/commands/upgrade.test.ts +82 -82
  69. package/src/commands/upgrade.ts +148 -148
  70. package/src/commands/watch.test.ts +1313 -1041
  71. package/src/commands/watch.ts +824 -664
  72. package/src/lib/account-guidance.test.ts +32 -32
  73. package/src/lib/account-guidance.ts +62 -62
  74. package/src/lib/auth.test.ts +116 -116
  75. package/src/lib/auth.ts +189 -189
  76. package/src/lib/command-meta.ts +37 -37
  77. package/src/lib/competition.ts +79 -79
  78. package/src/lib/game-client.test.ts +82 -82
  79. package/src/lib/game-client.ts +443 -409
  80. package/src/lib/game-context.ts +92 -92
  81. package/src/lib/host-config-patcher.test.ts +130 -130
  82. package/src/lib/host-config-patcher.ts +151 -151
  83. package/src/lib/http-keepalive.ts +15 -15
  84. package/src/lib/http-transport.test.ts +61 -61
  85. package/src/lib/http-transport.ts +118 -118
  86. package/src/lib/hub-client.test.ts +57 -57
  87. package/src/lib/hub-client.ts +88 -88
  88. package/src/lib/hub-install.test.ts +139 -139
  89. package/src/lib/hub-install.ts +198 -198
  90. package/src/lib/hub-reminder.ts +81 -81
  91. package/src/lib/hub-unzip.test.ts +69 -69
  92. package/src/lib/hub-unzip.ts +62 -62
  93. package/src/lib/init-command.test.ts +75 -75
  94. package/src/lib/init-command.ts +130 -130
  95. package/src/lib/knowledge-store.test.ts +170 -170
  96. package/src/lib/knowledge-store.ts +369 -369
  97. package/src/lib/load-context.test.ts +62 -62
  98. package/src/lib/load-context.ts +49 -49
  99. package/src/lib/match-state.test.ts +134 -134
  100. package/src/lib/match-state.ts +94 -94
  101. package/src/lib/normalize.ts +42 -42
  102. package/src/lib/persona.test.ts +84 -84
  103. package/src/lib/persona.ts +120 -120
  104. package/src/lib/room.test.ts +74 -0
  105. package/src/lib/room.ts +129 -0
  106. package/src/lib/server-registry.test.ts +54 -0
  107. package/src/lib/server-registry.ts +185 -152
  108. package/src/lib/skill-version.test.ts +48 -48
  109. package/src/lib/skill-version.ts +19 -19
  110. package/src/lib/strategy-export.test.ts +240 -240
  111. package/src/lib/strategy-export.ts +247 -247
  112. package/src/lib/user-data.test.ts +97 -97
  113. package/src/lib/user-data.ts +374 -374
  114. package/src/lib/workspace-argv.test.ts +49 -49
  115. package/src/lib/workspace-argv.ts +44 -44
  116. package/src/perception/player-history-store.test.ts +177 -87
  117. package/src/perception/player-history-store.ts +262 -194
  118. package/src/pipeline/event-format.test.ts +307 -247
  119. package/src/pipeline/event-format.ts +595 -507
  120. package/src/pipeline/event-hints.ts +204 -195
  121. package/src/pipeline/event-store.test.ts +28 -28
  122. package/src/pipeline/event-store.ts +193 -193
  123. package/src/pipeline/pipeline.ts +35 -35
  124. package/src/pipeline/player-projection.test.ts +168 -168
  125. package/src/pipeline/player-projection.ts +370 -370
  126. package/src/runtime/auto-upgrade.test.ts +66 -66
  127. package/src/runtime/auto-upgrade.ts +31 -31
  128. package/src/runtime/event-daemon.test.ts +268 -225
  129. package/src/runtime/event-daemon.ts +531 -527
  130. package/src/runtime/owner-control.ts +150 -150
  131. package/src/runtime/raw-ws-log.test.ts +33 -33
  132. package/src/runtime/raw-ws-log.ts +32 -32
  133. package/src/runtime/room-lobby-runtime.test.ts +95 -0
  134. package/src/runtime/room-lobby-runtime.ts +367 -0
  135. package/src/runtime/runtime-logger.ts +107 -107
  136. package/src/runtime/ws-client.test.ts +169 -169
  137. package/src/runtime/ws-client.ts +280 -280
  138. package/src/sdk/action.ts +155 -155
  139. package/src/sdk/index.ts +112 -112
  140. package/src/sdk/types.ts +163 -163
  141. package/src/strategies/avoid-lone.ts +14 -14
  142. package/src/strategies/avoid-players.knowledge.md +19 -19
  143. package/src/strategies/avoid-players.ts +18 -18
  144. package/src/strategies/corpse-patrol.ts +21 -21
  145. package/src/strategies/crab-sabotage.ts +24 -24
  146. package/src/strategies/custom-module.test.ts +270 -270
  147. package/src/strategies/find-player.ts +19 -19
  148. package/src/strategies/game-utils.test.ts +242 -242
  149. package/src/strategies/game-utils.ts +853 -853
  150. package/src/strategies/goals/anchor-linger.ts +77 -77
  151. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  152. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  153. package/src/strategies/goals/avoid-players-top.ts +121 -121
  154. package/src/strategies/goals/conversation-goal.ts +51 -51
  155. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  156. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  157. package/src/strategies/goals/crab-sabotage-top.ts +226 -226
  158. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  159. package/src/strategies/goals/find-player-top.ts +93 -93
  160. package/src/strategies/goals/flee-players-goal.ts +53 -53
  161. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  162. package/src/strategies/goals/goal-manager.ts +41 -41
  163. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  164. package/src/strategies/goals/goal.ts +28 -28
  165. package/src/strategies/goals/hide-top.ts +197 -197
  166. package/src/strategies/goals/keep-away-goal.ts +221 -221
  167. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  168. package/src/strategies/goals/kill-lone-top.ts +160 -160
  169. package/src/strategies/goals/kill-target-goal.ts +59 -59
  170. package/src/strategies/goals/kill-target-top.ts +109 -109
  171. package/src/strategies/goals/leaf-goal.ts +27 -27
  172. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  173. package/src/strategies/goals/lone-kill-core.ts +82 -82
  174. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  175. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  176. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  177. package/src/strategies/goals/move-room-goal.ts +60 -60
  178. package/src/strategies/goals/normal-shrimp-top.test.ts +97 -97
  179. package/src/strategies/goals/normal-shrimp-top.ts +248 -248
  180. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  181. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  182. package/src/strategies/goals/patrol-top.ts +57 -57
  183. package/src/strategies/goals/report-patrol-top.ts +86 -86
  184. package/src/strategies/goals/safe-task-goal.ts +102 -102
  185. package/src/strategies/goals/social-task-top.ts +161 -161
  186. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  187. package/src/strategies/goals/task-only-top.ts +57 -57
  188. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  189. package/src/strategies/goals/task-report-top.ts +57 -57
  190. package/src/strategies/goals/wander-task-goal.ts +33 -33
  191. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  192. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  193. package/src/strategies/greeting.ts +53 -53
  194. package/src/strategies/hide-spots.ts +59 -59
  195. package/src/strategies/hide.ts +26 -26
  196. package/src/strategies/kill-frenzy.ts +15 -15
  197. package/src/strategies/kill-lone.knowledge.md +17 -17
  198. package/src/strategies/kill-lone.ts +16 -16
  199. package/src/strategies/kill-target.ts +21 -21
  200. package/src/strategies/knowledge-contract.ts +85 -85
  201. package/src/strategies/loader.test.ts +678 -678
  202. package/src/strategies/loader.ts +181 -181
  203. package/src/strategies/lone-kill-task.ts +24 -24
  204. package/src/strategies/meeting-gate.test.ts +59 -59
  205. package/src/strategies/meeting-gate.ts +28 -28
  206. package/src/strategies/move-room.ts +18 -18
  207. package/src/strategies/new-events-backfill.ts +98 -98
  208. package/src/strategies/off-route-points.ts +105 -105
  209. package/src/strategies/paradise-fish.knowledge.md +19 -19
  210. package/src/strategies/paradise-fish.ts +24 -24
  211. package/src/strategies/pathfind/distance-field.ts +150 -150
  212. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  213. package/src/strategies/pathfind/escape-planner.ts +355 -355
  214. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  215. package/src/strategies/patrol.ts +14 -14
  216. package/src/strategies/player-targets.ts +13 -13
  217. package/src/strategies/report-patrol.ts +14 -14
  218. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  219. package/src/strategies/shrimp-memory.ts +24 -24
  220. package/src/strategies/social-task.test.ts +28 -28
  221. package/src/strategies/social-task.ts +52 -52
  222. package/src/strategies/spawn.ts +82 -82
  223. package/src/strategies/speech-module.ts +123 -123
  224. package/src/strategies/strategy-loop.test.ts +15 -15
  225. package/src/strategies/strategy-loop.ts +748 -748
  226. package/src/strategies/task-kill-report.ts +20 -20
  227. package/src/strategies/task-only.ts +14 -14
  228. package/src/strategies/task-report.ts +21 -21
  229. package/src/strategies/types.ts +155 -155
  230. package/src/strategies/warrior-memory.knowledge.md +21 -21
  231. package/src/strategies/warrior-memory.ts +19 -19
@@ -1,664 +1,824 @@
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
- }
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 = 30_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
+ // Room-mode lobby events
89
+ 'room.snapshot': { priority: 50 },
90
+ 'room.member_joined': { priority: 50 },
91
+ 'room.member_left': { priority: 50 },
92
+ 'room.owner_changed': { priority: 50 },
93
+ 'room.full': { priority: 60 },
94
+ 'room.chat': { priority: 50 },
95
+ 'room.game_starting': { priority: 80 },
96
+ 'room.game_started': { priority: 90 },
97
+ 'room.game_start_failed': { priority: 80 },
98
+ 'room.game_finished': { priority: 80 },
99
+ 'room.cooldown': { priority: 60 },
100
+ 'room.self_left': { priority: 80 },
101
+ room_self_left: { priority: 80 },
102
+ room_ready_to_start: { priority: 90 },
103
+ room_returning_to_lobby: { priority: 60 },
104
+ room_ping_timeout: { priority: 60 },
105
+
106
+ // Strategy → agent real-time briefing (the automation explaining a decisive
107
+ // autonomous move, e.g. self-reporting its own kill). Ranked above ambient
108
+ // wander events so it leads the events[] list.
109
+ strategy_alert: { priority: 60 },
110
+ };
111
+
112
+ export const NOTABLE_EVENT_TYPES = new Set(Object.keys(MONITOR_EVENT_CONFIG));
113
+
114
+ /** Events whose trigger should be delayed to allow merging with nearby events.
115
+ * Key = event type, Value = delay in milliseconds.
116
+ * During the delay window, all incoming events (both delayable and non-delayable)
117
+ * are buffered and emitted together when the timer expires.
118
+ * Only one delay runs at a time — subsequent delayable events do NOT reset the timer. */
119
+ export const DELAYABLE_EVENT_CONFIG: Record<string, number> = {
120
+ kill: 2000,
121
+ emergency_started: 2000,
122
+ corpse_spotted: 2000,
123
+ };
124
+
125
+ export interface GameEvent {
126
+ type: string;
127
+ tick?: number;
128
+ ts?: string;
129
+ [key: string]: any;
130
+ }
131
+
132
+ export function eventKey(evt: GameEvent): string {
133
+ const type = evt.type ?? '?';
134
+ const tick = evt.tick ?? 0;
135
+ const roomDiscriminator = typeof type === 'string' && (type.startsWith('room.') || type.startsWith('room_'))
136
+ ? [
137
+ evt.room_code,
138
+ evt.status,
139
+ evt.agent_id,
140
+ evt.name,
141
+ evt.seat,
142
+ evt.content,
143
+ evt.reason,
144
+ Array.isArray(evt.members) ? evt.members.length : evt.member_count,
145
+ evt.ts,
146
+ ]
147
+ : [];
148
+ const parts = [
149
+ evt.actor_name,
150
+ evt.spotted_name,
151
+ evt.killer_name,
152
+ evt.result_target,
153
+ evt.target_name,
154
+ evt.corpse_name,
155
+ evt.task_name,
156
+ ...roomDiscriminator,
157
+ ].filter(Boolean);
158
+ const disc = parts.length > 0 ? parts.join('|') : '';
159
+ return `${type}@${tick}#${disc}`;
160
+ }
161
+
162
+ export interface EventClassification {
163
+ notable: boolean;
164
+ }
165
+
166
+ export function classifyEvent(evt: GameEvent, _youName: string | null = null): EventClassification {
167
+ const notable = !!(evt.type && NOTABLE_EVENT_TYPES.has(evt.type));
168
+ return { notable };
169
+ }
170
+
171
+ function monitorEventPriority(event: GameEvent): number {
172
+ return MONITOR_EVENT_CONFIG[event.type]?.priority ?? DEFAULT_MONITOR_EVENT_PRIORITY;
173
+ }
174
+
175
+ interface RouteRule {
176
+ reason: string;
177
+ match: (triggers: string[]) => boolean;
178
+ nextStep: string;
179
+ }
180
+
181
+ interface RouteContext {
182
+ summary?: any | null;
183
+ events?: Array<Record<string, any>>;
184
+ }
185
+
186
+ const ROUTING_RULES: RouteRule[] = [
187
+ { 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.' },
188
+ { reason: 'role_assigned', match: (t) => t.includes('role_assigned'), nextStep: 'Tell user your role, faction, win condition, and first plan.' },
189
+ { 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.' },
190
+ { 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.' },
191
+ { 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.' },
192
+ { 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.' },
193
+ { 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.` },
194
+ { reason: 'room_ready_to_start', match: (t) => t.includes('room_ready_to_start') || t.includes('room.full'), nextStep: 'Room is full. Ask the user whether to start now before running `ccl game start-room`.' },
195
+ { reason: 'room_game_started', match: (t) => t.includes('room.game_started'), nextStep: 'Room match is starting. Stay attached; the runtime will switch to the GameServer stream.' },
196
+ { reason: 'room_game_finished', match: (t) => t.includes('room.game_finished'), nextStep: '上一轮房间对局已结束;如果你提前回房间等待,现在告知用户上局已结束,并继续留在房间。' },
197
+ { reason: 'room_self_left', match: (t) => t.includes('room.self_left') || t.includes('room_self_left'), nextStep: 'The user left the room from the web page, or the current CLI quit command has left the room. Stop the room flow and do not create or join another room unless the user asks.' },
198
+ { 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.' },
199
+ { 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.' },
200
+ ];
201
+
202
+ const DEFAULT_NEXT_STEP = 'React to summary fields. No relaunch needed — the stream stays attached.';
203
+ const ROOM_GAME_OVER_NEXT_STEP = 'This room match round has ended. Wait for the room stream to resume; do not start normal matchmaking.';
204
+
205
+ function hasRoomGameContext(ctx?: RouteContext): boolean {
206
+ if (!ctx) return false;
207
+ if (ctx.summary?.game?.mode === 'room' || ctx.summary?.game_mode === 'room') return true;
208
+ return (ctx.events ?? []).some((event) => event.game_mode === 'room');
209
+ }
210
+
211
+ function routeTriggers(triggers: string[], ctx?: RouteContext): { exitReason: string; nextStep: string } {
212
+ if (triggers.includes('game_over') && hasRoomGameContext(ctx)) {
213
+ return {
214
+ exitReason: 'game_over',
215
+ nextStep: ROOM_GAME_OVER_NEXT_STEP,
216
+ };
217
+ }
218
+ const rule = ROUTING_RULES.find((r) => r.match(triggers));
219
+ return {
220
+ exitReason: rule?.reason ?? triggers[0],
221
+ nextStep: rule?.nextStep ?? DEFAULT_NEXT_STEP,
222
+ };
223
+ }
224
+
225
+ export function nextStepFor(reason: string, ctx?: RouteContext): string {
226
+ return routeTriggers([reason], ctx).nextStep;
227
+ }
228
+
229
+ export function nextStepForTriggers(triggers: string[], ctx?: RouteContext): string {
230
+ return routeTriggers(triggers, ctx).nextStep;
231
+ }
232
+
233
+ export function sortEventsForMonitor(events: GameEvent[]): GameEvent[] {
234
+ return events
235
+ .map((event, index) => ({
236
+ event,
237
+ index,
238
+ priority: monitorEventPriority(event),
239
+ }))
240
+ .sort((a, b) => (b.priority - a.priority) || (a.index - b.index))
241
+ .map(({ event }) => event);
242
+ }
243
+
244
+ function readSeatMapForMonitor(sessionPath: string | null): Record<string, number> {
245
+ if (!sessionPath) return {};
246
+ try {
247
+ return PlayerHistoryStore.forSession(sessionPath).read()?.seats ?? {};
248
+ } catch {
249
+ return {};
250
+ }
251
+ }
252
+
253
+ function cleanObject<T extends Record<string, any>>(obj: T): T {
254
+ for (const key of Object.keys(obj)) {
255
+ if (obj[key] === undefined) delete obj[key];
256
+ }
257
+ return obj;
258
+ }
259
+
260
+ export function compactEventForMonitor(event: GameEvent): Record<string, any> {
261
+ return compactEventForEvents(event);
262
+ }
263
+
264
+ export function summarizeFeed(feed: any): any | null {
265
+ if (!feed || typeof feed !== 'object') return null;
266
+ const summary: any = {
267
+ phase: feed.phase,
268
+ you: {
269
+ name: feed.you?.name,
270
+ seat: feed.you?.seat,
271
+ role: feed.you?.role,
272
+ role_display: feed.you?.role_display,
273
+ faction: feed.you?.faction,
274
+ alive: feed.you?.alive,
275
+ x: feed.you?.x,
276
+ y: feed.you?.y,
277
+ currently_moving: feed.you?.currently_moving,
278
+ doing_task: feed.you?.doing_task,
279
+ kill_cooldown_secs: feed.you?.kill_cooldown_secs,
280
+ kills_remaining: feed.you?.kills_remaining,
281
+ },
282
+ game: feed.game,
283
+ urgent: feed.urgent,
284
+ meeting: feed.meeting,
285
+ };
286
+ if (feed.automation) summary.automation = feed.automation;
287
+ if (typeof feed.phase === 'string' && feed.phase.startsWith('room_')) {
288
+ summary.room = feed.room;
289
+ }
290
+ return summary;
291
+ }
292
+
293
+ export function readFeedSummary(feedPath: string): any | null {
294
+ try {
295
+ const feed = JSON.parse(readFileSync(feedPath, 'utf8'));
296
+ return summarizeFeed(feed);
297
+ } catch {
298
+ return null;
299
+ }
300
+ }
301
+
302
+ export function compactSummaryForMonitor(summary: any | null, triggers: string[]): any | null {
303
+ if (!summary || summary.phase !== 'meeting') return summary;
304
+ const oldMeeting = summary.meeting ?? {};
305
+ const oldYou = summary.you ?? {};
306
+ const isVotePhase = triggers.includes('vote_phase_start')
307
+ || (!triggers.includes('speech_your_turn') && oldMeeting.sub_phase === 'vote');
308
+ const meeting: Record<string, any> = {
309
+ caller: oldMeeting.caller,
310
+ sub_phase: triggers.includes('vote_phase_start') ? 'vote' : oldMeeting.sub_phase,
311
+ alive_players: oldMeeting.alive_players,
312
+ };
313
+ if (triggers.includes('speech_your_turn')) {
314
+ meeting.sub_phase = 'speech';
315
+ meeting.current_speaker = oldYou.name;
316
+ meeting.is_my_turn = true;
317
+ } else if (!isVotePhase) {
318
+ meeting.current_speaker = oldMeeting.current_speaker;
319
+ meeting.is_my_turn = oldMeeting.is_my_turn;
320
+ }
321
+ if (isVotePhase) {
322
+ meeting.votes_submitted_count = Array.isArray(oldMeeting.votes_submitted)
323
+ ? oldMeeting.votes_submitted.length
324
+ : 0;
325
+ }
326
+ return cleanObject({
327
+ phase: summary.phase,
328
+ you: cleanObject({
329
+ name: oldYou.name,
330
+ role: oldYou.role,
331
+ faction: oldYou.faction,
332
+ }),
333
+ game: summary.game,
334
+ meeting: cleanObject(meeting),
335
+ automation: summary.automation,
336
+ });
337
+ }
338
+
339
+ function roomHeartbeatMessage(summary: any | null): string | null {
340
+ if (!summary || typeof summary.phase !== 'string' || !summary.phase.startsWith('room_')) return null;
341
+ const room = summary.room ?? {};
342
+ const label = typeof room.room_code === 'string' && room.room_code.length > 0
343
+ ? `房间 ${room.room_code}`
344
+ : '房间';
345
+ const count = typeof room.member_count === 'number'
346
+ ? room.member_count
347
+ : Array.isArray(room.members)
348
+ ? room.members.length
349
+ : undefined;
350
+ const countText = count === undefined ? '?/10' : `${count}/10`;
351
+ if (room.status === 'playing' || summary.phase === 'room_playing') {
352
+ return `${label} 上一轮对局仍在进行,正在等待其他玩家结束。`;
353
+ }
354
+ if (room.status === 'starting' || summary.phase === 'room_starting') {
355
+ return `${label} 对局正在开始,继续等待。`;
356
+ }
357
+ if (count !== undefined && count >= 10) {
358
+ return `${label} 当前 ${countText} 人,等待房主操作。`;
359
+ }
360
+ return `${label} 当前 ${countText} 人,正在等待更多玩家加入。`;
361
+ }
362
+
363
+ export interface RunStreamingOptions {
364
+ feedPath: string;
365
+ sessionPath: string | null;
366
+ readSummary?: () => any | null;
367
+ /** Optional dynamic resolver — called each poll so the stream can follow session rotation across games. */
368
+ getSessionPath?: () => string | null;
369
+ stdout: (line: string) => void;
370
+ signal?: AbortSignal;
371
+ skipFeedWait?: boolean;
372
+ pollIntervalMs?: number;
373
+ /** 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. */
374
+ heartbeatIntervalMs?: number;
375
+ /** Max ms to wait for feed.json when launching alongside `game start`. Default 30s. */
376
+ runtimeWaitMs?: number;
377
+ /**
378
+ * Per-event-type delay overrides for the delay buffer (see DELAYABLE_EVENT_CONFIG).
379
+ * Pass `{ kill: 0 }` to disable the kill delay in tests.
380
+ * Values from DELAYABLE_EVENT_CONFIG are used for any type not overridden here.
381
+ */
382
+ delayableEventMs?: Record<string, number>;
383
+ /**
384
+ * Event types to exclude from the initial `caught_up` backlog (useful when the
385
+ * caller already emitted them live before chaining into runStreaming, e.g.
386
+ * `ccl game start` emits `match_waiting` / `match_timeout` during its polling
387
+ * phase). Does NOT affect ongoing event tailing — only the one-time pre-attach
388
+ * backlog drain.
389
+ */
390
+ skipBacklogTypes?: string[];
391
+ /**
392
+ * Emit a first `game_start` beat even when no backlog is present. `ccl game start`
393
+ * uses this to tell the agent the stream is attached without carrying a huge
394
+ * `initial_payload`.
395
+ */
396
+ emitGameStart?: boolean;
397
+ /**
398
+ * On intentional stream handoff, drain already-written events once more before
399
+ * returning so the next WS stage does not inherit them as backlog.
400
+ */
401
+ finalDrainOnAbort?: boolean | (() => boolean);
402
+ /** Max ms to wait for final written events during a handoff. Default 500ms. */
403
+ finalDrainTimeoutMs?: number;
404
+ /**
405
+ * When set, attached to the `game_over` emission (as a `hub_reminder` field
406
+ * and appended to `next_step`) so the agent sees the nudge in the same beat it
407
+ * starts the post-game debrief. Callers compute it via `hubReminder()`; pass
408
+ * nothing once the account has adopted a hub or custom strategy.
409
+ */
410
+ hubReminder?: string;
411
+ }
412
+
413
+ export async function runStreaming(opts: RunStreamingOptions): Promise<void> {
414
+ if (!opts.skipFeedWait) {
415
+ const feedReady = await waitForFeed(opts.feedPath, {
416
+ signal: opts.signal,
417
+ timeoutMs: opts.runtimeWaitMs ?? RUNTIME_WAIT_MS,
418
+ pollMs: opts.pollIntervalMs ?? POLL_INTERVAL_MS,
419
+ });
420
+ if (!feedReady) {
421
+ throw new WatchNotReadyError(
422
+ 'Game runtime not ready (no feed.json). Run `ccl game start` to start or recover the game stream.',
423
+ );
424
+ }
425
+ }
426
+ const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;
427
+ const heartbeatInterval = opts.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
428
+ const resolvedDelays: Record<string, number> = { ...DELAYABLE_EVENT_CONFIG, ...(opts.delayableEventMs ?? {}) };
429
+ let lastEmitMs = Date.now();
430
+ const emit = (obj: any): void => {
431
+ opts.stdout(JSON.stringify(obj) + '\n');
432
+ lastEmitMs = Date.now();
433
+ };
434
+
435
+ // Initial player name from owner snapshot or legacy feed file (best-effort).
436
+ let youName: string | null = null;
437
+ try {
438
+ youName = opts.readSummary?.()?.you?.name
439
+ ?? JSON.parse(readFileSync(opts.feedPath, 'utf8'))?.you?.name
440
+ ?? null;
441
+ } catch {}
442
+
443
+ // Tail state for the .jsonl
444
+ const seenKeys = new Set<string>();
445
+ let filePos = 0;
446
+ let fileIno = 0;
447
+ let lineBuffer = '';
448
+ let currentSessionPath: string | null = opts.sessionPath;
449
+
450
+ if (currentSessionPath && existsSync(currentSessionPath)) {
451
+ filePos = 0;
452
+ fileIno = statSync(currentSessionPath).ino;
453
+ }
454
+
455
+ // Cross-game session rotation: the runtime may create a new events.jsonl when a new
456
+ // game starts. If the caller provided a dynamic resolver, poll it and switch
457
+ // tail state to the new file. Without this, the stream would silently follow the
458
+ // previous game's file forever and look like a huge event delay.
459
+ const refreshSessionPath = (): void => {
460
+ if (!opts.getSessionPath) return;
461
+ const latest = opts.getSessionPath();
462
+ if (!latest || latest === currentSessionPath) return;
463
+ currentSessionPath = latest;
464
+ filePos = 0;
465
+ lineBuffer = '';
466
+ try { fileIno = existsSync(latest) ? statSync(latest).ino : 0; } catch { fileIno = 0; }
467
+ };
468
+
469
+ const drainNewEvents = (): GameEvent[] => {
470
+ if (!currentSessionPath || !existsSync(currentSessionPath)) return [];
471
+ let stat;
472
+ try { stat = statSync(currentSessionPath); } catch { return []; }
473
+ if (stat.ino !== fileIno || stat.size < filePos) {
474
+ filePos = 0; fileIno = stat.ino; lineBuffer = '';
475
+ }
476
+ if (stat.size <= filePos) return [];
477
+ let fd: number;
478
+ try { fd = openSync(currentSessionPath, 'r'); } catch { return []; }
479
+ const buf = Buffer.alloc(stat.size - filePos);
480
+ readSync(fd, buf, 0, buf.length, filePos);
481
+ closeSync(fd);
482
+ filePos = stat.size;
483
+ lineBuffer += buf.toString('utf8');
484
+ const lastNl = lineBuffer.lastIndexOf('\n');
485
+ if (lastNl < 0) return [];
486
+ const chunk = lineBuffer.slice(0, lastNl);
487
+ lineBuffer = lineBuffer.slice(lastNl + 1);
488
+ const events: GameEvent[] = [];
489
+ for (const line of chunk.split('\n')) {
490
+ if (!line) continue;
491
+ try {
492
+ const evt = JSON.parse(line);
493
+ if (!isLocalControlEvent(evt)) events.push(evt);
494
+ for (const nested of extractNewEvents(evt) as GameEvent[]) {
495
+ if (!isLocalControlEvent(nested)) events.push(nested);
496
+ }
497
+ } catch {}
498
+ }
499
+ return events;
500
+ };
501
+
502
+ // Pre-attach backlog: drain once, classify, hold for first emit.
503
+ const backlogEvents = drainNewEvents();
504
+ const skipSet = new Set(opts.skipBacklogTypes ?? []);
505
+ const backlogNotable = backlogEvents.filter((e) => {
506
+ if (e.type && skipSet.has(e.type as string)) return false;
507
+ return classifyEvent(e, youName).notable;
508
+ });
509
+ let caughtUpEvents: GameEvent[] = backlogNotable.slice(-20);
510
+ for (const e of backlogEvents) seenKeys.add(eventKey(e));
511
+
512
+ const buildOut = (
513
+ triggers: string[],
514
+ nextStep: string,
515
+ events: GameEvent[] = [],
516
+ ): any => {
517
+ const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
518
+ const summary = compactSummaryForMonitor(rawSummary, triggers);
519
+ // Server pushes `meeting_briefing` without `speech_order` (that field only lives in
520
+ // meeting state, which the runtime projects onto the owner snapshot).
521
+ // Inject it onto the briefing event here so consumers can read it from events[]
522
+ // directly. Guarded by caller match so a stale speech_order from a previous
523
+ // meeting isn't ever attached.
524
+ const enrichMeetingBriefing = (e: GameEvent): GameEvent => {
525
+ if (e.type !== 'meeting_briefing') return e;
526
+ if (e.speech_order) return e;
527
+ const so = rawSummary?.meeting?.speech_order;
528
+ if (!Array.isArray(so)) return e;
529
+ const sumCaller = rawSummary?.meeting?.caller;
530
+ if (sumCaller && e.caller && sumCaller !== e.caller) return e;
531
+ return { ...e, speech_order: so };
532
+ };
533
+ const heartbeatMessage = triggers.length === 1 && triggers[0] === 'heartbeat'
534
+ ? roomHeartbeatMessage(summary)
535
+ : null;
536
+ const sourceEvents: GameEvent[] = events.length > 0
537
+ ? sortEventsForMonitor(events).map(enrichMeetingBriefing)
538
+ : heartbeatMessage
539
+ ? [{ type: 'heartbeat', message: heartbeatMessage }]
540
+ : triggers.map((type) => ({ type }));
541
+ const gameMode = sourceEvents.find(
542
+ (event) => event.game_mode === 'match' || event.game_mode === 'competition' || event.game_mode === 'room',
543
+ )?.game_mode;
544
+ const context = {
545
+ summary,
546
+ seats: readSeatMapForMonitor(currentSessionPath),
547
+ maxTextLength: 90,
548
+ };
549
+ return {
550
+ events: sourceEvents.map((event) => event.type),
551
+ ...(gameMode ? { game_mode: gameMode } : {}),
552
+ messages: sourceEvents.map((event) => formatEventMessage(event, context)),
553
+ state: shortStateText(summary),
554
+ ...(nextStep === ROOM_GAME_OVER_NEXT_STEP ? { next_step: nextStep } : {}),
555
+ };
556
+ };
557
+
558
+ const fireTrigger = (
559
+ triggers: string[],
560
+ triggeredEvents: GameEvent[],
561
+ ): void => {
562
+ if (triggers.length === 0) return;
563
+ const routeEvents = triggeredEvents.slice(-10);
564
+ const rawSummary = opts.readSummary?.() ?? readFeedSummary(opts.feedPath);
565
+ const { nextStep } = routeTriggers(triggers, { summary: rawSummary, events: routeEvents });
566
+ const out = buildOut(triggers, nextStep, routeEvents);
567
+ if (opts.hubReminder && triggers.includes('game_over')) {
568
+ out.hub_reminder = opts.hubReminder;
569
+ }
570
+ emit(out);
571
+ };
572
+
573
+ const collectNotableEvents = (
574
+ events: GameEvent[],
575
+ triggers: string[],
576
+ triggeredEvents: GameEvent[],
577
+ ): void => {
578
+ for (const evt of events) {
579
+ const cls = classifyEvent(evt, youName);
580
+ if (!cls.notable) continue;
581
+ const key = eventKey(evt);
582
+ if (seenKeys.has(key)) continue;
583
+ seenKeys.add(key);
584
+ triggeredEvents.push(evt);
585
+ if (evt.type && !triggers.includes(evt.type)) {
586
+ triggers.push(evt.type);
587
+ }
588
+ }
589
+ };
590
+
591
+ const shouldFinalDrainOnAbort = (): boolean => {
592
+ if (typeof opts.finalDrainOnAbort === 'function') return opts.finalDrainOnAbort();
593
+ return opts.finalDrainOnAbort === true;
594
+ };
595
+
596
+ const waitForNextPoll = async (): Promise<void> => {
597
+ await new Promise<void>((resolve) => {
598
+ if (opts.signal?.aborted) {
599
+ resolve();
600
+ return;
601
+ }
602
+ let done = false;
603
+ let timer: ReturnType<typeof setTimeout> | null = null;
604
+ const finish = (): void => {
605
+ if (done) return;
606
+ done = true;
607
+ if (timer) clearTimeout(timer);
608
+ opts.signal?.removeEventListener('abort', finish);
609
+ resolve();
610
+ };
611
+ timer = setTimeout(finish, interval);
612
+ opts.signal?.addEventListener('abort', finish, { once: true });
613
+ });
614
+ };
615
+
616
+ const flushDelayBuffer = (triggers: string[], triggeredEvents: GameEvent[]): void => {
617
+ for (const t of delayBuffer.triggers) {
618
+ if (!triggers.includes(t)) triggers.push(t);
619
+ }
620
+ triggeredEvents.push(...delayBuffer.events);
621
+ delayBuffer.triggers.clear();
622
+ delayBuffer.events.length = 0;
623
+ delayActive = false;
624
+ };
625
+
626
+ const finalDrain = async (): Promise<void> => {
627
+ if (!shouldFinalDrainOnAbort()) return;
628
+ const deadline = Date.now() + (opts.finalDrainTimeoutMs ?? 500);
629
+ while (Date.now() <= deadline) {
630
+ refreshSessionPath();
631
+ const triggers: string[] = [];
632
+ const triggeredEvents: GameEvent[] = [];
633
+ if (delayBuffer.triggers.size > 0 || delayBuffer.events.length > 0) {
634
+ flushDelayBuffer(triggers, triggeredEvents);
635
+ }
636
+ collectNotableEvents(drainNewEvents(), triggers, triggeredEvents);
637
+ if (triggers.length > 0) {
638
+ fireTrigger(triggers, triggeredEvents);
639
+ return;
640
+ }
641
+ const remaining = deadline - Date.now();
642
+ if (remaining <= 0) break;
643
+ await new Promise((r) => setTimeout(r, Math.min(20, remaining)));
644
+ }
645
+ };
646
+
647
+ // Always emit an attached first beat when there is a pre-attach backlog OR
648
+ // the caller explicitly requests one.
649
+ if (caughtUpEvents.length > 0 || opts.emitGameStart) {
650
+ const hasBacklog = caughtUpEvents.length > 0;
651
+ const nextStep = opts.emitGameStart
652
+ ? hasBacklog
653
+ ? 'Game stream attached. Read summary and caught_up.notable_events for opening events; current strategy appears in summary.automation.strategy.'
654
+ : 'Game stream attached. Read summary and wait for role_assigned; current strategy appears in summary.automation.strategy.'
655
+ : 'Catch-up complete. Read summary, then continue play.';
656
+ const attachedEvents = hasBacklog ? caughtUpEvents : [{ type: 'game_start' }];
657
+ const attachedOut = buildOut(attachedEvents.map((event) => event.type), nextStep, attachedEvents);
658
+ caughtUpEvents = [];
659
+ emit(attachedOut);
660
+ }
661
+
662
+ // Delay buffer: merge rapid-fire wandering-phase events into one notification
663
+ let delayActive = false;
664
+ let delayDeadline = 0;
665
+ const delayBuffer: { triggers: Set<string>; events: GameEvent[] } = {
666
+ triggers: new Set(),
667
+ events: [],
668
+ };
669
+
670
+ while (!opts.signal?.aborted) {
671
+ refreshSessionPath();
672
+
673
+ const triggers: string[] = [];
674
+ const triggeredEvents: GameEvent[] = [];
675
+
676
+ collectNotableEvents(drainNewEvents(), triggers, triggeredEvents);
677
+
678
+ // ── Delay buffer: merge rapid-fire wandering-phase events ──
679
+ // Only active during wandering; meeting-phase events (my_turn, speech, etc.)
680
+ // are not in DELAYABLE_EVENT_CONFIG and won't start a delay.
681
+ if (delayActive) {
682
+ if (Date.now() < delayDeadline) {
683
+ // Still within delay window — buffer everything and wait
684
+ for (const t of triggers) delayBuffer.triggers.add(t);
685
+ for (const e of triggeredEvents) delayBuffer.events.push(e);
686
+ triggers.length = 0;
687
+ triggeredEvents.length = 0;
688
+ } else {
689
+ // Delay expired — flush buffer in front of current batch
690
+ for (const t of delayBuffer.triggers) {
691
+ if (!triggers.includes(t)) triggers.unshift(t);
692
+ }
693
+ triggeredEvents.unshift(...delayBuffer.events);
694
+ delayBuffer.triggers.clear();
695
+ delayBuffer.events.length = 0;
696
+ delayActive = false;
697
+ }
698
+ } else if (triggers.length > 0) {
699
+ // Check if any trigger is delayable; start a delay if so
700
+ let delayMs = 0;
701
+ for (const t of triggers) {
702
+ const ms = resolvedDelays[t];
703
+ if (ms !== undefined && ms > delayMs) delayMs = ms;
704
+ }
705
+ if (delayMs > 0) {
706
+ delayActive = true;
707
+ delayDeadline = Date.now() + delayMs;
708
+ for (const t of triggers) delayBuffer.triggers.add(t);
709
+ for (const e of triggeredEvents) delayBuffer.events.push(e);
710
+ triggers.length = 0;
711
+ triggeredEvents.length = 0;
712
+ }
713
+ }
714
+
715
+ if (triggers.length > 0) {
716
+ fireTrigger(triggers, triggeredEvents);
717
+ if (triggers.includes('game_over') || triggers.includes('user_left_game') || triggers.includes('room.self_left') || triggers.includes('room_self_left')) return;
718
+ } else if (!delayActive && heartbeatInterval > 0 && Date.now() - lastEmitMs >= heartbeatInterval) {
719
+ // Idle keepalive — prevents downstream adapters from interpreting a quiet
720
+ // wandering/transit period as a hung subprocess and killing it on their
721
+ // own default timeout (commonly 60s).
722
+ emit(buildOut(
723
+ ['heartbeat'],
724
+ 'Stream is alive; no notable events. Continue waiting — no action required.',
725
+ ));
726
+ }
727
+
728
+ if (opts.signal?.aborted) break;
729
+ await waitForNextPoll();
730
+ }
731
+ if (opts.signal?.aborted) await finalDrain();
732
+ }
733
+
734
+ export interface SnapshotOnceOptions {
735
+ feedPath: string;
736
+ stdout: (line: string) => void;
737
+ }
738
+
739
+ export function snapshotOnce(opts: SnapshotOnceOptions): void {
740
+ if (!existsSync(opts.feedPath)) {
741
+ throw new Error('ccl game runtime is not running. Start it first with `ccl game start`.');
742
+ }
743
+ const summary = readFeedSummary(opts.feedPath);
744
+ opts.stdout(JSON.stringify({
745
+ events: ['snapshot'],
746
+ messages: [formatEventMessage({ type: 'snapshot' })],
747
+ state: shortStateText(summary),
748
+ }) + '\n');
749
+ }
750
+
751
+ export function buildErrorLine(err: any, opts?: { notReadyNextStep?: string }): string {
752
+ const msg = err?.message ?? String(err);
753
+ const notReady = err?.name === 'WatchNotReadyError' || /not ready|feed\.json/i.test(msg);
754
+ const reason = notReady ? 'not_ready' : 'error';
755
+ const event = {
756
+ type: reason,
757
+ message: notReady
758
+ ? (opts?.notReadyNextStep ?? 'Game runtime not running. Run `ccl game start` to begin a new session.')
759
+ : msg,
760
+ };
761
+ return JSON.stringify({
762
+ events: [reason],
763
+ messages: [formatEventMessage(event)],
764
+ state: 'state unavailable',
765
+ error: msg,
766
+ }) + '\n';
767
+ }
768
+
769
+ export function createWatchCommand(): Command {
770
+ const cmd = new Command('watch')
771
+ .description('Stream notable game events as NDJSON. Exits on game_over. For a one-shot snapshot use `ccl peek`.')
772
+ .action(async () => {
773
+ const store = new AuthStore();
774
+ const profile = store.getActive();
775
+ if (!profile) {
776
+ process.stdout.write(JSON.stringify({ exit_reason: ['not_logged_in'], error: 'Not logged in' }) + '\n');
777
+ return;
778
+ }
779
+ const stateDir = getProfileStateDir(profile);
780
+ const feedPath = join(stateDir, 'feed.json');
781
+ const sessionPath = EventStore.latestSessionPath();
782
+ const ctrl = new AbortController();
783
+ process.on('SIGINT', () => ctrl.abort());
784
+ process.on('SIGTERM', () => ctrl.abort());
785
+ let summaryCache: any | null = null;
786
+ let summaryPoll: ReturnType<typeof setInterval> | null = null;
787
+ try {
788
+ const snapshot = await sendOwnerControlRequest(stateDir, 'snapshot');
789
+ if (!snapshot?.ok) {
790
+ throw new WatchNotReadyError(
791
+ 'Game runtime not ready (no active ccl game start owner). Run `ccl game start` to start or recover the game stream.',
792
+ );
793
+ }
794
+ summaryCache = snapshot.summary ?? null;
795
+ summaryPoll = setInterval(() => {
796
+ void sendOwnerControlRequest(stateDir, 'snapshot')
797
+ .then((response) => {
798
+ if (response?.ok) summaryCache = response.summary ?? null;
799
+ })
800
+ .catch(() => {});
801
+ }, 1000);
802
+ await runStreaming({
803
+ feedPath,
804
+ sessionPath,
805
+ getSessionPath: () => EventStore.latestSessionPath(),
806
+ stdout: (s) => process.stdout.write(s),
807
+ signal: ctrl.signal,
808
+ skipFeedWait: true,
809
+ readSummary: () => summaryCache,
810
+ hubReminder: hubReminder(readCachedGamesPlayed()),
811
+ });
812
+ } catch (err: any) {
813
+ process.stdout.write(buildErrorLine(err, {
814
+ notReadyNextStep: 'Run `ccl game start` to start or recover the game stream.',
815
+ }));
816
+ process.exit(1);
817
+ } finally {
818
+ if (summaryPoll) clearInterval(summaryPoll);
819
+ }
820
+ });
821
+ // ── Adapter metadata: streaming mode blocks until game_over; cap at 30min for stuck-process safety ──
822
+ setMeta(cmd, { longRunning: true, timeoutMs: 1_800_000 });
823
+ return cmd;
824
+ }