@chrischall/warapp-mcp 0.0.0 → 0.1.0
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/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +199 -8
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +159 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +551 -0
- package/dist/analysis/opponents.js +1245 -0
- package/dist/analysis/outlook.js +633 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1218 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +927 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2922 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +577 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1109 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +117959 -36172
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +192 -0
- package/dist/client.js +361 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/live.js +278 -0
- package/dist/map-stats.js +152 -0
- package/dist/map-store.js +204 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +180 -0
- package/dist/normalize.js +411 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +138 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +229 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +677 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +531 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +215 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +269 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2168 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +146 -0
- package/dist/tools/chat.js +483 -0
- package/dist/tools/check-plan.js +688 -0
- package/dist/tools/commander-check.js +102 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/game.js +126 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +142 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-stats.js +117 -0
- package/dist/tools/map.js +133 -0
- package/dist/tools/my-games.js +123 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +151 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/picks.js +292 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +385 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +200 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender.js +240 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +182 -0
- package/dist/tools/turn.js +2761 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +275 -0
- package/dist/tools/write-kit.js +158 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +452 -0
- package/dist/version.js +4 -0
- package/manifest.json +174 -4
- package/mint.yaml +101 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +969 -21
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// The persistent map store: GameFeed maps by map id, so a known map is not downloaded again after a
|
|
2
|
+
// restart and the cached boards (`<dataDir>/boards/`) can be replayed offline (src/replay.ts).
|
|
3
|
+
//
|
|
4
|
+
// - `<dataDir>/maps/<mapId>.json`: `{ version: 1, storedAt, map }`, the map exactly as `MapCache` holds
|
|
5
|
+
// it (normalized: territories with adjacency, bonuses with their BASE values — overrides are per game
|
|
6
|
+
// and applied by `mapOf`). Maps are public data. At most MAX_STORED_MAPS files; the least recently
|
|
7
|
+
// used (file mtime, touched on every read and on every memory hit in `MapCache`) is evicted on a
|
|
8
|
+
// write.
|
|
9
|
+
// A map maker can publish an edit under the same map id and GameFeed sends no map version, so a
|
|
10
|
+
// stored map is trusted for MAX_MAP_AGE_MS after `storedAt` (the download time, epoch ms) and then
|
|
11
|
+
// reads as absent: the game is fetched with its map again and the fresh copy replaces it (sooner when
|
|
12
|
+
// a feed standing names land the map lacks: src/client.ts `getGame`). A file with
|
|
13
|
+
// no readable `storedAt` is stale. Offline replay (src/replay.ts) reads a map whatever its age.
|
|
14
|
+
// - `<dataDir>/maps/games.json`: `{ version: 1, games: [[gameId, mapId], …] }`, newest last, at most
|
|
15
|
+
// MAX_GAME_INDEX entries — which map a game is on, so a game seen before a restart is still asked
|
|
16
|
+
// `GetMap=false`.
|
|
17
|
+
//
|
|
18
|
+
// Files are 0600 in a 0700 folder and written atomically; every read is loose (a bad file is ignored,
|
|
19
|
+
// and replaced by the next write) and nothing here throws. Another process sharing the data directory
|
|
20
|
+
// may lose an index entry to a concurrent write, which only costs one map download.
|
|
21
|
+
import { randomBytes } from 'node:crypto';
|
|
22
|
+
import { mkdir, readdir, readFile, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { withPathLock } from './path-lock.js';
|
|
25
|
+
/** Maps kept on disk; the least recently used goes first. */
|
|
26
|
+
export const MAX_STORED_MAPS = 40;
|
|
27
|
+
/** How long a stored map is trusted before it is downloaded again (30 days). */
|
|
28
|
+
export const MAX_MAP_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
29
|
+
/** Game → map entries kept in the index; the oldest goes first. */
|
|
30
|
+
export const MAX_GAME_INDEX = 500;
|
|
31
|
+
const VERSION = 1;
|
|
32
|
+
const MAP_FILE = /^\d+\.json$/;
|
|
33
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
34
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
35
|
+
const isIntArray = (v) => Array.isArray(v) && v.every(isInt);
|
|
36
|
+
export const mapsDir = (dir) => join(dir, 'maps');
|
|
37
|
+
export const mapStorePath = (dir, mapId) => join(mapsDir(dir), `${mapId}.json`);
|
|
38
|
+
const indexPath = (dir) => join(mapsDir(dir), 'games.json');
|
|
39
|
+
/** Write `body` as JSON at `path` atomically (0600; folder 0700). */
|
|
40
|
+
export async function writeJsonAtomic(path, folder, body) {
|
|
41
|
+
await mkdir(folder, { recursive: true, mode: 0o700 });
|
|
42
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
43
|
+
try {
|
|
44
|
+
await writeFile(tmp, JSON.stringify(body), { mode: 0o600 });
|
|
45
|
+
await rename(tmp, path);
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
await unlink(tmp).catch(() => { });
|
|
49
|
+
throw e;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function territoryOf(t) {
|
|
53
|
+
if (!isRec(t) || !isInt(t.id) || typeof t.name !== 'string' || !isIntArray(t.connectedTo))
|
|
54
|
+
return undefined;
|
|
55
|
+
const out = { id: t.id, name: t.name, connectedTo: t.connectedTo };
|
|
56
|
+
if (isRec(t.coords) && typeof t.coords.x === 'number' && typeof t.coords.y === 'number')
|
|
57
|
+
out.coords = { x: t.coords.x, y: t.coords.y };
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
function bonusOf(b) {
|
|
61
|
+
if (!isRec(b) || !isInt(b.id) || typeof b.name !== 'string' || !isInt(b.value))
|
|
62
|
+
return undefined;
|
|
63
|
+
if (!isIntArray(b.territoryIds) || !isIntArray(b.bonusIds))
|
|
64
|
+
return undefined;
|
|
65
|
+
const out = { id: b.id, name: b.name, value: b.value, territoryIds: b.territoryIds, bonusIds: b.bonusIds };
|
|
66
|
+
if (isIntArray(b.unknownIds) && b.unknownIds.length)
|
|
67
|
+
out.unknownIds = b.unknownIds;
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function modeOf(d) {
|
|
71
|
+
if (!isRec(d) || !isInt(d.id) || typeof d.name !== 'string')
|
|
72
|
+
return undefined;
|
|
73
|
+
const out = { id: d.id, name: d.name };
|
|
74
|
+
if (typeof d.type === 'string')
|
|
75
|
+
out.type = d.type;
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
/** Every element of `xs` read by `f`, or `undefined` when any is unreadable. */
|
|
79
|
+
function all(xs, f) {
|
|
80
|
+
if (!Array.isArray(xs))
|
|
81
|
+
return undefined;
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const x of xs) {
|
|
84
|
+
const v = f(x);
|
|
85
|
+
if (v === undefined)
|
|
86
|
+
return undefined;
|
|
87
|
+
out.push(v);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
/** A stored map, read strictly enough that the planner can trust it; `undefined` when anything is off or it is too old. */
|
|
92
|
+
function storedMapOf(raw, mapId, now, maxAgeMs) {
|
|
93
|
+
if (!isRec(raw) || raw.version !== VERSION || !isRec(raw.map))
|
|
94
|
+
return undefined;
|
|
95
|
+
if (maxAgeMs !== Number.POSITIVE_INFINITY) {
|
|
96
|
+
const at = raw.storedAt;
|
|
97
|
+
if (typeof at !== 'number' || !Number.isFinite(at) || now - at > maxAgeMs)
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
const m = raw.map;
|
|
101
|
+
if (m.id !== mapId || typeof m.name !== 'string')
|
|
102
|
+
return undefined;
|
|
103
|
+
const territories = all(m.territories, territoryOf);
|
|
104
|
+
const bonuses = all(m.bonuses, bonusOf);
|
|
105
|
+
const distributionModes = all(m.distributionModes, modeOf);
|
|
106
|
+
if (!territories || !bonuses || !distributionModes)
|
|
107
|
+
return undefined;
|
|
108
|
+
return { id: mapId, name: m.name, territories, bonuses, distributionModes };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The map stored for `mapId`, marking it recently used; `undefined` when absent, unusable or older
|
|
112
|
+
* than `maxAgeMs` ({@link MAX_MAP_AGE_MS} by default). Never throws.
|
|
113
|
+
*/
|
|
114
|
+
export async function readStoredMap(dir, mapId, opts = {}) {
|
|
115
|
+
const path = mapStorePath(dir, mapId);
|
|
116
|
+
try {
|
|
117
|
+
const map = storedMapOf(JSON.parse(await readFile(path, 'utf8')), mapId, opts.now ?? Date.now(), opts.maxAgeMs ?? MAX_MAP_AGE_MS);
|
|
118
|
+
if (map) {
|
|
119
|
+
const now = new Date();
|
|
120
|
+
await utimes(path, now, now).catch(() => { });
|
|
121
|
+
}
|
|
122
|
+
return map;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Delete the least recently used maps beyond {@link MAX_STORED_MAPS}, keeping `keep`. Best effort. */
|
|
129
|
+
async function evictMaps(dir, keep) {
|
|
130
|
+
const folder = mapsDir(dir);
|
|
131
|
+
const files = [];
|
|
132
|
+
for (const name of await readdir(folder)) {
|
|
133
|
+
if (!MAP_FILE.test(name))
|
|
134
|
+
continue;
|
|
135
|
+
try {
|
|
136
|
+
files.push({ name, at: (await stat(join(folder, name))).mtimeMs });
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// Gone already.
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const excess = files.length - MAX_STORED_MAPS;
|
|
143
|
+
if (excess <= 0)
|
|
144
|
+
return;
|
|
145
|
+
const victims = files.filter((f) => f.name !== `${keep}.json`).sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
|
|
146
|
+
for (const f of victims.slice(0, excess))
|
|
147
|
+
await unlink(join(folder, f.name)).catch(() => { });
|
|
148
|
+
}
|
|
149
|
+
/** Store `map` (its base values) stamped `storedAt`, then evict beyond the cap. `true` when written; never throws. */
|
|
150
|
+
export async function writeStoredMap(dir, map, storedAt = Date.now()) {
|
|
151
|
+
try {
|
|
152
|
+
await writeJsonAtomic(mapStorePath(dir, map.id), mapsDir(dir), { version: VERSION, storedAt, map });
|
|
153
|
+
await evictMaps(dir, map.id).catch(() => { });
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Mark the stored copy of `map` recently used, storing it when its file has gone. A map served from
|
|
162
|
+
* memory is otherwise never read from disk, so the map of a game played all session long would age
|
|
163
|
+
* out of the store and leave its replay without a map. Never throws.
|
|
164
|
+
*/
|
|
165
|
+
export async function touchStoredMap(dir, map) {
|
|
166
|
+
const now = new Date();
|
|
167
|
+
try {
|
|
168
|
+
await utimes(mapStorePath(dir, map.id), now, now);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
await writeStoredMap(dir, map);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** The index entries, loosely: unusable entries are dropped. */
|
|
175
|
+
async function readIndex(dir) {
|
|
176
|
+
try {
|
|
177
|
+
const raw = JSON.parse(await readFile(indexPath(dir), 'utf8'));
|
|
178
|
+
if (!isRec(raw) || raw.version !== VERSION || !Array.isArray(raw.games))
|
|
179
|
+
return [];
|
|
180
|
+
return raw.games.filter((e) => Array.isArray(e) && e.length === 2 && isInt(e[0]) && isInt(e[1]));
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return [];
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** The map id stored for `gameId`; `undefined` when not known. Never throws. */
|
|
187
|
+
export async function readGameMapId(dir, gameId) {
|
|
188
|
+
const hit = (await readIndex(dir)).reverse().find(([g]) => g === gameId);
|
|
189
|
+
return hit?.[1];
|
|
190
|
+
}
|
|
191
|
+
/** Remember that `gameId` is on `mapId` (newest kept, {@link MAX_GAME_INDEX} at most). `true` when written; never throws. */
|
|
192
|
+
export async function rememberGameMap(dir, gameId, mapId) {
|
|
193
|
+
try {
|
|
194
|
+
return await withPathLock(indexPath(dir), async () => {
|
|
195
|
+
const games = (await readIndex(dir)).filter(([g]) => g !== gameId);
|
|
196
|
+
games.push([gameId, mapId]);
|
|
197
|
+
await writeJsonAtomic(indexPath(dir), mapsDir(dir), { version: VERSION, games: games.slice(-MAX_GAME_INDEX) });
|
|
198
|
+
return true;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Who moved first, kept between turns (#127). Under a cyclic move order (`Cycle`, `NoLuckCycle`)
|
|
2
|
+
// the order reverses every turn (the client's own help text: "ABCD becomes DCBA the next turn"),
|
|
3
|
+
// so in a two-player game one turn whose first mover is known gives every other turn's. The
|
|
4
|
+
// first mover of a turn is learnt from `first_mover` given to warapp_plan_turn (the user saw it)
|
|
5
|
+
// or from the award of picks (src/analysis/award.ts: the wiki's rule, not verified live), and is
|
|
6
|
+
// kept at `<dataDir>/move-order/<gameId>.json` so later turns default to it, alternated.
|
|
7
|
+
//
|
|
8
|
+
// The game history is not read for it: war.app does not say who moves first under a plain cycle
|
|
9
|
+
// ("you must deduce it by observing the sequence that orders happen"), and whether GameFeed's
|
|
10
|
+
// `GetHistory` carries a game in progress's orders, in the order they ran, is UNVERIFIED
|
|
11
|
+
// (docs/WARAPP-API.md "Move order"). The first mover kept is the cycle's: an Order Priority or
|
|
12
|
+
// Order Delay card played on a turn changes who moves first on that turn only.
|
|
13
|
+
//
|
|
14
|
+
// One record per game: the newest turn known, with where it came from. A first mover given
|
|
15
|
+
// explicitly outranks one read from the award. Turn number and the two words only: no names.
|
|
16
|
+
// Best effort and never throws; a game's file not written for 60 days is deleted on the first
|
|
17
|
+
// write of a process.
|
|
18
|
+
import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
/** Where a game's first mover is kept. */
|
|
21
|
+
export const firstMoverPath = (dir, gameId) => join(dir, 'move-order', `${gameId}.json`);
|
|
22
|
+
/** A game's file not written for this long is deleted (finished or abandoned games). */
|
|
23
|
+
export const FIRST_MOVER_MAX_AGE_MS = 60 * 86_400_000;
|
|
24
|
+
const FILE = /^\d+\.json$/;
|
|
25
|
+
const pruned = new Set();
|
|
26
|
+
const other = (m) => (m === 'me' ? 'opponent' : 'me');
|
|
27
|
+
const isTurn = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
|
|
28
|
+
const isMover = (v) => v === 'me' || v === 'opponent';
|
|
29
|
+
const isSource = (v) => v === 'explicit' || v === 'award';
|
|
30
|
+
/** The first mover on `turn`, from one known turn: the same every second turn, the other in between. */
|
|
31
|
+
export function projectFirstMover(seen, turn) {
|
|
32
|
+
return Math.abs(turn - seen.turn) % 2 === 0 ? seen.firstMover : other(seen.firstMover);
|
|
33
|
+
}
|
|
34
|
+
const RANK = { award: 0, explicit: 1 };
|
|
35
|
+
const said = (m, turn) => `${m === 'me' ? 'you move' : 'the opponent moves'} first on turn ${turn}`;
|
|
36
|
+
/**
|
|
37
|
+
* Who moves first on `turn` and how it is known, with the record to keep (absent when nothing new
|
|
38
|
+
* is known). An explicit first mover wins; then a remembered explicit turn, alternated; then the
|
|
39
|
+
* award; then a remembered award turn. Outside a two-player cyclic order (or without a turn) only
|
|
40
|
+
* an explicit first mover counts, for this turn alone, and nothing is kept. A source that
|
|
41
|
+
* disagrees with the one used is a warning. Pure.
|
|
42
|
+
*/
|
|
43
|
+
export function resolveFirstMover(input) {
|
|
44
|
+
const { turn, explicit, award } = input;
|
|
45
|
+
if (turn === null || !input.cyclicDuel)
|
|
46
|
+
return { resolved: explicit ? { firstMover: explicit, source: 'explicit' } : null, warnings: [] };
|
|
47
|
+
const candidates = [];
|
|
48
|
+
const kept = input.remembered;
|
|
49
|
+
const fromKept = () => kept && {
|
|
50
|
+
firstMover: projectFirstMover(kept, turn),
|
|
51
|
+
label: kept.source === 'explicit' ? `the first_mover given on turn ${kept.turn}` : `the award of picks (kept on turn ${kept.turn})`,
|
|
52
|
+
resolved: { firstMover: projectFirstMover(kept, turn), source: 'remembered', from: { turn: kept.turn, source: kept.source } },
|
|
53
|
+
};
|
|
54
|
+
if (explicit)
|
|
55
|
+
candidates.push({ firstMover: explicit, label: 'first_mover', resolved: { firstMover: explicit, source: 'explicit' }, record: { turn, firstMover: explicit, source: 'explicit' } });
|
|
56
|
+
if (kept?.source === 'explicit')
|
|
57
|
+
candidates.push(fromKept());
|
|
58
|
+
if (award)
|
|
59
|
+
candidates.push({ firstMover: award, label: 'the award of picks', resolved: { firstMover: award, source: 'award' }, record: { turn, firstMover: award, source: 'award' } });
|
|
60
|
+
if (kept?.source === 'award')
|
|
61
|
+
candidates.push(fromKept());
|
|
62
|
+
const used = candidates[0];
|
|
63
|
+
if (!used)
|
|
64
|
+
return { resolved: null, warnings: [] };
|
|
65
|
+
const warnings = [];
|
|
66
|
+
const against = candidates.slice(1).filter((c) => c.firstMover !== used.firstMover);
|
|
67
|
+
if (against.length)
|
|
68
|
+
warnings.push(`Move order: the plan takes it that ${said(used.firstMover, turn)} (from ${used.label}), but ` +
|
|
69
|
+
against.map((c) => `${c.label} says ${said(c.firstMover, turn)}`).join(', and ') +
|
|
70
|
+
'. Give first_mover as the cycle has it, without an Order Priority or Order Delay card played this turn.');
|
|
71
|
+
// Keep what is newly known, unless a better-ranked turn is kept already.
|
|
72
|
+
const record = used.record && (!kept || RANK[used.record.source] >= RANK[kept.source]) && !same(used.record, kept) ? used.record : undefined;
|
|
73
|
+
return { resolved: used.resolved, ...(record ? { record } : {}), warnings };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* #215 review: a first mover the user gave (`first_mover`, now or on a remembered turn, alternated)
|
|
77
|
+
* is verified; one read from the award of picks — the wiki's rule, not verified live — is not, and
|
|
78
|
+
* the planner's hold sizing treats it as unknown (`movesFirstUnverified`).
|
|
79
|
+
*/
|
|
80
|
+
export function verifiedFirstMover(resolved) {
|
|
81
|
+
return resolved.source === 'explicit' || (resolved.source === 'remembered' && resolved.from?.source === 'explicit');
|
|
82
|
+
}
|
|
83
|
+
const same = (a, b) => b !== undefined && a.turn === b.turn && a.firstMover === b.firstMover && a.source === b.source;
|
|
84
|
+
/** The first mover kept for `gameId` when it is `playerId`'s; `undefined` when absent or unusable. Never throws. */
|
|
85
|
+
export async function readFirstMover(dir, gameId, playerId) {
|
|
86
|
+
try {
|
|
87
|
+
const c = JSON.parse(await readFile(firstMoverPath(dir, gameId), 'utf8'));
|
|
88
|
+
if (typeof c !== 'object' || c === null || Array.isArray(c))
|
|
89
|
+
return undefined;
|
|
90
|
+
const r = c;
|
|
91
|
+
if (r.gameId !== gameId || r.playerId !== playerId)
|
|
92
|
+
return undefined;
|
|
93
|
+
if (!isTurn(r.turn) || !isMover(r.firstMover) || !isSource(r.source))
|
|
94
|
+
return undefined;
|
|
95
|
+
return { turn: r.turn, firstMover: r.firstMover, source: r.source };
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async function prune(dir) {
|
|
102
|
+
const base = join(dir, 'move-order');
|
|
103
|
+
if (pruned.has(base))
|
|
104
|
+
return;
|
|
105
|
+
pruned.add(base);
|
|
106
|
+
const cutoff = Date.now() - FIRST_MOVER_MAX_AGE_MS;
|
|
107
|
+
try {
|
|
108
|
+
for (const name of await readdir(base)) {
|
|
109
|
+
if (!FILE.test(name))
|
|
110
|
+
continue;
|
|
111
|
+
const file = join(base, name);
|
|
112
|
+
try {
|
|
113
|
+
if ((await stat(file)).mtimeMs < cutoff)
|
|
114
|
+
await unlink(file);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// Gone already, or unreadable: leave it.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// No directory yet.
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Keep `seen` as `playerId`'s first mover for `gameId`, replacing what was kept. Never throws. */
|
|
126
|
+
export async function writeFirstMover(dir, gameId, playerId, seen) {
|
|
127
|
+
if (!isTurn(seen.turn) || !isMover(seen.firstMover) || !isSource(seen.source))
|
|
128
|
+
return false;
|
|
129
|
+
try {
|
|
130
|
+
const path = firstMoverPath(dir, gameId);
|
|
131
|
+
await mkdir(join(dir, 'move-order'), { recursive: true, mode: 0o700 });
|
|
132
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
133
|
+
await writeFile(tmp, JSON.stringify({ gameId, playerId, turn: seen.turn, firstMover: seen.firstMover, source: seen.source }), { mode: 0o600 });
|
|
134
|
+
await rename(tmp, path);
|
|
135
|
+
await prune(dir);
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
package/dist/my-games.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// My games: a GetMyGames reply, decoded by the client bundle's own readers,
|
|
2
|
+
// turned into a per-game summary that says which games are waiting on me.
|
|
3
|
+
//
|
|
4
|
+
// Field names in the bundle are minified and change between releases, so
|
|
5
|
+
// nothing here keys on them. Classes are found by their stable registered type
|
|
6
|
+
// name (`$type`) and fields by read order, as observed through the bridge
|
|
7
|
+
// (docs/PLAN-SCOUT.md, GetMyGames). Each record must have exactly its known
|
|
8
|
+
// field count and the positions used are checked for their type, so a field
|
|
9
|
+
// inserted, dropped or reordered is an error rather than a silently wrong list.
|
|
10
|
+
import { McpToolError } from '@chrischall/mcp-utils';
|
|
11
|
+
import { playerStateName } from './player-states.js';
|
|
12
|
+
import { fields, isObj } from './protocol/decoded.js';
|
|
13
|
+
import { carriesTeam } from './teams.js';
|
|
14
|
+
export const MY_GAMES_RETURN = 'warlight.shared.MyGamesReturn';
|
|
15
|
+
export const GAME_INFO = 'warlight.shared.GameInfo';
|
|
16
|
+
export const GAME_INFO_PLAYER = 'warlight.shared.GameInfoPlayer';
|
|
17
|
+
/** GameState. */
|
|
18
|
+
const GAME_STATE_NAMES = {
|
|
19
|
+
2: 'WaitingForPlayers',
|
|
20
|
+
3: 'Playing',
|
|
21
|
+
4: 'Finished',
|
|
22
|
+
5: 'DistributingTerritories',
|
|
23
|
+
};
|
|
24
|
+
const GAME_WAITING = 2;
|
|
25
|
+
const GAME_PLAYING = 3;
|
|
26
|
+
const GAME_DISTRIBUTING = 5;
|
|
27
|
+
const GAME_FINISHED = 4;
|
|
28
|
+
const PLAYER_PLAYING = 2;
|
|
29
|
+
/** GameInfo field positions in read order, and its whole field count (src/open-games.ts reads the same record). */
|
|
30
|
+
const GI = { gameId: 7, name: 13, lastTurn: 14, players: 16, state: 22 };
|
|
31
|
+
export const GAME_INFO_FIELDS = 27;
|
|
32
|
+
/** GameInfoPlayer field positions in read order, and its whole field count. */
|
|
33
|
+
const GP = { committed: 2, name: 5, id: 6, state: 7, team: 8 };
|
|
34
|
+
export const GAME_INFO_PLAYER_FIELDS = 10;
|
|
35
|
+
/** The GetMyGames reply arrived in a shape this server does not understand. */
|
|
36
|
+
export class MyGamesFormatError extends McpToolError {
|
|
37
|
+
constructor(detail) {
|
|
38
|
+
super(`war.app's game list arrived in an unexpected shape (${detail}).`, {
|
|
39
|
+
kind: 'unknown',
|
|
40
|
+
hint: 'The war.app client may have changed. warapp_get_game still reads a game by id.',
|
|
41
|
+
});
|
|
42
|
+
this.name = 'MyGamesFormatError';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
46
|
+
const isStr = (v) => v === null || typeof v === 'string';
|
|
47
|
+
function playerOf(p) {
|
|
48
|
+
if (!isObj(p) || p.$type !== GAME_INFO_PLAYER)
|
|
49
|
+
throw new MyGamesFormatError('a player is not a GameInfoPlayer');
|
|
50
|
+
const f = fields(p);
|
|
51
|
+
if (f.length !== GAME_INFO_PLAYER_FIELDS) {
|
|
52
|
+
throw new MyGamesFormatError(`a GameInfoPlayer has ${f.length} fields, not ${GAME_INFO_PLAYER_FIELDS}`);
|
|
53
|
+
}
|
|
54
|
+
const committed = f[GP.committed];
|
|
55
|
+
const name = f[GP.name];
|
|
56
|
+
const id = f[GP.id];
|
|
57
|
+
const state = f[GP.state];
|
|
58
|
+
if (typeof committed !== 'boolean' || !isStr(name) || !isInt(id) || !isInt(state)) {
|
|
59
|
+
throw new MyGamesFormatError('a GameInfoPlayer lacks its fields');
|
|
60
|
+
}
|
|
61
|
+
// The team is read loosely: it is a fallback for GameFeed's (C1), so a value that is not a number is left out
|
|
62
|
+
// rather than refusing the whole list.
|
|
63
|
+
const team = f[GP.team];
|
|
64
|
+
return { id, name: name ?? '', stateCode: state, committed, ...(isInt(team) && carriesTeam(team) ? { team } : {}) };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The teams GetMyGames gives a game's players, by in-game id (C1, docs/PLAN-TEAMS.md): what a tool falls back on
|
|
68
|
+
* when GameFeed sends no team (V1). Empty when the game is not in the list or no player carries a team.
|
|
69
|
+
*/
|
|
70
|
+
export function myGamesTeams(games, gameId) {
|
|
71
|
+
const out = new Map();
|
|
72
|
+
for (const p of games.find((g) => g.id === gameId)?.players ?? [])
|
|
73
|
+
if (p.team !== undefined)
|
|
74
|
+
out.set(p.id, p.team);
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
function gameOf(g) {
|
|
78
|
+
if (!isObj(g) || g.$type !== GAME_INFO)
|
|
79
|
+
throw new MyGamesFormatError('a game is not a GameInfo');
|
|
80
|
+
const f = fields(g);
|
|
81
|
+
if (f.length !== GAME_INFO_FIELDS)
|
|
82
|
+
throw new MyGamesFormatError(`a GameInfo has ${f.length} fields, not ${GAME_INFO_FIELDS}`);
|
|
83
|
+
const id = f[GI.gameId];
|
|
84
|
+
const name = f[GI.name];
|
|
85
|
+
const lastTurn = f[GI.lastTurn];
|
|
86
|
+
const players = f[GI.players];
|
|
87
|
+
const state = f[GI.state];
|
|
88
|
+
if (!isInt(id) ||
|
|
89
|
+
!isStr(name) ||
|
|
90
|
+
!isInt(lastTurn) ||
|
|
91
|
+
!(players === null || Array.isArray(players)) ||
|
|
92
|
+
!isInt(state)) {
|
|
93
|
+
throw new MyGamesFormatError('a GameInfo lacks its fields');
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
id,
|
|
97
|
+
name: name ?? '',
|
|
98
|
+
lastTurn,
|
|
99
|
+
stateCode: state,
|
|
100
|
+
players: (players ?? []).filter((p) => p !== null).map(playerOf),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** Read a GetMyGames result (the body positioned at the result-present flag). */
|
|
104
|
+
export function readMyGames(bundle, body) {
|
|
105
|
+
if (!body.bool())
|
|
106
|
+
return [];
|
|
107
|
+
const ret = bundle.readClass(MY_GAMES_RETURN, body);
|
|
108
|
+
if (!isObj(ret))
|
|
109
|
+
throw new MyGamesFormatError('no MyGamesReturn');
|
|
110
|
+
const list = fields(ret)[0];
|
|
111
|
+
if (list === null)
|
|
112
|
+
return [];
|
|
113
|
+
if (!Array.isArray(list))
|
|
114
|
+
throw new MyGamesFormatError('no game list');
|
|
115
|
+
return list.filter((g) => g !== null).map(gameOf);
|
|
116
|
+
}
|
|
117
|
+
/** Whether the game has finished. */
|
|
118
|
+
export const isFinished = (g) => g.stateCode === GAME_FINISHED;
|
|
119
|
+
/**
|
|
120
|
+
* Name the codes and decide which games wait on me (`myInGameId`): the game is
|
|
121
|
+
* being played or distributing territories, my player is Playing, and I have
|
|
122
|
+
* not committed. Games waiting on me come first; otherwise war.app's order.
|
|
123
|
+
*/
|
|
124
|
+
export function summarizeMyGames(games, myInGameId) {
|
|
125
|
+
const out = games.map((g) => {
|
|
126
|
+
const me = g.players.find((p) => p.id === myInGameId);
|
|
127
|
+
const active = g.stateCode === GAME_PLAYING || g.stateCode === GAME_DISTRIBUTING;
|
|
128
|
+
return {
|
|
129
|
+
id: g.id,
|
|
130
|
+
name: g.name,
|
|
131
|
+
state: GAME_STATE_NAMES[g.stateCode] ?? String(g.stateCode),
|
|
132
|
+
turn: g.lastTurn < 0 ? null : g.lastTurn + 1,
|
|
133
|
+
waitingOnYou: active && me !== undefined && me.stateCode === PLAYER_PLAYING && !me.committed,
|
|
134
|
+
players: g.players.map((p) => ({
|
|
135
|
+
name: p.name,
|
|
136
|
+
state: playerStateName(p.stateCode),
|
|
137
|
+
committed: p.committed,
|
|
138
|
+
})),
|
|
139
|
+
};
|
|
140
|
+
});
|
|
141
|
+
return [...out.filter((g) => g.waitingOnYou), ...out.filter((g) => !g.waitingOnYou)];
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Games I can still take a turn in (`myInGameId`): being played or distributing
|
|
145
|
+
* territories, with my player Playing — committed or not. war.app's order.
|
|
146
|
+
*/
|
|
147
|
+
export function activeGameIds(games, myInGameId) {
|
|
148
|
+
return games
|
|
149
|
+
.filter((g) => g.stateCode === GAME_PLAYING || g.stateCode === GAME_DISTRIBUTING)
|
|
150
|
+
.filter((g) => g.players.some((p) => p.id === myInGameId && p.stateCode === PLAYER_PLAYING))
|
|
151
|
+
.map((g) => g.id);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Games whose chat is live (#256): lobbies, games being picked and games being played — every
|
|
155
|
+
* game in the list but a finished one, whatever my seat's state. Ascending id order, so a cursor
|
|
156
|
+
* (the last id read) resumes the list even when games join or leave it between calls.
|
|
157
|
+
*/
|
|
158
|
+
export function chatGameIds(games) {
|
|
159
|
+
return games
|
|
160
|
+
.filter((g) => g.stateCode === GAME_WAITING || g.stateCode === GAME_PLAYING || g.stateCode === GAME_DISTRIBUTING)
|
|
161
|
+
.map((g) => g.id)
|
|
162
|
+
.sort((a, b) => a - b);
|
|
163
|
+
}
|
|
164
|
+
/** The longest line `view: 'brief'` answers (the context-groups contract). */
|
|
165
|
+
const BRIEF_MAX = 120;
|
|
166
|
+
/**
|
|
167
|
+
* One brief line, `name — <turn N | state> — waiting on you | waiting on others`,
|
|
168
|
+
* at most {@link BRIEF_MAX} characters: the name (another player's text) is
|
|
169
|
+
* flattened to one line and shortened first; a name starting `-- ` or `\` gets
|
|
170
|
+
* one leading `\` so it can never read as a note line.
|
|
171
|
+
*/
|
|
172
|
+
export function briefGameLine(game) {
|
|
173
|
+
const where = game.state === 'Playing' && game.turn !== null ? `turn ${game.turn}` : game.state;
|
|
174
|
+
const tail = ` — ${where} — ${game.waitingOnYou ? 'waiting on you' : 'waiting on others'}`;
|
|
175
|
+
const flat = game.name.replace(/\s+/g, ' ').trim() || '(untitled)';
|
|
176
|
+
const escaped = flat.startsWith('-- ') || flat.startsWith('\\') ? `\\${flat}` : flat;
|
|
177
|
+
const room = BRIEF_MAX - tail.length;
|
|
178
|
+
const shown = escaped.length > room ? `${escaped.slice(0, room - 1).trimEnd()}…` : escaped;
|
|
179
|
+
return `${shown}${tail}`;
|
|
180
|
+
}
|