@chrischall/warapp-mcp 0.4.0 → 0.6.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 (92) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +41 -5
  4. package/dist/analysis/card-support.js +2 -1
  5. package/dist/analysis/card-threats.js +59 -12
  6. package/dist/analysis/game-lessons.js +3 -4
  7. package/dist/analysis/hold-diff.js +3 -1
  8. package/dist/analysis/income-trend.js +38 -0
  9. package/dist/analysis/intel.js +75 -0
  10. package/dist/analysis/opens.js +64 -0
  11. package/dist/analysis/opponent-profile.js +75 -7
  12. package/dist/analysis/opponents.js +2 -2
  13. package/dist/analysis/outlook.js +39 -0
  14. package/dist/analysis/picks.js +91 -12
  15. package/dist/analysis/plan/bonus-attempts.js +105 -0
  16. package/dist/analysis/plan/capture-instead.js +116 -0
  17. package/dist/analysis/plan/captures.js +45 -4
  18. package/dist/analysis/plan/conceded-out.js +13 -2
  19. package/dist/analysis/plan/estimates.js +135 -26
  20. package/dist/analysis/plan/holds.js +31 -3
  21. package/dist/analysis/plan/jabs.js +113 -0
  22. package/dist/analysis/plan/leftover.js +249 -4
  23. package/dist/analysis/plan/orders.js +76 -4
  24. package/dist/analysis/plan/relations.js +21 -1
  25. package/dist/analysis/plan/report.js +69 -3
  26. package/dist/analysis/plan/second-sizing.js +133 -0
  27. package/dist/analysis/plan/shared.js +82 -20
  28. package/dist/analysis/plan/siege.js +303 -0
  29. package/dist/analysis/plan/stand-still.js +7 -3
  30. package/dist/analysis/plan/state.js +8 -0
  31. package/dist/analysis/plan/strike.js +10 -5
  32. package/dist/analysis/plan/targets.js +91 -60
  33. package/dist/analysis/plan/threats.js +41 -6
  34. package/dist/analysis/plan/transfers.js +46 -6
  35. package/dist/analysis/planner.js +234 -16
  36. package/dist/analysis/profile.js +13 -2
  37. package/dist/analysis/stress.js +8 -2
  38. package/dist/bonus-attempt-store.js +55 -0
  39. package/dist/bundle.js +48009 -39350
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +46 -4
  42. package/dist/commerce.js +111 -0
  43. package/dist/index.js +9 -1
  44. package/dist/live.js +43 -0
  45. package/dist/move-order.js +64 -3
  46. package/dist/my-games.js +1 -1
  47. package/dist/normalize.js +17 -0
  48. package/dist/profile-store.js +12 -2
  49. package/dist/protocol/bundle.js +28 -10
  50. package/dist/protocol/codec.js +1 -1
  51. package/dist/protocol/dialect.js +371 -0
  52. package/dist/protocol/interp.js +143 -66
  53. package/dist/protocol/methods.js +95 -34
  54. package/dist/protocol/rpc.js +35 -3
  55. package/dist/push/socketio.js +2 -2
  56. package/dist/relations-store.js +38 -4
  57. package/dist/siege-store.js +49 -0
  58. package/dist/state-bundle.js +525 -0
  59. package/dist/state-cli.js +69 -0
  60. package/dist/surrender-pending.js +4 -4
  61. package/dist/team-cards.js +25 -0
  62. package/dist/tools/award.js +15 -1
  63. package/dist/tools/card-advice.js +16 -5
  64. package/dist/tools/card-plays.js +2 -2
  65. package/dist/tools/card-support-advice.js +2 -1
  66. package/dist/tools/chat-inbox.js +36 -3
  67. package/dist/tools/chat-read-mark.js +3 -1
  68. package/dist/tools/chat.js +65 -6
  69. package/dist/tools/check-plan.js +54 -10
  70. package/dist/tools/commerce-deploy.js +33 -0
  71. package/dist/tools/common.js +31 -0
  72. package/dist/tools/end-of-game.js +5 -3
  73. package/dist/tools/index.js +7 -0
  74. package/dist/tools/my-games.js +10 -3
  75. package/dist/tools/notifications.js +2 -2
  76. package/dist/tools/picks.js +12 -0
  77. package/dist/tools/profile-opponents.js +2 -0
  78. package/dist/tools/push.js +2 -1
  79. package/dist/tools/relations.js +137 -0
  80. package/dist/tools/state.js +227 -0
  81. package/dist/tools/stress-opponents.js +5 -2
  82. package/dist/tools/surrender-pending.js +11 -6
  83. package/dist/tools/survival.js +11 -3
  84. package/dist/tools/team-brief.js +2 -2
  85. package/dist/tools/team.js +12 -3
  86. package/dist/tools/turn.js +332 -60
  87. package/dist/version.js +1 -1
  88. package/manifest.json +10 -2
  89. package/mint.yaml +14 -4
  90. package/package.json +4 -4
  91. package/server.json +2 -2
  92. package/skills/warapp-mcp/SKILL.md +31 -9
