@myclaw163/clawclaw-cli 0.6.54

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 (198) hide show
  1. package/README.md +440 -0
  2. package/bin/clawclaw-cli.mjs +4 -0
  3. package/package.json +48 -0
  4. package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +23 -0
  5. package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +22 -0
  6. package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +22 -0
  7. package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +22 -0
  8. package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +23 -0
  9. package/scripts/postinstall.mjs +20 -0
  10. package/scripts/sync-bundled-skill.mjs +245 -0
  11. package/scripts/sync-bundled-skill.test.mjs +152 -0
  12. package/skills/clawclaw/SKILL.md +240 -0
  13. package/skills/clawclaw/references/CHATTERBOX.md +142 -0
  14. package/skills/clawclaw/references/COMMANDS.md +132 -0
  15. package/skills/clawclaw/references/GAME-MECHANICS.md +186 -0
  16. package/skills/clawclaw/references/HUB.md +48 -0
  17. package/skills/clawclaw/references/KNOWLEDGE.md +43 -0
  18. package/skills/clawclaw/references/STRATEGIES.md +57 -0
  19. package/skills/clawclaw/references/STREAM.md +58 -0
  20. package/skills/clawclaw/references/TACTICS.md +65 -0
  21. package/src/assets/clawclaw-ascii-map.txt +40 -0
  22. package/src/cli.ts +153 -0
  23. package/src/commands/_schema.ts +109 -0
  24. package/src/commands/account.ts +209 -0
  25. package/src/commands/config.ts +30 -0
  26. package/src/commands/do.test.ts +37 -0
  27. package/src/commands/do.ts +95 -0
  28. package/src/commands/events.ts +22 -0
  29. package/src/commands/game-map.test.ts +28 -0
  30. package/src/commands/game-start-plan.test.ts +142 -0
  31. package/src/commands/game.ts +882 -0
  32. package/src/commands/history-player.test.ts +102 -0
  33. package/src/commands/history.ts +573 -0
  34. package/src/commands/hub.test.ts +96 -0
  35. package/src/commands/hub.ts +234 -0
  36. package/src/commands/knowledge.test.ts +19 -0
  37. package/src/commands/knowledge.ts +168 -0
  38. package/src/commands/load.test.ts +51 -0
  39. package/src/commands/load.ts +13 -0
  40. package/src/commands/meeting-history.test.ts +106 -0
  41. package/src/commands/memory.ts +40 -0
  42. package/src/commands/peek.ts +38 -0
  43. package/src/commands/persona.ts +57 -0
  44. package/src/commands/setup/codex.ts +248 -0
  45. package/src/commands/setup/hermes.test.ts +96 -0
  46. package/src/commands/setup/hermes.ts +76 -0
  47. package/src/commands/setup/index.ts +13 -0
  48. package/src/commands/setup/openclaw.test.ts +114 -0
  49. package/src/commands/setup/openclaw.ts +147 -0
  50. package/src/commands/skill.ts +128 -0
  51. package/src/commands/state.ts +46 -0
  52. package/src/commands/strategy.test.ts +135 -0
  53. package/src/commands/strategy.ts +189 -0
  54. package/src/commands/tts.ts +128 -0
  55. package/src/commands/upgrade.test.ts +91 -0
  56. package/src/commands/upgrade.ts +154 -0
  57. package/src/commands/watch.test.ts +973 -0
  58. package/src/commands/watch.ts +709 -0
  59. package/src/lib/auth.test.ts +59 -0
  60. package/src/lib/auth.ts +186 -0
  61. package/src/lib/command-meta.ts +37 -0
  62. package/src/lib/game-client.ts +391 -0
  63. package/src/lib/host-config-patcher.test.ts +130 -0
  64. package/src/lib/host-config-patcher.ts +151 -0
  65. package/src/lib/http-keepalive.ts +15 -0
  66. package/src/lib/http-transport.test.ts +42 -0
  67. package/src/lib/http-transport.ts +113 -0
  68. package/src/lib/hub-client.test.ts +56 -0
  69. package/src/lib/hub-client.ts +88 -0
  70. package/src/lib/hub-install.test.ts +98 -0
  71. package/src/lib/hub-install.ts +121 -0
  72. package/src/lib/hub-reminder.ts +75 -0
  73. package/src/lib/hub-unzip.test.ts +69 -0
  74. package/src/lib/hub-unzip.ts +62 -0
  75. package/src/lib/init-command.test.ts +75 -0
  76. package/src/lib/init-command.ts +120 -0
  77. package/src/lib/knowledge-store.test.ts +180 -0
  78. package/src/lib/knowledge-store.ts +374 -0
  79. package/src/lib/load-context.test.ts +52 -0
  80. package/src/lib/load-context.ts +52 -0
  81. package/src/lib/match-state.test.ts +134 -0
  82. package/src/lib/match-state.ts +94 -0
  83. package/src/lib/netease-tts.ts +83 -0
  84. package/src/lib/normalize.ts +42 -0
  85. package/src/lib/persona.test.ts +41 -0
  86. package/src/lib/persona.ts +72 -0
  87. package/src/lib/server-registry.ts +152 -0
  88. package/src/lib/skill-version.test.ts +48 -0
  89. package/src/lib/skill-version.ts +19 -0
  90. package/src/lib/strategy-export.test.ts +232 -0
  91. package/src/lib/strategy-export.ts +242 -0
  92. package/src/lib/tts-keys.ts +7 -0
  93. package/src/lib/tts-speech.test.ts +63 -0
  94. package/src/lib/tts-speech.ts +76 -0
  95. package/src/lib/workspace-argv.test.ts +49 -0
  96. package/src/lib/workspace-argv.ts +44 -0
  97. package/src/perception/player-history-store.test.ts +87 -0
  98. package/src/perception/player-history-store.ts +194 -0
  99. package/src/pipeline/event-store.ts +124 -0
  100. package/src/pipeline/pipeline.ts +35 -0
  101. package/src/runtime/auto-upgrade.test.ts +66 -0
  102. package/src/runtime/auto-upgrade.ts +31 -0
  103. package/src/runtime/daemon.ts +100 -0
  104. package/src/runtime/event-daemon.test.ts +28 -0
  105. package/src/runtime/event-daemon.ts +371 -0
  106. package/src/runtime/opening-mover.ts +303 -0
  107. package/src/runtime/raw-ws-log.test.ts +33 -0
  108. package/src/runtime/raw-ws-log.ts +32 -0
  109. package/src/runtime/runtime-logger.ts +99 -0
  110. package/src/runtime/ws-client.test.ts +47 -0
  111. package/src/runtime/ws-client.ts +272 -0
  112. package/src/sdk/action.ts +166 -0
  113. package/src/sdk/index.ts +110 -0
  114. package/src/sdk/types.ts +146 -0
  115. package/src/strategies/avoid-lone.ts +11 -0
  116. package/src/strategies/avoid-players.knowledge.md +20 -0
  117. package/src/strategies/avoid-players.ts +15 -0
  118. package/src/strategies/corpse-patrol.ts +22 -0
  119. package/src/strategies/crab-sabotage.ts +21 -0
  120. package/src/strategies/custom-module.test.ts +269 -0
  121. package/src/strategies/find-player.ts +16 -0
  122. package/src/strategies/game-utils.test.ts +164 -0
  123. package/src/strategies/game-utils.ts +721 -0
  124. package/src/strategies/goals/avoid-lone-top.ts +168 -0
  125. package/src/strategies/goals/avoid-players-top.test.ts +83 -0
  126. package/src/strategies/goals/avoid-players-top.ts +121 -0
  127. package/src/strategies/goals/conversation-goal.ts +51 -0
  128. package/src/strategies/goals/corpse-patrol-top.ts +91 -0
  129. package/src/strategies/goals/crab-octopus-reflexes.ts +93 -0
  130. package/src/strategies/goals/crab-sabotage-top.ts +197 -0
  131. package/src/strategies/goals/emergency-hunt-goal.ts +28 -0
  132. package/src/strategies/goals/find-player-top.ts +93 -0
  133. package/src/strategies/goals/flee-players-goal.ts +53 -0
  134. package/src/strategies/goals/goal-manager.ts +41 -0
  135. package/src/strategies/goals/goal-root-strategy.ts +49 -0
  136. package/src/strategies/goals/goal.ts +28 -0
  137. package/src/strategies/goals/keep-away-goal.ts +206 -0
  138. package/src/strategies/goals/kill-frenzy-top.ts +80 -0
  139. package/src/strategies/goals/kill-lone-top.ts +160 -0
  140. package/src/strategies/goals/kill-target-goal.ts +59 -0
  141. package/src/strategies/goals/kill-target-top.ts +109 -0
  142. package/src/strategies/goals/leaf-goal.ts +25 -0
  143. package/src/strategies/goals/linger-corpse-goal.ts +79 -0
  144. package/src/strategies/goals/lone-kill-core.ts +82 -0
  145. package/src/strategies/goals/lone-kill-goal.ts +24 -0
  146. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -0
  147. package/src/strategies/goals/lone-kill-task-top.ts +86 -0
  148. package/src/strategies/goals/move-room-goal.ts +60 -0
  149. package/src/strategies/goals/normal-shrimp-top.test.ts +80 -0
  150. package/src/strategies/goals/normal-shrimp-top.ts +242 -0
  151. package/src/strategies/goals/paradise-fish-top.test.ts +126 -0
  152. package/src/strategies/goals/paradise-fish-top.ts +219 -0
  153. package/src/strategies/goals/patrol-top.ts +57 -0
  154. package/src/strategies/goals/report-patrol-top.ts +80 -0
  155. package/src/strategies/goals/safe-task-goal.ts +102 -0
  156. package/src/strategies/goals/social-task-top.ts +161 -0
  157. package/src/strategies/goals/task-kill-report-top.ts +163 -0
  158. package/src/strategies/goals/task-only-top.ts +57 -0
  159. package/src/strategies/goals/task-or-patrol-goal.ts +41 -0
  160. package/src/strategies/goals/task-report-top.ts +57 -0
  161. package/src/strategies/goals/wander-task-goal.ts +33 -0
  162. package/src/strategies/goals/warrior-shrimp-top.test.ts +86 -0
  163. package/src/strategies/goals/warrior-shrimp-top.ts +248 -0
  164. package/src/strategies/greeting.ts +53 -0
  165. package/src/strategies/kill-frenzy.ts +12 -0
  166. package/src/strategies/kill-lone.knowledge.md +20 -0
  167. package/src/strategies/kill-lone.ts +13 -0
  168. package/src/strategies/kill-target.ts +18 -0
  169. package/src/strategies/loader.test.ts +678 -0
  170. package/src/strategies/loader.ts +172 -0
  171. package/src/strategies/lone-kill-task.ts +21 -0
  172. package/src/strategies/meeting-gate.test.ts +59 -0
  173. package/src/strategies/meeting-gate.ts +23 -0
  174. package/src/strategies/move-room.ts +15 -0
  175. package/src/strategies/new-events-backfill.ts +98 -0
  176. package/src/strategies/paradise-fish.knowledge.md +20 -0
  177. package/src/strategies/paradise-fish.ts +25 -0
  178. package/src/strategies/pathfind/clawclaw-walkable.bin +0 -0
  179. package/src/strategies/pathfind/distance-field.ts +150 -0
  180. package/src/strategies/pathfind/escape-planner.test.ts +197 -0
  181. package/src/strategies/pathfind/escape-planner.ts +348 -0
  182. package/src/strategies/pathfind/walkable-grid.ts +117 -0
  183. package/src/strategies/patrol.ts +11 -0
  184. package/src/strategies/player-targets.ts +13 -0
  185. package/src/strategies/report-patrol.ts +11 -0
  186. package/src/strategies/shrimp-memory.knowledge.md +20 -0
  187. package/src/strategies/shrimp-memory.ts +25 -0
  188. package/src/strategies/social-task.test.ts +28 -0
  189. package/src/strategies/social-task.ts +49 -0
  190. package/src/strategies/spawn.ts +71 -0
  191. package/src/strategies/speech-module.ts +123 -0
  192. package/src/strategies/strategy-loop.ts +757 -0
  193. package/src/strategies/task-kill-report.ts +17 -0
  194. package/src/strategies/task-only.ts +11 -0
  195. package/src/strategies/task-report.ts +22 -0
  196. package/src/strategies/types.ts +96 -0
  197. package/src/strategies/warrior-memory.knowledge.md +20 -0
  198. package/src/strategies/warrior-memory.ts +16 -0
