@chrischall/warapp-mcp 0.0.0 → 0.2.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 +211 -9
- package/dist/analysis/accept-surrender.js +56 -0
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/calibrate.js +239 -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/finished-game.js +136 -0
- package/dist/analysis/game-lessons.js +217 -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 +179 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +552 -0
- package/dist/analysis/opponents.js +1253 -0
- package/dist/analysis/outlook.js +695 -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 +1405 -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 +1001 -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 +2927 -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 +584 -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 +1112 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +121082 -36148
- package/dist/calibration-source.js +75 -0
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +265 -0
- package/dist/client.js +439 -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/finished-store.js +357 -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/lessons-store.js +356 -0
- package/dist/live.js +287 -0
- package/dist/map-details.js +127 -0
- package/dist/map-stats.js +160 -0
- package/dist/map-store.js +242 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +218 -0
- package/dist/normalize.js +443 -0
- package/dist/notifications.js +143 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +165 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +231 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +727 -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 +615 -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 +227 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +291 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2223 -0
- package/dist/surrender-pending.js +126 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/accept-surrender.js +311 -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 +158 -0
- package/dist/tools/chat-read-mark.js +179 -0
- package/dist/tools/chat.js +525 -0
- package/dist/tools/check-plan.js +689 -0
- package/dist/tools/commander-check.js +103 -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/end-of-game.js +384 -0
- package/dist/tools/game.js +151 -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 +152 -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-details.js +88 -0
- package/dist/tools/map-stats.js +130 -0
- package/dist/tools/map.js +141 -0
- package/dist/tools/my-games.js +193 -0
- package/dist/tools/notifications.js +484 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +163 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/past-games.js +94 -0
- package/dist/tools/picks.js +305 -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 +445 -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 +257 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender-pending.js +74 -0
- package/dist/tools/surrender.js +247 -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 +178 -0
- package/dist/tools/turn.js +2825 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +300 -0
- package/dist/tools/write-kit.js +164 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +577 -0
- package/dist/version.js +4 -0
- package/manifest.json +194 -4
- package/mint.yaml +106 -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 +1096 -21
package/dist/my-games.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
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: the web client's codes, named as GameFeed names them. */
|
|
18
|
+
export const GAME_STATE_NAMES = {
|
|
19
|
+
2: 'WaitingForPlayers',
|
|
20
|
+
3: 'Playing',
|
|
21
|
+
4: 'Finished',
|
|
22
|
+
5: 'DistributingTerritories',
|
|
23
|
+
};
|
|
24
|
+
/** A GameState code's name; the code itself when it has none. */
|
|
25
|
+
export const gameStateName = (code) => GAME_STATE_NAMES[code] ?? String(code);
|
|
26
|
+
const GAME_WAITING = 2;
|
|
27
|
+
const GAME_PLAYING = 3;
|
|
28
|
+
const GAME_DISTRIBUTING = 5;
|
|
29
|
+
const GAME_FINISHED = 4;
|
|
30
|
+
const PLAYER_PLAYING = 2;
|
|
31
|
+
/** GameInfo field positions in read order, and its whole field count (src/open-games.ts reads the same record). */
|
|
32
|
+
const GI = { gameId: 7, name: 13, lastTurn: 14, players: 16, state: 22 };
|
|
33
|
+
/**
|
|
34
|
+
* GameInfo's four "unread … messages" flags (#311, docs/WEB-PROTOCOL.md "Marking a game's chat read"): read from
|
|
35
|
+
* the client bundle, UNVERIFIED live. The read-back for RegisterChatView.
|
|
36
|
+
*/
|
|
37
|
+
const GI_UNREAD = { group: 8, private: 17, public: 18, team: 23 };
|
|
38
|
+
export const GAME_INFO_FIELDS = 27;
|
|
39
|
+
/** GameInfoPlayer field positions in read order, and its whole field count. */
|
|
40
|
+
const GP = { committed: 2, name: 5, id: 6, state: 7, team: 8 };
|
|
41
|
+
export const GAME_INFO_PLAYER_FIELDS = 10;
|
|
42
|
+
/** Whether any of the flags is set. */
|
|
43
|
+
export const anyUnreadChat = (f) => f !== undefined && (f.group || f.private || f.public || f.team);
|
|
44
|
+
/** The game's unread-chat flags in the list, or undefined (not listed, or the flags did not read). */
|
|
45
|
+
export function unreadChatOf(games, gameId) {
|
|
46
|
+
return games.find((g) => g.id === gameId)?.unreadChat;
|
|
47
|
+
}
|
|
48
|
+
/** The flags, read loosely: a field that is not a boolean leaves them all unknown, never refuses the list. */
|
|
49
|
+
function unreadFlagsOf(f) {
|
|
50
|
+
const group = f[GI_UNREAD.group];
|
|
51
|
+
const priv = f[GI_UNREAD.private];
|
|
52
|
+
const pub = f[GI_UNREAD.public];
|
|
53
|
+
const team = f[GI_UNREAD.team];
|
|
54
|
+
if (typeof group !== 'boolean' || typeof priv !== 'boolean' || typeof pub !== 'boolean' || typeof team !== 'boolean')
|
|
55
|
+
return undefined;
|
|
56
|
+
return { group, private: priv, public: pub, team };
|
|
57
|
+
}
|
|
58
|
+
/** The GetMyGames reply arrived in a shape this server does not understand. */
|
|
59
|
+
export class MyGamesFormatError extends McpToolError {
|
|
60
|
+
constructor(detail) {
|
|
61
|
+
super(`war.app's game list arrived in an unexpected shape (${detail}).`, {
|
|
62
|
+
kind: 'unknown',
|
|
63
|
+
hint: 'The war.app client may have changed. warapp_get_game still reads a game by id.',
|
|
64
|
+
});
|
|
65
|
+
this.name = 'MyGamesFormatError';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
|
|
69
|
+
const isStr = (v) => v === null || typeof v === 'string';
|
|
70
|
+
function playerOf(p) {
|
|
71
|
+
if (!isObj(p) || p.$type !== GAME_INFO_PLAYER)
|
|
72
|
+
throw new MyGamesFormatError('a player is not a GameInfoPlayer');
|
|
73
|
+
const f = fields(p);
|
|
74
|
+
if (f.length !== GAME_INFO_PLAYER_FIELDS) {
|
|
75
|
+
throw new MyGamesFormatError(`a GameInfoPlayer has ${f.length} fields, not ${GAME_INFO_PLAYER_FIELDS}`);
|
|
76
|
+
}
|
|
77
|
+
const committed = f[GP.committed];
|
|
78
|
+
const name = f[GP.name];
|
|
79
|
+
const id = f[GP.id];
|
|
80
|
+
const state = f[GP.state];
|
|
81
|
+
if (typeof committed !== 'boolean' || !isStr(name) || !isInt(id) || !isInt(state)) {
|
|
82
|
+
throw new MyGamesFormatError('a GameInfoPlayer lacks its fields');
|
|
83
|
+
}
|
|
84
|
+
// The team is read loosely: it is a fallback for GameFeed's (C1), so a value that is not a number is left out
|
|
85
|
+
// rather than refusing the whole list.
|
|
86
|
+
const team = f[GP.team];
|
|
87
|
+
return { id, name: name ?? '', stateCode: state, committed, ...(isInt(team) && carriesTeam(team) ? { team } : {}) };
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The teams GetMyGames gives a game's players, by in-game id (C1, docs/PLAN-TEAMS.md): what a tool falls back on
|
|
91
|
+
* when GameFeed sends no team (V1). Empty when the game is not in the list or no player carries a team.
|
|
92
|
+
*/
|
|
93
|
+
export function myGamesTeams(games, gameId) {
|
|
94
|
+
const out = new Map();
|
|
95
|
+
for (const p of games.find((g) => g.id === gameId)?.players ?? [])
|
|
96
|
+
if (p.team !== undefined)
|
|
97
|
+
out.set(p.id, p.team);
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
function gameOf(g) {
|
|
101
|
+
if (!isObj(g) || g.$type !== GAME_INFO)
|
|
102
|
+
throw new MyGamesFormatError('a game is not a GameInfo');
|
|
103
|
+
const f = fields(g);
|
|
104
|
+
if (f.length !== GAME_INFO_FIELDS)
|
|
105
|
+
throw new MyGamesFormatError(`a GameInfo has ${f.length} fields, not ${GAME_INFO_FIELDS}`);
|
|
106
|
+
const id = f[GI.gameId];
|
|
107
|
+
const name = f[GI.name];
|
|
108
|
+
const lastTurn = f[GI.lastTurn];
|
|
109
|
+
const players = f[GI.players];
|
|
110
|
+
const state = f[GI.state];
|
|
111
|
+
if (!isInt(id) ||
|
|
112
|
+
!isStr(name) ||
|
|
113
|
+
!isInt(lastTurn) ||
|
|
114
|
+
!(players === null || Array.isArray(players)) ||
|
|
115
|
+
!isInt(state)) {
|
|
116
|
+
throw new MyGamesFormatError('a GameInfo lacks its fields');
|
|
117
|
+
}
|
|
118
|
+
const unreadChat = unreadFlagsOf(f);
|
|
119
|
+
return {
|
|
120
|
+
id,
|
|
121
|
+
name: name ?? '',
|
|
122
|
+
lastTurn,
|
|
123
|
+
stateCode: state,
|
|
124
|
+
players: (players ?? []).filter((p) => p !== null).map(playerOf),
|
|
125
|
+
...(unreadChat ? { unreadChat } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/** Read a GetMyGames result (the body positioned at the result-present flag). */
|
|
129
|
+
export function readMyGames(bundle, body) {
|
|
130
|
+
if (!body.bool())
|
|
131
|
+
return [];
|
|
132
|
+
const ret = bundle.readClass(MY_GAMES_RETURN, body);
|
|
133
|
+
if (!isObj(ret))
|
|
134
|
+
throw new MyGamesFormatError('no MyGamesReturn');
|
|
135
|
+
const list = fields(ret)[0];
|
|
136
|
+
if (list === null)
|
|
137
|
+
return [];
|
|
138
|
+
if (!Array.isArray(list))
|
|
139
|
+
throw new MyGamesFormatError('no game list');
|
|
140
|
+
return list.filter((g) => g !== null).map(gameOf);
|
|
141
|
+
}
|
|
142
|
+
/** Whether the game has finished. */
|
|
143
|
+
export const isFinished = (g) => g.stateCode === GAME_FINISHED;
|
|
144
|
+
/**
|
|
145
|
+
* Name the codes and decide which games wait on me (`myInGameId`): the game is
|
|
146
|
+
* being played or distributing territories, my player is Playing, and I have
|
|
147
|
+
* not committed. Games waiting on me come first; otherwise war.app's order.
|
|
148
|
+
*/
|
|
149
|
+
export function summarizeMyGames(games, myInGameId) {
|
|
150
|
+
const out = games.map((g) => {
|
|
151
|
+
const me = g.players.find((p) => p.id === myInGameId);
|
|
152
|
+
const active = g.stateCode === GAME_PLAYING || g.stateCode === GAME_DISTRIBUTING;
|
|
153
|
+
return {
|
|
154
|
+
id: g.id,
|
|
155
|
+
name: g.name,
|
|
156
|
+
state: gameStateName(g.stateCode),
|
|
157
|
+
turn: g.lastTurn < 0 ? null : g.lastTurn + 1,
|
|
158
|
+
waitingOnYou: active && me !== undefined && me.stateCode === PLAYER_PLAYING && !me.committed,
|
|
159
|
+
players: g.players.map((p) => ({
|
|
160
|
+
name: p.name,
|
|
161
|
+
state: playerStateName(p.stateCode),
|
|
162
|
+
committed: p.committed,
|
|
163
|
+
})),
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
return [...out.filter((g) => g.waitingOnYou), ...out.filter((g) => !g.waitingOnYou)];
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Games I can still take a turn in (`myInGameId`): being played or distributing
|
|
170
|
+
* territories, with my player Playing — committed or not. war.app's order.
|
|
171
|
+
*/
|
|
172
|
+
export function activeGameIds(games, myInGameId) {
|
|
173
|
+
return games
|
|
174
|
+
.filter((g) => g.stateCode === GAME_PLAYING || g.stateCode === GAME_DISTRIBUTING)
|
|
175
|
+
.filter((g) => g.players.some((p) => p.id === myInGameId && p.stateCode === PLAYER_PLAYING))
|
|
176
|
+
.map((g) => g.id);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Games whose chat is live (#256): lobbies, games being picked and games being played — every
|
|
180
|
+
* game in the list but a finished one, whatever my seat's state — plus a finished game whose chat
|
|
181
|
+
* war.app flags unread, or whose flags did not read at all (#311, GameInfo's unread flags: UNVERIFIED
|
|
182
|
+
* live — a misread position must not hide a finished game's chat without a word; `unflaggedFinished`
|
|
183
|
+
* names those). Ascending id order, so a cursor (the last id read) resumes the list even when games
|
|
184
|
+
* join or leave it between calls.
|
|
185
|
+
*/
|
|
186
|
+
export function chatGameIds(games) {
|
|
187
|
+
return games
|
|
188
|
+
.filter((g) => g.stateCode === GAME_WAITING ||
|
|
189
|
+
g.stateCode === GAME_PLAYING ||
|
|
190
|
+
g.stateCode === GAME_DISTRIBUTING ||
|
|
191
|
+
(g.stateCode === GAME_FINISHED && (g.unreadChat === undefined || anyUnreadChat(g.unreadChat))))
|
|
192
|
+
.map((g) => g.id)
|
|
193
|
+
.sort((a, b) => a - b);
|
|
194
|
+
}
|
|
195
|
+
/** Finished games whose unread-chat flags did not read (#311): `chatGameIds` keeps them, unjudged. Ascending ids. */
|
|
196
|
+
export function unflaggedFinished(games) {
|
|
197
|
+
return games
|
|
198
|
+
.filter((g) => g.stateCode === GAME_FINISHED && g.unreadChat === undefined)
|
|
199
|
+
.map((g) => g.id)
|
|
200
|
+
.sort((a, b) => a - b);
|
|
201
|
+
}
|
|
202
|
+
/** The longest line `view: 'brief'` answers (the context-groups contract). */
|
|
203
|
+
const BRIEF_MAX = 120;
|
|
204
|
+
/**
|
|
205
|
+
* One brief line, `name — <turn N | state> — waiting on you | waiting on others`,
|
|
206
|
+
* at most {@link BRIEF_MAX} characters: the name (another player's text) is
|
|
207
|
+
* flattened to one line and shortened first; a name starting `-- ` or `\` gets
|
|
208
|
+
* one leading `\` so it can never read as a note line.
|
|
209
|
+
*/
|
|
210
|
+
export function briefGameLine(game) {
|
|
211
|
+
const where = game.state === 'Playing' && game.turn !== null ? `turn ${game.turn}` : game.state;
|
|
212
|
+
const tail = ` — ${where} — ${game.waitingOnYou ? 'waiting on you' : 'waiting on others'}`;
|
|
213
|
+
const flat = game.name.replace(/\s+/g, ' ').trim() || '(untitled)';
|
|
214
|
+
const escaped = flat.startsWith('-- ') || flat.startsWith('\\') ? `\\${flat}` : flat;
|
|
215
|
+
const room = BRIEF_MAX - tail.length;
|
|
216
|
+
const shown = escaped.length > room ? `${escaped.slice(0, room - 1).trimEnd()}…` : escaped;
|
|
217
|
+
return `${shown}${tail}`;
|
|
218
|
+
}
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
// GameFeed normalizers. war.app sends EVERY scalar as a string ("-1", "False",
|
|
2
|
+
// territory "id": "1", bonus "value": "6") while adjacency / membership lists
|
|
3
|
+
// are number arrays, and settings are mostly real JSON types. Everything is
|
|
4
|
+
// turned into real types here, once, so nothing downstream re-parses strings.
|
|
5
|
+
import { McpToolError } from '@chrischall/mcp-utils';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { boardFromStanding } from './board.js';
|
|
8
|
+
export { asBool, asInt, asNum } from './scalars.js';
|
|
9
|
+
import { asBool, asInt, asNum } from './scalars.js';
|
|
10
|
+
const asStr = (v) => (typeof v === 'string' ? v : undefined);
|
|
11
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
12
|
+
/** The `error` string of a GameFeed error body (`{ termsOfUse, error }`), if it is one. */
|
|
13
|
+
export function feedErrorOf(body) {
|
|
14
|
+
return isRec(body) && typeof body.error === 'string' ? body.error : undefined;
|
|
15
|
+
}
|
|
16
|
+
/** A GameFeed body that does not have the shape a game or map must have. */
|
|
17
|
+
class WarappFormatError extends McpToolError {
|
|
18
|
+
constructor(what, detail) {
|
|
19
|
+
super(`war.app returned a ${what} in an unexpected shape (${detail}).`, { kind: 'unknown' });
|
|
20
|
+
this.name = 'WarappFormatError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
// ---------- raw shapes (loose: unknown keys pass through, scalars may be string or number) ----------
|
|
24
|
+
const scalar = z.union([z.string(), z.number()]);
|
|
25
|
+
const intLike = scalar.refine((v) => asInt(v) !== undefined, 'not an integer');
|
|
26
|
+
const RawTerritory = z.looseObject({
|
|
27
|
+
id: intLike,
|
|
28
|
+
name: z.string(),
|
|
29
|
+
coords: z.string().optional(),
|
|
30
|
+
connectedTo: z.array(intLike).default([]),
|
|
31
|
+
});
|
|
32
|
+
const RawBonus = z.looseObject({
|
|
33
|
+
id: intLike,
|
|
34
|
+
name: z.string(),
|
|
35
|
+
value: intLike,
|
|
36
|
+
territoryIDs: z.array(intLike).default([]),
|
|
37
|
+
});
|
|
38
|
+
const RawDistributionMode = z.looseObject({ id: intLike, name: z.string(), type: z.string().optional() });
|
|
39
|
+
const RawMap = z.looseObject({
|
|
40
|
+
id: intLike,
|
|
41
|
+
name: z.string(),
|
|
42
|
+
territories: z.array(RawTerritory),
|
|
43
|
+
bonuses: z.array(RawBonus).default([]),
|
|
44
|
+
distributionModes: z.array(RawDistributionMode).default([]),
|
|
45
|
+
});
|
|
46
|
+
const RawPlayer = z.looseObject({ id: intLike, name: z.string().default('') });
|
|
47
|
+
const RawGame = z.looseObject({
|
|
48
|
+
id: intLike,
|
|
49
|
+
state: z.string(),
|
|
50
|
+
name: z.string().optional(),
|
|
51
|
+
players: z.array(RawPlayer).default([]),
|
|
52
|
+
});
|
|
53
|
+
function issueOf(err) {
|
|
54
|
+
const i = err.issues[0];
|
|
55
|
+
return i ? `${i.path.join('.') || '(root)'}: ${i.message}` : 'invalid';
|
|
56
|
+
}
|
|
57
|
+
function coordsOf(s) {
|
|
58
|
+
if (!s)
|
|
59
|
+
return undefined;
|
|
60
|
+
const [x, y, ...rest] = s.split(',').map((p) => asNum(p));
|
|
61
|
+
return x !== undefined && y !== undefined && rest.length === 0 ? { x, y } : undefined;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Normalize a GameFeed `map`. A bonus member id is a territory whenever a
|
|
65
|
+
* territory has that id (ids overlap between the two namespaces on real maps),
|
|
66
|
+
* else a member bonus (superbonus), else unknown.
|
|
67
|
+
*/
|
|
68
|
+
export function normalizeMap(raw) {
|
|
69
|
+
const parsed = RawMap.safeParse(raw);
|
|
70
|
+
if (!parsed.success)
|
|
71
|
+
throw new WarappFormatError('map', issueOf(parsed.error));
|
|
72
|
+
const m = parsed.data;
|
|
73
|
+
const territories = m.territories.map((t) => {
|
|
74
|
+
const id = asInt(t.id);
|
|
75
|
+
const connectedTo = t.connectedTo.map((n) => asInt(n));
|
|
76
|
+
const coords = coordsOf(t.coords);
|
|
77
|
+
return coords ? { id, name: t.name, coords, connectedTo } : { id, name: t.name, connectedTo };
|
|
78
|
+
});
|
|
79
|
+
const territoryIds = new Set(territories.map((t) => t.id));
|
|
80
|
+
const bonusIdSet = new Set(m.bonuses.map((b) => asInt(b.id)));
|
|
81
|
+
const bonuses = m.bonuses.map((b) => {
|
|
82
|
+
const bonus = { id: asInt(b.id), name: b.name, value: asInt(b.value), territoryIds: [], bonusIds: [] };
|
|
83
|
+
const unknown = [];
|
|
84
|
+
for (const raw of b.territoryIDs) {
|
|
85
|
+
const id = asInt(raw);
|
|
86
|
+
if (territoryIds.has(id))
|
|
87
|
+
bonus.territoryIds.push(id);
|
|
88
|
+
else if (bonusIdSet.has(id))
|
|
89
|
+
bonus.bonusIds.push(id);
|
|
90
|
+
else
|
|
91
|
+
unknown.push(id);
|
|
92
|
+
}
|
|
93
|
+
if (unknown.length)
|
|
94
|
+
bonus.unknownIds = unknown;
|
|
95
|
+
return bonus;
|
|
96
|
+
});
|
|
97
|
+
const distributionModes = m.distributionModes.map((d) => {
|
|
98
|
+
const out = { id: asInt(d.id), name: d.name };
|
|
99
|
+
if (d.type !== undefined)
|
|
100
|
+
out.type = d.type;
|
|
101
|
+
return out;
|
|
102
|
+
});
|
|
103
|
+
return { id: asInt(m.id), name: m.name, territories, bonuses, distributionModes };
|
|
104
|
+
}
|
|
105
|
+
export function normalizePlayer(raw) {
|
|
106
|
+
const r = RawPlayer.parse(raw);
|
|
107
|
+
const p = {
|
|
108
|
+
id: asInt(r.id),
|
|
109
|
+
name: r.name,
|
|
110
|
+
isAI: asBool(r.isAI) ?? false,
|
|
111
|
+
humanTurnedIntoAI: asBool(r.humanTurnedIntoAI) ?? false,
|
|
112
|
+
hasCommittedOrders: asBool(r.hasCommittedOrders) ?? false,
|
|
113
|
+
};
|
|
114
|
+
if (typeof r.id === 'string' && r.id.trim() !== String(p.id))
|
|
115
|
+
p.feedId = r.id.trim();
|
|
116
|
+
const color = asStr(r.color);
|
|
117
|
+
if (color !== undefined)
|
|
118
|
+
p.color = color;
|
|
119
|
+
const state = asStr(r.state);
|
|
120
|
+
if (state !== undefined)
|
|
121
|
+
p.state = state;
|
|
122
|
+
const team = asInt(r.team);
|
|
123
|
+
if (team !== undefined)
|
|
124
|
+
p.team = team;
|
|
125
|
+
return p;
|
|
126
|
+
}
|
|
127
|
+
const INT_SETTINGS = {
|
|
128
|
+
mapId: 'Map',
|
|
129
|
+
minimumArmyBonus: 'MinimumArmyBonus',
|
|
130
|
+
bonusArmyPer: 'BonusArmyPer',
|
|
131
|
+
distributionMode: 'DistributionMode',
|
|
132
|
+
territoryLimit: 'TerritoryLimit',
|
|
133
|
+
initialPlayerArmiesPerTerritory: 'InitialPlayerArmiesPerTerritory',
|
|
134
|
+
initialNonDistributionArmies: 'InitialNonDistributionArmies',
|
|
135
|
+
initialNeutralsInDistribution: 'InitialNeutralsInDistribution',
|
|
136
|
+
};
|
|
137
|
+
const BOOL_SETTINGS = {
|
|
138
|
+
oneArmyStandsGuard: 'OneArmyStandsGuard',
|
|
139
|
+
multiAttack: 'MultiAttack',
|
|
140
|
+
localDeployments: 'LocalDeployments',
|
|
141
|
+
noSplit: 'NoSplit',
|
|
142
|
+
commanders: 'Commanders',
|
|
143
|
+
allowTransferOnly: 'AllowTransferOnly',
|
|
144
|
+
allowAttackOnly: 'AllowAttackOnly',
|
|
145
|
+
allowPercentageAttacks: 'AllowPercentageAttacks',
|
|
146
|
+
privateMessaging: 'PrivateMessaging',
|
|
147
|
+
};
|
|
148
|
+
const STR_SETTINGS = { pace: 'Pace', fog: 'Fog', roundingMode: 'RoundingMode', moveOrder: 'MoveOrder' };
|
|
149
|
+
export function normalizeSettings(raw) {
|
|
150
|
+
const r = isRec(raw) ? raw : {};
|
|
151
|
+
const s = { cards: [], raw: r };
|
|
152
|
+
for (const [k, src] of Object.entries(INT_SETTINGS)) {
|
|
153
|
+
const v = asInt(r[src]);
|
|
154
|
+
if (v !== undefined)
|
|
155
|
+
s[k] = v;
|
|
156
|
+
}
|
|
157
|
+
for (const [k, src] of Object.entries(BOOL_SETTINGS)) {
|
|
158
|
+
const v = asBool(r[src]);
|
|
159
|
+
if (v !== undefined)
|
|
160
|
+
s[k] = v;
|
|
161
|
+
}
|
|
162
|
+
for (const [k, src] of Object.entries(STR_SETTINGS)) {
|
|
163
|
+
const v = asStr(r[src]);
|
|
164
|
+
if (v !== undefined)
|
|
165
|
+
s[k] = v;
|
|
166
|
+
}
|
|
167
|
+
// Kill rates are read as numbers, not integers: a rate sent as "20.0" must
|
|
168
|
+
// never be dropped, or every combat computation would silently assume 60/70.
|
|
169
|
+
const off = asNum(r.OffensiveKillRate);
|
|
170
|
+
if (off !== undefined)
|
|
171
|
+
s.offensiveKillRate = off;
|
|
172
|
+
const def = asNum(r.DefensiveKillRate);
|
|
173
|
+
if (def !== undefined)
|
|
174
|
+
s.defensiveKillRate = def;
|
|
175
|
+
const luck = asNum(r.LuckModifier);
|
|
176
|
+
if (luck !== undefined)
|
|
177
|
+
s.luckModifier = luck;
|
|
178
|
+
// A number, not an integer: a cap of 1.5× income read as an integer would be "no cap" (#131).
|
|
179
|
+
if ('ArmyCap' in r)
|
|
180
|
+
s.armyCap = asNum(r.ArmyCap) ?? null;
|
|
181
|
+
for (const [k, v] of Object.entries(r)) {
|
|
182
|
+
if (k.endsWith('Card') && isRec(v))
|
|
183
|
+
s.cards.push(k.slice(0, -'Card'.length));
|
|
184
|
+
}
|
|
185
|
+
if (isRec(r.Wastelands)) {
|
|
186
|
+
const count = asInt(r.Wastelands.NumberOfWastelands);
|
|
187
|
+
const size = asInt(r.Wastelands.WastelandSize);
|
|
188
|
+
if (count !== undefined && size !== undefined)
|
|
189
|
+
s.wastelands = { count, size };
|
|
190
|
+
}
|
|
191
|
+
if (r.Commerce !== undefined && r.Commerce !== null)
|
|
192
|
+
s.commerce = isRec(r.Commerce) ? Object.keys(r.Commerce).length > 0 : true;
|
|
193
|
+
if (r.Mods !== undefined && r.Mods !== null) {
|
|
194
|
+
const empty = r.Mods === '' || (isRec(r.Mods) && Object.keys(r.Mods).length === 0);
|
|
195
|
+
s.mods = Array.isArray(r.Mods) ? r.Mods.length : empty ? 0 : -1;
|
|
196
|
+
}
|
|
197
|
+
if (r.OverriddenBonuses !== undefined && r.OverriddenBonuses !== null) {
|
|
198
|
+
const o = parseOverriddenBonuses(r.OverriddenBonuses);
|
|
199
|
+
s.overriddenBonuses = o.values;
|
|
200
|
+
if (o.unparsed)
|
|
201
|
+
s.overriddenBonusesUnparsed = true;
|
|
202
|
+
}
|
|
203
|
+
return s;
|
|
204
|
+
}
|
|
205
|
+
/** Key spellings tried for an override entry: `bonusID` / `value` is the verified live shape (#62); the rest are read only to be tolerant. */
|
|
206
|
+
const OVERRIDE_ID_KEYS = ['bonusID', 'BonusID', 'bonusId', 'BonusId', 'bonusid', 'id', 'ID', 'Id', 'key', 'Key', 'bonus', 'Bonus'];
|
|
207
|
+
const OVERRIDE_VALUE_KEYS = ['value', 'Value', 'val', 'Val', 'armies', 'Armies'];
|
|
208
|
+
function overrideEntry(e) {
|
|
209
|
+
if (Array.isArray(e)) {
|
|
210
|
+
if (e.length !== 2)
|
|
211
|
+
return undefined;
|
|
212
|
+
const id = asInt(e[0]);
|
|
213
|
+
const value = asInt(e[1]);
|
|
214
|
+
return id !== undefined && value !== undefined ? [id, value] : undefined;
|
|
215
|
+
}
|
|
216
|
+
if (!isRec(e))
|
|
217
|
+
return undefined;
|
|
218
|
+
const idKey = OVERRIDE_ID_KEYS.find((k) => k in e);
|
|
219
|
+
const valueKey = OVERRIDE_VALUE_KEYS.find((k) => k in e);
|
|
220
|
+
if (idKey === undefined || valueKey === undefined)
|
|
221
|
+
return undefined;
|
|
222
|
+
const id = asInt(e[idKey]);
|
|
223
|
+
const value = asInt(e[valueKey]);
|
|
224
|
+
return id !== undefined && value !== undefined ? [id, value] : undefined;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Read GameFeed's `OverriddenBonuses` (bonus id → value). Verified live (#62, 2026-11-12):
|
|
228
|
+
* GameFeed sends an array of `{ "bonusID": <int>, "value": <int> }` with JSON numbers, and
|
|
229
|
+
* `[]` when nothing is overridden (war.app's client keeps a `Dictionary<bonusId, value>`,
|
|
230
|
+
* values −1000..1000). Read loosely, never throwing: string numbers, other key spellings,
|
|
231
|
+
* `[id, value]` pairs, an object keyed by bonus id, or any of those as a JSON string. A
|
|
232
|
+
* malformed entry is skipped (the rest are kept) and the read flagged `unparsed`, so the
|
|
233
|
+
* pre-checks stay soft; an unreadable shape gives no values and `unparsed: true`.
|
|
234
|
+
*/
|
|
235
|
+
export function parseOverriddenBonuses(raw) {
|
|
236
|
+
const none = { values: new Map(), unparsed: false };
|
|
237
|
+
const fail = { values: new Map(), unparsed: true };
|
|
238
|
+
let v = raw;
|
|
239
|
+
if (typeof v === 'string') {
|
|
240
|
+
const t = v.trim();
|
|
241
|
+
if (t === '')
|
|
242
|
+
return none;
|
|
243
|
+
try {
|
|
244
|
+
v = JSON.parse(t);
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
return fail;
|
|
248
|
+
}
|
|
249
|
+
if (typeof v === 'string')
|
|
250
|
+
return fail;
|
|
251
|
+
}
|
|
252
|
+
const values = new Map();
|
|
253
|
+
let bad = false;
|
|
254
|
+
if (Array.isArray(v)) {
|
|
255
|
+
for (const e of v) {
|
|
256
|
+
const pair = overrideEntry(e);
|
|
257
|
+
if (!pair) {
|
|
258
|
+
bad = true;
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
values.set(pair[0], pair[1]);
|
|
262
|
+
}
|
|
263
|
+
return { values, unparsed: bad };
|
|
264
|
+
}
|
|
265
|
+
if (isRec(v)) {
|
|
266
|
+
for (const [k, val] of Object.entries(v)) {
|
|
267
|
+
const id = asInt(k);
|
|
268
|
+
const value = asInt(val);
|
|
269
|
+
if (id === undefined || value === undefined) {
|
|
270
|
+
bad = true;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
values.set(id, value);
|
|
274
|
+
}
|
|
275
|
+
return { values, unparsed: bad };
|
|
276
|
+
}
|
|
277
|
+
return fail;
|
|
278
|
+
}
|
|
279
|
+
/** Normalize a GameFeed game body (the map is left to the client). */
|
|
280
|
+
export function normalizeGame(raw) {
|
|
281
|
+
const parsed = RawGame.safeParse(raw);
|
|
282
|
+
if (!parsed.success)
|
|
283
|
+
throw new WarappFormatError('game', issueOf(parsed.error));
|
|
284
|
+
const g = parsed.data;
|
|
285
|
+
const game = { id: asInt(g.id), state: g.state, players: g.players.map(normalizePlayer) };
|
|
286
|
+
if (g.name !== undefined)
|
|
287
|
+
game.name = g.name;
|
|
288
|
+
const turns = asInt(g.numberOfTurns);
|
|
289
|
+
if (turns !== undefined)
|
|
290
|
+
game.numberOfTurns = turns;
|
|
291
|
+
const created = asStr(g.created);
|
|
292
|
+
if (created !== undefined)
|
|
293
|
+
game.created = created;
|
|
294
|
+
const last = asStr(g.lastTurnTime);
|
|
295
|
+
if (last !== undefined)
|
|
296
|
+
game.lastTurnTime = last;
|
|
297
|
+
if (isRec(g.settings)) {
|
|
298
|
+
game.settings = normalizeSettings(g.settings);
|
|
299
|
+
game.endRules = parseEndRules(g.settings);
|
|
300
|
+
}
|
|
301
|
+
const standing = boardFromStanding(g.standing ?? g.standings ?? g.latestStanding);
|
|
302
|
+
if (standing)
|
|
303
|
+
game.standing = standing;
|
|
304
|
+
const history = historyOf(g);
|
|
305
|
+
if (history !== undefined)
|
|
306
|
+
game.history = history;
|
|
307
|
+
if (g.chat !== undefined)
|
|
308
|
+
game.chat = g.chat;
|
|
309
|
+
const settings = isRec(g.settings) ? g.settings : undefined;
|
|
310
|
+
const description = [g.description, g.Description, settings?.description, settings?.Description]
|
|
311
|
+
.map(asStr)
|
|
312
|
+
.find((d) => d !== undefined && d.trim() !== '');
|
|
313
|
+
if (description !== undefined)
|
|
314
|
+
game.description = description;
|
|
315
|
+
return game;
|
|
316
|
+
}
|
|
317
|
+
/** A top-level key that carries a turn of the history (#302): `standing<N>`, `turn<N>`, `distributionStanding`. */
|
|
318
|
+
const HISTORY_KEY = /^(?:(?:standing|turn)_?\d+|distributionStanding)$/i;
|
|
319
|
+
/**
|
|
320
|
+
* The game's history as sent (#302): `history` / `History` (a JSON string parsed when it parses), else
|
|
321
|
+
* the history-like top-level keys gathered into one object, else a per-turn `standings` / `turns` list
|
|
322
|
+
* — `standings` only when it does not read as the current board. `undefined` when none came.
|
|
323
|
+
*/
|
|
324
|
+
function historyOf(g) {
|
|
325
|
+
const named = g.history ?? g.History;
|
|
326
|
+
if (named !== undefined) {
|
|
327
|
+
if (typeof named !== 'string')
|
|
328
|
+
return named;
|
|
329
|
+
try {
|
|
330
|
+
return JSON.parse(named);
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
return named;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const out = {};
|
|
337
|
+
for (const [k, v] of Object.entries(g))
|
|
338
|
+
if (HISTORY_KEY.test(k))
|
|
339
|
+
out[k] = v;
|
|
340
|
+
if (Object.keys(out).length)
|
|
341
|
+
return out;
|
|
342
|
+
if (Array.isArray(g.turns))
|
|
343
|
+
return { turns: g.turns };
|
|
344
|
+
if ((Array.isArray(g.standings) || isRec(g.standings)) && !boardFromStanding(g.standings))
|
|
345
|
+
return { standings: g.standings };
|
|
346
|
+
return undefined;
|
|
347
|
+
}
|
|
348
|
+
const INSTANT_WORDS = new Set(['instant', 'instantly', 'immediate', 'yes']);
|
|
349
|
+
const NOT_INSTANT_WORDS = new Set(['notinstant', 'noninstant', 'notimmediate', 'requireacceptance', 'requiresacceptance', 'vote', 'no', 'never']);
|
|
350
|
+
/** {@link EndRules} from a raw settings object; never throws. */
|
|
351
|
+
export function parseEndRules(raw) {
|
|
352
|
+
const r = isRec(raw) ? raw : {};
|
|
353
|
+
const out = {};
|
|
354
|
+
const instant = r.InstantSurrender;
|
|
355
|
+
if (instant !== undefined && instant !== null) {
|
|
356
|
+
const b = asBool(instant);
|
|
357
|
+
const word = typeof instant === 'string' ? instant.trim().toLowerCase().replace(/[\s_-]/g, '') : '';
|
|
358
|
+
if (b !== undefined)
|
|
359
|
+
out.instantSurrender = b;
|
|
360
|
+
else if (INSTANT_WORDS.has(word))
|
|
361
|
+
out.instantSurrender = true;
|
|
362
|
+
else if (NOT_INSTANT_WORDS.has(word))
|
|
363
|
+
out.instantSurrender = false;
|
|
364
|
+
else
|
|
365
|
+
out.instantSurrenderRaw = String(instant);
|
|
366
|
+
}
|
|
367
|
+
const bools = [
|
|
368
|
+
['surrenderedTurnIntoAI', 'SurrenderedPlayersTurnIntoAIs'],
|
|
369
|
+
['bootedTurnIntoAI', 'BootedPlayersTurnIntoAIs'],
|
|
370
|
+
['aisSurrenderWhenOneHumanRemains', 'AIsSurrenderWhenOneHumanRemains'],
|
|
371
|
+
['allowVacations', 'AllowVacations'],
|
|
372
|
+
];
|
|
373
|
+
for (const [k, src] of bools) {
|
|
374
|
+
const v = asBool(r[src]);
|
|
375
|
+
if (v !== undefined)
|
|
376
|
+
out[k] = v;
|
|
377
|
+
}
|
|
378
|
+
const comeBack = asInt(r.TimesCanComeBackFromAI);
|
|
379
|
+
if (comeBack !== undefined)
|
|
380
|
+
out.timesCanComeBackFromAI = comeBack;
|
|
381
|
+
const direct = asNum(r.DirectBoot);
|
|
382
|
+
if (direct !== undefined)
|
|
383
|
+
out.directBootMinutes = direct;
|
|
384
|
+
const auto = asNum(r.AutoBoot);
|
|
385
|
+
if (auto !== undefined)
|
|
386
|
+
out.autoBootMinutes = auto;
|
|
387
|
+
if (isRec(r.BankingBootTimes)) {
|
|
388
|
+
const bank = asNum(r.BankingBootTimes.BankAmount);
|
|
389
|
+
const initial = asNum(r.BankingBootTimes.InitialBankInMinutes);
|
|
390
|
+
if (bank !== undefined && initial !== undefined)
|
|
391
|
+
out.bankingBoot = { bankMinutes: bank, initialBankMinutes: initial };
|
|
392
|
+
}
|
|
393
|
+
return out;
|
|
394
|
+
}
|
|
395
|
+
/** A feed time (`M/D/YYYY HH:MM:SS` live, or ISO `YYYY-MM-DDTHH:MM:SS`; UTC assumed, docs/WARAPP-API.md) as epoch ms; `undefined` when unreadable. */
|
|
396
|
+
export function parseFeedTime(s) {
|
|
397
|
+
if (s === undefined)
|
|
398
|
+
return undefined;
|
|
399
|
+
const us = /^\s*(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s*$/.exec(s);
|
|
400
|
+
const iso = /^\s*(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z?\s*$/.exec(s);
|
|
401
|
+
if (!us && !iso)
|
|
402
|
+
return undefined;
|
|
403
|
+
const [, mo, d, y, h, mi, se] = us
|
|
404
|
+
? us.map(Number)
|
|
405
|
+
: [0, iso[2], iso[3], iso[1], iso[4], iso[5], iso[6]].map(Number);
|
|
406
|
+
const t = Date.UTC(y, mo - 1, d, h, mi, se);
|
|
407
|
+
return Number.isFinite(t) ? t : undefined;
|
|
408
|
+
}
|
|
409
|
+
const LEAVERS_UNVERIFIED = "Read from the game's lastTurnTime, taken as the moment this turn began (UNVERIFIED: it may mean something else), " +
|
|
410
|
+
'against the AutoBoot and DirectBoot minutes. Banked boot time and vacations can delay a boot, and are not counted.';
|
|
411
|
+
/**
|
|
412
|
+
* Humans still playing who have not committed this turn, with the time left before each boot and
|
|
413
|
+
* what their seat becomes (#178). `withinMinutes` keeps only those whose nearest boot is that close.
|
|
414
|
+
* Empty unless the game is being played and `lastTurnTime` reads. Never throws.
|
|
415
|
+
*/
|
|
416
|
+
export function leavers(game, now, opts = {}) {
|
|
417
|
+
const out = { players: [], unverified: LEAVERS_UNVERIFIED };
|
|
418
|
+
if (game.state !== 'Playing')
|
|
419
|
+
return out;
|
|
420
|
+
const start = parseFeedTime(game.lastTurnTime);
|
|
421
|
+
if (start === undefined)
|
|
422
|
+
return out;
|
|
423
|
+
const rules = game.endRules ?? {};
|
|
424
|
+
const waiting = Math.max(0, Math.floor((now - start) / 60_000));
|
|
425
|
+
const left = (m) => (m !== undefined && m > 0 ? Math.max(0, Math.ceil(m - waiting)) : undefined);
|
|
426
|
+
for (const p of game.players) {
|
|
427
|
+
if ((p.state ?? 'Playing') !== 'Playing' || p.isAI || p.humanTurnedIntoAI || p.hasCommittedOrders)
|
|
428
|
+
continue;
|
|
429
|
+
const auto = left(rules.autoBootMinutes);
|
|
430
|
+
const direct = left(rules.directBootMinutes);
|
|
431
|
+
const nearest = Math.min(auto ?? Infinity, direct ?? Infinity);
|
|
432
|
+
if (opts.withinMinutes !== undefined && !(nearest <= opts.withinMinutes))
|
|
433
|
+
continue;
|
|
434
|
+
out.players.push({
|
|
435
|
+
playerId: p.id,
|
|
436
|
+
waitingMinutes: waiting,
|
|
437
|
+
...(auto !== undefined ? { autoBootInMinutes: auto } : {}),
|
|
438
|
+
...(direct !== undefined ? { directBootInMinutes: direct } : {}),
|
|
439
|
+
becomes: rules.bootedTurnIntoAI ? 'AI' : 'neutral',
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
return out;
|
|
443
|
+
}
|