@myclaw163/clawclaw-cli 0.6.91 → 0.6.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +385 -385
  2. package/bin/clawclaw-cli.mjs +3 -3
  3. package/package.json +48 -48
  4. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -50
  5. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -51
  6. package/personas//346/227/240/344/272/272/350/256/276.md +1 -1
  7. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -48
  8. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -51
  9. package/scripts/check-skill-command-surface.mjs +118 -118
  10. package/scripts/check_monitor.cjs +435 -435
  11. package/scripts/check_monitor.test.mjs +212 -212
  12. package/scripts/enable_ccl_permissions.cjs +147 -147
  13. package/scripts/enable_ccl_permissions.test.mjs +132 -132
  14. package/scripts/enable_monitor.cjs +677 -677
  15. package/scripts/enable_monitor.test.mjs +201 -201
  16. package/scripts/find-hide-spots.py +157 -157
  17. package/scripts/postinstall.mjs +20 -20
  18. package/scripts/sync-bundled-skill.mjs +254 -254
  19. package/scripts/sync-bundled-skill.test.mjs +152 -152
  20. package/skills/clawclaw/SKILL.md +274 -274
  21. package/skills/clawclaw/references/CHATTERBOX.md +142 -142
  22. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -224
  23. package/skills/clawclaw/references/COMMANDS.md +165 -165
  24. package/skills/clawclaw/references/GAME-MECHANICS.md +190 -190
  25. package/skills/clawclaw/references/HUB.md +48 -48
  26. package/skills/clawclaw/references/KNOWLEDGE.md +42 -42
  27. package/skills/clawclaw/references/STRATEGIES.md +59 -59
  28. package/skills/clawclaw/references/STREAM.md +74 -74
  29. package/skills/clawclaw/references/TACTICS.md +65 -65
  30. package/src/assets/clawclaw-ascii-map.txt +40 -40
  31. package/src/cli.ts +113 -113
  32. package/src/commands/_schema.ts +124 -124
  33. package/src/commands/account.test.ts +149 -149
  34. package/src/commands/account.ts +287 -287
  35. package/src/commands/competition.ts +42 -42
  36. package/src/commands/data.test.ts +33 -33
  37. package/src/commands/data.ts +22 -22
  38. package/src/commands/do.test.ts +91 -40
  39. package/src/commands/do.ts +130 -93
  40. package/src/commands/events.test.ts +124 -124
  41. package/src/commands/events.ts +262 -262
  42. package/src/commands/game-map.test.ts +28 -28
  43. package/src/commands/game-monitor-status.test.ts +58 -58
  44. package/src/commands/game-start-plan.test.ts +94 -94
  45. package/src/commands/game.ts +1286 -1286
  46. package/src/commands/history-player.test.ts +102 -102
  47. package/src/commands/history.ts +573 -573
  48. package/src/commands/hub.test.ts +113 -113
  49. package/src/commands/hub.ts +244 -244
  50. package/src/commands/knowledge.test.ts +13 -13
  51. package/src/commands/knowledge.ts +139 -139
  52. package/src/commands/load.test.ts +65 -65
  53. package/src/commands/load.ts +22 -22
  54. package/src/commands/meeting-history.test.ts +106 -106
  55. package/src/commands/memory.ts +40 -40
  56. package/src/commands/peek.ts +45 -45
  57. package/src/commands/persona.ts +62 -62
  58. package/src/commands/setup/codex.ts +266 -266
  59. package/src/commands/skill.ts +128 -128
  60. package/src/commands/state.ts +46 -46
  61. package/src/commands/strategy.test.ts +153 -153
  62. package/src/commands/strategy.ts +183 -183
  63. package/src/commands/upgrade.test.ts +82 -82
  64. package/src/commands/upgrade.ts +148 -148
  65. package/src/commands/watch.test.ts +1041 -1041
  66. package/src/commands/watch.ts +664 -664
  67. package/src/lib/account-guidance.test.ts +32 -32
  68. package/src/lib/account-guidance.ts +62 -62
  69. package/src/lib/auth.test.ts +116 -116
  70. package/src/lib/auth.ts +189 -189
  71. package/src/lib/command-meta.ts +37 -37
  72. package/src/lib/competition.ts +79 -79
  73. package/src/lib/game-client.test.ts +82 -82
  74. package/src/lib/game-client.ts +409 -382
  75. package/src/lib/game-context.ts +92 -92
  76. package/src/lib/http-keepalive.ts +15 -15
  77. package/src/lib/http-transport.test.ts +61 -61
  78. package/src/lib/http-transport.ts +118 -118
  79. package/src/lib/hub-client.test.ts +57 -57
  80. package/src/lib/hub-client.ts +88 -88
  81. package/src/lib/hub-install.test.ts +139 -139
  82. package/src/lib/hub-install.ts +198 -198
  83. package/src/lib/hub-reminder.ts +78 -78
  84. package/src/lib/hub-unzip.test.ts +69 -69
  85. package/src/lib/hub-unzip.ts +62 -62
  86. package/src/lib/init-command.test.ts +75 -75
  87. package/src/lib/init-command.ts +130 -130
  88. package/src/lib/knowledge-store.test.ts +170 -170
  89. package/src/lib/knowledge-store.ts +369 -369
  90. package/src/lib/load-context.test.ts +62 -62
  91. package/src/lib/load-context.ts +49 -49
  92. package/src/lib/match-state.test.ts +134 -134
  93. package/src/lib/match-state.ts +94 -94
  94. package/src/lib/normalize.ts +42 -42
  95. package/src/lib/persona.test.ts +84 -84
  96. package/src/lib/persona.ts +120 -120
  97. package/src/lib/server-registry.ts +152 -152
  98. package/src/lib/skill-version.test.ts +48 -48
  99. package/src/lib/skill-version.ts +19 -19
  100. package/src/lib/strategy-export.test.ts +240 -240
  101. package/src/lib/strategy-export.ts +247 -247
  102. package/src/lib/user-data.test.ts +97 -97
  103. package/src/lib/user-data.ts +374 -374
  104. package/src/lib/workspace-argv.test.ts +49 -49
  105. package/src/lib/workspace-argv.ts +44 -44
  106. package/src/perception/player-history-store.test.ts +87 -87
  107. package/src/perception/player-history-store.ts +194 -194
  108. package/src/pipeline/event-format.test.ts +247 -247
  109. package/src/pipeline/event-format.ts +507 -507
  110. package/src/pipeline/event-hints.ts +195 -195
  111. package/src/pipeline/event-store.test.ts +28 -28
  112. package/src/pipeline/event-store.ts +193 -193
  113. package/src/pipeline/pipeline.ts +35 -35
  114. package/src/pipeline/player-projection.test.ts +168 -168
  115. package/src/pipeline/player-projection.ts +370 -370
  116. package/src/runtime/auto-upgrade.test.ts +66 -66
  117. package/src/runtime/auto-upgrade.ts +31 -31
  118. package/src/runtime/event-daemon.test.ts +225 -225
  119. package/src/runtime/event-daemon.ts +527 -527
  120. package/src/runtime/owner-control.ts +150 -150
  121. package/src/runtime/raw-ws-log.test.ts +33 -33
  122. package/src/runtime/raw-ws-log.ts +32 -32
  123. package/src/runtime/runtime-logger.ts +107 -107
  124. package/src/runtime/ws-client.test.ts +169 -169
  125. package/src/runtime/ws-client.ts +280 -280
  126. package/src/sdk/action.ts +155 -153
  127. package/src/sdk/index.ts +107 -107
  128. package/src/sdk/types.ts +163 -161
  129. package/src/strategies/avoid-lone.ts +12 -12
  130. package/src/strategies/avoid-players.knowledge.md +19 -19
  131. package/src/strategies/avoid-players.ts +16 -16
  132. package/src/strategies/corpse-patrol.ts +19 -19
  133. package/src/strategies/crab-sabotage.ts +22 -22
  134. package/src/strategies/custom-module.test.ts +270 -270
  135. package/src/strategies/find-player.ts +17 -17
  136. package/src/strategies/game-utils.test.ts +242 -242
  137. package/src/strategies/game-utils.ts +846 -846
  138. package/src/strategies/goals/anchor-linger.ts +77 -77
  139. package/src/strategies/goals/avoid-lone-top.ts +168 -168
  140. package/src/strategies/goals/avoid-players-top.test.ts +83 -83
  141. package/src/strategies/goals/avoid-players-top.ts +121 -121
  142. package/src/strategies/goals/conversation-goal.ts +51 -51
  143. package/src/strategies/goals/corpse-patrol-top.ts +113 -113
  144. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -101
  145. package/src/strategies/goals/crab-sabotage-top.ts +226 -197
  146. package/src/strategies/goals/emergency-hunt-goal.ts +28 -28
  147. package/src/strategies/goals/find-player-top.ts +93 -93
  148. package/src/strategies/goals/flee-players-goal.ts +53 -53
  149. package/src/strategies/goals/follow-companion-goal.ts +106 -106
  150. package/src/strategies/goals/goal-manager.ts +41 -41
  151. package/src/strategies/goals/goal-root-strategy.ts +49 -49
  152. package/src/strategies/goals/goal.ts +28 -28
  153. package/src/strategies/goals/hide-top.ts +197 -197
  154. package/src/strategies/goals/keep-away-goal.ts +221 -221
  155. package/src/strategies/goals/kill-frenzy-top.ts +80 -80
  156. package/src/strategies/goals/kill-lone-top.ts +160 -160
  157. package/src/strategies/goals/kill-target-goal.ts +59 -59
  158. package/src/strategies/goals/kill-target-top.ts +109 -109
  159. package/src/strategies/goals/leaf-goal.ts +27 -27
  160. package/src/strategies/goals/linger-corpse-goal.ts +35 -35
  161. package/src/strategies/goals/lone-kill-core.ts +82 -82
  162. package/src/strategies/goals/lone-kill-goal.ts +24 -24
  163. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -85
  164. package/src/strategies/goals/lone-kill-task-top.ts +133 -133
  165. package/src/strategies/goals/move-room-goal.ts +60 -60
  166. package/src/strategies/goals/normal-shrimp-top.test.ts +80 -80
  167. package/src/strategies/goals/normal-shrimp-top.ts +242 -242
  168. package/src/strategies/goals/paradise-fish-top.test.ts +126 -126
  169. package/src/strategies/goals/paradise-fish-top.ts +224 -224
  170. package/src/strategies/goals/patrol-top.ts +57 -57
  171. package/src/strategies/goals/report-patrol-top.ts +80 -80
  172. package/src/strategies/goals/safe-task-goal.ts +102 -102
  173. package/src/strategies/goals/social-task-top.ts +161 -161
  174. package/src/strategies/goals/task-kill-report-top.ts +163 -163
  175. package/src/strategies/goals/task-only-top.ts +57 -57
  176. package/src/strategies/goals/task-or-patrol-goal.ts +41 -41
  177. package/src/strategies/goals/task-report-top.ts +57 -57
  178. package/src/strategies/goals/wander-task-goal.ts +33 -33
  179. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -87
  180. package/src/strategies/goals/warrior-shrimp-top.ts +267 -267
  181. package/src/strategies/greeting.ts +53 -53
  182. package/src/strategies/hide-spots.ts +59 -59
  183. package/src/strategies/hide.ts +24 -24
  184. package/src/strategies/kill-frenzy.ts +13 -13
  185. package/src/strategies/kill-lone.knowledge.md +17 -17
  186. package/src/strategies/kill-lone.ts +14 -14
  187. package/src/strategies/kill-target.ts +19 -19
  188. package/src/strategies/loader.test.ts +678 -678
  189. package/src/strategies/loader.ts +181 -181
  190. package/src/strategies/lone-kill-task.ts +22 -22
  191. package/src/strategies/meeting-gate.test.ts +59 -59
  192. package/src/strategies/meeting-gate.ts +23 -23
  193. package/src/strategies/move-room.ts +16 -16
  194. package/src/strategies/new-events-backfill.ts +98 -98
  195. package/src/strategies/off-route-points.ts +105 -105
  196. package/src/strategies/paradise-fish.knowledge.md +19 -19
  197. package/src/strategies/paradise-fish.ts +22 -22
  198. package/src/strategies/pathfind/distance-field.ts +150 -150
  199. package/src/strategies/pathfind/escape-planner.test.ts +197 -197
  200. package/src/strategies/pathfind/escape-planner.ts +355 -355
  201. package/src/strategies/pathfind/walkable-grid.ts +117 -117
  202. package/src/strategies/patrol.ts +12 -12
  203. package/src/strategies/player-targets.ts +13 -13
  204. package/src/strategies/report-patrol.ts +12 -12
  205. package/src/strategies/shrimp-memory.knowledge.md +19 -19
  206. package/src/strategies/shrimp-memory.ts +22 -22
  207. package/src/strategies/social-task.test.ts +28 -28
  208. package/src/strategies/social-task.ts +50 -50
  209. package/src/strategies/spawn.ts +82 -82
  210. package/src/strategies/speech-module.ts +123 -123
  211. package/src/strategies/strategy-loop.test.ts +15 -15
  212. package/src/strategies/strategy-loop.ts +722 -716
  213. package/src/strategies/task-kill-report.ts +18 -18
  214. package/src/strategies/task-only.ts +12 -12
  215. package/src/strategies/task-report.ts +19 -19
  216. package/src/strategies/types.ts +112 -107
  217. package/src/strategies/warrior-memory.knowledge.md +21 -21
  218. package/src/strategies/warrior-memory.ts +17 -17