@@ -0,0 +1,44 @@
1
+ import { resolve, win32 } from 'path';
2
+ import { CLAWCLAW_WORKSPACE_DIR } from './init-command.js';
3
+
4
+ const WORKSPACE_DIR_OPTION = '--workspace-dir';
5
+ export { CLAWCLAW_WORKSPACE_DIR };
6
+
7
+ function isPresent(value: string | undefined): value is string {
8
+ return typeof value === 'string' && value.trim() !== '' && !value.startsWith('-');
9
+ }
10
+
11
+ export function extractWorkspaceDirArgv(argv: readonly string[]): string | undefined {
12
+ for (let i = 0; i < argv.length; i += 1) {
13
+ const current = argv[i];
14
+ if (current === WORKSPACE_DIR_OPTION) {
15
+ const next = argv[i + 1];
16
+ return isPresent(next) ? next : undefined;
17
+ }
18
+
19
+ if (current.startsWith(`${WORKSPACE_DIR_OPTION}=`)) {
20
+ const value = current.slice(WORKSPACE_DIR_OPTION.length + 1);
21
+ return isPresent(value) ? value : undefined;
22
+ }
23
+ }
24
+
25
+ return undefined;
26
+ }
27
+
28
+ export function applyWorkspaceArgv(
29
+ argv: readonly string[],
30
+ env: NodeJS.ProcessEnv,
31
+ cwd: string = process.cwd(),
32
+ ): string | undefined {
33
+ const workspaceDir = extractWorkspaceDirArgv(argv);
34
+ if (!workspaceDir) {
35
+ return undefined;
36
+ }
37
+
38
+ const useWin32Path = /^[A-Za-z]:[\\/]/.test(cwd) || /^[A-Za-z]:[\\/]/.test(workspaceDir);
39
+ const resolvedWorkspaceDir = useWin32Path
40
+ ? win32.resolve(cwd, workspaceDir)
41
+ : resolve(cwd, workspaceDir);
42
+ env[CLAWCLAW_WORKSPACE_DIR] = resolvedWorkspaceDir;
43
+ return resolvedWorkspaceDir;
44
+ }
@@ -0,0 +1,87 @@
1
+ import { existsSync, mkdtempSync, readFileSync } from 'fs';
2
+ import { tmpdir } from 'os';
3
+ import { join } from 'path';
4
+ import { describe, expect, it } from 'vitest';
5
+ import { PlayerHistoryStore, playerHistoryPathForSession } from './player-history-store.js';
6
+
7
+ describe('PlayerHistoryStore', () => {
8
+ it('derives sidecar path from the session jsonl path', () => {
9
+ expect(playerHistoryPathForSession('/tmp/game.jsonl')).toBe('/tmp/game.player-history.json');
10
+ expect(playerHistoryPathForSession('/tmp/game')).toBe('/tmp/game.player-history.json');
11
+ });
12
+
13
+ it('records player_spotted by tick, fills empty frames, and merges same tick players', () => {
14
+ const dir = mkdtempSync(join(tmpdir(), 'player-history-'));
15
+ const store = new PlayerHistoryStore(join(dir, 'session.player-history.json'));
16
+ store.reset(Date.parse('2026-05-21T00:00:00.000Z'));
17
+
18
+ expect(store.recordPlayerSpotted({
19
+ type: 'player_spotted',
20
+ tick: 10,
21
+ spotted_name: '砂锅猎手',
22
+ spotted_room: '动力监控室',
23
+ spotted_x: 1,
24
+ spotted_y: 2,
25
+ }, Date.parse('2026-05-21T00:00:01.000Z'))).toBe(true);
26
+ store.recordPlayerSpotted({
27
+ type: 'player_spotted',
28
+ tick: 13,
29
+ spotted_name: '洋流王子',
30
+ spotted_room: 'hallway',
31
+ spotted_x: 3,
32
+ spotted_y: 4,
33
+ }, Date.parse('2026-05-21T00:00:02.000Z'));
34
+ store.recordPlayerSpotted({
35
+ type: 'player_spotted',
36
+ tick: 13,
37
+ spotted_name: '测试-浮沉-0bc9',
38
+ spotted_room: 'hallway',
39
+ spotted_x: 5,
40
+ spotted_y: 6,
41
+ }, Date.parse('2026-05-21T00:00:02.000Z'));
42
+
43
+ const data = store.read()!;
44
+ expect(data.visible_frames.map((frame) => frame.tick)).toEqual([10, 11, 12, 13]);
45
+ expect(data.visible_frames[1].players).toEqual({});
46
+ expect(data.visible_frames[2].players).toEqual({});
47
+ expect(new Set(Object.keys(data.visible_frames[3].players))).toEqual(new Set(['测试-浮沉-0bc9', '洋流王子']));
48
+ expect(data.last_history_tick).toBe(13);
49
+ });
50
+
51
+ it('does not backfill a missing old tick after later ticks have been processed', () => {
52
+ const dir = mkdtempSync(join(tmpdir(), 'player-history-'));
53
+ const store = new PlayerHistoryStore(join(dir, 'session.player-history.json'));
54
+ store.reset();
55
+ store.recordPlayerSpotted({ type: 'player_spotted', tick: 10, spotted_name: 'A', spotted_x: 1, spotted_y: 1 });
56
+ store.recordPlayerSpotted({ type: 'player_spotted', tick: 13, spotted_name: 'B', spotted_x: 2, spotted_y: 2 });
57
+ expect(store.recordPlayerSpotted({ type: 'player_spotted', tick: 9, spotted_name: 'C', spotted_x: 3, spotted_y: 3 })).toBe(false);
58
+ expect(store.read()!.visible_frames.some((frame) => frame.tick === 9)).toBe(false);
59
+ });
60
+
61
+ it('caches seats and lobster task locations from map data', () => {
62
+ const dir = mkdtempSync(join(tmpdir(), 'player-history-'));
63
+ const store = new PlayerHistoryStore(join(dir, 'session.player-history.json'));
64
+ store.reset();
65
+ store.updateMapCache({
66
+ all_players: [{ name: 'A', seat: 1 }, { name: 'B', seat: 2 }],
67
+ all_task_locations: [
68
+ { name: '修线', room: '电力', x: 10, y: 20, faction: 'lobster' },
69
+ { name: '破坏', room: '制氧', x: 30, y: 40, faction: 'crab' },
70
+ ],
71
+ });
72
+ const data = store.read()!;
73
+ expect(data.seats).toEqual({ A: 1, B: 2 });
74
+ expect(data.lobster_tasks).toEqual([{ name: '修线', room: '电力', x: 10, y: 20 }]);
75
+ });
76
+
77
+ it('deletes the sidecar when requested', () => {
78
+ const dir = mkdtempSync(join(tmpdir(), 'player-history-'));
79
+ const path = join(dir, 'session.player-history.json');
80
+ const store = new PlayerHistoryStore(path);
81
+ store.reset();
82
+ expect(existsSync(path)).toBe(true);
83
+ expect(JSON.parse(readFileSync(path, 'utf8')).visible_frames).toEqual([]);
84
+ store.delete();
85
+ expect(existsSync(path)).toBe(false);
86
+ });
87
+ });
@@ -0,0 +1,194 @@
1
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
2
+ import { dirname } from 'path';
3
+
4
+ export interface FramePlayer {
5
+ x: number;
6
+ y: number;
7
+ room?: string | null;
8
+ }
9
+
10
+ export interface VisibleFrame {
11
+ tick: number;
12
+ time: string;
13
+ players: Record<string, FramePlayer>;
14
+ }
15
+
16
+ export interface LobsterTaskPoint {
17
+ name: string;
18
+ room?: string | null;
19
+ x: number;
20
+ y: number;
21
+ }
22
+
23
+ export interface PlayerHistoryData {
24
+ time: string;
25
+ visible_frames: VisibleFrame[];
26
+ seats: Record<string, number>;
27
+ lobster_tasks: LobsterTaskPoint[];
28
+ last_raw_frame: null;
29
+ last_history_tick: number | null;
30
+ }
31
+
32
+ const TICK_MS = 100;
33
+
34
+ function nowIso(nowMs = Date.now()): string {
35
+ return new Date(nowMs).toISOString();
36
+ }
37
+
38
+ function isFiniteNumber(value: unknown): value is number {
39
+ return typeof value === 'number' && Number.isFinite(value);
40
+ }
41
+
42
+ function frameTimeFromPrevious(data: PlayerHistoryData, tick: number, nowMs: number): string {
43
+ const lastTick = data.last_history_tick;
44
+ if (lastTick == null || tick <= lastTick) return nowIso(nowMs);
45
+ const lastFrame = data.visible_frames.find((frame) => frame.tick === lastTick);
46
+ const lastMs = lastFrame ? Date.parse(lastFrame.time) : NaN;
47
+ const baseMs = Number.isFinite(lastMs) ? lastMs : nowMs - (tick - lastTick) * TICK_MS;
48
+ return nowIso(baseMs + (tick - lastTick) * TICK_MS);
49
+ }
50
+
51
+ function createEmptyData(nowMs = Date.now()): PlayerHistoryData {
52
+ return {
53
+ time: nowIso(nowMs),
54
+ visible_frames: [],
55
+ seats: {},
56
+ lobster_tasks: [],
57
+ last_raw_frame: null,
58
+ last_history_tick: null,
59
+ };
60
+ }
61
+
62
+ function normalizeData(raw: Partial<PlayerHistoryData> | null, nowMs = Date.now()): PlayerHistoryData {
63
+ return {
64
+ time: typeof raw?.time === 'string' ? raw.time : nowIso(nowMs),
65
+ visible_frames: Array.isArray(raw?.visible_frames) ? raw.visible_frames : [],
66
+ seats: raw?.seats && typeof raw.seats === 'object' ? raw.seats : {},
67
+ lobster_tasks: Array.isArray(raw?.lobster_tasks) ? raw.lobster_tasks : [],
68
+ last_raw_frame: null,
69
+ last_history_tick: isFiniteNumber(raw?.last_history_tick) ? raw.last_history_tick : null,
70
+ };
71
+ }
72
+
73
+ function ensureFrame(data: PlayerHistoryData, tick: number, time: string): VisibleFrame {
74
+ let frame = data.visible_frames.find((candidate) => candidate.tick === tick);
75
+ if (!frame) {
76
+ frame = { tick, time, players: {} };
77
+ data.visible_frames.push(frame);
78
+ data.visible_frames.sort((a, b) => a.tick - b.tick);
79
+ }
80
+ return frame;
81
+ }
82
+
83
+ export function playerHistoryPathForSession(sessionPath: string): string {
84
+ return sessionPath.endsWith('.jsonl')
85
+ ? `${sessionPath.slice(0, -'.jsonl'.length)}.player-history.json`
86
+ : `${sessionPath}.player-history.json`;
87
+ }
88
+
89
+ export class PlayerHistoryStore {
90
+ constructor(private filePath: string) {}
91
+
92
+ get path(): string {
93
+ return this.filePath;
94
+ }
95
+
96
+ static forSession(sessionPath: string): PlayerHistoryStore {
97
+ return new PlayerHistoryStore(playerHistoryPathForSession(sessionPath));
98
+ }
99
+
100
+ read(): PlayerHistoryData | null {
101
+ if (!existsSync(this.filePath)) return null;
102
+ try {
103
+ return normalizeData(JSON.parse(readFileSync(this.filePath, 'utf8')));
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+
109
+ reset(nowMs = Date.now()): PlayerHistoryData {
110
+ const data = createEmptyData(nowMs);
111
+ this.write(data);
112
+ return data;
113
+ }
114
+
115
+ delete(): void {
116
+ try { unlinkSync(this.filePath); } catch {}
117
+ }
118
+
119
+ updateMapCache(mapData: any, nowMs = Date.now()): void {
120
+ if (!mapData || typeof mapData !== 'object') return;
121
+ const data = this.read() ?? createEmptyData(nowMs);
122
+ const seats: Record<string, number> = {};
123
+ for (const player of Array.isArray(mapData.all_players) ? mapData.all_players : []) {
124
+ if (typeof player?.name !== 'string' || !isFiniteNumber(player.seat)) continue;
125
+ seats[player.name] = player.seat;
126
+ }
127
+ const lobsterTasks: LobsterTaskPoint[] = [];
128
+ for (const task of Array.isArray(mapData.all_task_locations) ? mapData.all_task_locations : []) {
129
+ if (task?.faction !== 'lobster') continue;
130
+ if (typeof task.name !== 'string' || !isFiniteNumber(task.x) || !isFiniteNumber(task.y)) continue;
131
+ lobsterTasks.push({
132
+ name: task.name,
133
+ room: typeof task.room === 'string' ? task.room : null,
134
+ x: task.x,
135
+ y: task.y,
136
+ });
137
+ }
138
+ data.seats = seats;
139
+ data.lobster_tasks = lobsterTasks;
140
+ data.time = nowIso(nowMs);
141
+ this.write(data);
142
+ }
143
+
144
+ recordPlayerSpotted(event: Record<string, any>, nowMs = Date.now()): boolean {
145
+ if (event.type !== 'player_spotted') return false;
146
+ const tick = event.tick;
147
+ const name = event.spotted_name;
148
+ const x = event.spotted_x;
149
+ const y = event.spotted_y;
150
+ if (!isFiniteNumber(tick) || !Number.isInteger(tick)) return false;
151
+ if (typeof name !== 'string' || name.length === 0) return false;
152
+ if (!isFiniteNumber(x) || !isFiniteNumber(y)) return false;
153
+
154
+ const data = this.read() ?? createEmptyData(nowMs);
155
+ let frame: VisibleFrame | undefined;
156
+ const lastTick = data.last_history_tick;
157
+
158
+ if (lastTick == null) {
159
+ frame = ensureFrame(data, tick, nowIso(nowMs));
160
+ data.last_history_tick = tick;
161
+ } else if (tick > lastTick) {
162
+ const lastFrame = data.visible_frames.find((candidate) => candidate.tick === lastTick);
163
+ const lastMs = lastFrame ? Date.parse(lastFrame.time) : NaN;
164
+ const baseMs = Number.isFinite(lastMs) ? lastMs : nowMs - (tick - lastTick) * TICK_MS;
165
+ for (let emptyTick = lastTick + 1; emptyTick < tick; emptyTick++) {
166
+ ensureFrame(data, emptyTick, nowIso(baseMs + (emptyTick - lastTick) * TICK_MS));
167
+ }
168
+ frame = ensureFrame(data, tick, nowIso(baseMs + (tick - lastTick) * TICK_MS));
169
+ data.last_history_tick = tick;
170
+ } else {
171
+ frame = data.visible_frames.find((candidate) => candidate.tick === tick);
172
+ if (!frame && tick === lastTick) frame = ensureFrame(data, tick, frameTimeFromPrevious(data, tick, nowMs));
173
+ if (!frame) return false;
174
+ }
175
+
176
+ frame.players[name] = {
177
+ x,
178
+ y,
179
+ room: typeof event.spotted_room === 'string'
180
+ ? event.spotted_room
181
+ : typeof event.room === 'string'
182
+ ? event.room
183
+ : null,
184
+ };
185
+ data.time = nowIso(nowMs);
186
+ this.write(data);
187
+ return true;
188
+ }
189
+
190
+ private write(data: PlayerHistoryData): void {
191
+ mkdirSync(dirname(this.filePath), { recursive: true });
192
+ writeFileSync(this.filePath, JSON.stringify(data, null, 2));
193
+ }
194
+ }
@@ -0,0 +1,124 @@
1
+ import { appendFileSync, readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';
2
+ import { dirname, join, basename } from 'path';
3
+ import { AuthStore } from '../lib/auth.js';
4
+ import { getProfileGamesDir } from '../lib/init-command.js';
5
+
6
+ interface GameSessionFile {
7
+ path: string;
8
+ sessionId: string;
9
+ mtimeMs: number;
10
+ }
11
+
12
+ export function extractNewEvents(source: any): Record<string, any>[] {
13
+ const candidates = [
14
+ source,
15
+ source?.new_events,
16
+ source?.data?.new_events,
17
+ source?.result?.new_events,
18
+ source?.result?.data?.new_events,
19
+ ];
20
+
21
+ for (const candidate of candidates) {
22
+ if (Array.isArray(candidate)) {
23
+ return candidate.filter((evt) => evt && typeof evt === 'object');
24
+ }
25
+ }
26
+
27
+ return [];
28
+ }
29
+
30
+ export class EventStore {
31
+ constructor(private filePath: string) {}
32
+
33
+ get path(): string {
34
+ return this.filePath;
35
+ }
36
+
37
+ static forActiveAccount(): EventStore {
38
+ return EventStore.forLatestGame();
39
+ }
40
+
41
+ static forLatestGame(): EventStore {
42
+ const store = new AuthStore();
43
+ const profile = store.getActive();
44
+ if (!profile) throw new Error('Not logged in.');
45
+
46
+ const latest = EventStore.latestSessionFile(getProfileGamesDir(profile));
47
+ if (!latest) {
48
+ throw new Error('No game events found. Join a game first.');
49
+ }
50
+
51
+ return new EventStore(latest.path);
52
+ }
53
+
54
+ /** Returns the path to the latest session jsonl, or null if none exists. */
55
+ static latestSessionPath(): string | null {
56
+ const store = new AuthStore();
57
+ const profile = store.getActive();
58
+ if (!profile) return null;
59
+ return EventStore.latestSessionFile(getProfileGamesDir(profile))?.path ?? null;
60
+ }
61
+
62
+ static createSessionForActiveAccount(sessionId = EventStore.createSessionId()): EventStore {
63
+ const store = new AuthStore();
64
+ const profile = store.getActive();
65
+ if (!profile) throw new Error('Not logged in.');
66
+
67
+ const dir = getProfileGamesDir(profile);
68
+ mkdirSync(dir, { recursive: true });
69
+ const filePath = join(dir, `${sessionId}.jsonl`);
70
+ if (!existsSync(filePath)) writeFileSync(filePath, '');
71
+ return new EventStore(filePath);
72
+ }
73
+
74
+ append(event: Record<string, any>): void {
75
+ mkdirSync(dirname(this.filePath), { recursive: true });
76
+ const line = JSON.stringify(event) + '\n';
77
+ appendFileSync(this.filePath, line);
78
+ }
79
+
80
+ appendNewEvents(events: any): void {
81
+ const extracted = extractNewEvents(events);
82
+ if (extracted.length === 0) return;
83
+ for (const evt of extracted) {
84
+ this.append(evt);
85
+ }
86
+ }
87
+
88
+ tail(n: number): Record<string, any>[] {
89
+ if (!existsSync(this.filePath)) return [];
90
+ const lines = readFileSync(this.filePath, 'utf8').trim().split('\n').filter(Boolean);
91
+ return lines.slice(-n).map(l => JSON.parse(l));
92
+ }
93
+
94
+ all(): Record<string, any>[] {
95
+ if (!existsSync(this.filePath)) return [];
96
+ const content = readFileSync(this.filePath, 'utf8').trim();
97
+ if (!content) return [];
98
+ return content.split('\n').filter(Boolean).map(l => JSON.parse(l));
99
+ }
100
+
101
+ clear(): void {
102
+ writeFileSync(this.filePath, '');
103
+ }
104
+
105
+ private static createSessionId(): string {
106
+ const id = new Date().toISOString();
107
+ return process.platform === 'win32' ? id.replace(/:/g, '_') : id;
108
+ }
109
+
110
+ private static latestSessionFile(dir: string): GameSessionFile | null {
111
+ if (!existsSync(dir)) return null;
112
+
113
+ const files = readdirSync(dir)
114
+ .filter(name => name.endsWith('.jsonl') && !name.endsWith('.raw-ws.jsonl') && !name.startsWith('index.'))
115
+ .map(name => {
116
+ const path = join(dir, name);
117
+ const stat = statSync(path);
118
+ return { path, sessionId: basename(name, '.jsonl'), mtimeMs: stat.mtimeMs };
119
+ })
120
+ .sort((a, b) => b.sessionId.localeCompare(a.sessionId) || b.mtimeMs - a.mtimeMs);
121
+
122
+ return files[0] ?? null;
123
+ }
124
+ }
@@ -0,0 +1,35 @@
1
+ import { GameClient } from '../lib/game-client.js';
2
+ import { EventStore } from './event-store.js';
3
+
4
+ interface PipelineAction {
5
+ action: Record<string, any>;
6
+ needsWait: boolean;
7
+ }
8
+
9
+ export async function runPipeline(actions: PipelineAction[], initialWaitMs?: number): Promise<void> {
10
+ const client = GameClient.fromAuth();
11
+ const store = EventStore.forActiveAccount();
12
+
13
+ if (initialWaitMs && initialWaitMs > 0) {
14
+ await new Promise(r => setTimeout(r, initialWaitMs));
15
+ }
16
+
17
+ for (const item of actions) {
18
+ const result = await client.submitAction(item.action as any);
19
+ store.appendNewEvents(result);
20
+ const durationSecs = result?.data?.duration_secs ?? result?.duration_secs ?? 0;
21
+
22
+ if (item.needsWait && durationSecs > 0) {
23
+ await new Promise(r => setTimeout(r, (durationSecs + 0.5) * 1000));
24
+ try {
25
+ const state = await client.getGameState();
26
+ if (state) store.appendNewEvents(state.new_events);
27
+ } catch {}
28
+ store.append({ type: 'pipeline', action: item.action, status: 'done' });
29
+ } else {
30
+ store.append({ type: 'pipeline', action: item.action, result });
31
+ }
32
+ }
33
+
34
+ store.append({ type: 'pipeline_done', count: actions.length });
35
+ }
@@ -0,0 +1,66 @@
1
+ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
2
+
3
+ vi.mock('../commands/upgrade.js', () => ({
4
+ runDefaultUpgrade: vi.fn(),
5
+ }));
6
+
7
+ import { runDefaultUpgrade } from '../commands/upgrade.js';
8
+ import { runAutoUpgradeOnLoad, shouldSkipAutoUpgrade } from './auto-upgrade.js';
9
+
10
+ describe('runAutoUpgradeOnLoad', () => {
11
+ const prev = process.env.CLAWCLAW_SKIP_AUTO_UPGRADE;
12
+
13
+ beforeEach(() => {
14
+ vi.mocked(runDefaultUpgrade).mockReset();
15
+ delete process.env.CLAWCLAW_SKIP_AUTO_UPGRADE;
16
+ });
17
+
18
+ afterEach(() => {
19
+ if (prev === undefined) delete process.env.CLAWCLAW_SKIP_AUTO_UPGRADE;
20
+ else process.env.CLAWCLAW_SKIP_AUTO_UPGRADE = prev;
21
+ });
22
+
23
+ it('skips when CLAWCLAW_SKIP_AUTO_UPGRADE=1', () => {
24
+ process.env.CLAWCLAW_SKIP_AUTO_UPGRADE = '1';
25
+ runAutoUpgradeOnLoad({ packageVersion: '0.5.25' });
26
+ expect(runDefaultUpgrade).not.toHaveBeenCalled();
27
+ });
28
+
29
+ it('skips prerelease/test package versions', () => {
30
+ runAutoUpgradeOnLoad({ packageVersion: '0.5.25-test' });
31
+ expect(runDefaultUpgrade).not.toHaveBeenCalled();
32
+ });
33
+
34
+ it('runs default upgrade when not skipped', () => {
35
+ vi.mocked(runDefaultUpgrade).mockReturnValue({ version: '0.4.8' });
36
+ runAutoUpgradeOnLoad({ packageVersion: '0.5.25' });
37
+ expect(runDefaultUpgrade).toHaveBeenCalledOnce();
38
+ });
39
+
40
+ it('does not write upgrade progress to stdout', () => {
41
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
42
+ vi.mocked(runDefaultUpgrade).mockReturnValue({ version: '0.4.8' });
43
+ try {
44
+ runAutoUpgradeOnLoad({ packageVersion: '0.5.25' });
45
+ expect(logSpy).not.toHaveBeenCalled();
46
+ } finally {
47
+ logSpy.mockRestore();
48
+ }
49
+ });
50
+
51
+ it('notifies on upgrade success and failure', () => {
52
+ const notify = vi.fn();
53
+ vi.mocked(runDefaultUpgrade).mockReturnValueOnce({ version: '0.4.8' });
54
+ runAutoUpgradeOnLoad({ packageVersion: '0.5.25', notify });
55
+ expect(notify).toHaveBeenCalledWith('[clawclaw-cli] auto-upgrade installed 0.4.8');
56
+
57
+ vi.mocked(runDefaultUpgrade).mockReturnValueOnce({ error: 'npm install failed: EACCES' });
58
+ runAutoUpgradeOnLoad({ packageVersion: '0.5.25', notify });
59
+ expect(notify).toHaveBeenCalledWith('[clawclaw-cli] auto-upgrade failed: npm install failed: EACCES');
60
+ });
61
+
62
+ it('treats prerelease versions as skip-worthy', () => {
63
+ expect(shouldSkipAutoUpgrade('0.5.25-test')).toBe(true);
64
+ expect(shouldSkipAutoUpgrade('0.5.25')).toBe(false);
65
+ });
66
+ });
@@ -0,0 +1,31 @@
1
+ import { readFileSync } from 'fs';
2
+ import { runDefaultUpgrade } from '../commands/upgrade.js';
3
+
4
+ function readPackageVersion(): string | null {
5
+ try {
6
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
7
+ return typeof pkg?.version === 'string' ? pkg.version : null;
8
+ } catch {
9
+ return null;
10
+ }
11
+ }
12
+
13
+ export function shouldSkipAutoUpgrade(packageVersion = readPackageVersion()): boolean {
14
+ if (process.env.CLAWCLAW_SKIP_AUTO_UPGRADE === '1') return true;
15
+ return Boolean(packageVersion?.includes('-'));
16
+ }
17
+
18
+ /** Run during `ccl load`, before game start and event streaming begin. */
19
+ export function runAutoUpgradeOnLoad(options?: { packageVersion?: string; notify?: (message: string) => void }): void {
20
+ if (shouldSkipAutoUpgrade(options?.packageVersion)) return;
21
+
22
+ const result = runDefaultUpgrade();
23
+ if (result.error) {
24
+ const msg = result.version ? `${result.version} (${result.error})` : result.error;
25
+ options?.notify?.(`[clawclaw-cli] auto-upgrade failed: ${msg}`);
26
+ return;
27
+ }
28
+ if (result.version) {
29
+ options?.notify?.(`[clawclaw-cli] auto-upgrade installed ${result.version}`);
30
+ }
31
+ }
@@ -0,0 +1,100 @@
1
+ import { existsSync, mkdirSync, openSync, readFileSync } from 'fs';
2
+ import { resolve, dirname, delimiter } from 'path';
3
+ import { spawn, execSync } from 'child_process';
4
+ import { join } from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { getProfileStateDir, getProfileLogsDir } from '../lib/init-command.js';
7
+ import { AuthStore } from '../lib/auth.js';
8
+ import { RuntimeLogger } from './runtime-logger.js';
9
+
10
+ const log = new RuntimeLogger();
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = dirname(__filename);
14
+
15
+ function isPidAlive(pid: number): boolean {
16
+ try { process.kill(pid, 0); return true; } catch { return false; }
17
+ }
18
+
19
+ export function getRunningDaemonPid(stateDir: string): number | null {
20
+ const runtimePath = join(stateDir, 'runtime.json');
21
+ if (!existsSync(runtimePath)) return null;
22
+ try {
23
+ const info = JSON.parse(readFileSync(runtimePath, 'utf8'));
24
+ if (typeof info?.pid === 'number' && isPidAlive(info.pid)) return info.pid;
25
+ } catch {}
26
+ return null;
27
+ }
28
+
29
+ export async function waitDaemonExit(stateDir: string, timeoutMs = 15000): Promise<void> {
30
+ const runtimePath = join(stateDir, 'runtime.json');
31
+ let pid: number | undefined;
32
+ try {
33
+ if (existsSync(runtimePath)) {
34
+ const info = JSON.parse(readFileSync(runtimePath, 'utf8'));
35
+ if (typeof info?.pid === 'number') pid = info.pid;
36
+ }
37
+ } catch {}
38
+
39
+ const deadline = Date.now() + timeoutMs;
40
+ while (Date.now() < deadline) {
41
+ const fileGone = !existsSync(runtimePath);
42
+ const procGone = pid === undefined ? true : !isPidAlive(pid);
43
+ if (fileGone && procGone) return;
44
+ await new Promise(r => setTimeout(r, 200));
45
+ }
46
+ throw new Error(
47
+ `Daemon did not exit within ${timeoutMs}ms (pid=${pid ?? 'unknown'}).`,
48
+ );
49
+ }
50
+
51
+ export function spawnDaemon(): { pid: number; logFile: string } {
52
+ const store = new AuthStore();
53
+ const active = store.getActive();
54
+ if (!active) throw new Error('Not logged in.');
55
+
56
+ const stateDir = getProfileStateDir(active);
57
+ mkdirSync(stateDir, { recursive: true });
58
+
59
+ const existingPid = getRunningDaemonPid(stateDir);
60
+ if (existingPid) {
61
+ throw new Error(`Daemon already running (pid=${existingPid}). Stop it first.`);
62
+ }
63
+
64
+ const logsDir = getProfileLogsDir(active);
65
+ mkdirSync(logsDir, { recursive: true });
66
+
67
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
68
+ const logFile = join(logsDir, `daemon-${timestamp}.log`);
69
+ const logFd = openSync(logFile, 'a');
70
+
71
+ const fwd = (p: string) => p.replace(/\\/g, '/');
72
+ const binEntry = fwd(resolve(__dirname, '..', '..', 'bin', 'clawclaw-cli.mjs'));
73
+ if (!existsSync(binEntry)) throw new Error('clawclaw-cli bin entry not found');
74
+
75
+ let npmGlobalModules = '';
76
+ try { npmGlobalModules = execSync('npm root -g', { encoding: 'utf8', windowsHide: true }).trim(); } catch {}
77
+
78
+ const existingNodePath = process.env.NODE_PATH ?? '';
79
+ const nodePath = [npmGlobalModules, existingNodePath].filter(Boolean).join(delimiter);
80
+ const isWin = process.platform === 'win32';
81
+
82
+ const child = spawn(process.execPath, [binEntry, '_daemon'], {
83
+ detached: true,
84
+ stdio: isWin ? ['ignore', 'ignore', 'ignore'] : ['ignore', logFd, logFd],
85
+ cwd: process.cwd(),
86
+ env: {
87
+ ...process.env,
88
+ NODE_PATH: nodePath,
89
+ ...(isWin ? { CLAWCLAW_LOG_FILE: logFile } : {}),
90
+ },
91
+ windowsHide: true,
92
+ });
93
+
94
+ child.on('error', (err) => {
95
+ log.error('DAEMON_SPAWN', `failed to start daemon`, err);
96
+ });
97
+
98
+ child.unref();
99
+ return { pid: child.pid!, logFile };
100
+ }