@myclaw163/clawclaw-cli 0.6.96 → 0.6.101
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/clawclaw-cli.mjs +3 -3
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +26 -10
- package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +17 -5
- package/skills/clawclaw/references/STREAM.md +15 -12
- package/src/commands/config.ts +30 -30
- package/src/commands/do.test.ts +27 -1
- package/src/commands/do.ts +61 -0
- package/src/commands/events.test.ts +21 -3
- package/src/commands/events.ts +8 -2
- package/src/commands/game-start-plan.test.ts +158 -0
- package/src/commands/game.ts +670 -64
- package/src/commands/history-player.test.ts +3 -0
- package/src/commands/setup/hermes.test.ts +96 -96
- package/src/commands/setup/hermes.ts +76 -76
- package/src/commands/setup/index.ts +13 -13
- package/src/commands/setup/openclaw.test.ts +124 -114
- package/src/commands/setup/openclaw.ts +162 -147
- package/src/commands/watch.test.ts +272 -0
- package/src/commands/watch.ts +185 -25
- package/src/lib/game-client.ts +34 -0
- package/src/lib/host-config-patcher.test.ts +130 -130
- package/src/lib/host-config-patcher.ts +151 -151
- package/src/lib/room.test.ts +74 -0
- package/src/lib/room.ts +129 -0
- package/src/lib/server-registry.test.ts +54 -0
- package/src/lib/server-registry.ts +35 -2
- package/src/perception/player-history-store.test.ts +92 -2
- package/src/perception/player-history-store.ts +68 -0
- package/src/pipeline/event-format.test.ts +61 -1
- package/src/pipeline/event-format.ts +88 -0
- package/src/pipeline/event-hints.ts +10 -1
- package/src/runtime/event-daemon.test.ts +43 -0
- package/src/runtime/event-daemon.ts +8 -4
- package/src/runtime/room-lobby-runtime.test.ts +95 -0
- package/src/runtime/room-lobby-runtime.ts +367 -0
|
@@ -1,151 +1,151 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Generic JSON-config setup runner shared by `ccl setup <host>` subcommands.
|
|
3
|
-
*
|
|
4
|
-
* Each host adapter only supplies:
|
|
5
|
-
* - resolveConfigPath(): where the host stores its global JSON config
|
|
6
|
-
* - computePatch(current, opts): pure function returning the desired next config + change/warning notes
|
|
7
|
-
*
|
|
8
|
-
* The runner handles dry-run, diff, atomic write, and timestamped backup uniformly,
|
|
9
|
-
* so adding a new host (gemini, claude-code, ...) is ~30 lines of glue.
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import { existsSync, readFileSync, renameSync, copyFileSync, writeFileSync } from 'fs';
|
|
13
|
-
|
|
14
|
-
export interface HostConfigPatcher<Opts extends object = Record<string, never>> {
|
|
15
|
-
hostName: string;
|
|
16
|
-
resolveConfigPath: () => string;
|
|
17
|
-
computePatch: (current: unknown, opts: Opts) => HostPatchResult;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export interface HostPatchResult {
|
|
21
|
-
next: unknown;
|
|
22
|
-
changes: string[];
|
|
23
|
-
warnings: string[];
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export interface RunHostSetupFlags {
|
|
27
|
-
yes?: boolean;
|
|
28
|
-
print?: boolean;
|
|
29
|
-
configPath?: string;
|
|
30
|
-
backup?: boolean;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export interface RunHostSetupResult {
|
|
34
|
-
exitCode: number;
|
|
35
|
-
output: string[];
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export function runHostConfigSetup<Opts extends object>(
|
|
39
|
-
patcher: HostConfigPatcher<Opts>,
|
|
40
|
-
hostOpts: Opts,
|
|
41
|
-
flags: RunHostSetupFlags,
|
|
42
|
-
): RunHostSetupResult {
|
|
43
|
-
const out: string[] = [];
|
|
44
|
-
const configPath = flags.configPath ?? patcher.resolveConfigPath();
|
|
45
|
-
|
|
46
|
-
if (flags.print) {
|
|
47
|
-
const sample = patcher.computePatch({}, hostOpts);
|
|
48
|
-
out.push(`# Recommended ${patcher.hostName} config patch:`);
|
|
49
|
-
out.push(JSON.stringify(sample.next, null, 2));
|
|
50
|
-
return { exitCode: 0, output: out };
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
if (!existsSync(configPath)) {
|
|
54
|
-
out.push(`${patcher.hostName} config not found at: ${configPath}`);
|
|
55
|
-
out.push(`Initialize it first (e.g. \`openclaw doctor\` for OpenClaw), then re-run.`);
|
|
56
|
-
return { exitCode: 0, output: out };
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
let raw: string;
|
|
60
|
-
try {
|
|
61
|
-
raw = readFileSync(configPath, 'utf-8');
|
|
62
|
-
} catch (err: any) {
|
|
63
|
-
out.push(`Failed to read ${configPath}: ${err?.message ?? err}`);
|
|
64
|
-
return { exitCode: 1, output: out };
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
let current: unknown;
|
|
68
|
-
try {
|
|
69
|
-
current = JSON.parse(raw);
|
|
70
|
-
} catch (err: any) {
|
|
71
|
-
out.push(`Failed to parse JSON at ${configPath}: ${err?.message ?? err}`);
|
|
72
|
-
out.push(`Fix the JSON manually first; this tool does not edit malformed files.`);
|
|
73
|
-
return { exitCode: 1, output: out };
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const { next, changes, warnings } = patcher.computePatch(current, hostOpts);
|
|
77
|
-
|
|
78
|
-
for (const w of warnings) out.push(`warning: ${w}`);
|
|
79
|
-
|
|
80
|
-
if (changes.length === 0) {
|
|
81
|
-
out.push(`${patcher.hostName} config already up to date at ${configPath}.`);
|
|
82
|
-
return { exitCode: 0, output: out };
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
if (!flags.yes) {
|
|
86
|
-
out.push(`Pending changes to ${configPath}:`);
|
|
87
|
-
for (const c of changes) out.push(` - ${c}`);
|
|
88
|
-
out.push(``);
|
|
89
|
-
out.push(diffJson(current, next));
|
|
90
|
-
out.push(``);
|
|
91
|
-
out.push(`Dry-run only. Re-run with -y to apply.`);
|
|
92
|
-
return { exitCode: 2, output: out };
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
let backupPath: string | undefined;
|
|
96
|
-
if (flags.backup !== false) {
|
|
97
|
-
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
|
98
|
-
backupPath = `${configPath}.bak.${ts}`;
|
|
99
|
-
try {
|
|
100
|
-
copyFileSync(configPath, backupPath);
|
|
101
|
-
} catch (err: any) {
|
|
102
|
-
out.push(`Failed to back up ${configPath} → ${backupPath}: ${err?.message ?? err}`);
|
|
103
|
-
return { exitCode: 1, output: out };
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const tmpPath = `${configPath}.tmp.${process.pid}`;
|
|
108
|
-
try {
|
|
109
|
-
const eol = raw.includes('\r\n') ? '\r\n' : '\n';
|
|
110
|
-
const serialized = JSON.stringify(next, null, 2).replace(/\n/g, eol) + eol;
|
|
111
|
-
writeFileSync(tmpPath, serialized, 'utf-8');
|
|
112
|
-
renameSync(tmpPath, configPath);
|
|
113
|
-
} catch (err: any) {
|
|
114
|
-
out.push(`Failed to write ${configPath}: ${err?.message ?? err}`);
|
|
115
|
-
return { exitCode: 1, output: out };
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
out.push(`Updated ${configPath}:`);
|
|
119
|
-
for (const c of changes) out.push(` - ${c}`);
|
|
120
|
-
if (backupPath) out.push(`Backup: ${backupPath}`);
|
|
121
|
-
return { exitCode: 0, output: out };
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** Minimal line-level JSON diff for the dry-run preview. Self-contained, zero deps. */
|
|
125
|
-
export function diffJson(before: unknown, after: unknown): string {
|
|
126
|
-
const a = JSON.stringify(before, null, 2).split('\n');
|
|
127
|
-
const b = JSON.stringify(after, null, 2).split('\n');
|
|
128
|
-
const aSet = new Set(a);
|
|
129
|
-
const bSet = new Set(b);
|
|
130
|
-
const lines: string[] = [];
|
|
131
|
-
const max = Math.max(a.length, b.length);
|
|
132
|
-
for (let i = 0; i < max; i++) {
|
|
133
|
-
const ax = a[i];
|
|
134
|
-
const bx = b[i];
|
|
135
|
-
if (ax === bx) {
|
|
136
|
-
lines.push(` ${ax ?? ''}`);
|
|
137
|
-
} else {
|
|
138
|
-
if (ax !== undefined && !bSet.has(ax)) lines.push(`- ${ax}`);
|
|
139
|
-
if (bx !== undefined && !aSet.has(bx)) lines.push(`+ ${bx}`);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
return lines.join('\n');
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** Shared helper for hosts: add an entry to an array field, returning a new array (Set union). */
|
|
146
|
-
export function unionArrayField(arr: unknown, entry: string): { next: string[]; added: boolean } | { warning: string } {
|
|
147
|
-
if (arr === undefined) return { next: [entry], added: true };
|
|
148
|
-
if (!Array.isArray(arr)) return { warning: `existing value is not an array, refusing to overwrite` };
|
|
149
|
-
if (arr.includes(entry)) return { next: arr.slice() as string[], added: false };
|
|
150
|
-
return { next: [...(arr as string[]), entry], added: true };
|
|
151
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Generic JSON-config setup runner shared by `ccl setup <host>` subcommands.
|
|
3
|
+
*
|
|
4
|
+
* Each host adapter only supplies:
|
|
5
|
+
* - resolveConfigPath(): where the host stores its global JSON config
|
|
6
|
+
* - computePatch(current, opts): pure function returning the desired next config + change/warning notes
|
|
7
|
+
*
|
|
8
|
+
* The runner handles dry-run, diff, atomic write, and timestamped backup uniformly,
|
|
9
|
+
* so adding a new host (gemini, claude-code, ...) is ~30 lines of glue.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { existsSync, readFileSync, renameSync, copyFileSync, writeFileSync } from 'fs';
|
|
13
|
+
|
|
14
|
+
export interface HostConfigPatcher<Opts extends object = Record<string, never>> {
|
|
15
|
+
hostName: string;
|
|
16
|
+
resolveConfigPath: () => string;
|
|
17
|
+
computePatch: (current: unknown, opts: Opts) => HostPatchResult;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface HostPatchResult {
|
|
21
|
+
next: unknown;
|
|
22
|
+
changes: string[];
|
|
23
|
+
warnings: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface RunHostSetupFlags {
|
|
27
|
+
yes?: boolean;
|
|
28
|
+
print?: boolean;
|
|
29
|
+
configPath?: string;
|
|
30
|
+
backup?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface RunHostSetupResult {
|
|
34
|
+
exitCode: number;
|
|
35
|
+
output: string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function runHostConfigSetup<Opts extends object>(
|
|
39
|
+
patcher: HostConfigPatcher<Opts>,
|
|
40
|
+
hostOpts: Opts,
|
|
41
|
+
flags: RunHostSetupFlags,
|
|
42
|
+
): RunHostSetupResult {
|
|
43
|
+
const out: string[] = [];
|
|
44
|
+
const configPath = flags.configPath ?? patcher.resolveConfigPath();
|
|
45
|
+
|
|
46
|
+
if (flags.print) {
|
|
47
|
+
const sample = patcher.computePatch({}, hostOpts);
|
|
48
|
+
out.push(`# Recommended ${patcher.hostName} config patch:`);
|
|
49
|
+
out.push(JSON.stringify(sample.next, null, 2));
|
|
50
|
+
return { exitCode: 0, output: out };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (!existsSync(configPath)) {
|
|
54
|
+
out.push(`${patcher.hostName} config not found at: ${configPath}`);
|
|
55
|
+
out.push(`Initialize it first (e.g. \`openclaw doctor\` for OpenClaw), then re-run.`);
|
|
56
|
+
return { exitCode: 0, output: out };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
let raw: string;
|
|
60
|
+
try {
|
|
61
|
+
raw = readFileSync(configPath, 'utf-8');
|
|
62
|
+
} catch (err: any) {
|
|
63
|
+
out.push(`Failed to read ${configPath}: ${err?.message ?? err}`);
|
|
64
|
+
return { exitCode: 1, output: out };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let current: unknown;
|
|
68
|
+
try {
|
|
69
|
+
current = JSON.parse(raw);
|
|
70
|
+
} catch (err: any) {
|
|
71
|
+
out.push(`Failed to parse JSON at ${configPath}: ${err?.message ?? err}`);
|
|
72
|
+
out.push(`Fix the JSON manually first; this tool does not edit malformed files.`);
|
|
73
|
+
return { exitCode: 1, output: out };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const { next, changes, warnings } = patcher.computePatch(current, hostOpts);
|
|
77
|
+
|
|
78
|
+
for (const w of warnings) out.push(`warning: ${w}`);
|
|
79
|
+
|
|
80
|
+
if (changes.length === 0) {
|
|
81
|
+
out.push(`${patcher.hostName} config already up to date at ${configPath}.`);
|
|
82
|
+
return { exitCode: 0, output: out };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!flags.yes) {
|
|
86
|
+
out.push(`Pending changes to ${configPath}:`);
|
|
87
|
+
for (const c of changes) out.push(` - ${c}`);
|
|
88
|
+
out.push(``);
|
|
89
|
+
out.push(diffJson(current, next));
|
|
90
|
+
out.push(``);
|
|
91
|
+
out.push(`Dry-run only. Re-run with -y to apply.`);
|
|
92
|
+
return { exitCode: 2, output: out };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let backupPath: string | undefined;
|
|
96
|
+
if (flags.backup !== false) {
|
|
97
|
+
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
|
98
|
+
backupPath = `${configPath}.bak.${ts}`;
|
|
99
|
+
try {
|
|
100
|
+
copyFileSync(configPath, backupPath);
|
|
101
|
+
} catch (err: any) {
|
|
102
|
+
out.push(`Failed to back up ${configPath} → ${backupPath}: ${err?.message ?? err}`);
|
|
103
|
+
return { exitCode: 1, output: out };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const tmpPath = `${configPath}.tmp.${process.pid}`;
|
|
108
|
+
try {
|
|
109
|
+
const eol = raw.includes('\r\n') ? '\r\n' : '\n';
|
|
110
|
+
const serialized = JSON.stringify(next, null, 2).replace(/\n/g, eol) + eol;
|
|
111
|
+
writeFileSync(tmpPath, serialized, 'utf-8');
|
|
112
|
+
renameSync(tmpPath, configPath);
|
|
113
|
+
} catch (err: any) {
|
|
114
|
+
out.push(`Failed to write ${configPath}: ${err?.message ?? err}`);
|
|
115
|
+
return { exitCode: 1, output: out };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
out.push(`Updated ${configPath}:`);
|
|
119
|
+
for (const c of changes) out.push(` - ${c}`);
|
|
120
|
+
if (backupPath) out.push(`Backup: ${backupPath}`);
|
|
121
|
+
return { exitCode: 0, output: out };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Minimal line-level JSON diff for the dry-run preview. Self-contained, zero deps. */
|
|
125
|
+
export function diffJson(before: unknown, after: unknown): string {
|
|
126
|
+
const a = JSON.stringify(before, null, 2).split('\n');
|
|
127
|
+
const b = JSON.stringify(after, null, 2).split('\n');
|
|
128
|
+
const aSet = new Set(a);
|
|
129
|
+
const bSet = new Set(b);
|
|
130
|
+
const lines: string[] = [];
|
|
131
|
+
const max = Math.max(a.length, b.length);
|
|
132
|
+
for (let i = 0; i < max; i++) {
|
|
133
|
+
const ax = a[i];
|
|
134
|
+
const bx = b[i];
|
|
135
|
+
if (ax === bx) {
|
|
136
|
+
lines.push(` ${ax ?? ''}`);
|
|
137
|
+
} else {
|
|
138
|
+
if (ax !== undefined && !bSet.has(ax)) lines.push(`- ${ax}`);
|
|
139
|
+
if (bx !== undefined && !aSet.has(bx)) lines.push(`+ ${bx}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return lines.join('\n');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Shared helper for hosts: add an entry to an array field, returning a new array (Set union). */
|
|
146
|
+
export function unionArrayField(arr: unknown, entry: string): { next: string[]; added: boolean } | { warning: string } {
|
|
147
|
+
if (arr === undefined) return { next: [entry], added: true };
|
|
148
|
+
if (!Array.isArray(arr)) return { warning: `existing value is not an array, refusing to overwrite` };
|
|
149
|
+
if (arr.includes(entry)) return { next: arr.slice() as string[], added: false };
|
|
150
|
+
return { next: [...(arr as string[]), entry], added: true };
|
|
151
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
hasRoomQueueContext,
|
|
4
|
+
isCurrentAgentRoomOwner,
|
|
5
|
+
isInRoomQueueStatus,
|
|
6
|
+
isRoomAllocatedQueueStatus,
|
|
7
|
+
isRoomReadyToStart,
|
|
8
|
+
memberCount,
|
|
9
|
+
queueMode,
|
|
10
|
+
queueRoomCode,
|
|
11
|
+
queueStatus,
|
|
12
|
+
} from './room.js';
|
|
13
|
+
|
|
14
|
+
const members = Array.from({ length: 10 }, (_, index) => ({
|
|
15
|
+
seat: index + 1,
|
|
16
|
+
name: `player-${index + 1}`,
|
|
17
|
+
is_owner: index === 0,
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
describe('room helpers', () => {
|
|
21
|
+
it('reads in-room queue status and room code from wrapped responses', () => {
|
|
22
|
+
const response = { data: { status: 'in_room', room_code: '123456' } };
|
|
23
|
+
|
|
24
|
+
expect(queueStatus(response)).toBe('in_room');
|
|
25
|
+
expect(queueRoomCode(response)).toBe('123456');
|
|
26
|
+
expect(isInRoomQueueStatus(response)).toBe(true);
|
|
27
|
+
expect(hasRoomQueueContext(response)).toBe(true);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('recognizes allocated room games as room context', () => {
|
|
31
|
+
const response = { data: { status: 'allocated', mode: 'room', game_server_name: 'room-gs' } };
|
|
32
|
+
|
|
33
|
+
expect(queueStatus(response)).toBe('allocated');
|
|
34
|
+
expect(queueMode(response)).toBe('room');
|
|
35
|
+
expect(isRoomAllocatedQueueStatus(response)).toBe(true);
|
|
36
|
+
expect(hasRoomQueueContext(response)).toBe(true);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('does not treat normal allocations as room context', () => {
|
|
40
|
+
const response = { data: { status: 'allocated', mode: 'match' } };
|
|
41
|
+
|
|
42
|
+
expect(isRoomAllocatedQueueStatus(response)).toBe(false);
|
|
43
|
+
expect(hasRoomQueueContext(response)).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('detects owner status by the current seat', () => {
|
|
47
|
+
expect(isCurrentAgentRoomOwner({
|
|
48
|
+
my_seat: 1,
|
|
49
|
+
members,
|
|
50
|
+
})).toBe(true);
|
|
51
|
+
|
|
52
|
+
expect(isCurrentAgentRoomOwner({
|
|
53
|
+
my_seat: 2,
|
|
54
|
+
members,
|
|
55
|
+
})).toBe(false);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('requires owner, waiting status, full room, and no cooldown before manual start', () => {
|
|
59
|
+
const ready = {
|
|
60
|
+
room_type: 'casual',
|
|
61
|
+
status: 'waiting',
|
|
62
|
+
my_seat: 1,
|
|
63
|
+
members,
|
|
64
|
+
cooldown_seconds: 0,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
expect(memberCount(ready)).toBe(10);
|
|
68
|
+
expect(isRoomReadyToStart(ready)).toBe(true);
|
|
69
|
+
expect(isRoomReadyToStart({ ...ready, cooldown_seconds: 5 })).toBe(false);
|
|
70
|
+
expect(isRoomReadyToStart({ ...ready, status: 'starting' })).toBe(false);
|
|
71
|
+
expect(isRoomReadyToStart({ ...ready, my_seat: 2 })).toBe(false);
|
|
72
|
+
expect(isRoomReadyToStart({ ...ready, members: members.slice(0, 9) })).toBe(false);
|
|
73
|
+
});
|
|
74
|
+
});
|
package/src/lib/room.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { ApiError } from './http-transport.js';
|
|
2
|
+
|
|
3
|
+
export interface RoomMember {
|
|
4
|
+
seat?: number;
|
|
5
|
+
agent_id?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
is_owner?: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface RoomSnapshot {
|
|
11
|
+
room_code?: string;
|
|
12
|
+
room_type?: string;
|
|
13
|
+
status?: string;
|
|
14
|
+
my_seat?: number;
|
|
15
|
+
seat?: number;
|
|
16
|
+
members?: RoomMember[];
|
|
17
|
+
cooldown_seconds?: number;
|
|
18
|
+
deadline?: number;
|
|
19
|
+
game_id?: string;
|
|
20
|
+
game_server_name?: string;
|
|
21
|
+
ws_url?: string;
|
|
22
|
+
[key: string]: any;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function unwrapData(value: any): any {
|
|
26
|
+
return value?.data ?? value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function queueStatus(value: any): string | undefined {
|
|
30
|
+
return unwrapData(value)?.status;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function queueMode(value: any): string | undefined {
|
|
34
|
+
const data = unwrapData(value);
|
|
35
|
+
const mode = data?.mode ?? data?.game?.mode ?? data?.allocation?.mode;
|
|
36
|
+
return typeof mode === 'string' ? mode : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function queueRoomCode(value: any): string | undefined {
|
|
40
|
+
const data = unwrapData(value);
|
|
41
|
+
return typeof data?.room_code === 'string' ? data.room_code : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isInRoomQueueStatus(value: any): boolean {
|
|
45
|
+
return queueStatus(value) === 'in_room' && !!queueRoomCode(value);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function isRoomAllocatedQueueStatus(value: any): boolean {
|
|
49
|
+
return queueStatus(value) === 'allocated' && queueMode(value) === 'room';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function hasRoomQueueContext(value: any): boolean {
|
|
53
|
+
return isInRoomQueueStatus(value) || isRoomAllocatedQueueStatus(value);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function normalizeRoomSnapshot(value: any): RoomSnapshot {
|
|
57
|
+
const data = unwrapData(value);
|
|
58
|
+
return data && typeof data === 'object' ? { ...data } : {};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function memberCount(snapshot: RoomSnapshot | null | undefined): number {
|
|
62
|
+
return Array.isArray(snapshot?.members) ? snapshot.members.length : 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function isCurrentAgentRoomOwner(snapshot: RoomSnapshot | null | undefined): boolean {
|
|
66
|
+
if (!snapshot) return false;
|
|
67
|
+
const mySeat = snapshot.my_seat ?? snapshot.seat;
|
|
68
|
+
return (snapshot.members ?? []).some((member) => {
|
|
69
|
+
if (!member?.is_owner) return false;
|
|
70
|
+
if (mySeat !== undefined && member.seat === mySeat) return true;
|
|
71
|
+
return false;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function isRoomReadyToStart(snapshot: RoomSnapshot | null | undefined): boolean {
|
|
76
|
+
if (!snapshot) return false;
|
|
77
|
+
return (
|
|
78
|
+
snapshot.room_type === 'casual'
|
|
79
|
+
&& snapshot.status === 'waiting'
|
|
80
|
+
&& isCurrentAgentRoomOwner(snapshot)
|
|
81
|
+
&& memberCount(snapshot) >= 10
|
|
82
|
+
&& ((snapshot.cooldown_seconds ?? 0) <= 0)
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function parseApiErrorBody(body: string): any | null {
|
|
87
|
+
try {
|
|
88
|
+
return JSON.parse(body);
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function apiErrorCode(err: unknown): string | undefined {
|
|
95
|
+
if (!(err instanceof ApiError)) return undefined;
|
|
96
|
+
const parsed = parseApiErrorBody(err.body);
|
|
97
|
+
return parsed?.error?.code ?? parsed?.code;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function apiErrorMessage(err: unknown): string {
|
|
101
|
+
if (err instanceof ApiError) {
|
|
102
|
+
const parsed = parseApiErrorBody(err.body);
|
|
103
|
+
const message = parsed?.error?.message ?? parsed?.message;
|
|
104
|
+
if (typeof message === 'string' && message.length > 0) return message;
|
|
105
|
+
return err.body;
|
|
106
|
+
}
|
|
107
|
+
if (err instanceof Error) return err.message;
|
|
108
|
+
return String(err);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function apiErrorCurrentStatus(err: unknown): string | undefined {
|
|
112
|
+
if (!(err instanceof ApiError)) return undefined;
|
|
113
|
+
const parsed = parseApiErrorBody(err.body);
|
|
114
|
+
const currentStatus = parsed?.error?.current_status
|
|
115
|
+
?? parsed?.current_status
|
|
116
|
+
?? parsed?.data?.current_status;
|
|
117
|
+
return typeof currentStatus === 'string' ? currentStatus : undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function isAlreadyInRoomError(err: unknown): boolean {
|
|
121
|
+
return apiErrorCode(err) === 'ALREADY_IN_ROOM'
|
|
122
|
+
|| (err instanceof ApiError && /ALREADY_IN_ROOM/.test(err.body));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function roomCodeFromAlreadyInRoomError(err: unknown): string | undefined {
|
|
126
|
+
if (!(err instanceof ApiError)) return undefined;
|
|
127
|
+
const parsed = parseApiErrorBody(err.body);
|
|
128
|
+
return parsed?.error?.room_code ?? parsed?.room_code ?? parsed?.data?.room_code;
|
|
129
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { ServerRegistry } from './server-registry.js';
|
|
3
|
+
|
|
4
|
+
describe('ServerRegistry lobby agent ws url', () => {
|
|
5
|
+
it('preserves a lobby path prefix', () => {
|
|
6
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
7
|
+
|
|
8
|
+
expect(registry.lobbyAgentWsUrl).toBe('ws://10.1.9.59:30900/claw/api/v1/agent/ws');
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('keeps the root lobby url behavior unchanged', () => {
|
|
12
|
+
const registry = new ServerRegistry({ lobbyUrl: 'https://lobby.example/' });
|
|
13
|
+
|
|
14
|
+
expect(registry.lobbyAgentWsUrl).toBe('wss://lobby.example/api/v1/agent/ws');
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe('ServerRegistry game server discovery', () => {
|
|
19
|
+
it('uses queue ws_url as the game server base', () => {
|
|
20
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
21
|
+
|
|
22
|
+
registry.updateFromQueueResponse({
|
|
23
|
+
data: {
|
|
24
|
+
status: 'allocated',
|
|
25
|
+
ws_url: 'ws://10.1.9.59:30433/gs/clawarena-gameserver-l2fzm-h5n5r',
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
expect(registry.gameServerUrl).toBe('http://10.1.9.59:30433/gs/clawarena-gameserver-l2fzm-h5n5r');
|
|
30
|
+
expect(registry.wsUrl).toBe('ws://10.1.9.59:30433/gs/clawarena-gameserver-l2fzm-h5n5r/api/v1/game/stream');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('strips stream suffixes when persisting a ws_url', () => {
|
|
34
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
35
|
+
|
|
36
|
+
registry.updateFromQueueResponse({
|
|
37
|
+
data: {
|
|
38
|
+
status: 'allocated',
|
|
39
|
+
ws_url: 'ws://10.1.9.59:30433/gs/room-gs/game/stream',
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
expect(registry.gameServerUrl).toBe('http://10.1.9.59:30433/gs/room-gs');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('normalizes manually supplied game server ws urls', () => {
|
|
47
|
+
const registry = new ServerRegistry({ lobbyUrl: 'http://10.1.9.59:30900/claw' });
|
|
48
|
+
|
|
49
|
+
registry.setGameServerUrl('ws://10.1.9.59:30433/gs/room-gs/api/v1/game/stream');
|
|
50
|
+
|
|
51
|
+
expect(registry.gameServerUrl).toBe('http://10.1.9.59:30433/gs/room-gs');
|
|
52
|
+
expect(registry.wsUrl).toBe('ws://10.1.9.59:30433/gs/room-gs/api/v1/game/stream');
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -7,6 +7,15 @@ export interface ServerAddresses {
|
|
|
7
7
|
wsUrl: string | null;
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
function normalizeGameServerUrl(url: string): string {
|
|
11
|
+
return url
|
|
12
|
+
.replace(/^wss:/, 'https:')
|
|
13
|
+
.replace(/^ws:/, 'http:')
|
|
14
|
+
.replace(/\/api\/v1\/game\/stream\/?$/, '')
|
|
15
|
+
.replace(/\/game\/stream\/?$/, '')
|
|
16
|
+
.replace(/\/$/, '');
|
|
17
|
+
}
|
|
18
|
+
|
|
10
19
|
export class ServerRegistry {
|
|
11
20
|
private lobbyUrl: string;
|
|
12
21
|
private _gameServerUrl: string | null;
|
|
@@ -53,6 +62,13 @@ export class ServerRegistry {
|
|
|
53
62
|
return this._gameServerUrl;
|
|
54
63
|
}
|
|
55
64
|
|
|
65
|
+
get lobbyAgentWsUrl(): string {
|
|
66
|
+
const u = new URL(this.lobbyUrl);
|
|
67
|
+
const protocol = u.protocol === 'https:' || u.protocol === 'wss:' ? 'wss:' : 'ws:';
|
|
68
|
+
const basePath = u.pathname && u.pathname !== '/' ? u.pathname.replace(/\/$/, '') : '';
|
|
69
|
+
return `${protocol}//${u.host}${basePath}/api/v1/agent/ws`;
|
|
70
|
+
}
|
|
71
|
+
|
|
56
72
|
/**
|
|
57
73
|
* Determine the correct base URL for a given API path.
|
|
58
74
|
*
|
|
@@ -98,7 +114,7 @@ export class ServerRegistry {
|
|
|
98
114
|
|
|
99
115
|
const wsUrl = qs.ws_url;
|
|
100
116
|
if (wsUrl && typeof wsUrl === 'string') {
|
|
101
|
-
const httpUrl = wsUrl
|
|
117
|
+
const httpUrl = normalizeGameServerUrl(wsUrl);
|
|
102
118
|
if (this._gatewayWsUrl !== httpUrl) {
|
|
103
119
|
this._gatewayWsUrl = httpUrl;
|
|
104
120
|
this._gameServerUrl = httpUrl;
|
|
@@ -124,7 +140,24 @@ export class ServerRegistry {
|
|
|
124
140
|
|
|
125
141
|
/** Manually set the game server URL. */
|
|
126
142
|
setGameServerUrl(url: string): void {
|
|
127
|
-
|
|
143
|
+
const normalized = normalizeGameServerUrl(url);
|
|
144
|
+
this._gameServerUrl = normalized;
|
|
145
|
+
try {
|
|
146
|
+
const parsed = new URL(normalized);
|
|
147
|
+
this._gatewayWsUrl = parsed.pathname && parsed.pathname !== '/' ? normalized : null;
|
|
148
|
+
} catch {
|
|
149
|
+
this._gatewayWsUrl = null;
|
|
150
|
+
}
|
|
151
|
+
this._urlPreconfigured = true;
|
|
152
|
+
this.persistGameServerUrl();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Set the game server URL via the public lobby gateway route. */
|
|
156
|
+
setGatewayGameServerName(gameServerName: string): void {
|
|
157
|
+
const cleanName = gameServerName.replace(/^\/+|\/+$/g, '');
|
|
158
|
+
const route = `${this.lobbyUrl}/gs/${encodeURIComponent(cleanName)}`;
|
|
159
|
+
this._gatewayWsUrl = route;
|
|
160
|
+
this._gameServerUrl = route;
|
|
128
161
|
this._urlPreconfigured = true;
|
|
129
162
|
this.persistGameServerUrl();
|
|
130
163
|
}
|