@chrischall/warapp-mcp 0.5.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 (80) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +37 -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 +47965 -39683
  40. package/dist/cards.js +7 -5
  41. package/dist/chat.js +35 -1
  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/normalize.js +17 -0
  47. package/dist/profile-store.js +12 -2
  48. package/dist/protocol/methods.js +60 -5
  49. package/dist/protocol/rpc.js +8 -0
  50. package/dist/relations-store.js +38 -4
  51. package/dist/siege-store.js +49 -0
  52. package/dist/state-bundle.js +525 -0
  53. package/dist/state-cli.js +69 -0
  54. package/dist/team-cards.js +25 -0
  55. package/dist/tools/award.js +15 -1
  56. package/dist/tools/card-advice.js +16 -5
  57. package/dist/tools/card-plays.js +2 -2
  58. package/dist/tools/card-support-advice.js +2 -1
  59. package/dist/tools/chat-inbox.js +4 -0
  60. package/dist/tools/chat.js +65 -6
  61. package/dist/tools/check-plan.js +54 -10
  62. package/dist/tools/commerce-deploy.js +33 -0
  63. package/dist/tools/common.js +31 -0
  64. package/dist/tools/end-of-game.js +5 -3
  65. package/dist/tools/index.js +7 -0
  66. package/dist/tools/picks.js +12 -0
  67. package/dist/tools/profile-opponents.js +2 -0
  68. package/dist/tools/relations.js +137 -0
  69. package/dist/tools/state.js +227 -0
  70. package/dist/tools/stress-opponents.js +5 -2
  71. package/dist/tools/survival.js +11 -3
  72. package/dist/tools/team-brief.js +2 -2
  73. package/dist/tools/team.js +12 -3
  74. package/dist/tools/turn.js +332 -60
  75. package/dist/version.js +1 -1
  76. package/manifest.json +10 -2
  77. package/mint.yaml +14 -4
  78. package/package.json +4 -4
  79. package/server.json +2 -2
  80. 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
@@ -122,7 +122,8 @@ export function readGameRefreshChat(bundle, body) {
122
122
  }
123
123
  /**
124
124
  * The SendChat reply: the updated message list, read straight after the result-present flag (each
125
- * 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).
126
127
  */
