@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,33 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync, rmSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { tmpdir } from 'os';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
import { appendRawWsMessage, isCclTestEnabled, rawWsLogPathForSession } from './raw-ws-log.js';
|
|
6
|
+
|
|
7
|
+
describe('raw websocket logging helpers', () => {
|
|
8
|
+
it('is enabled by ccl-test=true or CCL_TEST=true', () => {
|
|
9
|
+
expect(isCclTestEnabled({ 'ccl-test': 'true' })).toBe(true);
|
|
10
|
+
expect(isCclTestEnabled({ CCL_TEST: 'true' })).toBe(true);
|
|
11
|
+
expect(isCclTestEnabled({ 'ccl-test': 'false', CCL_TEST: '0' })).toBe(false);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('derives a per-session raw log path', () => {
|
|
15
|
+
expect(rawWsLogPathForSession('/tmp/game.jsonl')).toBe('/tmp/game.raw-ws.jsonl');
|
|
16
|
+
expect(rawWsLogPathForSession('/tmp/game')).toBe('/tmp/game.raw-ws.jsonl');
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('appends raw server frames as jsonl', () => {
|
|
20
|
+
const dir = mkdtempSync(join(tmpdir(), 'ccl-raw-ws-'));
|
|
21
|
+
try {
|
|
22
|
+
const file = join(dir, 'game.raw-ws.jsonl');
|
|
23
|
+
appendRawWsMessage(file, '{"type":"state","data":{"tick":1}}');
|
|
24
|
+
const line = readFileSync(file, 'utf8').trim();
|
|
25
|
+
const parsed = JSON.parse(line);
|
|
26
|
+
expect(parsed.direction).toBe('server_to_ccl');
|
|
27
|
+
expect(parsed.raw).toBe('{"type":"state","data":{"tick":1}}');
|
|
28
|
+
expect(typeof parsed.ts).toBe('string');
|
|
29
|
+
} finally {
|
|
30
|
+
rmSync(dir, { recursive: true, force: true });
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync } from 'fs';
|
|
2
|
+
import { dirname } from 'path';
|
|
3
|
+
|
|
4
|
+
function isTrue(value: string | undefined): boolean {
|
|
5
|
+
return typeof value === 'string' && value.trim().toLowerCase() === 'true';
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function isCclTestEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
9
|
+
return isTrue(env['ccl-test']) || isTrue(env.CCL_TEST);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function rawWsLogPathForSession(sessionPath: string): string {
|
|
13
|
+
return sessionPath.endsWith('.jsonl')
|
|
14
|
+
? `${sessionPath.slice(0, -'.jsonl'.length)}.raw-ws.jsonl`
|
|
15
|
+
: `${sessionPath}.raw-ws.jsonl`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function appendRawWsMessage(filePath: string, raw: string): void {
|
|
19
|
+
try {
|
|
20
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
21
|
+
appendFileSync(
|
|
22
|
+
filePath,
|
|
23
|
+
JSON.stringify({
|
|
24
|
+
ts: new Date().toISOString(),
|
|
25
|
+
direction: 'server_to_ccl',
|
|
26
|
+
raw,
|
|
27
|
+
}) + '\n',
|
|
28
|
+
);
|
|
29
|
+
} catch {
|
|
30
|
+
// Raw capture is diagnostic-only; never let it affect gameplay.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime Logger — structured, leveled logging for the daemon and CLI.
|
|
3
|
+
*
|
|
4
|
+
* Log format: [Runtime:<LEVEL>] <EVENT_TAG> <message>
|
|
5
|
+
*
|
|
6
|
+
* Levels (lowest → highest):
|
|
7
|
+
* DEBUG — verbose diagnostics (task detail lists, tick-level state)
|
|
8
|
+
* INFO — key lifecycle events (game start, phase changes, map loaded)
|
|
9
|
+
* WARN — recoverable issues (WS not ready, anti-stuck triggered)
|
|
10
|
+
* ERROR — failures that need attention (map load failed, tick error)
|
|
11
|
+
*
|
|
12
|
+
* Control via env var CLAWCLAW_LOG_LEVEL (default: DEBUG).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export enum LogLevel {
|
|
16
|
+
DEBUG = 0,
|
|
17
|
+
INFO = 1,
|
|
18
|
+
WARN = 2,
|
|
19
|
+
ERROR = 3,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const LEVEL_NAMES: Record<LogLevel, string> = {
|
|
23
|
+
[LogLevel.DEBUG]: 'DEBUG',
|
|
24
|
+
[LogLevel.INFO]: 'INFO',
|
|
25
|
+
[LogLevel.WARN]: 'WARN',
|
|
26
|
+
[LogLevel.ERROR]: 'ERROR',
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function parseLogLevel(raw: string | undefined): LogLevel {
|
|
30
|
+
switch (raw?.toUpperCase()) {
|
|
31
|
+
case 'DEBUG': return LogLevel.DEBUG;
|
|
32
|
+
case 'INFO': return LogLevel.INFO;
|
|
33
|
+
case 'WARN': return LogLevel.WARN;
|
|
34
|
+
case 'ERROR': return LogLevel.ERROR;
|
|
35
|
+
default: return LogLevel.DEBUG;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class RuntimeLogger {
|
|
40
|
+
private minLevel: LogLevel;
|
|
41
|
+
|
|
42
|
+
constructor() {
|
|
43
|
+
this.minLevel = parseLogLevel(process.env.CLAWCLAW_LOG_LEVEL);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ─── Core log methods ────────────────────────────────────────────────────
|
|
47
|
+
|
|
48
|
+
debug(tag: string, msg: string): void {
|
|
49
|
+
this.log(LogLevel.DEBUG, tag, msg);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
info(tag: string, msg: string): void {
|
|
53
|
+
this.log(LogLevel.INFO, tag, msg);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
warn(tag: string, msg: string): void {
|
|
57
|
+
this.log(LogLevel.WARN, tag, msg);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
error(tag: string, msg: string, err?: unknown): void {
|
|
61
|
+
const suffix = err instanceof Error ? ` err=${err.message}` : (err ? ` err=${err}` : '');
|
|
62
|
+
this.log(LogLevel.ERROR, tag, msg + suffix);
|
|
63
|
+
// Print full stack trace for Error objects (preserves diagnostics from original console.error)
|
|
64
|
+
if (err instanceof Error && err.stack) {
|
|
65
|
+
console.error(err.stack);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ─── Helpers ─────────────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Log a list of tasks at DEBUG level (reduces repetitive loop logging).
|
|
73
|
+
* Outputs one indented line per task — pair with a preceding info() call for the summary.
|
|
74
|
+
*/
|
|
75
|
+
logTaskList(tag: string, tasks: Array<{ name: string; room?: string; x?: number; y?: number; status?: string }>): void {
|
|
76
|
+
for (const t of tasks) {
|
|
77
|
+
this.debug(tag, ` └─ ${t.name} room=${t.room ?? '?'} coords=(${t.x ?? '?'},${t.y ?? '?'})${t.status ? ` status=${t.status}` : ''}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ─── Internal ────────────────────────────────────────────────────────────
|
|
82
|
+
|
|
83
|
+
private log(level: LogLevel, tag: string, msg: string): void {
|
|
84
|
+
if (level < this.minLevel) return;
|
|
85
|
+
const prefix = `[Runtime:${LEVEL_NAMES[level]}]`;
|
|
86
|
+
const line = `${prefix} ${tag} ${msg}`;
|
|
87
|
+
switch (level) {
|
|
88
|
+
case LogLevel.ERROR:
|
|
89
|
+
console.error(line);
|
|
90
|
+
break;
|
|
91
|
+
case LogLevel.WARN:
|
|
92
|
+
console.warn(line);
|
|
93
|
+
break;
|
|
94
|
+
default:
|
|
95
|
+
console.log(line);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const wsMock = vi.hoisted(() => ({
|
|
4
|
+
constructed: [] as Array<{ url: string; options: any; instance: any }>,
|
|
5
|
+
}));
|
|
6
|
+
|
|
7
|
+
vi.mock('ws', () => {
|
|
8
|
+
class MockWebSocket {
|
|
9
|
+
onopen: ((event: any) => void) | null = null;
|
|
10
|
+
onerror: ((event: any) => void) | null = null;
|
|
11
|
+
onclose: ((event: any) => void) | null = null;
|
|
12
|
+
onmessage: ((event: any) => void) | null = null;
|
|
13
|
+
send = vi.fn();
|
|
14
|
+
close = vi.fn();
|
|
15
|
+
|
|
16
|
+
constructor(url: string, options: any) {
|
|
17
|
+
wsMock.constructed.push({ url, options, instance: this });
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return { default: MockWebSocket };
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
describe('WsClient', () => {
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
wsMock.constructed.length = 0;
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('connects with Authorization header instead of api_key query', async () => {
|
|
30
|
+
const { WsClient } = await import('./ws-client.js');
|
|
31
|
+
const client = new WsClient({
|
|
32
|
+
url: 'wss://host.example/api/v1/game/stream',
|
|
33
|
+
apiKey: 'claw_secret',
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const connected = client.connect();
|
|
37
|
+
expect(wsMock.constructed).toHaveLength(1);
|
|
38
|
+
expect(wsMock.constructed[0].url).toBe('wss://host.example/api/v1/game/stream');
|
|
39
|
+
expect(wsMock.constructed[0].url).not.toContain('api_key');
|
|
40
|
+
expect(wsMock.constructed[0].options).toMatchObject({
|
|
41
|
+
headers: { Authorization: 'Bearer claw_secret' },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
wsMock.constructed[0].instance.onopen?.({});
|
|
45
|
+
await connected;
|
|
46
|
+
});
|
|
47
|
+
});
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// src/runtime/ws-client.ts
|
|
2
|
+
// Internal WebSocket client — NOT exported from index.ts
|
|
3
|
+
// Used only by Runtime and daemon internally.
|
|
4
|
+
|
|
5
|
+
import WebSocket from 'ws';
|
|
6
|
+
import { WsConnectionState } from '../sdk/types.js';
|
|
7
|
+
import { appendRawWsMessage } from './raw-ws-log.js';
|
|
8
|
+
|
|
9
|
+
export interface WsClientConfig {
|
|
10
|
+
url: string;
|
|
11
|
+
apiKey: string;
|
|
12
|
+
reconnectMaxMs?: number;
|
|
13
|
+
/** Heartbeat interval in ms (default: 15000). Set to 0 to disable. */
|
|
14
|
+
heartbeatIntervalMs?: number;
|
|
15
|
+
/** Diagnostic-only raw server frame log path. */
|
|
16
|
+
rawMessageLogPath?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Heartbeat interval — matches old auto_play.ts */
|
|
20
|
+
const DEFAULT_HEARTBEAT_INTERVAL_MS = 15000;
|
|
21
|
+
|
|
22
|
+
function wsMessageToString(data: WebSocket.Data): string {
|
|
23
|
+
if (typeof data === 'string') return data;
|
|
24
|
+
if (Buffer.isBuffer(data)) return data.toString('utf8');
|
|
25
|
+
if (data instanceof ArrayBuffer) return Buffer.from(data).toString('utf8');
|
|
26
|
+
return Buffer.concat(data).toString('utf8');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class WsClient {
|
|
30
|
+
private config: WsClientConfig;
|
|
31
|
+
private ws: WebSocket | null = null;
|
|
32
|
+
private _state: WsConnectionState = WsConnectionState.Disconnected;
|
|
33
|
+
private shouldReconnect = false;
|
|
34
|
+
private reconnectAttempt = 0;
|
|
35
|
+
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
36
|
+
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
37
|
+
|
|
38
|
+
// Type-safe event handlers (new)
|
|
39
|
+
private typedHandlers = new Map<string, Set<(data: Record<string, any>) => void>>();
|
|
40
|
+
private disconnectHandlers: ((reason: string) => void)[] = [];
|
|
41
|
+
private stateChangeHandlers: ((state: WsConnectionState) => void)[] = [];
|
|
42
|
+
/** High-water mark for tick-based dedup of state.new_events (align with agones) */
|
|
43
|
+
private lastEventTick = -1;
|
|
44
|
+
|
|
45
|
+
constructor(config: WsClientConfig) {
|
|
46
|
+
this.config = config;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
get connected(): boolean {
|
|
50
|
+
return this._state === WsConnectionState.Connected;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
get state(): WsConnectionState {
|
|
54
|
+
return this._state;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private setState(newState: WsConnectionState): void {
|
|
58
|
+
if (this._state === newState) return;
|
|
59
|
+
this._state = newState;
|
|
60
|
+
for (const handler of this.stateChangeHandlers) {
|
|
61
|
+
handler(newState);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
connect(): Promise<void> {
|
|
66
|
+
this.shouldReconnect = true;
|
|
67
|
+
this.reconnectAttempt = 0;
|
|
68
|
+
this.setState(WsConnectionState.Connecting);
|
|
69
|
+
return this._openSocket();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private _openSocket(): Promise<void> {
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
const ws = new WebSocket(this.config.url, {
|
|
75
|
+
headers: { Authorization: `Bearer ${this.config.apiKey}` },
|
|
76
|
+
});
|
|
77
|
+
this.ws = ws;
|
|
78
|
+
|
|
79
|
+
ws.onopen = () => {
|
|
80
|
+
this.setState(WsConnectionState.Connected);
|
|
81
|
+
this.reconnectAttempt = 0;
|
|
82
|
+
this._startHeartbeat();
|
|
83
|
+
resolve();
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
ws.onerror = (err) => {
|
|
87
|
+
reject(err);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
ws.onmessage = (e) => {
|
|
91
|
+
const data = wsMessageToString(e.data);
|
|
92
|
+
if (this.config.rawMessageLogPath) {
|
|
93
|
+
appendRawWsMessage(this.config.rawMessageLogPath, data);
|
|
94
|
+
}
|
|
95
|
+
if (data === 'pong') return;
|
|
96
|
+
try {
|
|
97
|
+
const msg = JSON.parse(data);
|
|
98
|
+
this.handleMessage(msg);
|
|
99
|
+
} catch {
|
|
100
|
+
// ignore malformed messages
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
ws.onclose = (e: { reason: string }) => {
|
|
105
|
+
this._stopHeartbeat();
|
|
106
|
+
const reason = e.reason ?? '';
|
|
107
|
+
for (const handler of this.disconnectHandlers) {
|
|
108
|
+
handler(reason);
|
|
109
|
+
}
|
|
110
|
+
if (this.shouldReconnect) {
|
|
111
|
+
this.setState(WsConnectionState.Reconnecting);
|
|
112
|
+
this._scheduleReconnect();
|
|
113
|
+
} else {
|
|
114
|
+
this.setState(WsConnectionState.Disconnected);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Central message handler: handles event_batch, state, and single events.
|
|
122
|
+
* Normalizes event format before dispatching.
|
|
123
|
+
*/
|
|
124
|
+
private handleMessage(msg: any): void {
|
|
125
|
+
// event_batch: unwrap and dispatch each event individually
|
|
126
|
+
if (msg.type === 'event_batch' && Array.isArray(msg.data)) {
|
|
127
|
+
for (const event of msg.data) {
|
|
128
|
+
this.dispatchEvent(event);
|
|
129
|
+
}
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
// state: always dispatch the full snapshot as _state for daemon feed tracking
|
|
133
|
+
// (current_speaker, sub_phase, vote progress, etc. update without necessarily
|
|
134
|
+
// shipping a new event). Process new_events with tick-based dedup if present.
|
|
135
|
+
if (msg.type === 'state' && msg.data) {
|
|
136
|
+
if (Array.isArray(msg.data.new_events)) {
|
|
137
|
+
const threshold = this.lastEventTick;
|
|
138
|
+
let maxTick = threshold;
|
|
139
|
+
for (const event of msg.data.new_events) {
|
|
140
|
+
const evtTick: number = event.tick ?? -1;
|
|
141
|
+
if (evtTick <= threshold) continue; // already processed
|
|
142
|
+
if (evtTick > maxTick) maxTick = evtTick;
|
|
143
|
+
this.dispatchEvent(event);
|
|
144
|
+
}
|
|
145
|
+
this.lastEventTick = maxTick;
|
|
146
|
+
}
|
|
147
|
+
this.dispatchEvent({ type: '_state', data: msg.data });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
// All other messages are dispatched as events
|
|
151
|
+
this.dispatchEvent(msg);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Normalize event format and dispatch to typed + legacy handlers.
|
|
156
|
+
*
|
|
157
|
+
* Server sends two formats:
|
|
158
|
+
* - { type, field1, field2 }
|
|
159
|
+
* - { type, data: { field1, field2 } }
|
|
160
|
+
* Normalize to consistent data object for typed handlers.
|
|
161
|
+
*/
|
|
162
|
+
private dispatchEvent(raw: any): void {
|
|
163
|
+
const type: string = raw.type;
|
|
164
|
+
if (!type) return;
|
|
165
|
+
|
|
166
|
+
// Normalize: extract data payload
|
|
167
|
+
const { type: _t, data, ...rest } = raw;
|
|
168
|
+
const normalizedData: Record<string, any> =
|
|
169
|
+
data && typeof data === 'object' && !Array.isArray(data) ? data : rest;
|
|
170
|
+
|
|
171
|
+
// Typed handlers (new API)
|
|
172
|
+
const handlers = this.typedHandlers.get(type);
|
|
173
|
+
if (handlers) {
|
|
174
|
+
for (const handler of handlers) {
|
|
175
|
+
handler(normalizedData);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Catch-all `*` handlers
|
|
180
|
+
const wildcardHandlers = this.typedHandlers.get('*');
|
|
181
|
+
if (wildcardHandlers) {
|
|
182
|
+
for (const handler of wildcardHandlers) {
|
|
183
|
+
handler({ type, ...normalizedData });
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ─── Public API ───
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Register a handler for a specific event type.
|
|
192
|
+
* Handler receives normalized data (always a flat object, never nested under .data).
|
|
193
|
+
* Returns an unsubscribe function.
|
|
194
|
+
*/
|
|
195
|
+
on(eventType: string, handler: (data: Record<string, any>) => void): () => void {
|
|
196
|
+
let set = this.typedHandlers.get(eventType);
|
|
197
|
+
if (!set) {
|
|
198
|
+
set = new Set();
|
|
199
|
+
this.typedHandlers.set(eventType, set);
|
|
200
|
+
}
|
|
201
|
+
set.add(handler);
|
|
202
|
+
return () => { set!.delete(handler); };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Send an action via WebSocket. */
|
|
206
|
+
send(action: { toJSON(): Record<string, any> }): void {
|
|
207
|
+
if (this._state !== WsConnectionState.Connected || !this.ws) return;
|
|
208
|
+
this.ws.send(JSON.stringify({ type: 'action', data: action.toJSON() }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Register a handler for state changes. */
|
|
212
|
+
onStateChange(handler: (state: WsConnectionState) => void): void {
|
|
213
|
+
this.stateChangeHandlers.push(handler);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
onDisconnect(handler: (reason: string) => void): void {
|
|
217
|
+
this.disconnectHandlers.push(handler);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Clear all typed event handlers (used when replacing WsClient). */
|
|
221
|
+
clearHandlers(): void {
|
|
222
|
+
this.typedHandlers.clear();
|
|
223
|
+
this.stateChangeHandlers = [];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
disconnect(): void {
|
|
227
|
+
this.shouldReconnect = false;
|
|
228
|
+
this._stopHeartbeat();
|
|
229
|
+
if (this.reconnectTimer !== null) {
|
|
230
|
+
clearTimeout(this.reconnectTimer);
|
|
231
|
+
this.reconnectTimer = null;
|
|
232
|
+
}
|
|
233
|
+
if (this.ws) {
|
|
234
|
+
this.ws.onclose = null;
|
|
235
|
+
this.ws.close();
|
|
236
|
+
this.ws = null;
|
|
237
|
+
}
|
|
238
|
+
this.setState(WsConnectionState.Disconnected);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ─── Heartbeat ───
|
|
242
|
+
|
|
243
|
+
private _startHeartbeat(): void {
|
|
244
|
+
this._stopHeartbeat();
|
|
245
|
+
const intervalMs = this.config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
|
|
246
|
+
if (intervalMs <= 0) return;
|
|
247
|
+
this.heartbeatTimer = setInterval(() => {
|
|
248
|
+
if (this.ws && this._state === WsConnectionState.Connected) {
|
|
249
|
+
this.ws.send('ping');
|
|
250
|
+
}
|
|
251
|
+
}, intervalMs);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private _stopHeartbeat(): void {
|
|
255
|
+
if (this.heartbeatTimer !== null) {
|
|
256
|
+
clearInterval(this.heartbeatTimer);
|
|
257
|
+
this.heartbeatTimer = null;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private _scheduleReconnect(): void {
|
|
262
|
+
const maxMs = this.config.reconnectMaxMs ?? 30000;
|
|
263
|
+
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempt), maxMs);
|
|
264
|
+
this.reconnectAttempt++;
|
|
265
|
+
this.reconnectTimer = setTimeout(() => {
|
|
266
|
+
if (this.shouldReconnect) {
|
|
267
|
+
this.setState(WsConnectionState.Connecting);
|
|
268
|
+
this._openSocket().catch(() => {});
|
|
269
|
+
}
|
|
270
|
+
}, delay);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Action — an immutable, typed game command sent to the server each tick.
|
|
3
|
+
*
|
|
4
|
+
* All static factories (`move`, `kill`, `speech`, …) return frozen `Action`
|
|
5
|
+
* instances. Attach spectator-visible reasoning with `.withThinking(content)`,
|
|
6
|
+
* which returns a new `Action` without mutating the original.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* return Action.move('kitchen').withThinking('Heading to the kitchen for my task.');
|
|
11
|
+
* return Action.kill('PlayerB').withThinking('Alone with target — safe window.');
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export class Action {
|
|
15
|
+
readonly type: string;
|
|
16
|
+
readonly payload: Record<string, any>;
|
|
17
|
+
/**
|
|
18
|
+
* Spectator-visible reasoning string sent as `thinking_content` to the server.
|
|
19
|
+
* Visible to observers only — not exposed to other in-game players.
|
|
20
|
+
*/
|
|
21
|
+
readonly thinkingContent: string | null;
|
|
22
|
+
|
|
23
|
+
private constructor(type: string, payload: Record<string, any>, thinkingContent: string | null = null) {
|
|
24
|
+
this.type = type;
|
|
25
|
+
this.payload = payload;
|
|
26
|
+
this.thinkingContent = thinkingContent;
|
|
27
|
+
Object.freeze(this);
|
|
28
|
+
Object.freeze(this.payload);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Attach (or replace) the spectator-visible thinking content.
|
|
33
|
+
* Returns a **new** immutable `Action` — the original is unchanged.
|
|
34
|
+
*
|
|
35
|
+
* @example Action.kill('playerA').withThinking('Safe kill — only one witness.')
|
|
36
|
+
*/
|
|
37
|
+
withThinking(content: string): Action {
|
|
38
|
+
return new Action(this.type, { ...this.payload }, content);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Attach (or replace) the speech audio URL.
|
|
43
|
+
* Returns a **new** immutable `Action` — the original is unchanged.
|
|
44
|
+
* Typically used by the runtime to inject TTS-generated audio into speech actions.
|
|
45
|
+
*/
|
|
46
|
+
withAudioUrl(audioUrl: string): Action {
|
|
47
|
+
return new Action(this.type, { ...this.payload, audio_url: audioUrl }, this.thinkingContent);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Move toward a room (by name) or a coordinate target.
|
|
52
|
+
*
|
|
53
|
+
* @param target Room id string, or a `{ x, y }` coordinate pair.
|
|
54
|
+
* @param stopOnPlayer If true, movement stops when encountering another alive player.
|
|
55
|
+
*/
|
|
56
|
+
static move(target: { x: number; y: number } | string, stopOnPlayer = false): Action {
|
|
57
|
+
if (typeof target === 'string') {
|
|
58
|
+
const payload: Record<string, any> = { target };
|
|
59
|
+
if (stopOnPlayer) payload.stop_on_player = true;
|
|
60
|
+
return new Action('move', payload, `前往 ${target}`);
|
|
61
|
+
}
|
|
62
|
+
const payload: Record<string, any> = { target_x: target.x, target_y: target.y };
|
|
63
|
+
if (stopOnPlayer) payload.stop_on_player = true;
|
|
64
|
+
return new Action('move', payload);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Kill the named player.
|
|
69
|
+
* Only succeeds when cooldown is ready, a kill use remains, and the target is in range.
|
|
70
|
+
*/
|
|
71
|
+
static kill(target: string): Action {
|
|
72
|
+
return new Action('kill', { target }, `击杀 ${target}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Broadcast a speech during the wandering phase.
|
|
77
|
+
*
|
|
78
|
+
* @param text Words spoken (audible to nearby players).
|
|
79
|
+
* @param thinkingContent Optional spectator-visible reasoning.
|
|
80
|
+
* @param audioUrl Optional TTS audio URL.
|
|
81
|
+
*/
|
|
82
|
+
static speech(text: string, thinkingContent?: string, audioUrl?: string): Action {
|
|
83
|
+
const payload: Record<string, any> = { text };
|
|
84
|
+
if (audioUrl) {
|
|
85
|
+
payload.audio_url = audioUrl;
|
|
86
|
+
}
|
|
87
|
+
return new Action('speech', payload, thinkingContent ?? null);
|
|
88
|
+
// speech: no default thinking (the speech content itself is the message)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Cast a vote during the meeting vote sub-phase.
|
|
93
|
+
*
|
|
94
|
+
* @param target Name of the player to vote out.
|
|
95
|
+
*/
|
|
96
|
+
static vote(target: string): Action {
|
|
97
|
+
return new Action('vote', { target }, `投票 ${target}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Execute (or move toward) a task.
|
|
102
|
+
*
|
|
103
|
+
* @param taskName Optional task name. Omit to let the server resolve which
|
|
104
|
+
* task to execute at the current location.
|
|
105
|
+
*/
|
|
106
|
+
static doTask(taskName?: string): Action {
|
|
107
|
+
return new Action('task', taskName ? { task_name: taskName } : {}, taskName ? `执行任务 ${taskName}` : '执行任务');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Report a corpse to trigger an emergency meeting.
|
|
112
|
+
*
|
|
113
|
+
* @param corpseName Name of the dead player (written to thinking log).
|
|
114
|
+
* @param room Room where the corpse was found.
|
|
115
|
+
*/
|
|
116
|
+
static report(corpseName?: string, room?: string): Action {
|
|
117
|
+
const thinking = corpseName
|
|
118
|
+
? `发现尸体(${corpseName}${room ? ` 在 ${room}` : ''}),报告召开会议`
|
|
119
|
+
: '发现尸体,报告召开会议';
|
|
120
|
+
return new Action('report', {}, thinking);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Pure thinking action — sends only `thinking_content` with no in-game effect.
|
|
125
|
+
* Useful for pushing reasoning text to spectators without altering game state.
|
|
126
|
+
*/
|
|
127
|
+
static think(): Action {
|
|
128
|
+
return new Action('think', {}, '正在思考...');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Trigger the emergency alarm. Crab faction exclusive.
|
|
133
|
+
* Starts a timed emergency event that Shrimp players must resolve.
|
|
134
|
+
*/
|
|
135
|
+
static triggerAlarm(): Action {
|
|
136
|
+
return new Action('trigger_alarm', {}, '触发紧急警报!');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Deserialize an `Action` from a plain JSON object.
|
|
141
|
+
* Accepts both `{ action: "move", … }` and `{ type: "move", … }` formats.
|
|
142
|
+
*
|
|
143
|
+
* @throws {Error} If the object contains no valid action type string.
|
|
144
|
+
*/
|
|
145
|
+
static fromJSON(json: Record<string, any>): Action {
|
|
146
|
+
// Support both { action: "move", ... } and { type: "move", ... } formats
|
|
147
|
+
const type = json.action ?? json.type;
|
|
148
|
+
if (!type || typeof type !== 'string') {
|
|
149
|
+
throw new Error(`Action.fromJSON: missing or invalid action type in ${JSON.stringify(json)}`);
|
|
150
|
+
}
|
|
151
|
+
const { action: _a, type: _t, thinking_content, ...payload } = json;
|
|
152
|
+
return new Action(type, payload, thinking_content ?? null);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Serialize this `Action` to a plain object for transmission to the server.
|
|
157
|
+
* The `thinking_content` key is omitted when `thinkingContent` is null.
|
|
158
|
+
*/
|
|
159
|
+
toJSON(): Record<string, any> {
|
|
160
|
+
const obj: Record<string, any> = { action: this.type, ...this.payload };
|
|
161
|
+
if (this.thinkingContent) {
|
|
162
|
+
obj.thinking_content = this.thinkingContent;
|
|
163
|
+
}
|
|
164
|
+
return obj;
|
|
165
|
+
}
|
|
166
|
+
}
|