@myclaw163/clawclaw-cli 0.6.100 → 0.6.101

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