127
128
  export function readSendChatReply(bundle, body) {
128
129
  try {
@@ -135,6 +136,39 @@ export function readSendChatReply(bundle, body) {
135
136
  return undefined;
136
137
  }
137
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
+ }
138
172
  const MESSAGE_ID = /^\d{1,20}$/;
139
173
  const higher = (a, b) => (a === undefined || BigInt(b) > BigInt(a) ? b : a);
140
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/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 = {};
@@ -11,6 +11,8 @@ export const Method = {
11
11
  GetLatestGameInfo: 41,
12
12
  SendChat: 43,
13
13
  RegisterChatView: 44,
14
+ RetrieveChat: 45,
15
+ RetrievePrivateMessageHistory: 46,
14
16
  GetGameSettings: 49,
15
17
  GetMyGames: 51,
16
18
  AcceptGame: 61,
@@ -304,11 +306,42 @@ export function writeRegisterChatViewParams(w, p) {
304
306
  writeMarkDict(w, p.privateMarks);
305
307
  writeMarkDict(w, p.groupMarks);
306
308
  }
309
+ /**
310
+ * The "older than" marker of a chat history read when nothing has been received on that channel yet: the
311
+ * client's 9999E14 (its initial lowest-id-received), written as text.
312
+ */
313
+ export const OLDEST_CHAT_MARKER = '999900000000000000';
314
+ const MESSAGE_ID_TEXT = /^\d{1,20}$/;
315
+ function beforeMarker(m) {
316
+ if (m === undefined)
317
+ return OLDEST_CHAT_MARKER;
318
+ if (!MESSAGE_ID_TEXT.test(m))
319
+ throw new RangeError(`not a message id: ${JSON.stringify(m)}`);
320
+ return m;
321
+ }
322
+ /**
323
+ * RetrieveChat(auth, …) — the web client's "show older messages" for the public and team channels (#363). READ
324
+ * FROM THE CLIENT BUNDLE's writer: the int32 game id, then per channel the lowest message id the client has
325
+ * received (string; 9999E14 when none). Reply: a result flag, then a list of optional `GameMessage` (as the
326
+ * SendChat reply). GameRefresh with `-1` markers leaves out messages war.app counts as seen (an own team
327
+ * message, seen live 2026-11-19); this read returns them.
328
+ */
329
+ export function writeRetrieveChatParams(w, p) {
330
+ w.int32(p.gameId).string(beforeMarker(p.publicBefore)).string(beforeMarker(p.teamBefore));
331
+ }
332
+ /**
333
+ * RetrievePrivateMessageHistory(auth, …) — the client's history button of one private conversation (#387). READ
334
+ * FROM THE CLIENT BUNDLE's writer: the int32 game id, the lowest message id received in it (string; 9999E14 when
335
+ * none), the counterpart's in-game id (int32). Reply as RetrieveChat's.
336
+ */
337
+ export function writeRetrievePrivateMessageHistoryParams(w, p) {
338
+ w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.counterpart);
339
+ }
307
340
  /**
308
341
  * SendChat(auth, …) per docs/WEB-PROTOCOL.md (read from the client's
309
342
  * serializer; the owner verifies it live): game id, text, channel, optional
310
343
  * private recipient, optional game-group id (absent), two marker strings
311
- * (absent), two optional "last seen" dicts (absent). An optional int32 is a
344
+ * (`-1`: seen nothing), two optional "last seen" dicts (absent). An optional int32 is a
312
345
  * present flag then the value.
313
346
  */
314
347
  export function writeSendChatParams(w, p) {
@@ -317,9 +350,11 @@ export function writeSendChatParams(w, p) {
317
350
  w.bool(false);
318
351
  else
319
352
  w.bool(true).int32(p.recipient);
353
+ // The two chat markers are the last message seen on each channel: war.app parses them as numbers
354
+ // (ParseLongSafe), so a null one is refused (server error 1); a client that has seen nothing sends `-1`.
320
355
  w.bool(false) // game-group id
321
- .string(null)
322
- .string(null)
356
+ .string(NO_CHAT_MARKER)
357
+ .string(NO_CHAT_MARKER)
323
358
  .bool(false)
324
359
  .bool(false)
325
360
  // Protocol 243 added a last, optional list of strings (the shared images a message carries): absent.
@@ -347,6 +382,17 @@ export function writeDeployOrder(w, o) {
347
382
  .int32(o.armies);
348
383
  writeOrderBase(w, o.playerId);
349
384
  }
385
+ const ORDER_TAG_PURCHASE = 24;
386
+ /**
387
+ * Encode a Purchase order (`GameOrderPurchase`, client 6.08.0.2's writer; UNVERIFIED live): tag 24, a present bool,
388
+ * an int32 count of territory → cities entries, each two int32s, then the order base.
389
+ */
390
+ export function writePurchaseOrder(w, o) {
391
+ w.u8(ORDER_TAG_PURCHASE).bool(true).int32(o.cities.length);
392
+ for (const c of o.cities)
393
+ w.int32(c.territoryId).int32(c.count);
394
+ writeOrderBase(w, o.playerId);
395
+ }
350
396
  /** The special-unit tag of a Commander (`warlight.shared.Commander`, from the bundle; docs/WEB-PROTOCOL.md). */
351
397
  const SPECIAL_UNIT_COMMANDER = 1;
352
398
  /**
@@ -408,9 +454,11 @@ export const TARGETED_CARD_PLAYS = new Set([
408
454
  ]);
409
455
  /**
410
456
  * The card plays whose encoding is read from the bundle but not yet sent live (V9): the preview warns
411
- * and the result carries `cardPlayCheck`. Airlift left it once verified live 2026-11-16 (#296).
457
+ * and the result carries `cardPlayCheck`. Airlift left it once verified live 2026-11-16 (#296), Diplomacy
458
+ * once verified live 2026-11-18 (#369: played through warapp_submit_turn, read in force on later boards).
412
459
  */
413
- export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => kind !== 'Airlift'));
460
+ const VERIFIED_CARD_PLAYS = new Set(['Airlift', 'Diplomacy']);
461
+ export const UNVERIFIED_CARD_PLAYS = new Set([...TARGETED_CARD_PLAYS].filter((kind) => !VERIFIED_CARD_PLAYS.has(kind)));
414
462
  function need(v, card, what) {
415
463
  if (v === undefined)
416
464
  throw new Error(`A ${card} card play needs ${what}.`);
@@ -490,6 +538,8 @@ export function writeDiscardOrder(w, o) {
490
538
  * from the bundle's `GameOrderDiscard.Vd`).
491
539
  */
492
540
  export const TurnPhase = {
541
+ /** #332, bundle (`GameOrderPurchase`), UNVERIFIED live: a commerce game's purchase, before every other order. */
542
+ Purchases: 0,
493
543
  Discards: 10,
494
544
  OrderPriorityCards: 12,
495
545
  /** Spy, Reconnaissance and Surveillance (bundle, UNVERIFIED live). */
@@ -534,6 +584,8 @@ export function turnPhaseOf(o) {
534
584
  return TurnPhase.Attacks;
535
585
  if (o.kind === 'discard')
536
586
  return TurnPhase.Discards;
587
+ if (o.kind === 'purchase')
588
+ return TurnPhase.Purchases;
537
589
  return CARD_PHASE[o.card];
538
590
  }
539
591
  /**
@@ -609,6 +661,9 @@ export function writeSendOrdersParams(w, gameId, playerId, orders, turnNumber) {
609
661
  else if (o.kind === 'discard') {
610
662
  writeDiscardOrder(w, { playerId, cardId: o.cardId });
611
663
  }
664
+ else if (o.kind === 'purchase') {
665
+ writePurchaseOrder(w, { playerId, cities: o.cities });
666
+ }
612
667
  else if (o.kind === 'deploy') {
613
668
  writeDeployOrder(w, { playerId, territoryId: o.territoryId, armies: o.armies });
614
669
  }
@@ -45,6 +45,14 @@ export const SERVER_ERROR_MESSAGES = {
45
45
  254: 'Sorry, your slot was assigned to someone else by the game creator. Please ask the game creator to open up your slot.',
46
46
  473: "You don't have enough coins to join this game. Please deposit some coins and try again.",
47
47
  750: 'Sorry, the slot you joined is no longer available. Please try again with a different slot.',
48
+ // #332, commerce games: the client names these but shows no wording; these are ours.
49
+ 593: 'war.app worked out a different gold cost for these orders than the client did (ExpectedCostInaccurate).',
50
+ 596: 'In a commerce game every deploy must be paid for in gold (DeploymentsCannotBeFree).',
51
+ 597: 'You do not have enough gold for these orders (InsufficientGold): deploy fewer armies or buy fewer cities.',
52
+ 599: 'Only one purchase order may be sent in a turn (CannotSendDuplicatePurchaseOrders).',
53
+ 600: 'A city can only be built on a territory you hold (CannotBuildCityOnAnotherPlayersTerritory).',
54
+ 601: 'The number of cities to build cannot be negative (CannotBuildNegativeCitites).',
55
+ 602: 'This game does not allow cities (CannotBuildCities).',
48
56
  };
49
57
  /** The longest slice of an unmapped server message shown to the caller. */
50
58
  const MAX_SERVER_MESSAGE = 200;