@@ -1,716 +1,722 @@
1
- import type { GameState } from '../sdk/types.js';
2
- import { existsSync, writeFileSync, unlinkSync, readFileSync, statSync } from 'fs';
3
- import { join } from 'path';
4
- import { execFileSync } from 'child_process';
5
- import { GameClient } from '../lib/game-client.js';
6
- import { ApiError, formatApiError } from '../lib/http-transport.js';
7
- import { EventStore, extractNewEvents } from '../pipeline/event-store.js';
8
- import { AuthStore } from '../lib/auth.js';
9
- import { getProfileStateDir } from '../lib/init-command.js';
10
- import type { Action } from '../sdk/action.js';
11
- import type { Strategy, StrategyContext, BehaviorDecision } from './types.js';
12
- import { resolveStrategy } from './loader.js';
13
- import { CorpseMemory } from './game-utils.js';
14
- import {
15
- meetingEndedInEvents,
16
- meetingStartedInEvents,
17
- shouldPauseForMeeting,
18
- } from './meeting-gate.js';
19
- import { createStrategyNewEventsBackfill } from './new-events-backfill.js';
20
- import {
21
- buildKnowledgeView,
22
- currentGameId,
23
- emptyKnowledgeView,
24
- knowledgeFilePathForActiveAccount,
25
- readKnowledgeFileResult,
26
- } from '../lib/knowledge-store.js';
27
-
28
- function sleep(ms: number): Promise<void> {
29
- return new Promise(r => setTimeout(r, ms));
30
- }
31
-
32
- const RECENT_KILL_IGNORE_MS = 3000;
33
- const SETUP_EVENTS_BACKFILLED_BY_STATE = new Set(['role_assigned', 'game_started', 'crab_teammates']);
34
-
35
- function formatErrorMessage(err: unknown): string {
36
- if (err instanceof ApiError) return formatApiError(err);
37
- return err instanceof Error ? err.message : String(err);
38
- }
39
-
40
- export function eventsForStrategyStateLog(events: any): Record<string, any>[] {
41
- return extractNewEvents(events).filter((event) => !SETUP_EVENTS_BACKFILLED_BY_STATE.has(event.type));
42
- }
43
-
44
- function getPidPath(): string {
45
- const profile = new AuthStore().getActive();
46
- if (!profile) throw new Error('Not logged in.');
47
- return join(getProfileStateDir(profile), 'auto.pid');
48
- }
49
-
50
- function getStatusPath(): string {
51
- const profile = new AuthStore().getActive();
52
- if (!profile) throw new Error('Not logged in.');
53
- return join(getProfileStateDir(profile), 'auto.json');
54
- }
55
-
56
- function shouldWriteStrategyRuntimeFiles(): boolean {
57
- return process.env.CLAWCLAW_STRATEGY_RUNTIME_FILES === '1';
58
- }
59
-
60
- export function isStrategyRunning(): boolean {
61
- try {
62
- const pidPath = getPidPath();
63
- if (!existsSync(pidPath)) return false;
64
- const pid = Number(readFileSync(pidPath, 'utf8').trim());
65
- if (pid <= 0) return false;
66
- try {
67
- process.kill(pid, 0);
68
- return true;
69
- } catch {
70
- try { unlinkSync(pidPath); } catch {}
71
- try { unlinkSync(getStatusPath()); } catch {}
72
- return false;
73
- }
74
- } catch {
75
- return false;
76
- }
77
- }
78
-
79
- export function stopStrategyIfRunning(): void {
80
- try {
81
- const pidPath = getPidPath();
82
- if (existsSync(pidPath)) {
83
- const pid = Number(readFileSync(pidPath, 'utf8').trim());
84
- stopPid(pid);
85
- try { unlinkSync(pidPath); } catch {}
86
- try { unlinkSync(getStatusPath()); } catch {}
87
- }
88
- try { unlinkSync(getStatusPath()); } catch {}
89
- } catch {}
90
- stopOrphanProcesses();
91
- }
92
-
93
- function stopPid(pid: number): void {
94
- if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return;
95
- try { process.kill(pid, 'SIGTERM'); } catch {}
96
- const waitBuffer = new SharedArrayBuffer(4);
97
- Atomics.wait(new Int32Array(waitBuffer), 0, 0, 200);
98
- try {
99
- process.kill(pid, 0);
100
- process.kill(pid, 'SIGKILL');
101
- } catch {}
102
- }
103
-
104
- function stopOrphanProcesses(): void {
105
- if (process.platform === 'win32') return;
106
- try {
107
- const lines = execFileSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf8' }).split('\n');
108
- for (const line of lines) {
109
- const match = line.trim().match(/^(\d+)\s+(.+)$/);
110
- if (!match) continue;
111
- const pid = Number(match[1]);
112
- const command = match[2];
113
- if (pid === process.pid) continue;
114
- if (!command.includes('clawclaw-cli') || !command.includes(' _strategy ')) continue;
115
- stopPid(pid);
116
- }
117
- } catch {}
118
- }
119
-
120
- interface RoomTarget {
121
- name: string;
122
- x: number;
123
- y: number;
124
- }
125
-
126
- function pointFromMapEntry(entry: any): { x: number; y: number } | null {
127
- const x = Number(entry?.x ?? entry?.[0]);
128
- const y = Number(entry?.y ?? entry?.[1]);
129
- return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : null;
130
- }
131
-
132
- function roomName(r: any, index = 0): string {
133
- return String(r?.name ?? r?.id ?? r?.room ?? `room-${index + 1}`);
134
- }
135
-
136
- function taskLocationsByRoom(allTaskLocations: any[] | undefined): Map<string, any[]> {
137
- const byRoom = new Map<string, any[]>();
138
- if (!Array.isArray(allTaskLocations)) return byRoom;
139
- for (const task of allTaskLocations) {
140
- const room = typeof task?.room === 'string' ? task.room : '';
141
- const point = pointFromMapEntry(task);
142
- if (!room || !point) continue;
143
- const list = byRoom.get(room) ?? [];
144
- list.push(task);
145
- byRoom.set(room, list);
146
- }
147
- return byRoom;
148
- }
149
-
150
- function roomAnchor(r: any, index = 0, allTaskLocationsByRoom = new Map<string, any[]>()): RoomTarget {
151
- const taskLocations = Array.isArray(r?.task_locations) ? r.task_locations : [];
152
- const name = roomName(r, index);
153
- const candidates = [
154
- ...taskLocations,
155
- ...(allTaskLocationsByRoom.get(name) ?? []),
156
- ]
157
- .map(pointFromMapEntry)
158
- .filter((p): p is { x: number; y: number } => p != null);
159
- if (candidates.length > 0) {
160
- return { name, ...candidates[Math.floor(Math.random() * candidates.length)] };
161
- }
162
-
163
- const poly: number[][] = Array.isArray(r?.polygon) ? r.polygon : [];
164
- if (poly.length === 0) return { name, x: 0, y: 0 };
165
-
166
- let area = 0;
167
- let cx = 0;
168
- let cy = 0;
169
- for (let i = 0; i < poly.length; i += 1) {
170
- const [x1, y1] = poly[i];
171
- const [x2, y2] = poly[(i + 1) % poly.length];
172
- const cross = x1 * y2 - x2 * y1;
173
- area += cross;
174
- cx += (x1 + x2) * cross;
175
- cy += (y1 + y2) * cross;
176
- }
177
- area *= 0.5;
178
- if (Math.abs(area) < 1e-6) {
179
- const ax = poly.reduce((s, p) => s + p[0], 0) / poly.length;
180
- const ay = poly.reduce((s, p) => s + p[1], 0) / poly.length;
181
- return { name, x: ax, y: ay };
182
- }
183
- return { name, x: cx / (6 * area), y: cy / (6 * area) };
184
- }
185
-
186
- function learnTeammatesFromEvents(events: any[] | undefined, teammates: Set<string>): void {
187
- if (!Array.isArray(events)) return;
188
- for (const evt of events) {
189
- if (evt?.type !== 'crab_teammates') continue;
190
- const list = Array.isArray(evt.teammates) ? evt.teammates : [];
191
- for (const name of list) {
192
- if (typeof name === 'string' && name.length > 0) teammates.add(name);
193
- }
194
- }
195
- }
196
-
197
- const MOVEMENT_TERMINAL_EVENT_TYPES = new Set(['move_end', 'move_interrupted']);
198
-
199
- function ownMovementTerminalEvent(events: any[] | undefined, playerName: string): any | null {
200
- if (!Array.isArray(events)) return null;
201
- return events.find(evt => {
202
- if (!MOVEMENT_TERMINAL_EVENT_TYPES.has(evt?.type)) return false;
203
- if (evt.actor_name && evt.actor_name !== playerName) return false;
204
- return true;
205
- }) ?? null;
206
- }
207
-
208
- function ownKillEvent(events: any[] | undefined, playerName: string): boolean {
209
- if (!Array.isArray(events) || !playerName) return false;
210
- return events.some(evt => evt?.type === 'kill' && evt.actor_name === playerName);
211
- }
212
-
213
- function learnSeatNames(players: any[] | undefined, target: Record<string, string>): void {
214
- if (!Array.isArray(players)) return;
215
- for (const player of players) {
216
- const seat = player?.seat;
217
- const name = player?.name;
218
- if (seat == null || typeof name !== 'string' || name.length === 0) continue;
219
- target[String(seat)] = name;
220
- }
221
- }
222
-
223
- function eventsSinceCurrentSession(events: any[] | undefined): any[] {
224
- if (!Array.isArray(events)) return [];
225
- let idx = -1;
226
- for (let i = events.length - 1; i >= 0; i--) {
227
- if (events[i]?.type === 'session_started') { idx = i; break; }
228
- }
229
- return idx >= 0 ? events.slice(idx + 1) : events;
230
- }
231
-
232
- interface MoveTarget {
233
- kind: 'point' | 'room';
234
- x?: number;
235
- y?: number;
236
- room?: string;
237
- }
238
-
239
- interface ActiveMoveTarget extends MoveTarget {
240
- until: number;
241
- }
242
-
243
- const SAME_MOVE_TARGET_DISTANCE = 10;
244
-
245
- function moveTargetFromPayload(payload: Record<string, any>): MoveTarget | null {
246
- if (typeof payload.target === 'string' && payload.target.trim()) {
247
- return { kind: 'room', room: payload.target.trim().toLowerCase() };
248
- }
249
- const x = Number(payload.target_x);
250
- const y = Number(payload.target_y);
251
- if (Number.isFinite(x) && Number.isFinite(y)) return { kind: 'point', x, y };
252
- return null;
253
- }
254
-
255
- function sameMoveTarget(a: MoveTarget, b: MoveTarget): boolean {
256
- if (a.kind !== b.kind) return false;
257
- if (a.kind === 'room') return a.room === b.room;
258
- const dx = (a.x ?? 0) - (b.x ?? 0);
259
- const dy = (a.y ?? 0) - (b.y ?? 0);
260
- return Math.sqrt(dx ** 2 + dy ** 2) <= SAME_MOVE_TARGET_DISTANCE;
261
- }
262
-
263
- function activeMoveTargetFromPayload(payload: Record<string, any>, until: number): ActiveMoveTarget | null {
264
- const target = moveTargetFromPayload(payload);
265
- return target ? { ...target, until } : null;
266
- }
267
-
268
- function repeatsActiveMoveTarget(decision: BehaviorDecision, activeMoveTarget: ActiveMoveTarget | null): boolean {
269
- if (!activeMoveTarget || Date.now() >= activeMoveTarget.until) return false;
270
- const payload = decision.action.toJSON();
271
- if (payload.action !== 'move') return false;
272
- const target = moveTargetFromPayload(payload);
273
- return !!target && sameMoveTarget(target, activeMoveTarget);
274
- }
275
-
276
- function pickDecision(
277
- decisions: BehaviorDecision[],
278
- blockedMoveTarget: ({ x: number; y: number; until: number }) | null,
279
- activeMoveTarget: ActiveMoveTarget | null,
280
- ): BehaviorDecision | null {
281
- return decisions.find(d => {
282
- if (repeatsActiveMoveTarget(d, activeMoveTarget)) return false;
283
- const a = d.action.toJSON();
284
- if (a.action !== 'move') return true;
285
- if (!blockedMoveTarget || Date.now() >= blockedMoveTarget.until) return true;
286
- const x = Number(a.target_x);
287
- const y = Number(a.target_y);
288
- if (!Number.isFinite(x) || !Number.isFinite(y)) return true;
289
- const dx = x - blockedMoveTarget.x;
290
- const dy = y - blockedMoveTarget.y;
291
- return Math.sqrt(dx ** 2 + dy ** 2) > 10;
292
- }) ?? null;
293
- }
294
-
295
- function isSpeechDecision(decision: BehaviorDecision): boolean {
296
- return decision.action.toJSON().action === 'speech';
297
- }
298
-
299
- function supportsSidecarSpeech(strategyId: string): boolean {
300
- return strategyId === 'task-report'
301
- || strategyId === 'corpse-patrol'
302
- || strategyId === 'shrimp-memory'
303
- || strategyId === 'paradise-fish';
304
- }
305
-
306
- export async function runStrategyLoop(strategyId: string, args?: string[]): Promise<void> {
307
- const strategy = await resolveStrategy(strategyId, args);
308
- const store = EventStore.forActiveAccount();
309
- const pidPath = getPidPath();
310
-
311
- if (shouldWriteStrategyRuntimeFiles()) writeFileSync(pidPath, String(process.pid));
312
- store.append({ type: 'auto', message: 'strategy started', strategy: strategyId, pid: process.pid });
313
-
314
- const client = GameClient.fromAuth();
315
- await client.discoverGameServer();
316
-
317
- const teammates = new Set<string>();
318
- const playerNamesBySeat: Record<string, string> = {};
319
- let blockedMoveTarget: { x: number; y: number; until: number } | null = null;
320
- let consecutiveBlocks = 0;
321
- const BLOCK_SKIP_THRESHOLD = 3;
322
- let mapDirty = true;
323
- let lastMapRefreshAt = 0;
324
- const MAP_REFRESH_INTERVAL_MS = 10_000;
325
-
326
- const knowledgePath = (() => { try { return knowledgeFilePathForActiveAccount(); } catch { return ''; } })();
327
- const knowledgeGameId = currentGameId();
328
- let lastKnowledgeMtimeMs = -1;
329
-
330
- const ctx: StrategyContext = {
331
- taskData: [],
332
- taskLocations: [],
333
- emergency: null,
334
- taskLocalBlockedUntil: 0,
335
- reportCorpseTarget: null,
336
- reportBlockedUntil: 0,
337
- notifications: [],
338
- lastProgressNotifyAt: 0,
339
- teammates,
340
- alarmDone: false,
341
- rooms: [],
342
- playerNamesBySeat,
343
- forcePatrolAdvance: false,
344
- blockedMoveTarget: null,
345
- mySeat: 0,
346
- speechNotifications: [],
347
- agentAlerts: [],
348
- knownCorpses: [],
349
- knowledge: emptyKnowledgeView(),
350
- recentlyKilledTargets: new Map(),
351
- };
352
-
353
- // 全局唯一的尸体记忆:每 tick observe 后写入 ctx.knownCorpses,开会清场时 reset。
354
- const corpseMemory = new CorpseMemory();
355
-
356
- try { learnTeammatesFromEvents(eventsSinceCurrentSession(store.tail(1000)), teammates); } catch {}
357
- const newEventsBackfill = createStrategyNewEventsBackfill(store.path);
358
- try {
359
- const roleInfo = await client.getRoleInfo();
360
- learnSeatNames(roleInfo?.data?.all_seats ?? roleInfo?.all_seats, playerNamesBySeat);
361
- const crabTeammates: any[] = roleInfo?.data?.crab_teammates ?? roleInfo?.crab_teammates ?? [];
362
- for (const name of crabTeammates) {
363
- if (typeof name === 'string' && name.length > 0) teammates.add(name);
364
- }
365
- const mySeat = Number(roleInfo?.data?.seat ?? roleInfo?.seat ?? 0);
366
- if (mySeat > 0) ctx.mySeat = mySeat;
367
- const role: string = roleInfo?.data?.role ?? roleInfo?.role ?? '';
368
- if (role && strategy.updateRole) strategy.updateRole(role);
369
- } catch {}
370
-
371
- // Register custom modules before main loop so tick-1 events are captured
372
- const customModules = strategy.customModules?.() ?? [];
373
- if (customModules.length > 0) ctx.customModules = customModules;
374
-
375
- let running = true;
376
- let activeMoveTarget: ActiveMoveTarget | null = null;
377
- let pausedForMeeting = false;
378
- let releasedMeetingPause = false;
379
- let currentRole = '';
380
- let currentPlayerName = '';
381
- let pistolKillUsed = false;
382
- let pistolKillInitialized = false;
383
- const onSignal = () => { running = false; };
384
- process.on('SIGINT', onSignal);
385
- process.on('SIGTERM', onSignal);
386
-
387
- const submitAction = async (action: Action): Promise<{ acted: boolean }> => {
388
- try {
389
- const payload = action.toJSON();
390
- const actionType = payload.action;
391
- const result = await client.submitAction(payload as any);
392
- const newEvents = extractNewEvents(result);
393
- store.appendNewEvents(newEvents);
394
- // action 结果里回来的 corpse_spotted 也入账尸体记忆——主循环只 observe state.new_events,
395
- // 那条通道会被 runtime WS listener 抢游标,这里补上避免尸体坐标漏记(ctx.knownCorpses 与 list() 同引用,立即可见)。
396
- corpseMemory.ingestEvents(newEvents);
397
- learnTeammatesFromEvents(newEvents, teammates);
398
- if (currentRole === 'shrimp_pistol' && ownKillEvent(newEvents, currentPlayerName)) {
399
- pistolKillUsed = true;
400
- }
401
- const actionResult = result?.data ?? result;
402
- store.append({ type: 'auto', action: actionType, result: actionResult ?? result?.error ?? 'ok' });
403
-
404
- const errorCode = actionResult?.error?.code ?? actionResult?.code ?? result?.error?.code;
405
- const errorMessage = String(
406
- actionResult?.error?.message ?? actionResult?.message ?? result?.error?.message ?? actionResult?.reason ?? '',
407
- );
408
- const failed = errorCode === 'ACTION_FAILED' || actionResult?.success === false || result?.success === false;
409
- const queued = actionResult?.status === 'queued';
410
-
411
- if (failed) {
412
- ctx.reportCorpseTarget = null;
413
- const failureText = JSON.stringify(actionResult ?? result ?? {});
414
- if (actionType === 'kill' && currentRole === 'shrimp_pistol' && failureText.includes('role_cannot_kill')) {
415
- pistolKillUsed = true;
416
- }
417
- if (actionType === 'task' || actionType === 'kill' || actionType === 'report' || actionType === 'trigger_alarm') {
418
- activeMoveTarget = null;
419
- }
420
- if (actionType === 'kill' && errorMessage.includes('cannot_kill_teammate')) {
421
- const target = action.toJSON().target;
422
- if (typeof target === 'string' && target.length > 0) teammates.add(target);
423
- }
424
- if (actionType === 'task' && errorMessage.includes('not_at_task_location')) {
425
- ctx.taskLocalBlockedUntil = Date.now() + 5000;
426
- activeMoveTarget = null;
427
- }
428
- if (actionType === 'report') {
429
- // doing_task 型失败不是真报不了:服务端只是因正在做任务而拒绝,下一 tick 任务被 move 打断后即可补报。
430
- // 这种情况不设 5 秒退避,否则会错过「目击者刚靠近尸体」的报尸自证窗口;其余原因(距离不够等)仍退避避免空报刷屏。
431
- if (!failureText.includes('doing_task')) {
432
- ctx.reportBlockedUntil = Date.now() + 5000;
433
- }
434
- activeMoveTarget = null;
435
- }
436
- if (actionType === 'move') {
437
- if (errorMessage.includes('invalid_position_blocked')) {
438
- consecutiveBlocks++;
439
- const payload = action.toJSON();
440
- const x = Number(payload.target_x);
441
- const y = Number(payload.target_y);
442
- if (Number.isFinite(x) && Number.isFinite(y)) {
443
- if (consecutiveBlocks >= BLOCK_SKIP_THRESHOLD) {
444
- blockedMoveTarget = null;
445
- consecutiveBlocks = 0;
446
- ctx.forcePatrolAdvance = true;
447
- ctx.notifications.push('移动目标多次不可达,跳过。');
448
- } else {
449
- blockedMoveTarget = { x, y, until: Date.now() + 5000 };
450
- }
451
- }
452
- } else {
453
- consecutiveBlocks = 0;
454
- }
455
- activeMoveTarget = null;
456
- }
457
- }
458
-
459
- if (!failed && actionType === 'kill') {
460
- const target = typeof payload.target === 'string' ? payload.target.trim().toLowerCase() : '';
461
- if (target) ctx.recentlyKilledTargets?.set(target, Date.now() + RECENT_KILL_IGNORE_MS);
462
- if (currentRole === 'shrimp_pistol') pistolKillUsed = true;
463
- activeMoveTarget = null;
464
- }
465
-
466
- if (!failed && actionType === 'trigger_alarm') {
467
- activeMoveTarget = null;
468
- }
469
-
470
- if (queued) {
471
- if (actionType === 'task') {
472
- mapDirty = true;
473
- activeMoveTarget = null;
474
- }
475
- } else if (actionType === 'move' && !failed) {
476
- consecutiveBlocks = 0;
477
- const durationSecs = actionResult?.duration_secs ?? result?.duration_secs ?? 0;
478
- const arrivalAt = Date.now() + Math.max(0.5, durationSecs) * 1000;
479
- activeMoveTarget = activeMoveTargetFromPayload(payload, arrivalAt + 500);
480
- } else if (!failed && (actionType === 'task' || actionType === 'report')) {
481
- activeMoveTarget = null;
482
- }
483
-
484
- return { acted: true };
485
- } catch (e: any) {
486
- store.append({ type: 'auto', error: 'submit_action_failed', message: formatErrorMessage(e) });
487
- ctx.reportCorpseTarget = null;
488
- if (action.toJSON().action === 'move') {
489
- activeMoveTarget = null;
490
- }
491
- return { acted: true };
492
- }
493
- };
494
-
495
- while (running) {
496
- let state: GameState | null;
497
- try {
498
- state = await client.getGameState();
499
- } catch {
500
- await sleep(2000);
501
- continue;
502
- }
503
-
504
- if (!state) {
505
- store.append({ type: 'auto', message: 'no active game, retrying' });
506
- await sleep(2000);
507
- continue;
508
- }
509
-
510
- store.appendNewEvents(eventsForStrategyStateLog(state.new_events));
511
- state.new_events = newEventsBackfill.correct(state.new_events);
512
- currentRole = state.you.role ?? currentRole;
513
- currentPlayerName = state.you.name ?? currentPlayerName;
514
- if (currentRole === 'shrimp_pistol') {
515
- if (!pistolKillInitialized) {
516
- pistolKillUsed = pistolKillUsed || ownKillEvent(eventsSinceCurrentSession(store.tail(1000)), currentPlayerName);
517
- pistolKillInitialized = true;
518
- }
519
- if (state.you.kills_remaining === 0 || ownKillEvent(state.new_events, currentPlayerName)) {
520
- pistolKillUsed = true;
521
- }
522
- state.you.kills_remaining = pistolKillUsed ? 0 : (state.you.kills_remaining ?? 1);
523
- }
524
-
525
- learnTeammatesFromEvents(state.new_events, teammates);
526
- learnSeatNames(state.all_players, playerNamesBySeat);
527
- const terminalMove = ownMovementTerminalEvent(state.new_events, state.you.name);
528
- if (terminalMove) {
529
- activeMoveTarget = null;
530
- }
531
-
532
- // Process events through strategy-registered custom modules
533
- const currentTick = state.tick ?? 0;
534
- const newEvents = state.new_events ?? [];
535
- for (const mod of ctx.customModules ?? []) {
536
- mod.processEvents(newEvents, currentTick, state);
537
- }
538
-
539
- if (ctx.mySeat === 0 && state.you.seat != null) {
540
- ctx.mySeat = state.you.seat;
541
- }
542
-
543
- const prevEmergency = ctx.emergency;
544
- ctx.emergency = state.emergency ?? null;
545
- if (ctx.emergency && !prevEmergency) {
546
- const room = ctx.emergency.room ?? '未知';
547
- ctx.notifications.push(`紧急任务出现!「${ctx.emergency.task_name}」在${room},剩余${Math.round(ctx.emergency.remaining_secs)}秒。`);
548
- }
549
-
550
- if (meetingStartedInEvents(state.new_events)) {
551
- releasedMeetingPause = false;
552
- }
553
- if (state.phase !== 'meeting') {
554
- releasedMeetingPause = false;
555
- }
556
- if (meetingEndedInEvents(state.new_events)) {
557
- releasedMeetingPause = true;
558
- }
559
-
560
- if (state.phase === 'game_over') {
561
- store.append({ type: 'auto', message: 'game over' });
562
- break;
563
- }
564
- if (state.you.is_alive === false) {
565
- store.append({ type: 'auto', message: 'player dead, stopping strategy', strategy: strategyId });
566
- break;
567
- }
568
- if (shouldPauseForMeeting(state, releasedMeetingPause)) {
569
- if (!pausedForMeeting) {
570
- store.append({ type: 'auto', message: 'meeting started, pausing strategy', strategy: strategyId });
571
- pausedForMeeting = true;
572
- activeMoveTarget = null;
573
- }
574
- await sleep(2000);
575
- continue;
576
- }
577
- if (pausedForMeeting) {
578
- store.append({ type: 'auto', message: 'meeting ended, resuming strategy', strategy: strategyId });
579
- pausedForMeeting = false;
580
- releasedMeetingPause = true;
581
- mapDirty = true;
582
- activeMoveTarget = null;
583
- blockedMoveTarget = null;
584
- consecutiveBlocks = 0;
585
- ctx.taskLocalBlockedUntil = 0;
586
- ctx.reportCorpseTarget = null;
587
- ctx.reportBlockedUntil = 0;
588
- ctx.forcePatrolAdvance = false;
589
- ctx.blockedMoveTarget = null;
590
- // 开会后尸体清场:清空尸体记忆,避免回避/报告已不存在的尸体。
591
- corpseMemory.reset();
592
- ctx.knownCorpses = [];
593
- // Notify strategy-registered custom modules (decay instead of full reset)
594
- for (const mod of ctx.customModules ?? []) {
595
- mod.onMeetingResume?.();
596
- }
597
- strategy.onMeetingResume?.();
598
- }
599
-
600
- if (mapDirty || Date.now() - lastMapRefreshAt >= MAP_REFRESH_INTERVAL_MS) {
601
- try {
602
- const mapData = await client.getMap();
603
- const taskFactionByName = new Map<string, 'lobster' | 'crab'>(
604
- (mapData?.all_task_locations ?? [])
605
- .filter((t: any) => t?.name && (t.faction === 'lobster' || t.faction === 'crab'))
606
- .map((t: any) => [t.name, t.faction]),
607
- );
608
- ctx.taskData = (mapData?.your_tasks ?? []).map((t: any) => ({
609
- task_id: t.name ?? '',
610
- task_name: t.name ?? '',
611
- room: t.room ?? '',
612
- status: t.status ?? 'normal',
613
- x: t.x,
614
- y: t.y,
615
- is_fake_shrimp: t.is_fake_shrimp ?? false,
616
- faction: taskFactionByName.get(t.name),
617
- }));
618
- ctx.taskLocations = (mapData?.all_task_locations ?? [])
619
- .filter((t: any) => t && typeof t.name === 'string' && typeof t.x === 'number' && typeof t.y === 'number')
620
- .map((t: any) => ({ name: t.name, room: t.room, x: t.x, y: t.y, faction: t.faction }));
621
- if (Array.isArray(mapData?.rooms)) {
622
- if (ctx.rooms.length === 0) {
623
- const byRoom = taskLocationsByRoom(mapData?.all_task_locations);
624
- ctx.rooms = mapData.rooms.map((r: any, index: number) => roomAnchor(r, index, byRoom));
625
- }
626
- // Notify custom modules of new map data
627
- for (const mod of ctx.customModules ?? []) {
628
- mod.onMapLoaded?.(mapData.rooms);
629
- }
630
- }
631
- mapDirty = false;
632
- lastMapRefreshAt = Date.now();
633
- } catch (e: any) {
634
- store.append({ type: 'auto', error: 'map_load_failed', message: formatErrorMessage(e) });
635
- }
636
- }
637
-
638
- const activeBlockedMoveTarget = ((): { x: number; y: number; until: number } | null => blockedMoveTarget)();
639
- ctx.blockedMoveTarget = activeBlockedMoveTarget && Date.now() < activeBlockedMoveTarget.until
640
- ? { x: activeBlockedMoveTarget.x, y: activeBlockedMoveTarget.y }
641
- : null;
642
-
643
- if (knowledgePath) {
644
- try {
645
- const mtime = existsSync(knowledgePath) ? statSync(knowledgePath).mtimeMs : 0;
646
- if (mtime !== lastKnowledgeMtimeMs) {
647
- lastKnowledgeMtimeMs = mtime;
648
- const result = readKnowledgeFileResult(knowledgePath);
649
- if (result.status !== 'invalid') {
650
- const scoped = result.status === 'ok' && result.file.gameId === knowledgeGameId ? result.file : null;
651
- ctx.knowledge = buildKnowledgeView(scoped, { playerNamesBySeat });
652
- }
653
- }
654
- } catch {}
655
- }
656
-
657
- // 更新跨 tick 尸体记忆,暴露给所有策略(检测/接近/任务回避/死亡确认统一读 ctx.knownCorpses)。
658
- corpseMemory.observe(state, ctx.recentlyKilledTargets);
659
- ctx.knownCorpses = corpseMemory.list();
660
-
661
- let decisions = strategy.decide(state, ctx);
662
-
663
- // Run custom module afterDecide pipeline (chained by registration order)
664
- for (const mod of ctx.customModules ?? []) {
665
- if (mod.afterDecide) {
666
- decisions = mod.afterDecide(decisions, state, ctx);
667
- }
668
- }
669
-
670
- const sidecarSpeech = supportsSidecarSpeech(strategyId) ? decisions.filter(isSpeechDecision) : [];
671
- const mainDecisions = sidecarSpeech.length > 0 ? decisions.filter(d => !isSpeechDecision(d)) : decisions;
672
-
673
- const decision = pickDecision(
674
- mainDecisions,
675
- activeBlockedMoveTarget,
676
- activeMoveTarget,
677
- );
678
-
679
- if (decision) {
680
- await submitAction(decision.action);
681
- }
682
- for (const speech of sidecarSpeech) {
683
- await submitAction(speech.action);
684
- }
685
-
686
- if (ctx.notifications.length > 0) {
687
- for (const msg of ctx.notifications) {
688
- store.append({ type: 'auto', message: msg, strategy: strategyId });
689
- }
690
- ctx.notifications.length = 0;
691
- }
692
-
693
- if (ctx.agentAlerts.length > 0) {
694
- const tick = typeof state.tick === 'number' ? state.tick : undefined;
695
- for (const msg of ctx.agentAlerts) {
696
- store.append({ type: 'strategy_alert', message: msg, strategy: strategyId, tick });
697
- }
698
- ctx.agentAlerts.length = 0;
699
- }
700
-
701
- if (ctx.speechNotifications.length > 0) {
702
- for (const msg of ctx.speechNotifications) {
703
- store.append({ type: 'robot_speak_rule', message: msg });
704
- }
705
- ctx.speechNotifications.length = 0;
706
- }
707
-
708
- await sleep(500);
709
- }
710
-
711
- process.off('SIGINT', onSignal);
712
- process.off('SIGTERM', onSignal);
713
- if (shouldWriteStrategyRuntimeFiles()) {
714
- try { unlinkSync(pidPath); } catch {}
715
- }
716
- }
1
+ import type { GameState } from '../sdk/types.js';
2
+ import { existsSync, writeFileSync, unlinkSync, readFileSync, statSync } from 'fs';
3
+ import { join } from 'path';
4
+ import { execFileSync } from 'child_process';
5
+ import { GameClient } from '../lib/game-client.js';
6
+ import { ApiError, formatApiError } from '../lib/http-transport.js';
7
+ import { EventStore, extractNewEvents } from '../pipeline/event-store.js';
8
+ import { AuthStore } from '../lib/auth.js';
9
+ import { getProfileStateDir } from '../lib/init-command.js';
10
+ import type { Action } from '../sdk/action.js';
11
+ import type { Strategy, StrategyContext, BehaviorDecision } from './types.js';
12
+ import { resolveStrategy } from './loader.js';
13
+ import { CorpseMemory } from './game-utils.js';
14
+ import {
15
+ meetingEndedInEvents,
16
+ meetingStartedInEvents,
17
+ shouldPauseForMeeting,
18
+ } from './meeting-gate.js';
19
+ import { createStrategyNewEventsBackfill } from './new-events-backfill.js';
20
+ import {
21
+ buildKnowledgeView,
22
+ currentGameId,
23
+ emptyKnowledgeView,
24
+ knowledgeFilePathForActiveAccount,
25
+ readKnowledgeFileResult,
26
+ } from '../lib/knowledge-store.js';
27
+
28
+ function sleep(ms: number): Promise<void> {
29
+ return new Promise(r => setTimeout(r, ms));
30
+ }
31
+
32
+ const RECENT_KILL_IGNORE_MS = 3000;
33
+ const SETUP_EVENTS_BACKFILLED_BY_STATE = new Set(['role_assigned', 'game_started', 'crab_teammates']);
34
+
35
+ function formatErrorMessage(err: unknown): string {
36
+ if (err instanceof ApiError) return formatApiError(err);
37
+ return err instanceof Error ? err.message : String(err);
38
+ }
39
+
40
+ export function eventsForStrategyStateLog(events: any): Record<string, any>[] {
41
+ return extractNewEvents(events).filter((event) => !SETUP_EVENTS_BACKFILLED_BY_STATE.has(event.type));
42
+ }
43
+
44
+ function getPidPath(): string {
45
+ const profile = new AuthStore().getActive();
46
+ if (!profile) throw new Error('Not logged in.');
47
+ return join(getProfileStateDir(profile), 'auto.pid');
48
+ }
49
+
50
+ function getStatusPath(): string {
51
+ const profile = new AuthStore().getActive();
52
+ if (!profile) throw new Error('Not logged in.');
53
+ return join(getProfileStateDir(profile), 'auto.json');
54
+ }
55
+
56
+ function shouldWriteStrategyRuntimeFiles(): boolean {
57
+ return process.env.CLAWCLAW_STRATEGY_RUNTIME_FILES === '1';
58
+ }
59
+
60
+ export function isStrategyRunning(): boolean {
61
+ try {
62
+ const pidPath = getPidPath();
63
+ if (!existsSync(pidPath)) return false;
64
+ const pid = Number(readFileSync(pidPath, 'utf8').trim());
65
+ if (pid <= 0) return false;
66
+ try {
67
+ process.kill(pid, 0);
68
+ return true;
69
+ } catch {
70
+ try { unlinkSync(pidPath); } catch {}
71
+ try { unlinkSync(getStatusPath()); } catch {}
72
+ return false;
73
+ }
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
78
+
79
+ export function stopStrategyIfRunning(): void {
80
+ try {
81
+ const pidPath = getPidPath();
82
+ if (existsSync(pidPath)) {
83
+ const pid = Number(readFileSync(pidPath, 'utf8').trim());
84
+ stopPid(pid);
85
+ try { unlinkSync(pidPath); } catch {}
86
+ try { unlinkSync(getStatusPath()); } catch {}
87
+ }
88
+ try { unlinkSync(getStatusPath()); } catch {}
89
+ } catch {}
90
+ stopOrphanProcesses();
91
+ }
92
+
93
+ function stopPid(pid: number): void {
94
+ if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return;
95
+ try { process.kill(pid, 'SIGTERM'); } catch {}
96
+ const waitBuffer = new SharedArrayBuffer(4);
97
+ Atomics.wait(new Int32Array(waitBuffer), 0, 0, 200);
98
+ try {
99
+ process.kill(pid, 0);
100
+ process.kill(pid, 'SIGKILL');
101
+ } catch {}
102
+ }
103
+
104
+ function stopOrphanProcesses(): void {
105
+ if (process.platform === 'win32') return;
106
+ try {
107
+ const lines = execFileSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf8' }).split('\n');
108
+ for (const line of lines) {
109
+ const match = line.trim().match(/^(\d+)\s+(.+)$/);
110
+ if (!match) continue;
111
+ const pid = Number(match[1]);
112
+ const command = match[2];
113
+ if (pid === process.pid) continue;
114
+ if (!command.includes('clawclaw-cli') || !command.includes(' _strategy ')) continue;
115
+ stopPid(pid);
116
+ }
117
+ } catch {}
118
+ }
119
+
120
+ interface RoomTarget {
121
+ name: string;
122
+ x: number;
123
+ y: number;
124
+ }
125
+
126
+ function pointFromMapEntry(entry: any): { x: number; y: number } | null {
127
+ const x = Number(entry?.x ?? entry?.[0]);
128
+ const y = Number(entry?.y ?? entry?.[1]);
129
+ return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : null;
130
+ }
131
+
132
+ function roomName(r: any, index = 0): string {
133
+ return String(r?.name ?? r?.id ?? r?.room ?? `room-${index + 1}`);
134
+ }
135
+
136
+ function taskLocationsByRoom(allTaskLocations: any[] | undefined): Map<string, any[]> {
137
+ const byRoom = new Map<string, any[]>();
138
+ if (!Array.isArray(allTaskLocations)) return byRoom;
139
+ for (const task of allTaskLocations) {
140
+ const room = typeof task?.room === 'string' ? task.room : '';
141
+ const point = pointFromMapEntry(task);
142
+ if (!room || !point) continue;
143
+ const list = byRoom.get(room) ?? [];
144
+ list.push(task);
145
+ byRoom.set(room, list);
146
+ }
147
+ return byRoom;
148
+ }
149
+
150
+ function roomAnchor(r: any, index = 0, allTaskLocationsByRoom = new Map<string, any[]>()): RoomTarget {
151
+ const taskLocations = Array.isArray(r?.task_locations) ? r.task_locations : [];
152
+ const name = roomName(r, index);
153
+ const candidates = [
154
+ ...taskLocations,
155
+ ...(allTaskLocationsByRoom.get(name) ?? []),
156
+ ]
157
+ .map(pointFromMapEntry)
158
+ .filter((p): p is { x: number; y: number } => p != null);
159
+ if (candidates.length > 0) {
160
+ return { name, ...candidates[Math.floor(Math.random() * candidates.length)] };
161
+ }
162
+
163
+ const poly: number[][] = Array.isArray(r?.polygon) ? r.polygon : [];
164
+ if (poly.length === 0) return { name, x: 0, y: 0 };
165
+
166
+ let area = 0;
167
+ let cx = 0;
168
+ let cy = 0;
169
+ for (let i = 0; i < poly.length; i += 1) {
170
+ const [x1, y1] = poly[i];
171
+ const [x2, y2] = poly[(i + 1) % poly.length];
172
+ const cross = x1 * y2 - x2 * y1;
173
+ area += cross;
174
+ cx += (x1 + x2) * cross;
175
+ cy += (y1 + y2) * cross;
176
+ }
177
+ area *= 0.5;
178
+ if (Math.abs(area) < 1e-6) {
179
+ const ax = poly.reduce((s, p) => s + p[0], 0) / poly.length;
180
+ const ay = poly.reduce((s, p) => s + p[1], 0) / poly.length;
181
+ return { name, x: ax, y: ay };
182
+ }
183
+ return { name, x: cx / (6 * area), y: cy / (6 * area) };
184
+ }
185
+
186
+ function learnTeammatesFromEvents(events: any[] | undefined, teammates: Set<string>): void {
187
+ if (!Array.isArray(events)) return;
188
+ for (const evt of events) {
189
+ if (evt?.type !== 'crab_teammates') continue;
190
+ const list = Array.isArray(evt.teammates) ? evt.teammates : [];
191
+ for (const name of list) {
192
+ if (typeof name === 'string' && name.length > 0) teammates.add(name);
193
+ }
194
+ }
195
+ }
196
+
197
+ const MOVEMENT_TERMINAL_EVENT_TYPES = new Set(['move_end', 'move_interrupted']);
198
+
199
+ function ownMovementTerminalEvent(events: any[] | undefined, playerName: string): any | null {
200
+ if (!Array.isArray(events)) return null;
201
+ return events.find(evt => {
202
+ if (!MOVEMENT_TERMINAL_EVENT_TYPES.has(evt?.type)) return false;
203
+ if (evt.actor_name && evt.actor_name !== playerName) return false;
204
+ return true;
205
+ }) ?? null;
206
+ }
207
+
208
+ function ownKillEvent(events: any[] | undefined, playerName: string): boolean {
209
+ if (!Array.isArray(events) || !playerName) return false;
210
+ return events.some(evt => evt?.type === 'kill' && evt.actor_name === playerName);
211
+ }
212
+
213
+ function learnSeatNames(players: any[] | undefined, target: Record<string, string>): void {
214
+ if (!Array.isArray(players)) return;
215
+ for (const player of players) {
216
+ const seat = player?.seat;
217
+ const name = player?.name;
218
+ if (seat == null || typeof name !== 'string' || name.length === 0) continue;
219
+ target[String(seat)] = name;
220
+ }
221
+ }
222
+
223
+ function eventsSinceCurrentSession(events: any[] | undefined): any[] {
224
+ if (!Array.isArray(events)) return [];
225
+ let idx = -1;
226
+ for (let i = events.length - 1; i >= 0; i--) {
227
+ if (events[i]?.type === 'session_started') { idx = i; break; }
228
+ }
229
+ return idx >= 0 ? events.slice(idx + 1) : events;
230
+ }
231
+
232
+ interface MoveTarget {
233
+ kind: 'point' | 'room';
234
+ x?: number;
235
+ y?: number;
236
+ room?: string;
237
+ }
238
+
239
+ interface ActiveMoveTarget extends MoveTarget {
240
+ until: number;
241
+ }
242
+
243
+ const SAME_MOVE_TARGET_DISTANCE = 10;
244
+
245
+ function moveTargetFromPayload(payload: Record<string, any>): MoveTarget | null {
246
+ if (typeof payload.target === 'string' && payload.target.trim()) {
247
+ return { kind: 'room', room: payload.target.trim().toLowerCase() };
248
+ }
249
+ const x = Number(payload.target_x);
250
+ const y = Number(payload.target_y);
251
+ if (Number.isFinite(x) && Number.isFinite(y)) return { kind: 'point', x, y };
252
+ return null;
253
+ }
254
+
255
+ function sameMoveTarget(a: MoveTarget, b: MoveTarget): boolean {
256
+ if (a.kind !== b.kind) return false;
257
+ if (a.kind === 'room') return a.room === b.room;
258
+ const dx = (a.x ?? 0) - (b.x ?? 0);
259
+ const dy = (a.y ?? 0) - (b.y ?? 0);
260
+ return Math.sqrt(dx ** 2 + dy ** 2) <= SAME_MOVE_TARGET_DISTANCE;
261
+ }
262
+
263
+ function activeMoveTargetFromPayload(payload: Record<string, any>, until: number): ActiveMoveTarget | null {
264
+ const target = moveTargetFromPayload(payload);
265
+ return target ? { ...target, until } : null;
266
+ }
267
+
268
+ function repeatsActiveMoveTarget(decision: BehaviorDecision, activeMoveTarget: ActiveMoveTarget | null): boolean {
269
+ if (!activeMoveTarget || Date.now() >= activeMoveTarget.until) return false;
270
+ const payload = decision.action.toJSON();
271
+ if (payload.action !== 'move') return false;
272
+ const target = moveTargetFromPayload(payload);
273
+ return !!target && sameMoveTarget(target, activeMoveTarget);
274
+ }
275
+
276
+ function pickDecision(
277
+ decisions: BehaviorDecision[],
278
+ blockedMoveTarget: ({ x: number; y: number; until: number }) | null,
279
+ activeMoveTarget: ActiveMoveTarget | null,
280
+ ): BehaviorDecision | null {
281
+ return decisions.find(d => {
282
+ if (repeatsActiveMoveTarget(d, activeMoveTarget)) return false;
283
+ const a = d.action.toJSON();
284
+ if (a.action !== 'move') return true;
285
+ if (!blockedMoveTarget || Date.now() >= blockedMoveTarget.until) return true;
286
+ const x = Number(a.target_x);
287
+ const y = Number(a.target_y);
288
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return true;
289
+ const dx = x - blockedMoveTarget.x;
290
+ const dy = y - blockedMoveTarget.y;
291
+ return Math.sqrt(dx ** 2 + dy ** 2) > 10;
292
+ }) ?? null;
293
+ }
294
+
295
+ function isSpeechDecision(decision: BehaviorDecision): boolean {
296
+ return decision.action.toJSON().action === 'speech';
297
+ }
298
+
299
+ function supportsSidecarSpeech(strategyId: string): boolean {
300
+ return strategyId === 'task-report'
301
+ || strategyId === 'corpse-patrol'
302
+ || strategyId === 'shrimp-memory'
303
+ || strategyId === 'paradise-fish';
304
+ }
305
+
306
+ export async function runStrategyLoop(strategyId: string, args?: string[]): Promise<void> {
307
+ const strategy = await resolveStrategy(strategyId, args);
308
+ const store = EventStore.forActiveAccount();
309
+ const pidPath = getPidPath();
310
+
311
+ if (shouldWriteStrategyRuntimeFiles()) writeFileSync(pidPath, String(process.pid));
312
+ store.append({ type: 'auto', message: 'strategy started', strategy: strategyId, pid: process.pid });
313
+
314
+ const client = GameClient.fromAuth();
315
+ await client.discoverGameServer();
316
+
317
+ const teammates = new Set<string>();
318
+ const playerNamesBySeat: Record<string, string> = {};
319
+ let blockedMoveTarget: { x: number; y: number; until: number } | null = null;
320
+ let consecutiveBlocks = 0;
321
+ const BLOCK_SKIP_THRESHOLD = 3;
322
+ let mapDirty = true;
323
+ let lastMapRefreshAt = 0;
324
+ const MAP_REFRESH_INTERVAL_MS = 10_000;
325
+
326
+ const knowledgePath = (() => { try { return knowledgeFilePathForActiveAccount(); } catch { return ''; } })();
327
+ const knowledgeGameId = currentGameId();
328
+ let lastKnowledgeMtimeMs = -1;
329
+
330
+ const ctx: StrategyContext = {
331
+ taskData: [],
332
+ taskLocations: [],
333
+ emergency: null,
334
+ taskLocalBlockedUntil: 0,
335
+ reportCorpseTarget: null,
336
+ reportBlockedUntil: 0,
337
+ notifications: [],
338
+ lastProgressNotifyAt: 0,
339
+ teammates,
340
+ alarmDone: false,
341
+ alarmOnCooldown: false,
342
+ rooms: [],
343
+ playerNamesBySeat,
344
+ forcePatrolAdvance: false,
345
+ blockedMoveTarget: null,
346
+ mySeat: 0,
347
+ speechNotifications: [],
348
+ agentAlerts: [],
349
+ knownCorpses: [],
350
+ knowledge: emptyKnowledgeView(),
351
+ recentlyKilledTargets: new Map(),
352
+ };
353
+
354
+ // 全局唯一的尸体记忆:每 tick observe 后写入 ctx.knownCorpses,开会清场时 reset。
355
+ const corpseMemory = new CorpseMemory();
356
+
357
+ try { learnTeammatesFromEvents(eventsSinceCurrentSession(store.tail(1000)), teammates); } catch {}
358
+ const newEventsBackfill = createStrategyNewEventsBackfill(store.path);
359
+ try {
360
+ const roleInfo = await client.getRoleInfo();
361
+ learnSeatNames(roleInfo?.data?.all_seats ?? roleInfo?.all_seats, playerNamesBySeat);
362
+ const crabTeammates: any[] = roleInfo?.data?.crab_teammates ?? roleInfo?.crab_teammates ?? [];
363
+ for (const name of crabTeammates) {
364
+ if (typeof name === 'string' && name.length > 0) teammates.add(name);
365
+ }
366
+ const mySeat = Number(roleInfo?.data?.seat ?? roleInfo?.seat ?? 0);
367
+ if (mySeat > 0) ctx.mySeat = mySeat;
368
+ const role: string = roleInfo?.data?.role ?? roleInfo?.role ?? '';
369
+ if (role && strategy.updateRole) strategy.updateRole(role);
370
+ } catch {}
371
+
372
+ // Register custom modules before main loop so tick-1 events are captured
373
+ const customModules = strategy.customModules?.() ?? [];
374
+ if (customModules.length > 0) ctx.customModules = customModules;
375
+
376
+ let running = true;
377
+ let activeMoveTarget: ActiveMoveTarget | null = null;
378
+ let pausedForMeeting = false;
379
+ let releasedMeetingPause = false;
380
+ let currentRole = '';
381
+ let currentPlayerName = '';
382
+ let pistolKillUsed = false;
383
+ let pistolKillInitialized = false;
384
+ const onSignal = () => { running = false; };
385
+ process.on('SIGINT', onSignal);
386
+ process.on('SIGTERM', onSignal);
387
+
388
+ const submitAction = async (action: Action): Promise<{ acted: boolean }> => {
389
+ try {
390
+ const payload = action.toJSON();
391
+ const actionType = payload.action;
392
+ const result = await client.submitAction(payload as any);
393
+ const newEvents = extractNewEvents(result);
394
+ store.appendNewEvents(newEvents);
395
+ // action 结果里回来的 corpse_spotted 也入账尸体记忆——主循环只 observe state.new_events,
396
+ // 那条通道会被 runtime WS listener 抢游标,这里补上避免尸体坐标漏记(ctx.knownCorpses 与 list() 同引用,立即可见)。
397
+ corpseMemory.ingestEvents(newEvents);
398
+ learnTeammatesFromEvents(newEvents, teammates);
399
+ if (currentRole === 'shrimp_pistol' && ownKillEvent(newEvents, currentPlayerName)) {
400
+ pistolKillUsed = true;
401
+ }
402
+ const actionResult = result?.data ?? result;
403
+ store.append({ type: 'auto', action: actionType, result: actionResult ?? result?.error ?? 'ok' });
404
+
405
+ const errorCode = actionResult?.error?.code ?? actionResult?.code ?? result?.error?.code;
406
+ const errorMessage = String(
407
+ actionResult?.error?.message ?? actionResult?.message ?? result?.error?.message ?? actionResult?.reason ?? '',
408
+ );
409
+ const failed = errorCode === 'ACTION_FAILED' || actionResult?.success === false || result?.success === false;
410
+ const queued = actionResult?.status === 'queued';
411
+
412
+ if (failed) {
413
+ ctx.reportCorpseTarget = null;
414
+ const failureText = JSON.stringify(actionResult ?? result ?? {});
415
+ if (actionType === 'kill' && currentRole === 'shrimp_pistol' && failureText.includes('role_cannot_kill')) {
416
+ pistolKillUsed = true;
417
+ }
418
+ if (actionType === 'task' || actionType === 'kill' || actionType === 'report' || actionType === 'trigger_alarm') {
419
+ activeMoveTarget = null;
420
+ }
421
+ if (actionType === 'trigger_alarm') {
422
+ // on_cooldown = 撞上 20s 阵营共享 CD,破坏仍装填、CD 好后可补打——透给蟹策略回滚乐观去重、退避重试。
423
+ ctx.alarmOnCooldown = errorMessage.includes('on_cooldown');
424
+ }
425
+ if (actionType === 'kill' && errorMessage.includes('cannot_kill_teammate')) {
426
+ const target = action.toJSON().target;
427
+ if (typeof target === 'string' && target.length > 0) teammates.add(target);
428
+ }
429
+ if (actionType === 'task' && errorMessage.includes('not_at_task_location')) {
430
+ ctx.taskLocalBlockedUntil = Date.now() + 5000;
431
+ activeMoveTarget = null;
432
+ }
433
+ if (actionType === 'report') {
434
+ // doing_task 型失败不是真报不了:服务端只是因正在做任务而拒绝,下一 tick 任务被 move 打断后即可补报。
435
+ // 这种情况不设 5 秒退避,否则会错过「目击者刚靠近尸体」的报尸自证窗口;其余原因(距离不够等)仍退避避免空报刷屏。
436
+ if (!failureText.includes('doing_task')) {
437
+ ctx.reportBlockedUntil = Date.now() + 5000;
438
+ }
439
+ activeMoveTarget = null;
440
+ }
441
+ if (actionType === 'move') {
442
+ if (errorMessage.includes('invalid_position_blocked')) {
443
+ consecutiveBlocks++;
444
+ const payload = action.toJSON();
445
+ const x = Number(payload.target_x);
446
+ const y = Number(payload.target_y);
447
+ if (Number.isFinite(x) && Number.isFinite(y)) {
448
+ if (consecutiveBlocks >= BLOCK_SKIP_THRESHOLD) {
449
+ blockedMoveTarget = null;
450
+ consecutiveBlocks = 0;
451
+ ctx.forcePatrolAdvance = true;
452
+ ctx.notifications.push('移动目标多次不可达,跳过。');
453
+ } else {
454
+ blockedMoveTarget = { x, y, until: Date.now() + 5000 };
455
+ }
456
+ }
457
+ } else {
458
+ consecutiveBlocks = 0;
459
+ }
460
+ activeMoveTarget = null;
461
+ }
462
+ }
463
+
464
+ if (!failed && actionType === 'kill') {
465
+ const target = typeof payload.target === 'string' ? payload.target.trim().toLowerCase() : '';
466
+ if (target) ctx.recentlyKilledTargets?.set(target, Date.now() + RECENT_KILL_IGNORE_MS);
467
+ if (currentRole === 'shrimp_pistol') pistolKillUsed = true;
468
+ activeMoveTarget = null;
469
+ }
470
+
471
+ if (!failed && actionType === 'trigger_alarm') {
472
+ ctx.alarmOnCooldown = false;
473
+ activeMoveTarget = null;
474
+ }
475
+
476
+ if (queued) {
477
+ if (actionType === 'task') {
478
+ mapDirty = true;
479
+ activeMoveTarget = null;
480
+ }
481
+ } else if (actionType === 'move' && !failed) {
482
+ consecutiveBlocks = 0;
483
+ const durationSecs = actionResult?.duration_secs ?? result?.duration_secs ?? 0;
484
+ const arrivalAt = Date.now() + Math.max(0.5, durationSecs) * 1000;
485
+ activeMoveTarget = activeMoveTargetFromPayload(payload, arrivalAt + 500);
486
+ } else if (!failed && (actionType === 'task' || actionType === 'report')) {
487
+ activeMoveTarget = null;
488
+ }
489
+
490
+ return { acted: true };
491
+ } catch (e: any) {
492
+ store.append({ type: 'auto', error: 'submit_action_failed', message: formatErrorMessage(e) });
493
+ ctx.reportCorpseTarget = null;
494
+ if (action.toJSON().action === 'move') {
495
+ activeMoveTarget = null;
496
+ }
497
+ return { acted: true };
498
+ }
499
+ };
500
+
501
+ while (running) {
502
+ let state: GameState | null;
503
+ try {
504
+ state = await client.getGameState();
505
+ } catch {
506
+ await sleep(2000);
507
+ continue;
508
+ }
509
+
510
+ if (!state) {
511
+ store.append({ type: 'auto', message: 'no active game, retrying' });
512
+ await sleep(2000);
513
+ continue;
514
+ }
515
+
516
+ store.appendNewEvents(eventsForStrategyStateLog(state.new_events));
517
+ state.new_events = newEventsBackfill.correct(state.new_events);
518
+ currentRole = state.you.role ?? currentRole;
519
+ currentPlayerName = state.you.name ?? currentPlayerName;
520
+ if (currentRole === 'shrimp_pistol') {
521
+ if (!pistolKillInitialized) {
522
+ pistolKillUsed = pistolKillUsed || ownKillEvent(eventsSinceCurrentSession(store.tail(1000)), currentPlayerName);
523
+ pistolKillInitialized = true;
524
+ }
525
+ if (state.you.kills_remaining === 0 || ownKillEvent(state.new_events, currentPlayerName)) {
526
+ pistolKillUsed = true;
527
+ }
528
+ state.you.kills_remaining = pistolKillUsed ? 0 : (state.you.kills_remaining ?? 1);
529
+ }
530
+
531
+ learnTeammatesFromEvents(state.new_events, teammates);
532
+ learnSeatNames(state.all_players, playerNamesBySeat);
533
+ const terminalMove = ownMovementTerminalEvent(state.new_events, state.you.name);
534
+ if (terminalMove) {
535
+ activeMoveTarget = null;
536
+ }
537
+
538
+ // Process events through strategy-registered custom modules
539
+ const currentTick = state.tick ?? 0;
540
+ const newEvents = state.new_events ?? [];
541
+ for (const mod of ctx.customModules ?? []) {
542
+ mod.processEvents(newEvents, currentTick, state);
543
+ }
544
+
545
+ if (ctx.mySeat === 0 && state.you.seat != null) {
546
+ ctx.mySeat = state.you.seat;
547
+ }
548
+
549
+ const prevEmergency = ctx.emergency;
550
+ ctx.emergency = state.emergency ?? null;
551
+ if (ctx.emergency && !prevEmergency) {
552
+ const room = ctx.emergency.room ?? '未知';
553
+ ctx.notifications.push(`紧急任务出现!「${ctx.emergency.task_name}」在${room},剩余${Math.round(ctx.emergency.remaining_secs)}秒。`);
554
+ }
555
+
556
+ if (meetingStartedInEvents(state.new_events)) {
557
+ releasedMeetingPause = false;
558
+ }
559
+ if (state.phase !== 'meeting') {
560
+ releasedMeetingPause = false;
561
+ }
562
+ if (meetingEndedInEvents(state.new_events)) {
563
+ releasedMeetingPause = true;
564
+ }
565
+
566
+ if (state.phase === 'game_over') {
567
+ store.append({ type: 'auto', message: 'game over' });
568
+ break;
569
+ }
570
+ if (state.you.is_alive === false) {
571
+ store.append({ type: 'auto', message: 'player dead, stopping strategy', strategy: strategyId });
572
+ break;
573
+ }
574
+ if (shouldPauseForMeeting(state, releasedMeetingPause)) {
575
+ if (!pausedForMeeting) {
576
+ store.append({ type: 'auto', message: 'meeting started, pausing strategy', strategy: strategyId });
577
+ pausedForMeeting = true;
578
+ activeMoveTarget = null;
579
+ }
580
+ await sleep(2000);
581
+ continue;
582
+ }
583
+ if (pausedForMeeting) {
584
+ store.append({ type: 'auto', message: 'meeting ended, resuming strategy', strategy: strategyId });
585
+ pausedForMeeting = false;
586
+ releasedMeetingPause = true;
587
+ mapDirty = true;
588
+ activeMoveTarget = null;
589
+ blockedMoveTarget = null;
590
+ consecutiveBlocks = 0;
591
+ ctx.taskLocalBlockedUntil = 0;
592
+ ctx.reportCorpseTarget = null;
593
+ ctx.reportBlockedUntil = 0;
594
+ ctx.forcePatrolAdvance = false;
595
+ ctx.blockedMoveTarget = null;
596
+ // 开会后尸体清场:清空尸体记忆,避免回避/报告已不存在的尸体。
597
+ corpseMemory.reset();
598
+ ctx.knownCorpses = [];
599
+ // Notify strategy-registered custom modules (decay instead of full reset)
600
+ for (const mod of ctx.customModules ?? []) {
601
+ mod.onMeetingResume?.();
602
+ }
603
+ strategy.onMeetingResume?.();
604
+ }
605
+
606
+ if (mapDirty || Date.now() - lastMapRefreshAt >= MAP_REFRESH_INTERVAL_MS) {
607
+ try {
608
+ const mapData = await client.getMap();
609
+ const taskFactionByName = new Map<string, 'lobster' | 'crab'>(
610
+ (mapData?.all_task_locations ?? [])
611
+ .filter((t: any) => t?.name && (t.faction === 'lobster' || t.faction === 'crab'))
612
+ .map((t: any) => [t.name, t.faction]),
613
+ );
614
+ ctx.taskData = (mapData?.your_tasks ?? []).map((t: any) => ({
615
+ task_id: t.name ?? '',
616
+ task_name: t.name ?? '',
617
+ room: t.room ?? '',
618
+ status: t.status ?? 'normal',
619
+ x: t.x,
620
+ y: t.y,
621
+ is_fake_shrimp: t.is_fake_shrimp ?? false,
622
+ faction: taskFactionByName.get(t.name),
623
+ }));
624
+ ctx.taskLocations = (mapData?.all_task_locations ?? [])
625
+ .filter((t: any) => t && typeof t.name === 'string' && typeof t.x === 'number' && typeof t.y === 'number')
626
+ .map((t: any) => ({ name: t.name, room: t.room, x: t.x, y: t.y, faction: t.faction }));
627
+ if (Array.isArray(mapData?.rooms)) {
628
+ if (ctx.rooms.length === 0) {
629
+ const byRoom = taskLocationsByRoom(mapData?.all_task_locations);
630
+ ctx.rooms = mapData.rooms.map((r: any, index: number) => roomAnchor(r, index, byRoom));
631
+ }
632
+ // Notify custom modules of new map data
633
+ for (const mod of ctx.customModules ?? []) {
634
+ mod.onMapLoaded?.(mapData.rooms);
635
+ }
636
+ }
637
+ mapDirty = false;
638
+ lastMapRefreshAt = Date.now();
639
+ } catch (e: any) {
640
+ store.append({ type: 'auto', error: 'map_load_failed', message: formatErrorMessage(e) });
641
+ }
642
+ }
643
+
644
+ const activeBlockedMoveTarget = ((): { x: number; y: number; until: number } | null => blockedMoveTarget)();
645
+ ctx.blockedMoveTarget = activeBlockedMoveTarget && Date.now() < activeBlockedMoveTarget.until
646
+ ? { x: activeBlockedMoveTarget.x, y: activeBlockedMoveTarget.y }
647
+ : null;
648
+
649
+ if (knowledgePath) {
650
+ try {
651
+ const mtime = existsSync(knowledgePath) ? statSync(knowledgePath).mtimeMs : 0;
652
+ if (mtime !== lastKnowledgeMtimeMs) {
653
+ lastKnowledgeMtimeMs = mtime;
654
+ const result = readKnowledgeFileResult(knowledgePath);
655
+ if (result.status !== 'invalid') {
656
+ const scoped = result.status === 'ok' && result.file.gameId === knowledgeGameId ? result.file : null;
657
+ ctx.knowledge = buildKnowledgeView(scoped, { playerNamesBySeat });
658
+ }
659
+ }
660
+ } catch {}
661
+ }
662
+
663
+ // 更新跨 tick 尸体记忆,暴露给所有策略(检测/接近/任务回避/死亡确认统一读 ctx.knownCorpses)。
664
+ corpseMemory.observe(state, ctx.recentlyKilledTargets);
665
+ ctx.knownCorpses = corpseMemory.list();
666
+
667
+ let decisions = strategy.decide(state, ctx);
668
+
669
+ // Run custom module afterDecide pipeline (chained by registration order)
670
+ for (const mod of ctx.customModules ?? []) {
671
+ if (mod.afterDecide) {
672
+ decisions = mod.afterDecide(decisions, state, ctx);
673
+ }
674
+ }
675
+
676
+ const sidecarSpeech = supportsSidecarSpeech(strategyId) ? decisions.filter(isSpeechDecision) : [];
677
+ const mainDecisions = sidecarSpeech.length > 0 ? decisions.filter(d => !isSpeechDecision(d)) : decisions;
678
+
679
+ const decision = pickDecision(
680
+ mainDecisions,
681
+ activeBlockedMoveTarget,
682
+ activeMoveTarget,
683
+ );
684
+
685
+ if (decision) {
686
+ await submitAction(decision.action);
687
+ }
688
+ for (const speech of sidecarSpeech) {
689
+ await submitAction(speech.action);
690
+ }
691
+
692
+ if (ctx.notifications.length > 0) {
693
+ for (const msg of ctx.notifications) {
694
+ store.append({ type: 'auto', message: msg, strategy: strategyId });
695
+ }
696
+ ctx.notifications.length = 0;
697
+ }
698
+
699
+ if (ctx.agentAlerts.length > 0) {
700
+ const tick = typeof state.tick === 'number' ? state.tick : undefined;
701
+ for (const msg of ctx.agentAlerts) {
702
+ store.append({ type: 'strategy_alert', message: msg, strategy: strategyId, tick });
703
+ }
704
+ ctx.agentAlerts.length = 0;
705
+ }
706
+
707
+ if (ctx.speechNotifications.length > 0) {
708
+ for (const msg of ctx.speechNotifications) {
709
+ store.append({ type: 'robot_speak_rule', message: msg });
710
+ }
711
+ ctx.speechNotifications.length = 0;
712
+ }
713
+
714
+ await sleep(500);
715
+ }
716
+
717
+ process.off('SIGINT', onSignal);
718
+ process.off('SIGTERM', onSignal);
719
+ if (shouldWriteStrategyRuntimeFiles()) {
720
+ try { unlinkSync(pidPath); } catch {}
721
+ }
722
+ }