package/dist/cards.js CHANGED
@@ -77,9 +77,11 @@ function cardOf(o, key) {
77
77
  *
78
78
  * A team shares one hand and one card limit (the wiki's Team Games). Given several in-game
79
79
  * ids (mine and my teammates'), the hand is every card under any of them, each GUID once.
80
- * UNVERIFIED live (#163): how war.app keys a team's hand — under each player, under one, or
81
- * repeated under all — has not been seen on a team board. So each card of a team hand carries the
82
- * id it was read under (`owner`): the first id given (mine) when it is under that one at all.
80
+ * VERIFIED (V8, #310): the standing keeps each player's cards (`PlayerCards`) under that player's
81
+ * id, and the client's own team hand (GameValidateOrders) is every teammate's entry merged, whole
82
+ * cards by GUID; a live 2v2 board showed two cards under me and three under my teammate, none
83
+ * repeated. Each card of a team hand carries the id it was read under (`owner`): the first id
84
+ * given (mine) when it is under that one at all. The team's limit is `teamCardLimit` (src/team-cards.ts).
83
85
  */
84
86
  export function readHand(info, myInGameId) {
85
87
  const ids = typeof myInGameId === 'number' ? [myInGameId] : [...myInGameId];
@@ -228,7 +230,7 @@ const KEEP_VALUE = {
228
230
  };
229
231
  const INFORMATION_CARDS = new Set([2, 10, 11]);
230
232
  const ONE_V_ONE_CHEAP = new Set([7, 8]); // Gift, Diplomacy
231
- /** Whether a card is mine to play: not read under a teammate's id (V8 unverified). */
233
+ /** Whether a card is mine to play: not read under a teammate's id (V8, #310: the planner leaves theirs to them). */
232
234
  export const isMyCard = (c, me) => me === undefined || c.owner === undefined || c.owner === me;
233
235
  /**
234
236
  * A card's keep value in this game: the information cards (Spy, Reconnaissance, Surveillance)
@@ -300,7 +302,7 @@ export function chooseCardPlays(hand, rules, game = {}) {
300
302
  const theirs = short - Math.min(short, byValue.length);
301
303
  if (theirs > 0) {
302
304
  warnings.push(`${theirs} more card${theirs === 1 ? '' : 's'} must leave the team's hand from your teammates' cards: ` +
303
- 'ask them to play or discard (whether you can play a card read under a teammate is not yet verified).');
305
+ "ask them to play or discard (war.app's order check takes a teammate's card too, but no such play has been sent live yet).");
304
306
  }
305
307
  }
306
308
  const forced = plays.filter((c) => c.type === CARD_ORDER_PRIORITY);
package/dist/chat.js CHANGED
@@ -16,9 +16,12 @@ import { parseFeedTime } from './normalize.js';
16
16
  import { asInt } from './scalars.js';
17
17
  export const GAME_DETAILS_AND_CHAT = 'warlight.shared.GameDetailsAndChat';
18
18
  export const GAME_MESSAGE = 'warlight.shared.GameMessage';
19
- /** GameMessage field positions in read order, and its whole field count. */
20
- const GM = { date: 0, sender: 1, group: 2, id: 4, text: 5, channel: 6, to: 7, turn: 9 };
21
- export const GAME_MESSAGE_FIELDS = 10;
19
+ /**
20
+ * GameMessage field positions in read order, and its whole field count (protocol 243: the shared images,
21
+ * an optional list of strings, at 5, and the reactions, an optional list of records, at 7).
22
+ */
23
+ const GM = { date: 0, sender: 1, group: 2, id: 4, images: 5, text: 6, reactions: 7, channel: 8, to: 9, turn: 11 };
24
+ export const GAME_MESSAGE_FIELDS = 12;
22
25
  /** The public channel's value (any other is a team). */
23
26
  export const PUBLIC_CHANNEL = -1;
24
27
  export const CHAT_CHANNELS = ['public', 'team', 'private', 'unknown'];
@@ -39,8 +42,13 @@ function webLine(m) {
39
42
  const channel = f[GM.channel];
40
43
  const to = f[GM.to];
41
44
  const turn = f[GM.turn];
45
+ const images = f[GM.images];
46
+ const reactions = f[GM.reactions];
42
47
  if (!(date === null || date instanceof Date) || !optInt(sender) || !optInt(group) || !optInt(to) || !optInt(turn))
43
48
  return undefined;
49
+ // Not reported, but checked: a field of another type here means the layout is not 243's.
50
+ if (!(images === null || Array.isArray(images)) || !(reactions === null || Array.isArray(reactions)))
51
+ return undefined;
44
52
  if (!(id === null || typeof id === 'string' || isInt(id)) || typeof text !== 'string' || !isInt(channel))
45
53
  return undefined;
46
54
  const line = { sender, text, turn, channel: 'unknown' };
@@ -114,7 +122,8 @@ export function readGameRefreshChat(bundle, body) {
114
122
  }
115
123
  /**
116
124
  * The SendChat reply: the updated message list, read straight after the result-present flag (each
117
- * message behind its own present flag), oldest first; `undefined` when it cannot be read.
125
+ * message behind its own present flag), oldest first; `undefined` when it cannot be read. The replies of
126
+ * RetrieveChat and RetrievePrivateMessageHistory have the same shape (the client reads them alike).
118
127
  */
119
128
  export function readSendChatReply(bundle, body) {
120
129
  try {
@@ -127,6 +136,39 @@ export function readSendChatReply(bundle, body) {
127
136
  return undefined;
128
137
  }
129
138
  }
139
+ /** RetrieveChat's and RetrievePrivateMessageHistory's reply: a message list as SendChat's. */
140
+ export const readMessageHistoryReply = readSendChatReply;
141
+ /**
142
+ * `lines` with `more` added, each message once (by id; a line with no id is kept as it is), oldest first.
143
+ * GameRefresh and the history reads may both return a message.
144
+ */
145
+ export function mergeChatLines(lines, more) {
146
+ const ids = new Set(lines.flatMap((l) => (l.id === undefined ? [] : [l.id])));
147
+ const out = [...lines];
148
+ for (const l of more) {
149
+ if (l.id !== undefined) {
150
+ if (ids.has(l.id))
151
+ continue;
152
+ ids.add(l.id);
153
+ }
154
+ out.push(l);
155
+ }
156
+ return out.sort(byAge);
157
+ }
158
+ /**
159
+ * The oldest message id received among `lines` that `pick` keeps (decimal text), the "older than" marker of a
160
+ * history read; `undefined` when there is none (the read then asks from the newest).
161
+ */
162
+ export function oldestId(lines, pick) {
163
+ let best;
164
+ for (const l of lines) {
165
+ if (l.id === undefined || !/^\d{1,20}$/.test(l.id) || !pick(l))
166
+ continue;
167
+ if (best === undefined || BigInt(l.id) < BigInt(best))
168
+ best = l.id;
169
+ }
170
+ return best;
171
+ }
130
172
  const MESSAGE_ID = /^\d{1,20}$/;
131
173
  const higher = (a, b) => (a === undefined || BigInt(b) > BigInt(a) ? b : a);
132
174
  /**
@@ -0,0 +1,111 @@
1
+ /** The commerce rules of a game, or `undefined` outside a commerce game or when its settings were not read. */
2
+ export function commerceRules(s) {
3
+ if (!s?.commerce || !s.commerceRules)
4
+ return undefined;
5
+ const r = s.commerceRules;
6
+ return {
7
+ armyCostMultiplier: r.armyCostMultiplier ?? 0,
8
+ cityBaseCost: r.cityBaseCost ?? null,
9
+ territoryCityCostIncrease: r.territoryCityCostIncrease ?? 0,
10
+ globalCityCostIncrease: r.globalCityCostIncrease ?? 0,
11
+ cityIncome: r.cityIncome ?? 0,
12
+ };
13
+ }
14
+ const whole = (n) => (Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 0);
15
+ /** The armies `gold` buys in one turn at multiplier `m` (the client's GameSettings function). */
16
+ export function armiesForGold(gold, m) {
17
+ let left = whole(gold);
18
+ const batch = whole(m);
19
+ if (batch === 0)
20
+ return left;
21
+ let armies = 0;
22
+ for (let price = 1; left > 0; price++) {
23
+ const n = Math.min(batch, Math.floor(left / price));
24
+ if (n === 0)
25
+ break;
26
+ armies += n;
27
+ left -= n * price;
28
+ }
29
+ return armies;
30
+ }
31
+ /** What `armies` cost in one turn at multiplier `m` (the client's GameSettings function). */
32
+ export function goldForArmies(armies, m) {
33
+ let left = whole(armies);
34
+ const batch = whole(m);
35
+ if (batch === 0)
36
+ return left;
37
+ let gold = 0;
38
+ for (let price = 1; left > 0; price++) {
39
+ gold += price * Math.min(batch, left);
40
+ left -= batch;
41
+ }
42
+ return gold;
43
+ }
44
+ /** What `gold` buys as this turn's deploy: the armies, their cost and the gold left (which carries over). */
45
+ export function deployBudget(gold, m) {
46
+ const g = whole(gold);
47
+ const armies = armiesForGold(g, m);
48
+ const cost = goldForArmies(armies, m);
49
+ return { gold: g, armies, cost, left: g - cost };
50
+ }
51
+ /**
52
+ * The armies this turn's gold buys: the standing's gold when read (it already holds what was saved and any Sanctions,
53
+ * since war.app pays it), else the modelled income.
54
+ */
55
+ export function commerceDeploy(rules, standingGold, modelGold) {
56
+ const source = standingGold !== undefined ? 'standing' : 'model';
57
+ const b = deployBudget(standingGold ?? modelGold, rules.armyCostMultiplier);
58
+ return { source, ...b, armyCostMultiplier: rules.armyCostMultiplier };
59
+ }
60
+ /**
61
+ * What a purchase order's cities cost, by the client's formula (`GameOrderPurchase`, client 6.08.0.2): per city,
62
+ * CityBaseCost + (cities on that territory so far) × TerritoryCityCostIncrease + (my cities so far, everywhere — the
63
+ * ones I own, then each earlier city of this order) × GlobalCityCostIncrease, the global count starting at 0 when its
64
+ * increase is 0. `existing` gives the cities already on each territory, `myCities` all I own. `undefined` in a game
65
+ * that allows no cities.
66
+ */
67
+ export function cityPurchaseCost(rules, order, existing, myCities) {
68
+ if (rules.cityBaseCost === null)
69
+ return undefined;
70
+ let total = 0;
71
+ let global = rules.globalCityCostIncrease === 0 ? 0 : whole(myCities);
72
+ for (const { territoryId, count } of order) {
73
+ let onTerritory = whole(existing.get(territoryId) ?? 0);
74
+ for (let n = 0; n < count; n++) {
75
+ total += rules.cityBaseCost + onTerritory * rules.territoryCityCostIncrease + global * rules.globalCityCostIncrease;
76
+ onTerritory++;
77
+ global++;
78
+ }
79
+ }
80
+ return total;
81
+ }
82
+ /**
83
+ * #332, advice only (never an order of the plan): the cheapest city I can place on an interior territory this turn,
84
+ * and how many turns its income takes to repay its cost (`paysBackInTurns`, `worthIt` within `horizon` turns). A
85
+ * city's gold comes out of this turn's deploy. `undefined` when the game allows no cities or pays nothing for them,
86
+ * no interior territory is mine, or the gold does not cover one.
87
+ */
88
+ export function cityAdvice(rules, sites, gold, horizon) {
89
+ if (rules.cityBaseCost === null || !(rules.cityIncome > 0))
90
+ return undefined;
91
+ const myCities = sites.reduce((n, s) => n + s.cities, 0);
92
+ let best;
93
+ for (const s of sites) {
94
+ if (!s.interior)
95
+ continue;
96
+ const cost = cityPurchaseCost(rules, [{ territoryId: s.territoryId, count: 1 }], new Map([[s.territoryId, s.cities]]), myCities);
97
+ if (!best || cost < best.cost || (cost === best.cost && s.territoryId < best.territoryId))
98
+ best = { territoryId: s.territoryId, cost };
99
+ }
100
+ if (!best || best.cost > gold)
101
+ return undefined;
102
+ const paysBackInTurns = Math.ceil(best.cost / rules.cityIncome);
103
+ return {
104
+ territoryId: best.territoryId,
105
+ cost: best.cost,
106
+ cityIncome: rules.cityIncome,
107
+ paysBackInTurns,
108
+ worthIt: paysBackInTurns <= horizon,
109
+ order: { territory: best.territoryId, count: 1 },
110
+ };
111
+ }
package/dist/index.js CHANGED
@@ -13,11 +13,19 @@
13
13
  // user's signed-in war.app tab by the fetchproxy bridge (src/transport-bridge.ts).
14
14
  // One bridge per process, started at boot; start() only loads the identity —
15
15
  // the port binds on the first request.
16
+ //
17
+ // `warapp-mcp export-state --out <file>` (src/state-cli.ts) writes this install's history for
18
+ // warapp_import_state instead of serving; it is dispatched before the env file is read, so it never
19
+ // loads a credential.
16
20
  import { loadDotenvSafely, runMcp } from '@chrischall/mcp-utils';
17
21
  import { envFilePath } from './config.js';
22
+ import { runExportCli } from './state-cli.js';
18
23
  import { registerAllTools } from './tools/index.js';
19
24
  import { createWarappBridge } from './transport-bridge.js';
20
25
  import { VERSION } from './version.js';
26
+ if (process.argv[2] === 'export-state') {
27
+ process.exit(await runExportCli(process.argv.slice(3)));
28
+ }
21
29
  await loadDotenvSafely({ path: envFilePath() });
22
30
  const bridge = createWarappBridge();
23
31
  // A failed start (e.g. an unwritable identity dir) is not a boot failure: the
@@ -28,6 +36,6 @@ await runMcp({
28
36
  version: VERSION,
29
37
  tools: [(server) => registerAllTools(server, { bridge })],
30
38
  shutdown: { onSignal: () => bridge.transport().close() },
31
- banner: `[warapp-mcp] v${VERSION} — war.app (Warzone) advisor; joining, leaving or surrendering a game, accepting a surrender, Begin, picks, turn orders, withdrawing them, chat, marking notifications and chat read, deleting notifications and linking a session are confirm-gated. Set WARAPP_EMAIL and WARAPP_API_TOKEN. ` +
39
+ banner: `[warapp-mcp] v${VERSION} — war.app (Warzone) advisor; joining, leaving or surrendering a game, accepting a surrender, Begin, picks, turn orders, withdrawing them, chat, marking notifications and chat read, deleting notifications, importing local history and linking a session are confirm-gated. Set WARAPP_EMAIL and WARAPP_API_TOKEN. ` +
32
40
  'This project was developed and is maintained by AI (Claude). Use at your own discretion.',
33
41
  });
package/dist/live.js CHANGED
@@ -76,6 +76,19 @@ function specialUnitOf(u) {
76
76
  const kind = UNIT_KINDS[u.$type] ?? 'unknown';
77
77
  return kind === 'unknown' ? { kind, type: u.$type, id, owner } : { kind, id, owner };
78
78
  }
79
+ /** The structure type of a City in a territory standing's structures dict (`StructureType2`, client 6.08.0.2). */
80
+ export const CITY_STRUCTURE = '1';
81
+ /** The cities a territory standing's structures dict (its only dict keyed by strings) holds; 0 without one. */
82
+ function citiesOf(values) {
83
+ for (const v of values) {
84
+ const list = entries(v);
85
+ if (!list?.length || !list.every((e) => typeof e.key === 'string' && typeof e.value === 'number'))
86
+ continue;
87
+ const city = list.find((e) => e.key === CITY_STRUCTURE);
88
+ return typeof city?.value === 'number' && city.value > 0 ? city.value : 0;
89
+ }
90
+ return 0;
91
+ }
79
92
  function territoryOf(key, ts) {
80
93
  const values = fields(ts);
81
94
  const ints = values.filter((v) => typeof v === 'number');
@@ -120,6 +133,9 @@ function territoryOf(key, ts) {
120
133
  const units = armyFields.find((v) => Array.isArray(v));
121
134
  if (!armiesHidden && units?.length)
122
135
  out.specialUnits = units.map(specialUnitOf);
136
+ const cities = citiesOf(values);
137
+ if (cities > 0)
138
+ out.cities = cities;
123
139
  return out;
124
140
  }
125
141
  /**
@@ -174,6 +190,31 @@ export function currentStanding(info) {
174
190
  }
175
191
  return fields(info).find((v) => isType(v, GAME_STANDING));
176
192
  }
193
+ /** The resource type of gold (`ResourceType.Gold`, client 6.08.0.2). */
194
+ export const GOLD_RESOURCE = 1;
195
+ /**
196
+ * #332, commerce games: the gold `inGameId` holds at the start of this turn, from the current standing's Resources —
197
+ * its one field shaped player → (resource type → amount) (GameStanding's 7th field, client 6.08.0.2; VERIFIED live
198
+ * 2026-11-17: 25 and 8 in two games, each the turn's income with nothing carried). Under fog it lists only my own
199
+ * entry, so another player's gold is never read. `undefined` when there is no standing, no such field, two of them
200
+ * (never guessed), or no gold entry for that player.
201
+ */
202
+ export function standingGold(info, inGameId) {
203
+ const standing = currentStanding(info);
204
+ if (!standing)
205
+ return undefined;
206
+ const isPair = (x) => Array.isArray(x) && x.length === 2 && typeof x[0] === 'number' && typeof x[1] === 'number';
207
+ const resources = fields(standing).filter((v) => {
208
+ const list = entries(v);
209
+ return (!!list?.length &&
210
+ list.every((e) => typeof e.key === 'number' && Array.isArray(e.value) && e.value.every(isPair)));
211
+ });
212
+ if (resources.length !== 1)
213
+ return undefined;
214
+ const mine = entries(resources[0]).find((e) => e.key === inGameId);
215
+ const gold = mine?.value?.find(([type]) => type === GOLD_RESOURCE);
216
+ return gold ? gold[1] : undefined;
217
+ }
177
218
  /** The territories of a decoded LatestGameInfo; `null` when it carries no standing. */
178
219
  export function standingFromInfo(info) {
179
220
  const standing = currentStanding(info);
@@ -272,6 +313,8 @@ export function toBoardState(territories, players) {
272
313
  playerId: byInGame.get(u.owner)?.id ?? u.owner,
273
314
  }));
274
315
  }
316
+ if (t.cities)
317
+ out.cities = t.cities;
275
318
  return out;
276
319
  }),
277
320
  };
@@ -17,6 +17,7 @@
17
17
  // write of a process.
18
18
  import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
19
19
  import { join } from 'node:path';
20
+ import { armiesToTake } from './analysis/combat.js';
20
21
  /** Where a game's first mover is kept. */
21
22
  export const firstMoverPath = (dir, gameId) => join(dir, 'move-order', `${gameId}.json`);
22
23
  /** A game's file not written for this long is deleted (finished or abandoned games). */
@@ -26,12 +27,17 @@ const pruned = new Set();
26
27
  const other = (m) => (m === 'me' ? 'opponent' : 'me');
27
28
  const isTurn = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
28
29
  const isMover = (v) => v === 'me' || v === 'opponent';
29
- const isSource = (v) => v === 'explicit' || v === 'award';
30
+ const isSource = (v) => v === 'explicit' || v === 'award' || v === 'inferred';
30
31
  /** The first mover on `turn`, from one known turn: the same every second turn, the other in between. */
31
32
  export function projectFirstMover(seen, turn) {
32
33
  return Math.abs(turn - seen.turn) % 2 === 0 ? seen.firstMover : other(seen.firstMover);
33
34
  }
34
- const RANK = { award: 0, explicit: 1 };
35
+ const RANK = { award: 0, inferred: 1, explicit: 2 };
36
+ const KEPT_LABEL = {
37
+ explicit: (t) => `the first_mover given on turn ${t}`,
38
+ inferred: (t) => `my first order's result on turn ${t}`,
39
+ award: (t) => `the award of picks (kept on turn ${t})`,
40
+ };
35
41
  const said = (m, turn) => `${m === 'me' ? 'you move' : 'the opponent moves'} first on turn ${turn}`;
36
42
  /**
37
43
  * Who moves first on `turn` and how it is known, with the record to keep (absent when nothing new
@@ -48,13 +54,23 @@ export function resolveFirstMover(input) {
48
54
  const kept = input.remembered;
49
55
  const fromKept = () => kept && {
50
56
  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})`,
57
+ label: KEPT_LABEL[kept.source](kept.turn),
52
58
  resolved: { firstMover: projectFirstMover(kept, turn), source: 'remembered', from: { turn: kept.turn, source: kept.source } },
53
59
  };
54
60
  if (explicit)
55
61
  candidates.push({ firstMover: explicit, label: 'first_mover', resolved: { firstMover: explicit, source: 'explicit' }, record: { turn, firstMover: explicit, source: 'explicit' } });
56
62
  if (kept?.source === 'explicit')
57
63
  candidates.push(fromKept());
64
+ const inf = input.inferred;
65
+ if (inf && !same(inf, kept))
66
+ candidates.push({
67
+ firstMover: projectFirstMover(inf, turn),
68
+ label: KEPT_LABEL.inferred(inf.turn),
69
+ resolved: { firstMover: projectFirstMover(inf, turn), source: 'remembered', from: { turn: inf.turn, source: 'inferred' } },
70
+ record: inf,
71
+ });
72
+ if (kept?.source === 'inferred')
73
+ candidates.push(fromKept());
58
74
  if (award)
59
75
  candidates.push({ firstMover: award, label: 'the award of picks', resolved: { firstMover: award, source: 'award' }, record: { turn, firstMover: award, source: 'award' } });
60
76
  if (kept?.source === 'award')
@@ -72,6 +88,51 @@ export function resolveFirstMover(input) {
72
88
  const record = used.record && (!kept || RANK[used.record.source] >= RANK[kept.source]) && !same(used.record, kept) ? used.record : undefined;
73
89
  return { resolved: used.resolved, ...(record ? { record } : {}), warnings };
74
90
  }
91
+ /**
92
+ * #299: who moved first on the previous turn, read from my own first order on it. Moving first, my
93
+ * first order runs before any order of the opponent's, against the target as it stood plus deploys
94
+ * only, which never shrink it: so when that order captured a territory its sender could not have
95
+ * taken from the armies the target held at the start of the turn, the opponent's order ran before
96
+ * it (the stack had left). Read only when the result is exact (0% luck, straight rounding), the
97
+ * order is the only one of mine into the target, no commander was on either side, and no card could
98
+ * explain it: none of mine touching the source or target, nor an Order Priority or Order Delay of
99
+ * mine, nor one the opponent may hold (`orderPriorityPossible`: it reorders that turn alone). Gives
100
+ * `null` when it proves nothing. The other case of #299 (an attack of mine that failed against
101
+ * armies moved in first) is not read: my losses cannot be told apart from the opponent's attacks on
102
+ * my source. Pure.
103
+ */
104
+ export function inferFirstMover(input) {
105
+ const { before, after, orders, me, opponent, rates = {} } = input;
106
+ if (input.orderPriorityPossible || !orders.cards)
107
+ return null;
108
+ if ((rates.luckModifier ?? 0) !== 0 || (rates.roundingMode !== undefined && rates.roundingMode !== 'StraightRound'))
109
+ return null;
110
+ const sent = orders.sent ?? orders.moves;
111
+ const first = sent[0];
112
+ if (!first || ('transferOnly' in first && first.transferOnly) || first.commander)
113
+ return null;
114
+ const move = orders.moves[0];
115
+ if (!move || move.from !== first.from || move.to !== first.to)
116
+ return null;
117
+ if (sent.some((m, i) => i > 0 && m.to === move.to) || orders.moves.some((m, i) => i > 0 && m.to === move.to))
118
+ return null;
119
+ if (orders.cards.some((c) => c.card === 'Order Priority' || c.card === 'Order Delay' || [c.from, c.to, c.target].some((t) => t === move.from || t === move.to)))
120
+ return null;
121
+ const at = (b, id) => b.territories.find((t) => t.territoryId === id);
122
+ const held = (t, p) => t !== undefined && t.owner.kind === 'player' && t.owner.playerId === p && typeof t.armies === 'number' && !t.specialUnits?.length;
123
+ const source = at(before, move.from);
124
+ const target = at(before, move.to);
125
+ if (!held(source, me) || !held(target, opponent))
126
+ return null;
127
+ const now = at(after, move.to);
128
+ if (now?.owner.kind !== 'player' || now.owner.playerId !== me)
129
+ return null;
130
+ const deployed = orders.deploys.filter((d) => d.territoryId === move.from).reduce((s, d) => s + d.armies, 0);
131
+ const guard = rates.oneArmyStandsGuard === false ? 0 : 1;
132
+ const sendable = Math.min(move.armies, source.armies + deployed - guard);
133
+ const need = armiesToTake(target.armies, rates);
134
+ return need !== null && need > sendable ? { turn: input.turn, firstMover: 'opponent', source: 'inferred' } : null;
135
+ }
75
136
  /**
76
137
  * #215 review: a first mover the user gave (`first_mover`, now or on a remembered turn, alternated)
77
138
  * is verified; one read from the award of picks — the wiki's rule, not verified live — is not, and
package/dist/my-games.js CHANGED
@@ -26,7 +26,7 @@ export const gameStateName = (code) => GAME_STATE_NAMES[code] ?? String(code);
26
26
  const GAME_WAITING = 2;
27
27
  const GAME_PLAYING = 3;
28
28
  const GAME_DISTRIBUTING = 5;
29
- const GAME_FINISHED = 4;
29
+ export const GAME_FINISHED = 4;
30
30
  const PLAYER_PLAYING = 2;
31
31
  /** GameInfo field positions in read order, and its whole field count (src/open-games.ts reads the same record). */
32
32
  const GI = { gameId: 7, name: 13, lastTurn: 14, players: 16, state: 22 };
package/dist/normalize.js CHANGED
@@ -190,6 +190,23 @@ export function normalizeSettings(raw) {
190
190
  }
191
191
  if (r.Commerce !== undefined && r.Commerce !== null)
192
192
  s.commerce = isRec(r.Commerce) ? Object.keys(r.Commerce).length > 0 : true;
193
+ if (isRec(r.Commerce) && Object.keys(r.Commerce).length > 0) {
194
+ const c = r.Commerce;
195
+ const rules = {};
196
+ const pairs = [
197
+ ['armyCostMultiplier', c.ArmyCostMultiplier],
198
+ ['cityBaseCost', c.CityBaseCost],
199
+ ['territoryCityCostIncrease', c.TerritoryCityCostIncrease],
200
+ ['globalCityCostIncrease', c.GlobalCityCostIncrease],
201
+ ['cityIncome', c.CityIncome],
202
+ ];
203
+ for (const [k, v] of pairs) {
204
+ const n = asInt(v);
205
+ if (n !== undefined)
206
+ rules[k] = n;
207
+ }
208
+ s.commerceRules = rules;
209
+ }
193
210
  if (r.Mods !== undefined && r.Mods !== null) {
194
211
  const empty = r.Mods === '' || (isRec(r.Mods) && Object.keys(r.Mods).length === 0);
195
212
  s.mods = Array.isArray(r.Mods) ? r.Mods.length : empty ? 0 : -1;
@@ -97,6 +97,10 @@ function primitivesOf(v) {
97
97
  const lost = ids(v.lostToMe);
98
98
  if (took === undefined || !lost)
99
99
  return undefined;
100
+ // #361: absent in a record kept before it (unknown); a non-integer makes it unknown too.
101
+ const jabs = v.jabs === null ? null : isInt(v.jabs) ? v.jabs : undefined;
102
+ // #295: likewise.
103
+ const topUp = v.topUp === null || typeof v.topUp === 'boolean' ? v.topUp : undefined;
100
104
  return {
101
105
  contact: v.contact,
102
106
  attackedMe: v.attackedMe,
@@ -105,6 +109,8 @@ function primitivesOf(v) {
105
109
  stack: s === null ? null : { top: s.top, total: s.total },
106
110
  tookFromMe: took,
107
111
  lostToMe: lost,
112
+ ...(jabs !== undefined ? { jabs } : {}),
113
+ ...(topUp !== undefined ? { topUp } : {}),
108
114
  };
109
115
  }
110
116
  const seatsOf = (v) => isRec(v) && PROFILE_FORMATS.includes(v.format) && isInt(v.players) && ids(v.ai) && ids(v.turnedAI)
@@ -319,13 +325,17 @@ function habitsFrom(v) {
319
325
  const f = rateOf(v.firstStrike);
320
326
  const rt = rateOf(v.retaliate);
321
327
  const rk = rateOf(v.retake);
328
+ // #361: absent in counts kept before it: none read.
329
+ const jb = v.jab === undefined ? { e: 0, n: 0 } : rateOf(v.jab);
330
+ // #295: likewise.
331
+ const tu = v.capacityTopUp === undefined ? { e: 0, n: 0 } : rateOf(v.capacityTopUp);
322
332
  const x = v.reinforceExtra;
323
333
  const s = v.stacking;
324
- if (!r || !a || !f || !rt || !rk || !num(v.turns))
334
+ if (!r || !a || !f || !rt || !rk || !jb || !tu || !num(v.turns))
325
335
  return undefined;
326
336
  if (!isRec(x) || !num(x.n) || !num(x.sum) || !isRec(s) || !num(s.n) || !num(s.sum) || !num(s.sq))
327
337
  return undefined;
328
- return { reinforce: r, reinforceExtra: { n: x.n, sum: x.sum }, attack: a, firstStrike: f, stacking: { n: s.n, sum: s.sum, sq: s.sq }, retaliate: rt, retake: rk, turns: v.turns };
338
+ return { reinforce: r, reinforceExtra: { n: x.n, sum: x.sum }, attack: a, firstStrike: f, stacking: { n: s.n, sum: s.sum, sq: s.sq }, retaliate: rt, retake: rk, jab: jb, capacityTopUp: tu, turns: v.turns };
329
339
  }
330
340
  function totalsFrom(v) {
331
341
  const out = {};
@@ -24,7 +24,8 @@ import { createHash, randomBytes } from 'node:crypto';
24
24
  import { chmod, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
25
25
  import { join } from 'node:path';
26
26
  import { withPathLock } from '../path-lock.js';
27
- import { BundleInterpreter, parseBundle, READER_HELPERS, REQUIRED_HELPERS, } from './interp.js';
27
+ import { PROTOCOL_VERSION } from './codec.js';
28
+ import { BundleInterpreter, parseBundle, } from './interp.js';
28
29
  /** A page that loads the game client (the homepage does not). */
29
30
  const DEFAULT_PAGE_URL = 'https://war.app/MultiPlayer';
30
31
  /** The only host the bundle is downloaded from (exactly this host: no subdomain, no port). */
@@ -107,6 +108,17 @@ export class WarappBundle {
107
108
  constructor(src, version, opts = {}) {
108
109
  this.version = version;
109
110
  this.interp = new BundleInterpreter(parseBundle(src), opts);
111
+ // Every request is framed in this server's protocol, and war.app answers in the protocol a request
112
+ // declares, so the replies are in PROTOCOL_VERSION's layout: a client whose readers default to another
113
+ // protocol would read them in its own layout. Such a build (a newer release, or an old stand-in) is
114
+ // refused here, like a client whose helpers cannot be checked (docs/CLIENT-RELEASES.md).
115
+ const protocol = this.interp.bundleProtocol;
116
+ if (opts.version === undefined && protocol !== undefined && protocol !== PROTOCOL_VERSION) {
117
+ throw new BundleError('protocol-mismatch', `war.app's client bundle ${version} speaks protocol ${protocol}, and this server speaks ${PROTOCOL_VERSION}; ` +
118
+ 'its readers would read the replies in the wrong layout, so it is not used. ' +
119
+ (protocol > PROTOCOL_VERSION ? 'The client changed and this server needs an update.' : 'It is an older client.'));
120
+ }
121
+ this.protocol = protocol;
110
122
  // The built-in reader helpers are pinned to one client release while the bundle floats:
111
123
  // refuse a bundle whose own helpers read differently, rather than decode it wrongly (#131).
112
124
  this.dialectCheck = this.interp.verifyDialect();
@@ -116,7 +128,7 @@ export class WarappBundle {
116
128
  }
117
129
  // The count, flag and byte helpers decode every army count, fog flag and unit count: one this
118
130
  // check cannot verify could be a swapped same-width read, which no later check catches (#148).
119
- const unverifiedRequired = REQUIRED_HELPERS.map((n) => `${READER_HELPERS}.${n}`).filter((k) => this.dialectCheck.unverified.includes(k));
131
+ const unverifiedRequired = this.interp.requiredHelpers.map((n) => `${this.interp.helperClass}.${n}`).filter((k) => this.dialectCheck.unverified.includes(k));
120
132
  if (unverifiedRequired.length) {
121
133
  throw new BundleError('dialect-unverified', `war.app's client bundle ${version} defines ${unverifiedRequired.join(', ')} in a way this server cannot check ` +
122
134
  `(${unverifiedRequired.map((k) => this.dialectCheck.reasons?.[k] ?? 'unverified').join('; ')}); those read every ` +
@@ -125,6 +137,12 @@ export class WarappBundle {
125
137
  }
126
138
  /** The built-in reader helpers checked against this bundle's own definitions at load. */
127
139
  dialectCheck;
140
+ /** The protocol version the bundle's readers default to, when it can be read from the bundle. */
141
+ protocol;
142
+ /** The reader names were derived from this bundle (false: the built-in v6.07 names). */
143
+ get derivedDialect() {
144
+ return this.interp.derived;
145
+ }
128
146
  /** What this bundle's decoding rests on, for the tools to show (#148). */
129
147
  report() {
130
148
  const { verified, unverified, reasons } = this.dialectCheck;
@@ -157,15 +175,15 @@ export class WarappBundle {
157
175
  }
158
176
  }
159
177
  /**
160
- * The client release the built-in readers (src/protocol/interp.ts `DEFAULT_DIALECT`) and every
161
- * hand-written encoder are written for: client v6.07, protocol 242. war.app's CDN still serves it by
162
- * version, byte for byte, and war.app still answers a protocol-242 request in 242's layout. So when
163
- * the current client is refused (2026-11-17: 639304451701341657 renamed every reader on protocol
164
- * 243), this one stands in and decodes those replies exactly. Only bytes with this digest are used.
178
+ * The pinned known-good client: v6.08.0.2, protocol 243, the release every hand-written encoder and
179
+ * reader of this server is written for (#340). It stands in for a current client refused at load when
180
+ * no recorded build does, only with this digest. war.app's CDN ignores `?v=` and serves the current
181
+ * build, so it can be downloaded by version only while Cloudflare still caches that URL
182
+ * (docs/CLIENT-RELEASES.md): the copy kept in the data dir is what a stand-in really rests on.
165
183
  */
166
184
  export const KNOWN_GOOD_BUNDLE = {
167
- version: '639294131571648437',
168
- digest: 'dec5cf174f6affb9e4c08802534cf8c6c6496eff977847aaf1497535e3371404',
185
+ version: '639304508939095333',
186
+ digest: '3c55e2d08681d05661eb350b3d72d02f25729130bb78dc9c5d3b1febd73febd1',
169
187
  };
170
188
  /** The CDN URL of a client release, by version (the location {@link discoverBundleUrl} pins). */
171
189
  const bundleUrlOf = (version) => `https://${BUNDLE_HOST}${BUNDLE_PATH}?v=${version}`;
@@ -325,7 +343,7 @@ async function readVerified(file, digest) {
325
343
  return null;
326
344
  }
327
345
  /** Whether `e` is the load-time refusal of a client this server cannot read (#131, #148). */
328
- const isDialectRefusal = (e) => e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified');
346
+ const isDialectRefusal = (e) => e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified' || e.kind === 'protocol-mismatch');
329
347
  /** Write `src` into the cache as `name` (`0700` directories, an atomic `0600` file). */
330
348
  async function cacheBundle(dataDir, dir, name, src) {
331
349
  await ensurePrivateDir(dataDir);
@@ -19,7 +19,7 @@
19
19
  // parameters. Replies carry a byte (1 → MessageExtrasDown follows), a kind byte
20
20
  // (5 → a server error {code, message} follows) and the method's result.
21
21
  export const PREAMBLE = 1514664249;
22
- export const PROTOCOL_VERSION = 242;
22
+ export const PROTOCOL_VERSION = 243;
23
23
  const REPLY_FLAG = 0x8000;
24
24
  /** Milliseconds from the Unix epoch to 2000-01-01T00:00:00Z, the protocol's date epoch. */
25
25
  export const DATE_EPOCH_MS = Date.UTC(2000, 0, 1);