@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.
- package/README.md +440 -0
- package/bin/clawclaw-cli.mjs +4 -0
- package/package.json +48 -0
- package/personas//347/220/206/346/231/272/346/270/251/345/222/214.md +23 -0
- package/personas//350/200/201/350/260/213/346/267/261/347/256/227.md +22 -0
- package/personas//350/257/232/346/201/263/347/233/264/347/216/207.md +22 -0
- package/personas//350/275/273/346/235/276/346/264/273/346/263/274.md +22 -0
- package/personas//351/207/216/346/200/247/345/217/233/351/200/206.md +23 -0
- package/scripts/postinstall.mjs +20 -0
- package/scripts/sync-bundled-skill.mjs +245 -0
- package/scripts/sync-bundled-skill.test.mjs +152 -0
- package/skills/clawclaw/SKILL.md +240 -0
- package/skills/clawclaw/references/CHATTERBOX.md +142 -0
- package/skills/clawclaw/references/COMMANDS.md +132 -0
- package/skills/clawclaw/references/GAME-MECHANICS.md +186 -0
- package/skills/clawclaw/references/HUB.md +48 -0
- package/skills/clawclaw/references/KNOWLEDGE.md +43 -0
- package/skills/clawclaw/references/STRATEGIES.md +57 -0
- package/skills/clawclaw/references/STREAM.md +58 -0
- package/skills/clawclaw/references/TACTICS.md +65 -0
- package/src/assets/clawclaw-ascii-map.txt +40 -0
- package/src/cli.ts +153 -0
- package/src/commands/_schema.ts +109 -0
- package/src/commands/account.ts +209 -0
- package/src/commands/config.ts +30 -0
- package/src/commands/do.test.ts +37 -0
- package/src/commands/do.ts +95 -0
- package/src/commands/events.ts +22 -0
- package/src/commands/game-map.test.ts +28 -0
- package/src/commands/game-start-plan.test.ts +142 -0
- package/src/commands/game.ts +882 -0
- package/src/commands/history-player.test.ts +102 -0
- package/src/commands/history.ts +573 -0
- package/src/commands/hub.test.ts +96 -0
- package/src/commands/hub.ts +234 -0
- package/src/commands/knowledge.test.ts +19 -0
- package/src/commands/knowledge.ts +168 -0
- package/src/commands/load.test.ts +51 -0
- package/src/commands/load.ts +13 -0
- package/src/commands/meeting-history.test.ts +106 -0
- package/src/commands/memory.ts +40 -0
- package/src/commands/peek.ts +38 -0
- package/src/commands/persona.ts +57 -0
- package/src/commands/setup/codex.ts +248 -0
- package/src/commands/setup/hermes.test.ts +96 -0
- package/src/commands/setup/hermes.ts +76 -0
- package/src/commands/setup/index.ts +13 -0
- package/src/commands/setup/openclaw.test.ts +114 -0
- package/src/commands/setup/openclaw.ts +147 -0
- package/src/commands/skill.ts +128 -0
- package/src/commands/state.ts +46 -0
- package/src/commands/strategy.test.ts +135 -0
- package/src/commands/strategy.ts +189 -0
- package/src/commands/tts.ts +128 -0
- package/src/commands/upgrade.test.ts +91 -0
- package/src/commands/upgrade.ts +154 -0
- package/src/commands/watch.test.ts +973 -0
- package/src/commands/watch.ts +709 -0
- package/src/lib/auth.test.ts +59 -0
- package/src/lib/auth.ts +186 -0
- package/src/lib/command-meta.ts +37 -0
- package/src/lib/game-client.ts +391 -0
- package/src/lib/host-config-patcher.test.ts +130 -0
- package/src/lib/host-config-patcher.ts +151 -0
- package/src/lib/http-keepalive.ts +15 -0
- package/src/lib/http-transport.test.ts +42 -0
- package/src/lib/http-transport.ts +113 -0
- package/src/lib/hub-client.test.ts +56 -0
- package/src/lib/hub-client.ts +88 -0
- package/src/lib/hub-install.test.ts +98 -0
- package/src/lib/hub-install.ts +121 -0
- package/src/lib/hub-reminder.ts +75 -0
- package/src/lib/hub-unzip.test.ts +69 -0
- package/src/lib/hub-unzip.ts +62 -0
- package/src/lib/init-command.test.ts +75 -0
- package/src/lib/init-command.ts +120 -0
- package/src/lib/knowledge-store.test.ts +180 -0
- package/src/lib/knowledge-store.ts +374 -0
- package/src/lib/load-context.test.ts +52 -0
- package/src/lib/load-context.ts +52 -0
- package/src/lib/match-state.test.ts +134 -0
- package/src/lib/match-state.ts +94 -0
- package/src/lib/netease-tts.ts +83 -0
- package/src/lib/normalize.ts +42 -0
- package/src/lib/persona.test.ts +41 -0
- package/src/lib/persona.ts +72 -0
- package/src/lib/server-registry.ts +152 -0
- package/src/lib/skill-version.test.ts +48 -0
- package/src/lib/skill-version.ts +19 -0
- package/src/lib/strategy-export.test.ts +232 -0
- package/src/lib/strategy-export.ts +242 -0
- package/src/lib/tts-keys.ts +7 -0
- package/src/lib/tts-speech.test.ts +63 -0
- package/src/lib/tts-speech.ts +76 -0
- package/src/lib/workspace-argv.test.ts +49 -0
- package/src/lib/workspace-argv.ts +44 -0
- package/src/perception/player-history-store.test.ts +87 -0
- package/src/perception/player-history-store.ts +194 -0
- package/src/pipeline/event-store.ts +124 -0
- package/src/pipeline/pipeline.ts +35 -0
- package/src/runtime/auto-upgrade.test.ts +66 -0
- package/src/runtime/auto-upgrade.ts +31 -0
- package/src/runtime/daemon.ts +100 -0
- package/src/runtime/event-daemon.test.ts +28 -0
- package/src/runtime/event-daemon.ts +371 -0
- package/src/runtime/opening-mover.ts +303 -0
- package/src/runtime/raw-ws-log.test.ts +33 -0
- package/src/runtime/raw-ws-log.ts +32 -0
- package/src/runtime/runtime-logger.ts +99 -0
- package/src/runtime/ws-client.test.ts +47 -0
- package/src/runtime/ws-client.ts +272 -0
- package/src/sdk/action.ts +166 -0
- package/src/sdk/index.ts +110 -0
- package/src/sdk/types.ts +146 -0
- package/src/strategies/avoid-lone.ts +11 -0
- package/src/strategies/avoid-players.knowledge.md +20 -0
- package/src/strategies/avoid-players.ts +15 -0
- package/src/strategies/corpse-patrol.ts +22 -0
- package/src/strategies/crab-sabotage.ts +21 -0
- package/src/strategies/custom-module.test.ts +269 -0
- package/src/strategies/find-player.ts +16 -0
- package/src/strategies/game-utils.test.ts +164 -0
- package/src/strategies/game-utils.ts +721 -0
- package/src/strategies/goals/avoid-lone-top.ts +168 -0
- package/src/strategies/goals/avoid-players-top.test.ts +83 -0
- package/src/strategies/goals/avoid-players-top.ts +121 -0
- package/src/strategies/goals/conversation-goal.ts +51 -0
- package/src/strategies/goals/corpse-patrol-top.ts +91 -0
- package/src/strategies/goals/crab-octopus-reflexes.ts +93 -0
- package/src/strategies/goals/crab-sabotage-top.ts +197 -0
- package/src/strategies/goals/emergency-hunt-goal.ts +28 -0
- package/src/strategies/goals/find-player-top.ts +93 -0
- package/src/strategies/goals/flee-players-goal.ts +53 -0
- package/src/strategies/goals/goal-manager.ts +41 -0
- package/src/strategies/goals/goal-root-strategy.ts +49 -0
- package/src/strategies/goals/goal.ts +28 -0
- package/src/strategies/goals/keep-away-goal.ts +206 -0
- package/src/strategies/goals/kill-frenzy-top.ts +80 -0
- package/src/strategies/goals/kill-lone-top.ts +160 -0
- package/src/strategies/goals/kill-target-goal.ts +59 -0
- package/src/strategies/goals/kill-target-top.ts +109 -0
- package/src/strategies/goals/leaf-goal.ts +25 -0
- package/src/strategies/goals/linger-corpse-goal.ts +79 -0
- package/src/strategies/goals/lone-kill-core.ts +82 -0
- package/src/strategies/goals/lone-kill-goal.ts +24 -0
- package/src/strategies/goals/lone-kill-task-top.test.ts +85 -0
- package/src/strategies/goals/lone-kill-task-top.ts +86 -0
- package/src/strategies/goals/move-room-goal.ts +60 -0
- package/src/strategies/goals/normal-shrimp-top.test.ts +80 -0
- package/src/strategies/goals/normal-shrimp-top.ts +242 -0
- package/src/strategies/goals/paradise-fish-top.test.ts +126 -0
- package/src/strategies/goals/paradise-fish-top.ts +219 -0
- package/src/strategies/goals/patrol-top.ts +57 -0
- package/src/strategies/goals/report-patrol-top.ts +80 -0
- package/src/strategies/goals/safe-task-goal.ts +102 -0
- package/src/strategies/goals/social-task-top.ts +161 -0
- package/src/strategies/goals/task-kill-report-top.ts +163 -0
- package/src/strategies/goals/task-only-top.ts +57 -0
- package/src/strategies/goals/task-or-patrol-goal.ts +41 -0
- package/src/strategies/goals/task-report-top.ts +57 -0
- package/src/strategies/goals/wander-task-goal.ts +33 -0
- package/src/strategies/goals/warrior-shrimp-top.test.ts +86 -0
- package/src/strategies/goals/warrior-shrimp-top.ts +248 -0
- package/src/strategies/greeting.ts +53 -0
- package/src/strategies/kill-frenzy.ts +12 -0
- package/src/strategies/kill-lone.knowledge.md +20 -0
- package/src/strategies/kill-lone.ts +13 -0
- package/src/strategies/kill-target.ts +18 -0
- package/src/strategies/loader.test.ts +678 -0
- package/src/strategies/loader.ts +172 -0
- package/src/strategies/lone-kill-task.ts +21 -0
- package/src/strategies/meeting-gate.test.ts +59 -0
- package/src/strategies/meeting-gate.ts +23 -0
- package/src/strategies/move-room.ts +15 -0
- package/src/strategies/new-events-backfill.ts +98 -0
- package/src/strategies/paradise-fish.knowledge.md +20 -0
- package/src/strategies/paradise-fish.ts +25 -0
- package/src/strategies/pathfind/clawclaw-walkable.bin +0 -0
- package/src/strategies/pathfind/distance-field.ts +150 -0
- package/src/strategies/pathfind/escape-planner.test.ts +197 -0
- package/src/strategies/pathfind/escape-planner.ts +348 -0
- package/src/strategies/pathfind/walkable-grid.ts +117 -0
- package/src/strategies/patrol.ts +11 -0
- package/src/strategies/player-targets.ts +13 -0
- package/src/strategies/report-patrol.ts +11 -0
- package/src/strategies/shrimp-memory.knowledge.md +20 -0
- package/src/strategies/shrimp-memory.ts +25 -0
- package/src/strategies/social-task.test.ts +28 -0
- package/src/strategies/social-task.ts +49 -0
- package/src/strategies/spawn.ts +71 -0
- package/src/strategies/speech-module.ts +123 -0
- package/src/strategies/strategy-loop.ts +757 -0
- package/src/strategies/task-kill-report.ts +17 -0
- package/src/strategies/task-only.ts +11 -0
- package/src/strategies/task-report.ts +22 -0
- package/src/strategies/types.ts +96 -0
- package/src/strategies/warrior-memory.knowledge.md +20 -0
- package/src/strategies/warrior-memory.ts +16 -0
|
@@ -0,0 +1,882 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
import { AuthStore } from '../lib/auth.js';
|
|
5
|
+
import { ApiError, GameClient } from '../lib/game-client.js';
|
|
6
|
+
import { getProfileStateDir } from '../lib/init-command.js';
|
|
7
|
+
import { spawnDaemon, getRunningDaemonPid, waitDaemonExit } from '../runtime/daemon.js';
|
|
8
|
+
import { EventStore } from '../pipeline/event-store.js';
|
|
9
|
+
import { spawnOpeningMover, stopOpeningMoverIfRunning } from '../runtime/opening-mover.js';
|
|
10
|
+
import { spawnStrategyLoop } from '../strategies/spawn.js';
|
|
11
|
+
import { setMeta } from '../lib/command-meta.js';
|
|
12
|
+
import { runStreaming, buildErrorLine, readFeedSummary, nextStepFor } from './watch.js';
|
|
13
|
+
import { hubReminder, readCachedGamesPlayed } from '../lib/hub-reminder.js';
|
|
14
|
+
import {
|
|
15
|
+
startMatch,
|
|
16
|
+
endMatch,
|
|
17
|
+
readMatchState,
|
|
18
|
+
shouldEmitWaiting,
|
|
19
|
+
markWaitingEmitted,
|
|
20
|
+
getWaitedSecs,
|
|
21
|
+
hasMatchTimedOut,
|
|
22
|
+
} from '../lib/match-state.js';
|
|
23
|
+
|
|
24
|
+
function writeControl(stateDir: string, command: 'stop'): void {
|
|
25
|
+
writeFileSync(join(stateDir, 'control.json'), JSON.stringify({ command }));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sleep(ms: number): Promise<void> {
|
|
29
|
+
return new Promise(r => setTimeout(r, ms));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function positiveNumber(value: string, fallback: number): number {
|
|
33
|
+
const parsed = Number(value);
|
|
34
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function queueStatus(result: any): string | undefined {
|
|
38
|
+
return (result?.data ?? result)?.status;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const DEFAULT_QUEUE_WAIT_TIMEOUT_SECS = 30;
|
|
42
|
+
const GAME_START_RUNTIME_FILE = 'game-start.json';
|
|
43
|
+
|
|
44
|
+
function isPidAlive(pid: number): boolean {
|
|
45
|
+
if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return false;
|
|
46
|
+
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function gameStartRuntimePath(stateDir: string): string {
|
|
50
|
+
return join(stateDir, GAME_START_RUNTIME_FILE);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function getRunningGameStartPid(stateDir: string): number | null {
|
|
54
|
+
const runtimePath = gameStartRuntimePath(stateDir);
|
|
55
|
+
if (!existsSync(runtimePath)) return null;
|
|
56
|
+
try {
|
|
57
|
+
const info = JSON.parse(readFileSync(runtimePath, 'utf8'));
|
|
58
|
+
const pid = Number(info?.pid);
|
|
59
|
+
if (isPidAlive(pid)) return pid;
|
|
60
|
+
} catch {}
|
|
61
|
+
try { unlinkSync(runtimePath); } catch {}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function writeGameStartRuntime(stateDir: string, mode: GameStartPlanKind): void {
|
|
66
|
+
mkdirSync(stateDir, { recursive: true });
|
|
67
|
+
writeFileSync(gameStartRuntimePath(stateDir), JSON.stringify({
|
|
68
|
+
pid: process.pid,
|
|
69
|
+
started_at: new Date().toISOString(),
|
|
70
|
+
mode,
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function cleanupGameStartRuntime(stateDir: string): void {
|
|
75
|
+
const runtimePath = gameStartRuntimePath(stateDir);
|
|
76
|
+
try {
|
|
77
|
+
const info = JSON.parse(readFileSync(runtimePath, 'utf8'));
|
|
78
|
+
if (Number(info?.pid) !== process.pid) return;
|
|
79
|
+
} catch {}
|
|
80
|
+
try { unlinkSync(runtimePath); } catch {}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
type QueueStatus = 'allocated' | 'queued' | 'not_in_queue' | string | undefined;
|
|
84
|
+
|
|
85
|
+
export type GameStartPlan =
|
|
86
|
+
| { kind: 'already_running'; pid: number }
|
|
87
|
+
| { kind: 'attach_daemon' }
|
|
88
|
+
| { kind: 'resume_queue' }
|
|
89
|
+
| { kind: 'resume_allocated' }
|
|
90
|
+
| { kind: 'fresh_start' };
|
|
91
|
+
|
|
92
|
+
type GameStartPlanKind = GameStartPlan['kind'];
|
|
93
|
+
|
|
94
|
+
export function planGameStartAction(input: {
|
|
95
|
+
gameStartPid?: number | null;
|
|
96
|
+
daemonPid?: number | null;
|
|
97
|
+
hasMatchState: boolean;
|
|
98
|
+
queueStatus?: QueueStatus;
|
|
99
|
+
feedPhase?: string | null;
|
|
100
|
+
}): GameStartPlan {
|
|
101
|
+
if (input.gameStartPid) return { kind: 'already_running', pid: input.gameStartPid };
|
|
102
|
+
|
|
103
|
+
if (input.daemonPid) {
|
|
104
|
+
if (input.hasMatchState || input.feedPhase === 'matching') return { kind: 'resume_queue' };
|
|
105
|
+
if (input.feedPhase === 'lobby') return { kind: 'fresh_start' };
|
|
106
|
+
return { kind: 'attach_daemon' };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (input.queueStatus === 'allocated') return { kind: 'resume_allocated' };
|
|
110
|
+
if (input.queueStatus === 'queued' || input.queueStatus === 'already_in_queue') return { kind: 'resume_queue' };
|
|
111
|
+
return { kind: 'fresh_start' };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isAlreadyInGameError(err: unknown): boolean {
|
|
115
|
+
return err instanceof ApiError && err.body.includes('ALREADY_IN_GAME');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function ensureEventSession(source: string): EventStore {
|
|
119
|
+
const existing = EventStore.latestSessionPath();
|
|
120
|
+
if (existing) {
|
|
121
|
+
const events = EventStore.forActiveAccount();
|
|
122
|
+
events.append({ type: 'session_resumed', source });
|
|
123
|
+
return events;
|
|
124
|
+
}
|
|
125
|
+
const events = EventStore.createSessionForActiveAccount();
|
|
126
|
+
events.append({ type: 'session_started', source });
|
|
127
|
+
return events;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function readFeedPhase(feedPath: string): string | null {
|
|
131
|
+
try {
|
|
132
|
+
const phase = JSON.parse(readFileSync(feedPath, 'utf8'))?.phase;
|
|
133
|
+
return typeof phase === 'string' ? phase : null;
|
|
134
|
+
} catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function nonEmptyString(value: unknown): string | undefined {
|
|
140
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function unwrapData(value: any): any {
|
|
144
|
+
return value?.data ?? value;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface GameStrategyIdentity {
|
|
148
|
+
gameId?: string;
|
|
149
|
+
role?: string;
|
|
150
|
+
alive: boolean | null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface StrategyRuntimeInfo {
|
|
154
|
+
strategy?: string;
|
|
155
|
+
pid?: number;
|
|
156
|
+
source?: string;
|
|
157
|
+
gameId?: string;
|
|
158
|
+
role?: string;
|
|
159
|
+
running: boolean;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function gameStrategyIdentity(stateData: any, roleData: any): GameStrategyIdentity {
|
|
163
|
+
const state = unwrapData(stateData);
|
|
164
|
+
const role = unwrapData(roleData);
|
|
165
|
+
const you = state?.you ?? {};
|
|
166
|
+
const aliveRaw = you?.is_alive ?? you?.alive;
|
|
167
|
+
return {
|
|
168
|
+
gameId: nonEmptyString(state?.game_id) ?? nonEmptyString(state?.game?.id) ?? nonEmptyString(state?.game?.game_id),
|
|
169
|
+
role: nonEmptyString(role?.role) ?? nonEmptyString(you?.role),
|
|
170
|
+
alive: typeof aliveRaw === 'boolean' ? aliveRaw : null,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function strategyRuntimeMatchesIdentity(
|
|
175
|
+
runtime: StrategyRuntimeInfo | null,
|
|
176
|
+
identity: GameStrategyIdentity,
|
|
177
|
+
): boolean {
|
|
178
|
+
if (!runtime?.running) return false;
|
|
179
|
+
if (!runtime.gameId || !identity.gameId || runtime.gameId !== identity.gameId) return false;
|
|
180
|
+
if (runtime.role && identity.role && runtime.role !== identity.role) return false;
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function readStrategyRuntimeInfo(stateDir: string): StrategyRuntimeInfo | null {
|
|
185
|
+
try {
|
|
186
|
+
const raw = JSON.parse(readFileSync(join(stateDir, 'auto.json'), 'utf8'));
|
|
187
|
+
const pid = Number(raw?.pid);
|
|
188
|
+
return {
|
|
189
|
+
strategy: nonEmptyString(raw?.strategy),
|
|
190
|
+
pid: Number.isFinite(pid) ? pid : undefined,
|
|
191
|
+
source: nonEmptyString(raw?.source),
|
|
192
|
+
gameId: nonEmptyString(raw?.game_id) ?? nonEmptyString(raw?.gameId),
|
|
193
|
+
role: nonEmptyString(raw?.role),
|
|
194
|
+
running: Number.isFinite(pid) && pid > 0 ? isPidAlive(pid) : false,
|
|
195
|
+
};
|
|
196
|
+
} catch {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function commandError(command: string, err: unknown): { command: string; error: string } {
|
|
202
|
+
const message = err instanceof ApiError
|
|
203
|
+
? `${err.status}: ${err.body}`
|
|
204
|
+
: err instanceof Error
|
|
205
|
+
? err.message
|
|
206
|
+
: String(err);
|
|
207
|
+
return { command, error: message };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function briefMap(mapData: any): any {
|
|
211
|
+
if (!mapData) return null;
|
|
212
|
+
return {
|
|
213
|
+
rooms: mapData.rooms?.map((r: any) => ({
|
|
214
|
+
name: r.name,
|
|
215
|
+
polygon: r.polygon,
|
|
216
|
+
})),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function taskLocations(mapData: any): { lobster: any[]; crab: any[] } {
|
|
221
|
+
const taskLocations = { lobster: [] as any[], crab: [] as any[] };
|
|
222
|
+
for (const task of Array.isArray(mapData?.all_task_locations) ? mapData.all_task_locations : []) {
|
|
223
|
+
const item = {
|
|
224
|
+
name: task.name,
|
|
225
|
+
room: task.room,
|
|
226
|
+
x: task.x,
|
|
227
|
+
y: task.y,
|
|
228
|
+
};
|
|
229
|
+
if (task.faction === 'crab') taskLocations.crab.push(item);
|
|
230
|
+
else taskLocations.lobster.push(item);
|
|
231
|
+
}
|
|
232
|
+
return taskLocations;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function loadAsciiMapAsset(): string | null {
|
|
236
|
+
try {
|
|
237
|
+
return readFileSync(new URL('../assets/clawclaw-ascii-map.txt', import.meta.url), 'utf8').trimEnd();
|
|
238
|
+
} catch {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function summarizeGameMap(mapData: any, opts?: { ascii?: boolean }): any {
|
|
244
|
+
const output: Record<string, any> = {
|
|
245
|
+
rooms: mapData?.rooms?.map((r: any) => ({
|
|
246
|
+
name: r.name,
|
|
247
|
+
polygon: r.polygon,
|
|
248
|
+
})) ?? [],
|
|
249
|
+
task_locations: taskLocations(mapData),
|
|
250
|
+
};
|
|
251
|
+
if (opts?.ascii) {
|
|
252
|
+
const ascii = loadAsciiMapAsset();
|
|
253
|
+
output.ascii_map = ascii;
|
|
254
|
+
}
|
|
255
|
+
return output;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function fetchInitialGameContext(client: GameClient): Promise<{
|
|
259
|
+
state: any | null;
|
|
260
|
+
role: any | null;
|
|
261
|
+
map: any | null;
|
|
262
|
+
tasks: any[] | null;
|
|
263
|
+
errors?: Array<{ command: string; error: string }>;
|
|
264
|
+
}> {
|
|
265
|
+
await sleep(500);
|
|
266
|
+
const [stateResult, roleResult, mapResult] = await Promise.allSettled([
|
|
267
|
+
client.getGameState(),
|
|
268
|
+
client.getRoleInfo(),
|
|
269
|
+
client.getMap(),
|
|
270
|
+
]);
|
|
271
|
+
|
|
272
|
+
const errors: Array<{ command: string; error: string }> = [];
|
|
273
|
+
if (stateResult.status === 'rejected') errors.push(commandError('state', stateResult.reason));
|
|
274
|
+
if (roleResult.status === 'rejected') errors.push(commandError('game role', roleResult.reason));
|
|
275
|
+
if (mapResult.status === 'rejected') errors.push(commandError('game map', mapResult.reason));
|
|
276
|
+
|
|
277
|
+
const mapData = mapResult.status === 'fulfilled' ? mapResult.value : null;
|
|
278
|
+
const context = {
|
|
279
|
+
state: stateResult.status === 'fulfilled' ? stateResult.value : null,
|
|
280
|
+
role: roleResult.status === 'fulfilled' ? roleResult.value : null,
|
|
281
|
+
map: briefMap(mapData),
|
|
282
|
+
tasks: mapData?.your_tasks ?? null,
|
|
283
|
+
...(errors.length ? { errors } : {}),
|
|
284
|
+
};
|
|
285
|
+
return context;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const ROLE_DEFAULT_STRATEGY: Record<string, string> = {
|
|
289
|
+
'shrimp_generic': 'task-report',
|
|
290
|
+
'shrimp_warrior': 'task-report',
|
|
291
|
+
'shrimp_pistol': 'task-report',
|
|
292
|
+
'crab_generic': 'crab-sabotage',
|
|
293
|
+
'neutral_paradise_fish': 'corpse-patrol',
|
|
294
|
+
'neutral_octopus': 'lone-kill-task',
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
function autoStartStrategy(roleData: any, stateData?: any, gameId?: string): { strategy: string; pid: number | undefined } | null {
|
|
298
|
+
const roleId: string | undefined = roleData?.data?.role ?? roleData?.role;
|
|
299
|
+
if (!roleId) return null;
|
|
300
|
+
const strategyId = ROLE_DEFAULT_STRATEGY[roleId];
|
|
301
|
+
if (!strategyId) return null;
|
|
302
|
+
const child = spawnStrategyLoop(strategyId, [roleId], {
|
|
303
|
+
source: 'auto_start',
|
|
304
|
+
gameId: gameId ?? gameStrategyIdentity(stateData, roleData).gameId,
|
|
305
|
+
role: roleId,
|
|
306
|
+
});
|
|
307
|
+
return { strategy: strategyId, pid: child.pid };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function runGameStart(opts: { watch: boolean; force?: boolean }): Promise<void> {
|
|
311
|
+
if (process.env.CLAWCLAW_REQUIRE_STREAM_TOOL === '1' && process.env.CLAWCLAW_STREAMED !== '1') {
|
|
312
|
+
process.stderr.write(
|
|
313
|
+
'In OpenClaw, start the game via the clawclaw_game_start tool - do not exec `ccl game start` directly.\n' +
|
|
314
|
+
'When run raw, the event NDJSON only fills an unconsumed buffer, so you never receive speech_your_turn and stay silent.\n',
|
|
315
|
+
);
|
|
316
|
+
process.exit(2);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const authStore = new AuthStore();
|
|
320
|
+
const profile = authStore.getActive();
|
|
321
|
+
if (!profile) throw new Error('Not logged in.');
|
|
322
|
+
|
|
323
|
+
const stateDir = getProfileStateDir(profile);
|
|
324
|
+
const feedPath = join(stateDir, 'feed.json');
|
|
325
|
+
const client = GameClient.fromAuth();
|
|
326
|
+
const emit = (obj: Record<string, any>): void => {
|
|
327
|
+
process.stdout.write(JSON.stringify(obj) + '\n');
|
|
328
|
+
};
|
|
329
|
+
const emitLifecycle = (
|
|
330
|
+
reason: string,
|
|
331
|
+
payload: Record<string, any>,
|
|
332
|
+
nextStepOverride?: string,
|
|
333
|
+
): void => {
|
|
334
|
+
const event = { ...payload, type: reason };
|
|
335
|
+
emit({
|
|
336
|
+
exit_reason: [reason],
|
|
337
|
+
next_step: nextStepOverride ?? nextStepFor(reason),
|
|
338
|
+
events: [event],
|
|
339
|
+
summary: readFeedSummary(feedPath),
|
|
340
|
+
});
|
|
341
|
+
};
|
|
342
|
+
const emitMatchEvent = (evt: Record<string, any>): void => {
|
|
343
|
+
try {
|
|
344
|
+
const store = EventStore.forActiveAccount();
|
|
345
|
+
store.append({ ts: new Date().toISOString(), ...evt });
|
|
346
|
+
} catch {}
|
|
347
|
+
};
|
|
348
|
+
const ensureDaemonRunning = (): void => {
|
|
349
|
+
if (getRunningDaemonPid(stateDir)) return;
|
|
350
|
+
try {
|
|
351
|
+
spawnDaemon();
|
|
352
|
+
} catch (err) {
|
|
353
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
354
|
+
if (!msg.includes('Daemon already running')) throw err;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
const streamGame = async (): Promise<void> => {
|
|
358
|
+
const sessionPath = EventStore.latestSessionPath();
|
|
359
|
+
const ctrl = new AbortController();
|
|
360
|
+
const onSignal = (): void => ctrl.abort();
|
|
361
|
+
process.on('SIGINT', onSignal);
|
|
362
|
+
process.on('SIGTERM', onSignal);
|
|
363
|
+
try {
|
|
364
|
+
await runStreaming({
|
|
365
|
+
feedPath,
|
|
366
|
+
sessionPath,
|
|
367
|
+
getSessionPath: () => EventStore.latestSessionPath(),
|
|
368
|
+
stdout: (s) => process.stdout.write(s),
|
|
369
|
+
signal: ctrl.signal,
|
|
370
|
+
skipBacklogTypes: ['match_waiting', 'match_timeout'],
|
|
371
|
+
emitGameStart: true,
|
|
372
|
+
hubReminder: hubReminder(readCachedGamesPlayed()),
|
|
373
|
+
});
|
|
374
|
+
} catch (err: any) {
|
|
375
|
+
process.stdout.write(buildErrorLine(err));
|
|
376
|
+
process.exitCode = 1;
|
|
377
|
+
} finally {
|
|
378
|
+
process.off('SIGINT', onSignal);
|
|
379
|
+
process.off('SIGTERM', onSignal);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
const handleAllocated = async (queue: any, preserveStrategy: boolean): Promise<void> => {
|
|
383
|
+
const finalState = readMatchState(stateDir);
|
|
384
|
+
const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
|
|
385
|
+
endMatch(stateDir);
|
|
386
|
+
const context = await fetchInitialGameContext(client);
|
|
387
|
+
const identity = gameStrategyIdentity(context.state, context.role);
|
|
388
|
+
// Supplement game_id from queue response when /game/current doesn't carry it yet.
|
|
389
|
+
const queueGameId = nonEmptyString(queue?.game_id) ?? nonEmptyString(queue?.data?.game_id);
|
|
390
|
+
if (!identity.gameId && queueGameId) {
|
|
391
|
+
identity.gameId = queueGameId;
|
|
392
|
+
}
|
|
393
|
+
let strategyInfo: { strategy: string; pid: number | undefined } | null = null;
|
|
394
|
+
if (identity.alive !== false) {
|
|
395
|
+
if (preserveStrategy) {
|
|
396
|
+
const { isStrategyRunning, stopStrategyIfRunning } = await import('../strategies/strategy-loop.js');
|
|
397
|
+
if (isStrategyRunning()) {
|
|
398
|
+
const runtime = readStrategyRuntimeInfo(stateDir);
|
|
399
|
+
if (identity.gameId && !strategyRuntimeMatchesIdentity(runtime, identity)) {
|
|
400
|
+
stopStrategyIfRunning();
|
|
401
|
+
strategyInfo = autoStartStrategy(context.role, context.state, identity.gameId);
|
|
402
|
+
}
|
|
403
|
+
} else {
|
|
404
|
+
strategyInfo = autoStartStrategy(context.role, context.state, identity.gameId);
|
|
405
|
+
}
|
|
406
|
+
} else {
|
|
407
|
+
strategyInfo = autoStartStrategy(context.role, context.state, identity.gameId);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const allocationPayload = {
|
|
411
|
+
queue,
|
|
412
|
+
waited_secs: waitedSecs,
|
|
413
|
+
game_id: identity.gameId || undefined,
|
|
414
|
+
...context,
|
|
415
|
+
...(strategyInfo ? { default_strategy: strategyInfo } : {}),
|
|
416
|
+
};
|
|
417
|
+
if (!opts.watch) {
|
|
418
|
+
emitLifecycle('allocated', allocationPayload,
|
|
419
|
+
'Match secured. Read role/map/tasks from `events[0]`. Default strategy is active when `default_strategy` is present or summary.automation shows one. Move into Preparing phase.');
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
await streamGame();
|
|
423
|
+
};
|
|
424
|
+
const pollQueue = async (preserveStrategy: boolean): Promise<void> => {
|
|
425
|
+
const intervalMs = 2000;
|
|
426
|
+
const QUEUE_POLL_HEARTBEAT_MS = 60_000;
|
|
427
|
+
const MAX_CONSECUTIVE_FAILURES = 3;
|
|
428
|
+
let lastHeartbeat = Date.now();
|
|
429
|
+
let consecutiveFailures = 0;
|
|
430
|
+
|
|
431
|
+
while (true) {
|
|
432
|
+
let queue: any;
|
|
433
|
+
try {
|
|
434
|
+
queue = await client.getQueueStatus('clawclaw');
|
|
435
|
+
consecutiveFailures = 0;
|
|
436
|
+
} catch (err: any) {
|
|
437
|
+
consecutiveFailures++;
|
|
438
|
+
const msg = err?.message ?? String(err);
|
|
439
|
+
if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
|
|
440
|
+
emitLifecycle('error', {
|
|
441
|
+
error: msg,
|
|
442
|
+
consecutive_failures: consecutiveFailures,
|
|
443
|
+
message: `Queue status polling failed ${consecutiveFailures} times consecutively.`,
|
|
444
|
+
}, 'Queue polling has failed repeatedly. Check network, then launch a fresh `ccl game start` to retry.');
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
emitLifecycle('poll_error', {
|
|
448
|
+
error: msg,
|
|
449
|
+
consecutive_failures: consecutiveFailures,
|
|
450
|
+
message: `Queue poll failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}). Retrying...`,
|
|
451
|
+
}, 'Temporary polling failure. The stream will keep retrying - stay attached.');
|
|
452
|
+
await sleep(intervalMs);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (queueStatus(queue) === 'allocated') {
|
|
457
|
+
await handleAllocated(queue, preserveStrategy);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (queueStatus(queue) === 'not_in_queue') {
|
|
461
|
+
endMatch(stateDir);
|
|
462
|
+
emitLifecycle('not_in_queue', { queue, message: 'Left or dropped from queue.' },
|
|
463
|
+
'No longer in matchmaking queue. The stream will exit; launch a fresh `ccl game start` to retry if the user wants to continue.');
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const cur = readMatchState(stateDir);
|
|
468
|
+
if (cur && shouldEmitWaiting(cur)) {
|
|
469
|
+
const waitedSecs = getWaitedSecs(cur);
|
|
470
|
+
emitMatchEvent({ type: 'match_waiting', waited_secs: waitedSecs });
|
|
471
|
+
emitLifecycle('match_waiting', { waited_secs: waitedSecs });
|
|
472
|
+
markWaitingEmitted(stateDir);
|
|
473
|
+
lastHeartbeat = Date.now();
|
|
474
|
+
}
|
|
475
|
+
if (cur && hasMatchTimedOut(cur)) {
|
|
476
|
+
const waitedSecs = getWaitedSecs(cur);
|
|
477
|
+
emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
|
|
478
|
+
emitLifecycle('match_timeout', {
|
|
479
|
+
waited_secs: waitedSecs,
|
|
480
|
+
queue,
|
|
481
|
+
message: `No match after ${waitedSecs}s.`,
|
|
482
|
+
});
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
if (Date.now() - lastHeartbeat >= QUEUE_POLL_HEARTBEAT_MS) {
|
|
487
|
+
lastHeartbeat = Date.now();
|
|
488
|
+
const waitedSecs = cur ? getWaitedSecs(cur) : 0;
|
|
489
|
+
emitLifecycle('heartbeat', { waited_secs: waitedSecs },
|
|
490
|
+
'Stream is alive; still waiting for match allocation. Keep chatting with the user.');
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
await sleep(intervalMs);
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
const resumeQueue = async (source: string): Promise<void> => {
|
|
497
|
+
ensureEventSession(source);
|
|
498
|
+
if (!readMatchState(stateDir)) startMatch(stateDir);
|
|
499
|
+
ensureDaemonRunning();
|
|
500
|
+
spawnOpeningMover();
|
|
501
|
+
await pollQueue(true);
|
|
502
|
+
};
|
|
503
|
+
const recoverAlreadyInGame = async (): Promise<boolean> => {
|
|
504
|
+
let queue: any;
|
|
505
|
+
try {
|
|
506
|
+
queue = await client.getQueueStatus('clawclaw');
|
|
507
|
+
} catch {
|
|
508
|
+
return false;
|
|
509
|
+
}
|
|
510
|
+
const status = queueStatus(queue);
|
|
511
|
+
if (status === 'allocated') {
|
|
512
|
+
ensureEventSession('game_start_already_in_game');
|
|
513
|
+
ensureDaemonRunning();
|
|
514
|
+
spawnOpeningMover();
|
|
515
|
+
await handleAllocated(queue, true);
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
if (status === 'queued' || status === 'already_in_queue') {
|
|
519
|
+
await resumeQueue('game_start_already_in_game_queue');
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
522
|
+
return false;
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
const runningGameStartPid = getRunningGameStartPid(stateDir);
|
|
526
|
+
if (runningGameStartPid) {
|
|
527
|
+
if (opts.force) {
|
|
528
|
+
try { process.kill(runningGameStartPid, 'SIGKILL'); } catch {}
|
|
529
|
+
try { unlinkSync(gameStartRuntimePath(stateDir)); } catch {}
|
|
530
|
+
} else {
|
|
531
|
+
emitLifecycle('already_running', { pid: runningGameStartPid },
|
|
532
|
+
`A ccl game start stream is already running (pid ${runningGameStartPid}). To replace it, re-run with --force or stop it manually: taskkill /F /PID ${runningGameStartPid}`);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
let initialQueue: any;
|
|
538
|
+
try {
|
|
539
|
+
initialQueue = await client.getQueueStatus('clawclaw');
|
|
540
|
+
} catch {}
|
|
541
|
+
const plan = planGameStartAction({
|
|
542
|
+
gameStartPid: null,
|
|
543
|
+
daemonPid: getRunningDaemonPid(stateDir),
|
|
544
|
+
hasMatchState: readMatchState(stateDir) !== null,
|
|
545
|
+
queueStatus: queueStatus(initialQueue),
|
|
546
|
+
feedPhase: readFeedPhase(feedPath),
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
writeGameStartRuntime(stateDir, plan.kind);
|
|
550
|
+
try {
|
|
551
|
+
if (plan.kind === 'attach_daemon') {
|
|
552
|
+
ensureEventSession('game_start_attach_daemon');
|
|
553
|
+
if (!opts.watch) {
|
|
554
|
+
emitLifecycle('game_start', { mode: plan.kind },
|
|
555
|
+
'Game stream is active. Read summary; no additional events will follow from this --no-watch invocation.');
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
await streamGame();
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (plan.kind === 'resume_queue') {
|
|
563
|
+
await resumeQueue('game_start_resume_queue');
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
if (plan.kind === 'resume_allocated') {
|
|
568
|
+
ensureEventSession('game_start_resume_allocated');
|
|
569
|
+
ensureDaemonRunning();
|
|
570
|
+
spawnOpeningMover();
|
|
571
|
+
await handleAllocated(initialQueue, true);
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
let joinResult: any;
|
|
576
|
+
try {
|
|
577
|
+
joinResult = await client.joinQueue('clawclaw');
|
|
578
|
+
} catch (err) {
|
|
579
|
+
if (isAlreadyInGameError(err) && await recoverAlreadyInGame()) return;
|
|
580
|
+
throw err;
|
|
581
|
+
}
|
|
582
|
+
const joinedStatus = queueStatus(joinResult);
|
|
583
|
+
if (joinedStatus === 'already_in_queue') {
|
|
584
|
+
await resumeQueue('game_start_already_in_queue');
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
if (joinedStatus && joinedStatus !== 'queued') {
|
|
588
|
+
emitLifecycle('error', { queue: joinResult, message: `Unexpected queue status: ${joinedStatus}.` },
|
|
589
|
+
'Queue join did not enter the clawclaw queue. Check queue status before launching another `ccl game start`.');
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const { stopStrategyIfRunning } = await import('../strategies/strategy-loop.js');
|
|
594
|
+
stopStrategyIfRunning();
|
|
595
|
+
stopOpeningMoverIfRunning();
|
|
596
|
+
|
|
597
|
+
const events = EventStore.createSessionForActiveAccount();
|
|
598
|
+
events.append({ type: 'session_started', source: 'game_start' });
|
|
599
|
+
emitLifecycle('joined', joinResult,
|
|
600
|
+
'Match join request acknowledged. Spectate URL is in `events[0].url`; share it with the user. Daemon spawns next.');
|
|
601
|
+
startMatch(stateDir);
|
|
602
|
+
if (getRunningDaemonPid(stateDir)) {
|
|
603
|
+
writeControl(stateDir, 'stop');
|
|
604
|
+
await waitDaemonExit(stateDir);
|
|
605
|
+
}
|
|
606
|
+
spawnDaemon();
|
|
607
|
+
spawnOpeningMover();
|
|
608
|
+
await pollQueue(false);
|
|
609
|
+
} finally {
|
|
610
|
+
cleanupGameStartRuntime(stateDir);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
export function createGameCommand(): Command {
|
|
615
|
+
const game = new Command('game');
|
|
616
|
+
game.description('Game matchmaking & session');
|
|
617
|
+
|
|
618
|
+
game
|
|
619
|
+
.command('join')
|
|
620
|
+
.alias('j')
|
|
621
|
+
.description('Join matchmaking queue')
|
|
622
|
+
.action(async () => {
|
|
623
|
+
const authStore = new AuthStore();
|
|
624
|
+
const profile = authStore.getActive();
|
|
625
|
+
if (!profile) throw new Error('Not logged in.');
|
|
626
|
+
const { stopStrategyIfRunning } = await import('../strategies/strategy-loop.js');
|
|
627
|
+
stopStrategyIfRunning();
|
|
628
|
+
stopOpeningMoverIfRunning();
|
|
629
|
+
|
|
630
|
+
const client = GameClient.fromAuth();
|
|
631
|
+
const result = await client.joinQueue('clawclaw');
|
|
632
|
+
const events = EventStore.createSessionForActiveAccount();
|
|
633
|
+
events.append({ type: 'session_started', source: 'game_join' });
|
|
634
|
+
console.log(JSON.stringify(result, null, 2));
|
|
635
|
+
const stateDir = getProfileStateDir(profile);
|
|
636
|
+
// Reset match-state: a fresh queue session starts here so `ccl game queue`
|
|
637
|
+
// can compute `waited_secs` from a known anchor and emit the
|
|
638
|
+
// match_waiting / match_timeout synthetic events.
|
|
639
|
+
startMatch(stateDir);
|
|
640
|
+
if (getRunningDaemonPid(stateDir)) {
|
|
641
|
+
writeControl(stateDir, 'stop');
|
|
642
|
+
await waitDaemonExit(stateDir);
|
|
643
|
+
}
|
|
644
|
+
const { pid } = spawnDaemon();
|
|
645
|
+
console.log(JSON.stringify({ message: 'Event daemon started', pid }, null, 2));
|
|
646
|
+
spawnOpeningMover();
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
game
|
|
650
|
+
.command('start')
|
|
651
|
+
.alias('s')
|
|
652
|
+
.description('Attach to an active game stream or join queue, then stream events as NDJSON until game_over. Pass --no-watch to exit after allocation. Pass --force to replace an orphaned game-start stream.')
|
|
653
|
+
.option('--no-watch', 'exit after allocation instead of streaming events through game_over')
|
|
654
|
+
.option('--force', 'force restart: kill any lingering game-start stream process and start fresh')
|
|
655
|
+
.action(runGameStart);
|
|
656
|
+
|
|
657
|
+
game
|
|
658
|
+
.command('queue')
|
|
659
|
+
.alias('q')
|
|
660
|
+
.description('Wait for matchmaking allocation. Always run as a background bash task (run_in_background: true) — never block on it. Returns when allocated, queue is missing, or timeout (default 30s).')
|
|
661
|
+
.option('-w, --wait', '(no-op, kept for backwards compatibility — wait mode is now the default)')
|
|
662
|
+
.option('--interval <secs>', 'Polling interval', '2')
|
|
663
|
+
.option('--timeout <secs>', 'Max seconds to wait, 0 means forever', String(DEFAULT_QUEUE_WAIT_TIMEOUT_SECS))
|
|
664
|
+
.action(async (opts) => {
|
|
665
|
+
const authStore = new AuthStore();
|
|
666
|
+
const profile = authStore.getActive();
|
|
667
|
+
if (!profile) throw new Error('Not logged in.');
|
|
668
|
+
const stateDir = getProfileStateDir(profile);
|
|
669
|
+
const client = GameClient.fromAuth();
|
|
670
|
+
|
|
671
|
+
const intervalMs = positiveNumber(opts.interval, 2) * 1000;
|
|
672
|
+
const timeoutSecs = Number(opts.timeout);
|
|
673
|
+
const deadline = Number.isFinite(timeoutSecs) && timeoutSecs > 0
|
|
674
|
+
? Date.now() + timeoutSecs * 1000
|
|
675
|
+
: 0;
|
|
676
|
+
|
|
677
|
+
// Synthetic matchmaking events feed the game start stream so the agent can
|
|
678
|
+
// observe match progress through the same channel as in-game events.
|
|
679
|
+
// Concurrency note: the agent typically keeps a 30s `ccl game queue`
|
|
680
|
+
// background chain running, so two queue invocations may observe the
|
|
681
|
+
// same `allocated` server state. That is
|
|
682
|
+
// intentionally fine — stream dedups via `eventKey` (type+tick+actor),
|
|
683
|
+
// so consumers only see one notification.
|
|
684
|
+
const emitMatchEvent = (evt: Record<string, any>): void => {
|
|
685
|
+
try {
|
|
686
|
+
const store = EventStore.forActiveAccount();
|
|
687
|
+
store.append({ ts: new Date().toISOString(), ...evt });
|
|
688
|
+
} catch {
|
|
689
|
+
// No active session (user ran queue without join) — skip silently;
|
|
690
|
+
// queue's own JSON return still informs the caller.
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
// On entry: emit match_waiting if state exists and heartbeat is due.
|
|
695
|
+
const initialState = readMatchState(stateDir);
|
|
696
|
+
if (initialState && shouldEmitWaiting(initialState)) {
|
|
697
|
+
const waitedSecs = getWaitedSecs(initialState);
|
|
698
|
+
emitMatchEvent({ type: 'match_waiting', waited_secs: waitedSecs });
|
|
699
|
+
markWaitingEmitted(stateDir);
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
while (true) {
|
|
703
|
+
const queue = await client.getQueueStatus('clawclaw');
|
|
704
|
+
if (queueStatus(queue) === 'allocated') {
|
|
705
|
+
const finalState = readMatchState(stateDir);
|
|
706
|
+
const waitedSecs = finalState ? getWaitedSecs(finalState) : 0;
|
|
707
|
+
endMatch(stateDir);
|
|
708
|
+
const context = await fetchInitialGameContext(client);
|
|
709
|
+
console.log(JSON.stringify({
|
|
710
|
+
status: 'active_game',
|
|
711
|
+
queue,
|
|
712
|
+
waited_secs: waitedSecs,
|
|
713
|
+
...context,
|
|
714
|
+
next_step: 'Game allocated. Stop the queue loop. The game start stream (already running since `game join`) will surface subsequent gameplay events. Narrate the role / map / opening plan to the user.',
|
|
715
|
+
}, null, 2));
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (queueStatus(queue) === 'not_in_queue') {
|
|
719
|
+
// Queue session is gone (user manually left or server expired it):
|
|
720
|
+
// clean the match-state so next `game join` starts fresh.
|
|
721
|
+
endMatch(stateDir);
|
|
722
|
+
console.log(JSON.stringify({
|
|
723
|
+
status: 'not_in_queue',
|
|
724
|
+
queue,
|
|
725
|
+
message: 'You are not in the matchmaking queue. Did you forget to run `ccl game join` first?',
|
|
726
|
+
next_step: 'Run `ccl game join` to re-enter the queue, then launch the next `ccl game queue` background task.',
|
|
727
|
+
}, null, 2));
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
if (deadline > 0 && Date.now() >= deadline) {
|
|
731
|
+
const cur = readMatchState(stateDir);
|
|
732
|
+
const waitedSecs = cur ? getWaitedSecs(cur) : timeoutSecs;
|
|
733
|
+
// Total-wait timeout (>=10 min by default) gets its own synthetic
|
|
734
|
+
// event so the agent can prompt the user to keep waiting / leave /
|
|
735
|
+
// retry later. Single 30s queue-attempt timeouts do NOT emit anything
|
|
736
|
+
// — they are an internal polling boundary, not a user-visible event.
|
|
737
|
+
if (cur && hasMatchTimedOut(cur)) {
|
|
738
|
+
emitMatchEvent({ type: 'match_timeout', waited_secs: waitedSecs });
|
|
739
|
+
}
|
|
740
|
+
console.log(JSON.stringify({
|
|
741
|
+
status: 'timeout',
|
|
742
|
+
waited_secs: waitedSecs,
|
|
743
|
+
queue,
|
|
744
|
+
message: `No match after ${timeoutSecs} seconds (total wait ${waitedSecs}s).`,
|
|
745
|
+
next_step: 'ZERO-GAP PROTOCOL: (1) Launch the next `ccl game queue` background task IMMEDIATELY. (2) While it runs, chat with the user — share strategy, persona, banter — never go silent.',
|
|
746
|
+
}, null, 2));
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
await sleep(intervalMs);
|
|
750
|
+
}
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
game
|
|
754
|
+
.command('leave')
|
|
755
|
+
.alias('l')
|
|
756
|
+
.description('Leave queue')
|
|
757
|
+
.action(async () => {
|
|
758
|
+
stopOpeningMoverIfRunning();
|
|
759
|
+
const authStore = new AuthStore();
|
|
760
|
+
const profile = authStore.getActive();
|
|
761
|
+
if (profile) {
|
|
762
|
+
const stateDir = getProfileStateDir(profile);
|
|
763
|
+
endMatch(stateDir);
|
|
764
|
+
if (getRunningDaemonPid(stateDir)) {
|
|
765
|
+
writeControl(stateDir, 'stop');
|
|
766
|
+
await waitDaemonExit(stateDir);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
const { stopStrategyIfRunning } = await import('../strategies/strategy-loop.js');
|
|
770
|
+
stopStrategyIfRunning();
|
|
771
|
+
const client = GameClient.fromAuth();
|
|
772
|
+
const result = await client.leaveQueue('clawclaw');
|
|
773
|
+
console.log(JSON.stringify(result, null, 2));
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
game
|
|
778
|
+
.command('stop')
|
|
779
|
+
.alias('x')
|
|
780
|
+
.description('Stop event daemon')
|
|
781
|
+
.action(async () => {
|
|
782
|
+
const authStore = new AuthStore();
|
|
783
|
+
const profile = authStore.getActive();
|
|
784
|
+
if (!profile) throw new Error('Not logged in.');
|
|
785
|
+
const stateDir = getProfileStateDir(profile);
|
|
786
|
+
const pid = getRunningDaemonPid(stateDir);
|
|
787
|
+
stopOpeningMoverIfRunning();
|
|
788
|
+
if (!pid) {
|
|
789
|
+
console.log(JSON.stringify({ message: 'No daemon running.' }, null, 2));
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
writeControl(stateDir, 'stop');
|
|
793
|
+
await waitDaemonExit(stateDir);
|
|
794
|
+
console.log(JSON.stringify({ message: 'Daemon stopped.' }, null, 2));
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
game
|
|
798
|
+
.command('quit')
|
|
799
|
+
.description('Leave active game and stop daemon')
|
|
800
|
+
.action(async () => {
|
|
801
|
+
const authStore = new AuthStore();
|
|
802
|
+
const profile = authStore.getActive();
|
|
803
|
+
if (!profile) throw new Error('Not logged in.');
|
|
804
|
+
const client = GameClient.fromAuth();
|
|
805
|
+
let result: any;
|
|
806
|
+
try {
|
|
807
|
+
result = await client.leaveGame();
|
|
808
|
+
} catch (err: any) {
|
|
809
|
+
throw new Error(err?.message ?? String(err));
|
|
810
|
+
}
|
|
811
|
+
const stateDir = getProfileStateDir(profile);
|
|
812
|
+
endMatch(stateDir);
|
|
813
|
+
if (getRunningDaemonPid(stateDir)) {
|
|
814
|
+
writeControl(stateDir, 'stop');
|
|
815
|
+
await waitDaemonExit(stateDir);
|
|
816
|
+
}
|
|
817
|
+
stopOpeningMoverIfRunning();
|
|
818
|
+
const { stopStrategyIfRunning } = await import('../strategies/strategy-loop.js');
|
|
819
|
+
stopStrategyIfRunning();
|
|
820
|
+
const reminder = hubReminder(readCachedGamesPlayed());
|
|
821
|
+
const out: Record<string, any> = (result && typeof result === 'object' && !Array.isArray(result))
|
|
822
|
+
? { ...result }
|
|
823
|
+
: { result };
|
|
824
|
+
if (reminder) {
|
|
825
|
+
out.hub_reminder = reminder;
|
|
826
|
+
out.next_step = `Left the game. ${reminder}`;
|
|
827
|
+
}
|
|
828
|
+
console.log(JSON.stringify(out, null, 2));
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
game
|
|
832
|
+
.command('map')
|
|
833
|
+
.alias('m')
|
|
834
|
+
.description('Show game map')
|
|
835
|
+
.option('--ascii', 'Include packaged ASCII topology map')
|
|
836
|
+
.action(async (opts) => {
|
|
837
|
+
const client = GameClient.fromAuth();
|
|
838
|
+
await client.discoverGameServer();
|
|
839
|
+
const result = await client.getMap();
|
|
840
|
+
console.log(JSON.stringify(summarizeGameMap(result, { ascii: opts.ascii === true }), null, 2));
|
|
841
|
+
});
|
|
842
|
+
|
|
843
|
+
game
|
|
844
|
+
.command('tasks')
|
|
845
|
+
.alias('t')
|
|
846
|
+
.description('Show my tasks')
|
|
847
|
+
.action(async () => {
|
|
848
|
+
const client = GameClient.fromAuth();
|
|
849
|
+
await client.discoverGameServer();
|
|
850
|
+
const result = await client.getMap();
|
|
851
|
+
console.log(JSON.stringify(result?.your_tasks ?? [], null, 2));
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
game
|
|
855
|
+
.command('role')
|
|
856
|
+
.alias('r')
|
|
857
|
+
.description('Show my role info')
|
|
858
|
+
.action(async () => {
|
|
859
|
+
const client = GameClient.fromAuth();
|
|
860
|
+
const result = await client.getRoleInfo();
|
|
861
|
+
console.log(JSON.stringify(result, null, 2));
|
|
862
|
+
});
|
|
863
|
+
|
|
864
|
+
game
|
|
865
|
+
.command('watch')
|
|
866
|
+
.alias('w')
|
|
867
|
+
.description('Get spectating URL')
|
|
868
|
+
.action(() => {
|
|
869
|
+
const authStore = new AuthStore();
|
|
870
|
+
const profile = authStore.getActive();
|
|
871
|
+
if (!profile) throw new Error('Not logged in.');
|
|
872
|
+
const origin = new URL(profile.serverUrl).origin.replace(/^http:\/\//, 'https://');
|
|
873
|
+
const url = `${origin}/lobby?token=${encodeURIComponent(profile.apiKey)}`;
|
|
874
|
+
console.log(JSON.stringify({ url, message: 'Open in browser to spectate.' }, null, 2));
|
|
875
|
+
});
|
|
876
|
+
|
|
877
|
+
// ── Adapter metadata: queue blocks up to --timeout secs (default 30); cap L2 spawn at 60s ──
|
|
878
|
+
setMeta(game.commands.find((c) => c.name() === 'queue')!, { longRunning: true, timeoutMs: 60_000 });
|
|
879
|
+
setMeta(game.commands.find((c) => c.name() === 'start')!, { longRunning: true, timeoutMs: 1_800_000 });
|
|
880
|
+
|
|
881
|
+
return game;
|
|
882
|
+
}
|