@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.
Files changed (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,537 @@
1
+ // Open games: the list war.app's OpenGames page embeds, decoded by the client
2
+ // bundle's own GameInfo reader and normalized into what a player picks a game by.
3
+ //
4
+ // VERIFIED 2026-11-12 (docs/PLAN-OPEN-GAMES.md): `GET /MultiPlayer/OpenGames`
5
+ // carries `<script type="text/plain" id="AllOpenGamesData">HEX</script>`; the
6
+ // client hex-decodes it and reads an int32 count, then that many
7
+ // `warlight.shared.GameInfo` records (no present flags). Field names are
8
+ // minified, so GameInfo and its GameInfoSettings are read by registered type
9
+ // name and fields by read order (positions below, each checked for its type),
10
+ // the same as `my-games.ts`. Each record must have exactly the client's field
11
+ // count: one with a field inserted or dropped would shift every position, so it
12
+ // throws OpenGamesFormatError (#133). Otherwise the reader stays loose: a record
13
+ // whose positions do not hold their types is skipped, a payload that stops
14
+ // decoding keeps what was read, and a missing or malformed payload is an empty
15
+ // list with a note.
16
+ // Whatever the record does not carry reliably is omitted, never guessed.
17
+ import { McpToolError } from '@chrischall/mcp-utils';
18
+ import { armiesToTake } from './analysis/combat.js';
19
+ import { DEFAULT_BASE_INCOME } from './analysis/player.js';
20
+ import { cardTypeName } from './cards.js';
21
+ import { colorIndexOf } from './join-color.js';
22
+ import { GAME_INFO, GAME_INFO_FIELDS, GAME_INFO_PLAYER, GAME_INFO_PLAYER_FIELDS } from './my-games.js';
23
+ import { Reader } from './protocol/codec.js';
24
+ import { fields, isObj } from './protocol/decoded.js';
25
+ import { holdsSeat, playerStateName } from './player-states.js';
26
+ import { carriesTeam } from './teams.js';
27
+ export const OPEN_GAMES_URL = 'https://war.app/MultiPlayer/OpenGames';
28
+ export { GAME_INFO };
29
+ const GAME_INFO_SETTINGS = 'warlight.shared.GameInfoSettings';
30
+ /**
31
+ * The most records an OpenGames payload may claim. The count is read from the payload, and each
32
+ * record is a run of the downloaded bundle's reader, so it is bounded: the page lists a few hundred
33
+ * open games at most, and this is far above that.
34
+ */
35
+ export const MAX_OPEN_GAMES = 5_000;
36
+ /** GameInfo field positions in read order. */
37
+ const GI = {
38
+ randomTeamsOf: 0,
39
+ entryFee: 3,
40
+ prize: 4,
41
+ bootTime: 5,
42
+ gameId: 7,
43
+ mapId: 10,
44
+ maxPlayers: 12,
45
+ name: 13,
46
+ openSeats: 15,
47
+ players: 16,
48
+ realTime: 19,
49
+ settings: 21,
50
+ };
51
+ /** GameInfoPlayer: the colour (an optional GameColor), the in-game id, the state (GamePlayerState) and the team. */
52
+ // `ai` is the client's IsAI (GameInfoPlayer is built from GamePlayer's get_IsAI in that place; read from the bundle).
53
+ const GP = { color: 0, ai: 4, id: 6, state: 7, team: 8 };
54
+ /** GameInfoSettings field positions in read order. */
55
+ const GS = {
56
+ armyCap: 0,
57
+ autoDist: 1,
58
+ bonusArmiesPer: 2,
59
+ settingsString: 3,
60
+ attackOnly: 4,
61
+ transferOnly: 5,
62
+ commerce: 6,
63
+ defensiveKillRate: 7,
64
+ distribution: 9,
65
+ commanders: 10,
66
+ overriddenBonuses: 11,
67
+ bankingBoot: 12,
68
+ localDeployments: 13,
69
+ luck: 14,
70
+ minArmies: 15,
71
+ /** MoveOrderEnum (read from the bundle, #132): 0 Random, 1 Cycle, 2 NoLuckCycle. */
72
+ moveOrder: 16,
73
+ multiAttack: 17,
74
+ noSplit: 18,
75
+ wastelands: 19,
76
+ offensiveKillRate: 20,
77
+ oneArmyStandsGuard: 21,
78
+ ranked: 22,
79
+ roundingMode: 23,
80
+ };
81
+ /** GameInfoSettings' whole field count (as the client's reader has it, 2026-11-14). */
82
+ const GAME_INFO_SETTINGS_FIELDS = 24;
83
+ /** The distribution mode of a custom scenario. */
84
+ const DIST_CUSTOM_SCENARIO = -3;
85
+ const DEFAULT_MIN_ARMIES = 5;
86
+ const DEFAULT_OFFENSIVE = 0.6;
87
+ const DEFAULT_DEFENSIVE = 0.7;
88
+ const DEFAULT_ROUNDING = 1;
89
+ /** MoveOrderEnum's NoLuckCycle: the first turn is a speed race (docs/WEB-PROTOCOL.md "Begin first turn"). */
90
+ const MOVE_ORDER_NO_LUCK_CYCLE = 2;
91
+ /** The rule naming a non-default base income (`Minimum armies per turn is <n>`). */
92
+ const RULE_MIN_ARMIES = 'Minimum armies per turn is';
93
+ /** #276: the rule naming a game without One Army Must Stand Guard (the guard-on rule is `One army must stand guard`). */
94
+ export const GUARD_OFF_RULE = 'One army must stand guard is off';
95
+ /** The rule naming overridden bonus values. */
96
+ const RULE_OVERRIDDEN_BONUSES = 'Overridden bonuses';
97
+ /** TimeSpans at or beyond this many ms are war.app's "never". */
98
+ const NEVER_MS = 922_336_666_814_565;
99
+ /**
100
+ * A GameInfo (or its player or settings record) without exactly the client's field count: the
101
+ * client added, dropped or moved a field, so every position read would be another field's (#133).
102
+ */
103
+ export class OpenGamesFormatError extends McpToolError {
104
+ constructor(detail) {
105
+ super(`war.app's open-games list arrived in an unexpected shape (${detail}).`, {
106
+ kind: 'unknown',
107
+ hint: 'The war.app client may have changed. warapp_my_games and warapp_get_game still work.',
108
+ });
109
+ this.name = 'OpenGamesFormatError';
110
+ }
111
+ }
112
+ /** `o`'s fields, refused unless there are exactly `count` of them. */
113
+ function fieldsOf(o, type, count) {
114
+ const f = fields(o);
115
+ if (f.length !== count)
116
+ throw new OpenGamesFormatError(`a ${type.replace('warlight.shared.', '')} has ${f.length} fields, not ${count}`);
117
+ return f;
118
+ }
119
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
120
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
121
+ const isBool = (v) => typeof v === 'boolean';
122
+ const isIntList = (v) => Array.isArray(v) && v.every(isInt);
123
+ /** A TimeSpan in ms as war.app shows it: `3d`, `1d12h`, `6h`, `2h30m`, `5m`, `45s`. */
124
+ function formatDuration(ms) {
125
+ const days = Math.floor(ms / 86_400_000);
126
+ const hours = Math.floor(ms / 3_600_000) % 24;
127
+ const mins = Math.floor(ms / 60_000) % 60;
128
+ if (days > 0)
129
+ return hours > 0 ? `${days}d${hours}h` : `${days}d`;
130
+ if (hours > 5)
131
+ return `${hours}h`;
132
+ if (hours > 0)
133
+ return mins > 0 ? `${hours}h${mins}m` : `${hours}h`;
134
+ if (mins > 0)
135
+ return `${mins}m`;
136
+ return `${Math.floor(ms / 1000) % 60}s`;
137
+ }
138
+ const pct = (rate) => Math.round(rate * 100);
139
+ /** The settings string `<ver>;<f|r>;<card ids>;<p|b>;<o|p>;<m|n>`: cards and mods. */
140
+ function settingsString(s) {
141
+ const parts = s.split(';');
142
+ if (!['1', '2', '3'].includes(parts[0] ?? ''))
143
+ return undefined;
144
+ const cards = (parts[2] ?? '')
145
+ .split(',')
146
+ .filter((c) => c.trim() !== '')
147
+ .map(Number)
148
+ .filter((n) => Number.isInteger(n));
149
+ return { cards, mods: parts[0] === '3' && parts[5] === 'm' };
150
+ }
151
+ /** The flags a GameInfoSettings record carries; `undefined` when it is not one. */
152
+ function readSettings(v) {
153
+ if (!isObj(v) || v.$type !== GAME_INFO_SETTINGS)
154
+ return undefined;
155
+ const f = fieldsOf(v, GAME_INFO_SETTINGS, GAME_INFO_SETTINGS_FIELDS);
156
+ const rules = [];
157
+ const gaps = [];
158
+ let cards;
159
+ const bool = (k) => f[GS[k]] === true;
160
+ const dist = f[GS.distribution];
161
+ const scenario = isInt(dist) && dist === DIST_CUSTOM_SCENARIO;
162
+ if (scenario) {
163
+ rules.push('Custom scenario');
164
+ gaps.push('Custom scenario');
165
+ }
166
+ else if (isBool(f[GS.autoDist])) {
167
+ rules.push(f[GS.autoDist] ? 'Automatic distribution' : 'Manual distribution');
168
+ }
169
+ if (bool('commanders')) {
170
+ rules.push('Commanders');
171
+ gaps.push('Commanders');
172
+ }
173
+ const ss = typeof f[GS.settingsString] === 'string' ? settingsString(f[GS.settingsString]) : undefined;
174
+ if (ss?.cards.length) {
175
+ cards = ss.cards.map(cardTypeName);
176
+ rules.push(`Cards: ${cards.join(', ')}`);
177
+ }
178
+ const commerce = f[GS.commerce];
179
+ if (isInt(commerce)) {
180
+ rules.push(`Commerce (${commerce === 0 ? 'no army multiplier' : `army multiplier of ${commerce}`})`);
181
+ gaps.push('Commerce');
182
+ }
183
+ const banking = f[GS.bankingBoot];
184
+ if (isNum(banking) && banking > 0 && banking < NEVER_MS)
185
+ rules.push(`Start with ${formatDuration(banking)} banked`);
186
+ const waste = f[GS.wastelands];
187
+ if (isInt(waste) && waste > 0 && !scenario)
188
+ rules.push('Wastelands');
189
+ if (bool('oneArmyStandsGuard'))
190
+ rules.push('One army must stand guard');
191
+ else if (f[GS.oneArmyStandsGuard] === false) {
192
+ // #276: a rule, no longer a planner gap — the planner keeps a second line inside a held bonus,
193
+ // raids one step deeper and retakes for free with the guard off (plan/guard-off.ts).
194
+ rules.push(GUARD_OFF_RULE);
195
+ }
196
+ const luck = f[GS.luck];
197
+ const lucky = isNum(luck) && luck !== 0;
198
+ if (lucky)
199
+ rules.push(`Luck modifier ${pct(luck)}%`);
200
+ const rounding = f[GS.roundingMode];
201
+ const oddRounding = isInt(rounding) && rounding !== DEFAULT_ROUNDING;
202
+ if (oddRounding)
203
+ rules.push(`Non-default rounding mode (${rounding})`);
204
+ if (lucky || oddRounding) {
205
+ gaps.push('Luck or rounding — attacks are chances: sized for 95% with luck on (certain otherwise), holds for at most a 5% fall');
206
+ }
207
+ if (f[GS.ranked] === false)
208
+ rules.push('Practice game');
209
+ const minArmies = f[GS.minArmies];
210
+ if (isInt(minArmies) && minArmies !== DEFAULT_MIN_ARMIES)
211
+ rules.push(`${RULE_MIN_ARMIES} ${minArmies}`);
212
+ const per = f[GS.bonusArmiesPer];
213
+ if (isInt(per) && per > 0) {
214
+ // Modelled since #38 (docs/WARAPP-API.md "Income"): a rule, not a gap.
215
+ rules.push(`Extra army for every ${per} ${per === 1 ? 'territory' : 'territories'}`);
216
+ }
217
+ if (bool('overriddenBonuses'))
218
+ rules.push(RULE_OVERRIDDEN_BONUSES);
219
+ if (bool('attackOnly') || bool('transferOnly')) {
220
+ rules.push(bool('attackOnly') && bool('transferOnly')
221
+ ? 'Can attack-only and transfer-only'
222
+ : bool('attackOnly')
223
+ ? 'Can attack-only'
224
+ : 'Can transfer-only');
225
+ }
226
+ if (ss?.mods) {
227
+ rules.push('Mods');
228
+ gaps.push('Mods');
229
+ }
230
+ // Modelled since #29 (the planner's Local Deployment pools): a rule, not a gap.
231
+ if (bool('localDeployments'))
232
+ rules.push('Local deployments');
233
+ if (bool('noSplit'))
234
+ rules.push('No-split mode');
235
+ const cap = f[GS.armyCap];
236
+ if (isNum(cap)) {
237
+ rules.push(`Army cap: ${cap}× income`);
238
+ gaps.push('Army cap');
239
+ }
240
+ const off = f[GS.offensiveKillRate];
241
+ const def = f[GS.defensiveKillRate];
242
+ if (isNum(off) && isNum(def) && (pct(off) !== pct(DEFAULT_OFFENSIVE) || pct(def) !== pct(DEFAULT_DEFENSIVE))) {
243
+ // Modelled since #28 (every capture is sized at the game's rates): a rule, not a gap.
244
+ rules.push(`Kill rates: offensive ${pct(off)}%, defensive ${pct(def)}%`);
245
+ }
246
+ if (bool('multiAttack'))
247
+ rules.push('Multi-attack');
248
+ if (f[GS.moveOrder] === MOVE_ORDER_NO_LUCK_CYCLE) {
249
+ rules.push('Speed first turn (No-luck cycle move order)');
250
+ gaps.push('Speed first turn — the board stays hidden until Begin (warapp_begin_turn), and whoever orders fastest moves first');
251
+ }
252
+ return { rules, gaps, ...(cards ? { cards } : {}) };
253
+ }
254
+ /** One GameInfoPlayer record, or `undefined` when it does not fit. */
255
+ function lobbyPlayer(p) {
256
+ if (!isObj(p) || p.$type !== GAME_INFO_PLAYER)
257
+ return undefined;
258
+ const f = fieldsOf(p, GAME_INFO_PLAYER, GAME_INFO_PLAYER_FIELDS);
259
+ const id = f[GP.id];
260
+ const state = f[GP.state];
261
+ const team = f[GP.team];
262
+ const color = colorIndexOf(f[GP.color]);
263
+ if (!isInt(id) || !isInt(state) || !isInt(team))
264
+ return undefined;
265
+ const name = playerStateName(state);
266
+ return { id, team, seated: holdsSeat(name), invited: name === 'Invited', color: color ?? null, ai: f[GP.ai] === true };
267
+ }
268
+ /**
269
+ * One decoded GameInfo as an open game and its lobby; `undefined` when it is not a GameInfo or a
270
+ * position read does not hold its type. A record without the client's field count throws.
271
+ */
272
+ function readOpenGame(record) {
273
+ if (!isObj(record) || record.$type !== GAME_INFO)
274
+ return undefined;
275
+ const f = fieldsOf(record, GAME_INFO, GAME_INFO_FIELDS);
276
+ const id = f[GI.gameId];
277
+ const name = f[GI.name];
278
+ const mapId = f[GI.mapId];
279
+ const realTime = f[GI.realTime];
280
+ const seats = f[GI.openSeats];
281
+ const players = f[GI.players];
282
+ if (!isInt(id) || !(name === null || typeof name === 'string') || !isInt(mapId) || !isBool(realTime))
283
+ return undefined;
284
+ if (!(seats === null || isIntList(seats)) || !(players === null || Array.isArray(players)))
285
+ return undefined;
286
+ const openSeatTeams = seats ?? [];
287
+ const all = (players ?? []).map(lobbyPlayer).filter((p) => p !== undefined);
288
+ const seated = all.filter((p) => p.seated);
289
+ const invited = all.filter((p) => p.invited).length;
290
+ const randomTeamsOf = f[GI.randomTeamsOf];
291
+ const random = isInt(randomTeamsOf) && randomTeamsOf > 0 ? randomTeamsOf : undefined;
292
+ // The client's own test (its "Team Game" settings icon): random teams, or any player
293
+ // record — whatever its state — or open seat carrying a team.
294
+ const teamGame = random !== undefined || all.some((p) => carriesTeam(p.team)) || openSeatTeams.some(carriesTeam);
295
+ const settings = readSettings(f[GI.settings]);
296
+ const rules = [...(settings?.rules ?? [])];
297
+ if (teamGame)
298
+ rules.push(random !== undefined ? `Team game (random teams of ${random})` : 'Team game');
299
+ const game = {
300
+ id,
301
+ name: name ?? '',
302
+ url: `https://war.app/MultiPlayer?GameID=${id}`,
303
+ pace: realTime ? 'real-time' : 'multi-day',
304
+ players: seated.length,
305
+ openSeats: openSeatTeams.length,
306
+ seats: seated.length + invited + openSeatTeams.length,
307
+ teamGame,
308
+ mapId,
309
+ entryFeeCoins: isInt(f[GI.entryFee]) ? f[GI.entryFee] : 0,
310
+ prizeCoins: isInt(f[GI.prize]) ? f[GI.prize] : 0,
311
+ rules,
312
+ plannerGaps: settings?.gaps ?? [],
313
+ };
314
+ const boot = f[GI.bootTime];
315
+ if (isNum(boot) && boot > 0 && boot < NEVER_MS) {
316
+ game.bootTime = formatDuration(boot);
317
+ game.bootTimeMinutes = Math.round(boot / 60_000);
318
+ }
319
+ const max = f[GI.maxPlayers];
320
+ if (isInt(max) && max > 0)
321
+ game.maxPlayers = max;
322
+ if (random !== undefined)
323
+ game.randomTeamsOf = random;
324
+ if (teamGame)
325
+ game.openSeatTeams = openSeatTeams;
326
+ if (settings?.cards)
327
+ game.cards = settings.cards;
328
+ const colorsTaken = [...new Set(all.map((p) => p.color).filter((c) => c !== null))];
329
+ return {
330
+ game: orderKeys(game),
331
+ lobby: { seatedPlayerIds: seated.map((p) => p.id), colorsTaken, seated: seated.map((p) => ({ id: p.id, team: p.team, ai: p.ai })) },
332
+ };
333
+ }
334
+ /** `games` with `joined: true` on each lobby where the in-game id `me` holds a seat. */
335
+ export function markJoined(games, lobbies, me) {
336
+ return games.map((g) => (lobbies.get(g.id)?.seatedPlayerIds.includes(me) ? orderKeys({ ...g, joined: true }) : g));
337
+ }
338
+ /** `game` with a lottery verdict ({@link lotteryOf}) set, in the record's key order. */
339
+ export function withLottery(game, verdict) {
340
+ return orderKeys({ ...game, ...verdict });
341
+ }
342
+ const KEY_ORDER = [
343
+ 'id', 'name', 'url', 'pace', 'bootTime', 'bootTimeMinutes', 'players', 'openSeats', 'seats', 'maxPlayers',
344
+ 'teamGame', 'joined', 'lottery', 'lotteryBasis', 'randomTeamsOf', 'openSeatTeams', 'mapId', 'entryFeeCoins', 'prizeCoins', 'cards', 'rules', 'plannerGaps',
345
+ ];
346
+ function orderKeys(g) {
347
+ const out = {};
348
+ for (const k of KEY_ORDER)
349
+ if (g[k] !== undefined)
350
+ out[k] = g[k];
351
+ return out;
352
+ }
353
+ const PAYLOAD_RE = /<script\b[^>]*\bid=["']AllOpenGamesData["'][^>]*>([\s\S]*?)<\/script>/i;
354
+ const HIDDEN_RE = /(\d+)\s+games?\s+(?:is|are)\s+being\s+hidden\s+due\s+to\s+prerequisites/i;
355
+ function hexBytes(hex) {
356
+ const h = hex.replace(/\s+/g, '');
357
+ if (h.length === 0 || h.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(h))
358
+ return undefined;
359
+ const out = new Uint8Array(h.length / 2);
360
+ for (let i = 0; i < out.length; i++)
361
+ out[i] = parseInt(h.slice(2 * i, 2 * i + 2), 16);
362
+ return out;
363
+ }
364
+ const UNREADABLE = "war.app's open-games data could not be read (the client may have changed).";
365
+ /**
366
+ * The open games a signed-in OpenGames page lists. A missing, malformed or truncated payload is a
367
+ * note; a record without the client's field count throws {@link OpenGamesFormatError}.
368
+ */
369
+ export function parseOpenGamesPage(html, bundle) {
370
+ const out = { games: [], lobbies: new Map() };
371
+ const hidden = HIDDEN_RE.exec(html);
372
+ if (hidden)
373
+ out.hiddenByPrerequisites = Number(hidden[1]);
374
+ const m = PAYLOAD_RE.exec(html);
375
+ if (!m) {
376
+ out.note = 'The OpenGames page had no open-games data — war.app may have signed this session out.';
377
+ return out;
378
+ }
379
+ const bytes = hexBytes(m[1] ?? '');
380
+ if (!bytes) {
381
+ out.note = UNREADABLE;
382
+ return out;
383
+ }
384
+ const reader = new Reader(bytes);
385
+ let count;
386
+ try {
387
+ count = reader.int32();
388
+ }
389
+ catch {
390
+ out.note = UNREADABLE;
391
+ return out;
392
+ }
393
+ if (count < 0 || count > MAX_OPEN_GAMES) {
394
+ out.note = UNREADABLE;
395
+ return out;
396
+ }
397
+ let read = 0;
398
+ // One step budget for the whole payload, so the reader's CPU is bounded per page, not per record.
399
+ const budget = { spent: 0 };
400
+ try {
401
+ for (; read < count; read++) {
402
+ const before = reader.position;
403
+ const record = bundle.readClass(GAME_INFO, reader, budget);
404
+ // A GameInfo always takes bytes; one that takes none means the rest would repeat it endlessly.
405
+ if (reader.position === before)
406
+ throw new Error('a GameInfo record took no bytes');
407
+ const read = readOpenGame(record);
408
+ if (read) {
409
+ out.games.push(read.game);
410
+ out.lobbies.set(read.game.id, read.lobby);
411
+ }
412
+ }
413
+ }
414
+ catch (e) {
415
+ // A shifted layout is the client changing, not a damaged payload: say so loudly.
416
+ if (e instanceof OpenGamesFormatError)
417
+ throw e;
418
+ // Records are back to back with no lengths: after a failed one the rest cannot be found.
419
+ out.note = `${UNREADABLE} Read ${read} of ${count} games before: ${e instanceof Error ? e.message : String(e)}`;
420
+ }
421
+ return out;
422
+ }
423
+ /** The games matching `filters`, in war.app's order. */
424
+ export function filterOpenGames(games, filters) {
425
+ const pace = filters.pace ?? 'multi-day';
426
+ const freeOnly = filters.free_only ?? true;
427
+ const noTeams = filters.exclude_teams ?? true;
428
+ const out = games.filter((g) => (pace === 'both' || g.pace === pace) &&
429
+ (!freeOnly || g.entryFeeCoins === 0) &&
430
+ (!noTeams || !g.teamGame) &&
431
+ (filters.max_players === undefined || (g.maxPlayers ?? g.seats) <= filters.max_players));
432
+ return filters.limit === undefined ? out : out.slice(0, filters.limit);
433
+ }
434
+ /**
435
+ * What a lobby's GameFeed settings add to the join preview, which the open-games record does
436
+ * not carry (#132): the neutral-cost screen — a game whose cheapest neutral costs more than a
437
+ * turn of base income expands slowly, and live one cost five turns of income — and Light Fog.
438
+ * Pure; `screen` is absent when the settings name no neutral size.
439
+ */
440
+ export function feedScreen(s) {
441
+ const gaps = [];
442
+ let screen;
443
+ const sizes = [s.initialNonDistributionArmies, s.initialNeutralsInDistribution].filter((n) => n !== undefined && Number.isFinite(n) && n >= 0);
444
+ if (sizes.length) {
445
+ const cheapest = Math.min(...sizes);
446
+ const base = s.minimumArmyBonus ?? DEFAULT_BASE_INCOME;
447
+ const armies = armiesToTake(cheapest, {
448
+ ...(s.offensiveKillRate !== undefined ? { offensiveKillRate: s.offensiveKillRate } : {}),
449
+ ...(s.defensiveKillRate !== undefined ? { defensiveKillRate: s.defensiveKillRate } : {}),
450
+ });
451
+ const turns = armies === null || base <= 0 ? null : Math.round((armies / base) * 10) / 10;
452
+ const passes = armies !== null && armies <= base;
453
+ screen = { cheapestNeutral: cheapest, armiesToTake: armies, baseIncome: base, turnsOfBaseIncome: turns, passes };
454
+ if (!passes) {
455
+ gaps.push(armies === null
456
+ ? `Costly neutrals — at these kill rates the cheapest (${cheapest}) cannot be taken`
457
+ : `Costly neutrals — the cheapest (${cheapest}) takes ${armies} armies, ${turns ?? '∞'} turns of base income (${base}): expansion is slow`);
458
+ }
459
+ }
460
+ if (s.fog === 'LightFog') {
461
+ gaps.push('Light Fog — owners show everywhere but armies only near you; the planner counts every unseen stack as unknown');
462
+ }
463
+ return { ...(screen ? { screen } : {}), gaps };
464
+ }
465
+ /** The owner's joining policy (#134): at most this many seats (1v1 preferred). */
466
+ const POLICY_MAX_SEATS = 4;
467
+ /** …and a boot time of at least 12 hours (owner, 2026-11-14: a 12-hour boot is fine; near-real-time means a boot in minutes). */
468
+ const POLICY_MIN_BOOT_MINUTES = 12 * 60;
469
+ /**
470
+ * The owner's joining policy (#134), checked against an open game and, when GameFeed could read
471
+ * the lobby, its neutral-cost screen: no Commerce, mods or custom scenarios; the cheapest neutral
472
+ * costs at most one turn of base income; at most four seats; a boot time of at least 12 hours (no
473
+ * boot time — war.app's "never" — keeps it); no lotteries (#217: `game.lottery`; a likely one whose
474
+ * map size went unread breaks it too). Lobbies are not counted against the game cap. Pure.
475
+ */
476
+ export function joiningPolicy(game, screen) {
477
+ const breaks = [];
478
+ if (game.rules.some((r) => r.startsWith('Commerce')))
479
+ breaks.push('Commerce — the policy joins no Commerce games');
480
+ if (game.rules.includes('Mods'))
481
+ breaks.push('Mods — the policy joins no mod games');
482
+ if (game.rules.includes('Custom scenario'))
483
+ breaks.push('Custom scenario — the policy joins no custom scenarios');
484
+ if (screen && !screen.passes) {
485
+ breaks.push(screen.armiesToTake === null
486
+ ? 'Costly neutrals — the cheapest cannot be taken at these kill rates; the policy is at most one turn of base income'
487
+ : `Costly neutrals — the cheapest takes ${screen.armiesToTake} armies, ${screen.turnsOfBaseIncome ?? '∞'} turns of base income; the policy is at most one turn`);
488
+ }
489
+ const seats = game.maxPlayers ?? game.seats;
490
+ if (seats > POLICY_MAX_SEATS)
491
+ breaks.push(`${seats} seats — the policy is 1v1 or at most four players`);
492
+ if (game.bootTimeMinutes !== undefined && game.bootTimeMinutes < POLICY_MIN_BOOT_MINUTES) {
493
+ breaks.push(`Boot time ${game.bootTime} — the policy wants at least 12 hours`);
494
+ }
495
+ if (game.lottery === true)
496
+ breaks.push(`Lottery (${game.lotteryBasis ?? 'a tiny map'}) — pure luck; the policy joins no lotteries`);
497
+ // A likely lottery (the lottery shape, map size unread) breaks the policy too: a caller filtering on
498
+ // breaks must not let one through (#217 live check).
499
+ if (game.lottery === null)
500
+ breaks.push(`Likely a lottery (${game.lotteryBasis ?? 'map size not read'}) — the policy joins no lotteries`);
501
+ if (breaks.length)
502
+ return { passes: false, breaks };
503
+ const unchecked = [];
504
+ if (!screen)
505
+ unchecked.push("the cheapest neutral's cost");
506
+ return unchecked.length ? { passes: null, breaks, unchecked } : { passes: true, breaks };
507
+ }
508
+ /**
509
+ * A map of at most this many territories makes a lottery (#217): every player starts on (or next
510
+ * to) everything there is, so the game is decided by the luck of the distribution and the move
511
+ * order — nothing the planner can learn from. The live case: 2 territories, base income 0, one
512
+ * overridden +1 bonus.
513
+ */
514
+ export const LOTTERY_MAX_TERRITORIES = 4;
515
+ /** Whether a lobby's settings fit the lottery shape read so far: base income 0 and overridden bonuses. */
516
+ export function lotteryShape(game) {
517
+ return game.rules.includes(`${RULE_MIN_ARMIES} 0`) && game.rules.includes(RULE_OVERRIDDEN_BONUSES);
518
+ }
519
+ /**
520
+ * Whether an open game is a lottery (#217), from its data, never its name: a map of at most
521
+ * {@link LOTTERY_MAX_TERRITORIES} territories (`territories`, when the map could be read) is one;
522
+ * without the map size, settings with base income 0 and overridden bonuses make it a likely one
523
+ * (`null`). `undefined` when it is not one. Pure.
524
+ */
525
+ export function lotteryOf(game, territories) {
526
+ const shape = [];
527
+ if (game.rules.includes(`${RULE_MIN_ARMIES} 0`))
528
+ shape.push('base income 0');
529
+ if (game.rules.includes(RULE_OVERRIDDEN_BONUSES))
530
+ shape.push('overridden bonuses');
531
+ if (territories !== undefined) {
532
+ if (territories > LOTTERY_MAX_TERRITORIES)
533
+ return undefined;
534
+ return { lottery: true, lotteryBasis: [`${territories}-territory map`, ...shape].join(', ') };
535
+ }
536
+ return lotteryShape(game) ? { lottery: null, lotteryBasis: `${shape.join(', ')}; map size not read` } : undefined;
537
+ }
@@ -0,0 +1,138 @@
1
+ // The outlook log (#178): per game, the strength ratio of every turn this server planned and the
2
+ // latest outlook, plus the final result once a game this server logs is seen finished and, when
3
+ // it was lost, how (#274: `loss`, read from the cached boards; a log may hold only that). Local
4
+ // only, at `<dataDir>/outlook/<gameId>.json`, and name-free (player ids and figures, no names):
5
+ // it is the data the outlook's thresholds are to be calibrated from (OUTLOOK_RATIO is borrowed).
6
+ // Best effort: never throws.
7
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
8
+ import { randomUUID } from 'node:crypto';
9
+ import { join } from 'node:path';
10
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
11
+ /** Turns kept per game (a long game is still a small file). */
12
+ const OUTLOOK_LOG_TURNS = 500;
13
+ export const outlookLogPath = (dir, gameId) => join(dir, 'outlook', `${gameId}.json`);
14
+ /** The log of `gameId` as `playerId` played it; `undefined` when absent, another player's, or unusable. */
15
+ export async function readOutlookLog(dir, gameId, playerId) {
16
+ try {
17
+ const c = JSON.parse(await readFile(outlookLogPath(dir, gameId), 'utf8'));
18
+ if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec(c.turns))
19
+ return undefined;
20
+ return c;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ async function write(dir, log) {
27
+ const path = outlookLogPath(dir, log.gameId);
28
+ await mkdir(join(dir, 'outlook'), { recursive: true, mode: 0o700 });
29
+ // Unique per write: two plans of one game in this process must not share (and race on) a temp file.
30
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
31
+ await writeFile(tmp, JSON.stringify(log), { mode: 0o600 });
32
+ await rename(tmp, path);
33
+ }
34
+ /** Add the outlook's turns to the log and make it the latest. Best effort. */
35
+ export async function recordOutlook(dir, gameId, playerId, outlook) {
36
+ try {
37
+ const log = (await readOutlookLog(dir, gameId, playerId)) ?? { gameId, playerId, turns: {} };
38
+ for (const t of outlook.turns)
39
+ log.turns[String(t.turn)] = {
40
+ mine: t.mine,
41
+ low: t.strongest?.low ?? null,
42
+ high: t.strongest?.high ?? null,
43
+ ratio: t.ratio,
44
+ state: t.state,
45
+ ...(t.figures
46
+ ? {
47
+ figures: {
48
+ mine: { ...t.figures.mine },
49
+ strongest: t.figures.strongest && t.strongest
50
+ ? {
51
+ playerId: t.strongest.playerId,
52
+ ...(t.strongest.team !== undefined ? { team: t.strongest.team } : {}),
53
+ ...t.figures.strongest,
54
+ }
55
+ : null,
56
+ },
57
+ }
58
+ : {}),
59
+ };
60
+ const keep = Object.keys(log.turns)
61
+ .map(Number)
62
+ .sort((a, b) => b - a)
63
+ .slice(0, OUTLOOK_LOG_TURNS);
64
+ log.turns = Object.fromEntries(keep.sort((a, b) => a - b).map((k) => [String(k), log.turns[String(k)]]));
65
+ const last = outlook.turns.at(-1);
66
+ if (last)
67
+ log.latest = { turn: last.turn, state: outlook.state, heldTurns: outlook.heldTurns, basis: outlook.basis };
68
+ await write(dir, log);
69
+ }
70
+ catch {
71
+ // The log is optional.
72
+ }
73
+ }
74
+ /** Record the final result of a game the log already holds; `true` when written. Best effort. */
75
+ export async function recordResult(dir, gameId, playerId, result) {
76
+ try {
77
+ const log = await readOutlookLog(dir, gameId, playerId);
78
+ if (!log)
79
+ return false;
80
+ if (log.result === result)
81
+ return true;
82
+ await write(dir, { ...log, result });
83
+ return true;
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ /** The player whose log `gameId` is; `undefined` when there is none. Never throws. */
90
+ export async function readOutlookPlayer(dir, gameId) {
91
+ try {
92
+ const c = JSON.parse(await readFile(outlookLogPath(dir, gameId), 'utf8'));
93
+ return isRec(c) && c.gameId === gameId && typeof c.playerId === 'number' ? c.playerId : undefined;
94
+ }
95
+ catch {
96
+ return undefined;
97
+ }
98
+ }
99
+ /**
100
+ * Keep how `gameId` was lost (#274) in its log, starting one when this server logged no outlook for
101
+ * it (the boards were cached by another tool); `true` when written, `false` (nothing written) when the
102
+ * log is another account's. Name-free: ids and figures. Best effort.
103
+ */
104
+ export async function recordLoss(dir, gameId, playerId, loss) {
105
+ try {
106
+ // Another account's log (its calibration turns) is never replaced.
107
+ const owner = await readOutlookPlayer(dir, gameId);
108
+ if (owner !== undefined && owner !== playerId)
109
+ return false;
110
+ const log = (await readOutlookLog(dir, gameId, playerId)) ?? { gameId, playerId, turns: {} };
111
+ if (JSON.stringify(log.loss) === JSON.stringify(loss))
112
+ return true;
113
+ await write(dir, { ...log, loss });
114
+ return true;
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ }
120
+ /**
121
+ * When `game` is finished and this server logs it, record the logged player's final GameFeed state
122
+ * as the result; `true` when written. Best effort.
123
+ */
124
+ export async function recordFinalResult(dir, game) {
125
+ if (game.state !== 'Finished')
126
+ return false;
127
+ try {
128
+ const c = JSON.parse(await readFile(outlookLogPath(dir, game.id), 'utf8'));
129
+ if (!isRec(c) || typeof c.playerId !== 'number')
130
+ return false;
131
+ const playerId = c.playerId;
132
+ const state = game.players.find((p) => p.id === playerId)?.state;
133
+ return state === undefined ? false : await recordResult(dir, game.id, playerId, state);
134
+ }
135
+ catch {
136
+ return false;
137
+ }
138
+ }