@chrischall/warapp-mcp 0.10.0 → 0.12.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 (65) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +10 -8
  4. package/dist/analysis/cards-in-effect.js +10 -1
  5. package/dist/analysis/chat-mentions.js +17 -0
  6. package/dist/analysis/commander-fog.js +126 -0
  7. package/dist/analysis/end-game-stats.js +149 -0
  8. package/dist/analysis/local-deploy.js +3 -2
  9. package/dist/analysis/outlook.js +133 -55
  10. package/dist/analysis/picks.js +125 -0
  11. package/dist/analysis/plan/commander.js +3 -2
  12. package/dist/analysis/plan/deploy-estimates.js +11 -7
  13. package/dist/analysis/plan/estimates.js +63 -9
  14. package/dist/analysis/plan/relations.js +29 -14
  15. package/dist/analysis/plan/shared.js +21 -0
  16. package/dist/analysis/plan/threats.js +74 -5
  17. package/dist/analysis/player-record.js +31 -1
  18. package/dist/analysis/player.js +23 -10
  19. package/dist/analysis/relations.js +83 -9
  20. package/dist/analysis/scale.js +71 -0
  21. package/dist/analysis/single-pick.js +356 -0
  22. package/dist/bundle.js +3099 -809
  23. package/dist/chat-links.js +141 -0
  24. package/dist/finished-store.js +30 -0
  25. package/dist/index.js +1 -1
  26. package/dist/known-mods.js +33 -0
  27. package/dist/map-stats.js +24 -2
  28. package/dist/mod-alliances.js +217 -0
  29. package/dist/mod-data.js +160 -0
  30. package/dist/my-games.js +53 -2
  31. package/dist/normalize.js +7 -0
  32. package/dist/outlook-log.js +13 -0
  33. package/dist/player-record-store.js +5 -3
  34. package/dist/protocol/methods.js +14 -2
  35. package/dist/relations-store.js +29 -1
  36. package/dist/tools/card-advice.js +29 -9
  37. package/dist/tools/card-effects.js +3 -1
  38. package/dist/tools/card-support-advice.js +1 -1
  39. package/dist/tools/chat-advice.js +1 -1
  40. package/dist/tools/chat-inbox.js +67 -10
  41. package/dist/tools/chat.js +46 -8
  42. package/dist/tools/check-plan.js +115 -11
  43. package/dist/tools/close-finished-game.js +110 -0
  44. package/dist/tools/commander-check.js +80 -1
  45. package/dist/tools/diplomacy.js +11 -2
  46. package/dist/tools/end-of-game.js +57 -3
  47. package/dist/tools/game.js +7 -3
  48. package/dist/tools/how-lost.js +68 -5
  49. package/dist/tools/index.js +21 -1
  50. package/dist/tools/map.js +50 -1
  51. package/dist/tools/mod-alliances.js +191 -0
  52. package/dist/tools/my-games.js +12 -1
  53. package/dist/tools/pace.js +44 -0
  54. package/dist/tools/picks.js +41 -1
  55. package/dist/tools/relations.js +120 -7
  56. package/dist/tools/session.js +20 -6
  57. package/dist/tools/stress-opponents.js +25 -2
  58. package/dist/tools/turn.js +338 -42
  59. package/dist/tools/write-kit.js +1 -0
  60. package/dist/version.js +1 -1
  61. package/manifest.json +10 -2
  62. package/mint.yaml +3 -4
  63. package/package.json +1 -1
  64. package/server.json +2 -2
  65. package/skills/warapp-mcp/SKILL.md +73 -11
@@ -0,0 +1,141 @@
1
+ // Territory and bonus links in chat (docs/WEB-PROTOCOL.md "Territory and bonus links in chat").
2
+ //
3
+ // war.app's chat editor shows a link as <span class="ujsChatLink" data-link="t_<id>">Name</span>
4
+ // (`b_<id>` for a bonus). Before posting, the client serializes the editor to `<a t_<id>>Name</a>` and
5
+ // rewrites that (ChatTab's send) to the bare token `<a t=<id>>` — the name and `</a>` are dropped — and the
6
+ // receiving client (ChatChunk's parser) splits a message on `<a t=…>` / `<a b=…>` and renders the id
7
+ // through the map: the territory's or bonus's name, "(???)" for an id the map lacks. The territory token
8
+ // and the bonus token are VERIFIED live (owner, 2026-11-23: sent messages read back through GameRefresh, the
9
+ // links decoded and the text rendered by name).
10
+ //
11
+ // A caller writes `[[t:<id or name>]]` / `[[b:<id or name>]]` in a message; `link_territories` also links
12
+ // every whole-word mention of a territory name. Names are other players' maps' words: callers delimit them.
13
+ import { McpToolError } from '@chrischall/mcp-utils';
14
+ import { UNTRUSTED_LIST_MAX, untrustedList, untrustedText } from './tools/common.js';
15
+ /** A caller's link marker: `[[t:…]]` or `[[b:…]]`. */
16
+ const MARKER = /\[\[([tb]):([^[\]]*)\]\]/g;
17
+ /** The wire token war.app's client sends and parses (its parser takes 1–10 characters of id). */
18
+ const TOKEN = /<a ([tb])=(\d{1,10})>/g;
19
+ /** A marker or a wire token: never auto-linked inside. */
20
+ const PROTECTED = /\[\[[tb]:[^[\]]*\]\]|<a [tb]=\d{1,10}>/g;
21
+ const kindOf = (c) => (c === 't' ? 'territory' : 'bonus');
22
+ const token = (kind, id) => `<a ${kind === 'territory' ? 't' : 'b'}=${id}>`;
23
+ const plural = (kind) => (kind === 'territory' ? 'territories' : 'bonuses');
24
+ export const hasChatLinkMarkers = (text) => new RegExp(MARKER.source).test(text);
25
+ const itemsOf = (map, kind) => (kind === 'territory' ? map.territories : map.bonuses);
26
+ function ambiguous(kind, raw, hits) {
27
+ const label = (i) => `${untrustedText(i.name)} (${i.id})`;
28
+ return new McpToolError(`${JSON.stringify(raw)} matches ${hits.length} ${plural(kind)}: ${untrustedList(hits, UNTRUSTED_LIST_MAX, label)}; nothing was sent.`, { hint: `Link the one you mean by its id: [[${kind === 'territory' ? 't' : 'b'}:<id>]].` });
29
+ }
30
+ /** A marker's target: an id on the map first, else the one case-insensitive exact name (never part of a name). */
31
+ export function resolveChatLink(map, kind, input) {
32
+ const raw = input.trim();
33
+ if (!raw)
34
+ throw new McpToolError(`Name a ${kind} in the link (an id or a name); nothing was sent.`);
35
+ const items = itemsOf(map, kind);
36
+ if (/^\d+$/.test(raw)) {
37
+ const byId = items.find((i) => i.id === Number(raw));
38
+ if (byId)
39
+ return byId;
40
+ }
41
+ const q = raw.toLowerCase();
42
+ const hits = items.filter((i) => i.name.toLowerCase() === q);
43
+ if (hits.length === 1)
44
+ return hits[0];
45
+ if (hits.length === 0) {
46
+ throw new McpToolError(`No ${kind} on this game's map matches ${JSON.stringify(raw)}; nothing was sent.`, {
47
+ hint: `Use the ${kind}'s id, or its full name as the map spells it (warapp_get_map lists them).`,
48
+ });
49
+ }
50
+ throw ambiguous(kind, raw, hits);
51
+ }
52
+ const WORD = /[\p{L}\p{N}_]/u;
53
+ const isWord = (c) => c !== undefined && WORD.test(c);
54
+ /**
55
+ * Every whole-word, case-insensitive mention of a territory name in `text`, the longest name first where names
56
+ * overlap at one place, scanning left to right (a match is never re-entered). A name two territories share is refused.
57
+ */
58
+ function autoLink(text, map, push) {
59
+ const byName = new Map();
60
+ for (const t of map.territories) {
61
+ const k = t.name.trim().toLowerCase();
62
+ if (k)
63
+ byName.set(k, [...(byName.get(k) ?? []), t]);
64
+ }
65
+ const names = [...byName.keys()].sort((a, b) => b.length - a.length);
66
+ const lower = text.toLowerCase();
67
+ let plain = '';
68
+ for (let i = 0; i < text.length;) {
69
+ let hit;
70
+ if (!isWord(text[i - 1])) {
71
+ hit = names.find((n) => lower.startsWith(n, i) && !isWord(text[i + n.length]) && n.length > 0);
72
+ }
73
+ if (hit === undefined) {
74
+ plain += text[i];
75
+ i++;
76
+ continue;
77
+ }
78
+ const hits = byName.get(hit);
79
+ if (hits.length > 1)
80
+ throw ambiguous('territory', text.slice(i, i + hit.length), hits);
81
+ const t = hits[0];
82
+ if (plain)
83
+ push(plain, plain);
84
+ plain = '';
85
+ push(token('territory', t.id), t.name, { kind: 'territory', id: t.id, name: t.name });
86
+ i += hit.length;
87
+ }
88
+ if (plain)
89
+ push(plain, plain);
90
+ }
91
+ /**
92
+ * A caller's message with its `[[t:…]]` / `[[b:…]]` markers (and, with `linkTerritories`, every territory name
93
+ * it mentions) turned into the client's link tokens. With nothing to link the message comes back unchanged.
94
+ * Throws a `McpToolError` (nothing sent) on a name that is unknown or ambiguous.
95
+ */
96
+ export function encodeChatLinks(message, map, opts = {}) {
97
+ let wire = '';
98
+ let rendered = '';
99
+ const links = [];
100
+ const push = (w, r, link) => {
101
+ wire += w;
102
+ rendered += r;
103
+ if (link)
104
+ links.push(link);
105
+ };
106
+ const plainPart = (s) => (opts.linkTerritories ? autoLink(s, map, push) : push(s, s));
107
+ let at = 0;
108
+ for (const m of message.matchAll(PROTECTED)) {
109
+ plainPart(message.slice(at, m.index));
110
+ at = m.index + m[0].length;
111
+ const marker = /^\[\[([tb]):([^[\]]*)\]\]$/.exec(m[0]);
112
+ if (marker) {
113
+ const kind = kindOf(marker[1]);
114
+ const it = resolveChatLink(map, kind, marker[2]);
115
+ push(token(kind, it.id), it.name, { kind, id: it.id, name: it.name });
116
+ }
117
+ else {
118
+ // A token already in the message passes as written (a caller's own `<a t=ID>`).
119
+ push(m[0], m[0]);
120
+ }
121
+ }
122
+ plainPart(message.slice(at));
123
+ if (!links.length)
124
+ return { wire: message, rendered: message, links: [] };
125
+ return { wire, rendered, links };
126
+ }
127
+ /**
128
+ * A received message's link tokens decoded: `text` with each token rendered as its name (an id the map lacks,
129
+ * or no map, keeps the raw token) and `links` in order. A message with no token comes back unchanged.
130
+ */
131
+ export function decodeChatLinks(text, map) {
132
+ const links = [];
133
+ const out = text.replace(TOKEN, (raw, c, digits) => {
134
+ const kind = kindOf(c);
135
+ const id = Number(digits);
136
+ const it = map ? itemsOf(map, kind).find((i) => i.id === id) : undefined;
137
+ links.push({ kind, id, name: it?.name ?? null });
138
+ return it ? it.name : raw;
139
+ });
140
+ return { text: out, links };
141
+ }
@@ -32,6 +32,7 @@
32
32
  // switches the pass off (nothing read or written).
33
33
  import { readdir, readFile, stat, unlink, utimes } from 'node:fs/promises';
34
34
  import { join } from 'node:path';
35
+ import { highestIncomes } from './analysis/end-game-stats.js';
35
36
  import { profileFormatOf } from './analysis/opponent-profile.js';
36
37
  import { writeJsonAtomic } from './map-store.js';
37
38
  import { finishedGameKey, playerKey } from './player-record-store.js';
@@ -228,8 +229,37 @@ export function finishedRecordOf(p) {
228
229
  : {}),
229
230
  ...(stored ?? {}),
230
231
  ...(kept?.omitted ? { boardsOmitted: kept.omitted } : {}),
232
+ ...(h && p.stats ? { stats: storedStats(p.stats, h, key) } : {}),
231
233
  };
232
234
  }
235
+ /** #523: the stats as stored: by key, each with its highest income and its armies and territories by history board. Pure. */
236
+ export function storedStats(stats, c, key) {
237
+ const highest = highestIncomes(c.turns);
238
+ const players = {};
239
+ for (const [id, st] of stats.players) {
240
+ const { deployed, luck, offensiveLuck, defensiveLuck, ...totals } = st;
241
+ // The client stops a line once the seat is out: the boards before the turn it left.
242
+ const kept = c.turns.filter((t) => !totals.left || t.afterTurn < totals.left.turn);
243
+ const at = (t) => t.players.get(id);
244
+ players[key(id)] = {
245
+ ...totals,
246
+ highestIncome: highest.get(id) ?? 0,
247
+ series: {
248
+ armies: kept.map((t) => {
249
+ const pt = at(t);
250
+ return pt ? pt.armies : 0;
251
+ }),
252
+ territories: kept.map((t) => at(t)?.territories ?? 0),
253
+ income: kept.map((t) => at(t)?.income ?? 0),
254
+ deployed,
255
+ luck,
256
+ offensiveLuck,
257
+ defensiveLuck,
258
+ },
259
+ };
260
+ }
261
+ return { turnsRead: stats.turnsRead, players };
262
+ }
233
263
  /** The opening and closing boards a record keeps, and how many between them it leaves out. Pure. */
234
264
  function boundedBoards(boards) {
235
265
  const max = MAX_RECORD_BOARDS_HEAD + MAX_RECORD_BOARDS_TAIL;
package/dist/index.js CHANGED
@@ -36,6 +36,6 @@ await runMcp({
36
36
  version: VERSION,
37
37
  tools: [(server) => registerAllTools(server, { bridge })],
38
38
  shutdown: { onSignal: () => bridge.transport().close() },
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. ` +
39
+ banner: `[warapp-mcp] v${VERSION} — war.app (Warzone) advisor; joining, leaving or surrendering a game, closing out a finished 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. ` +
40
40
  'This project was developed and is maintained by AI (Claude). Use at your own discretion.',
41
41
  });
@@ -0,0 +1,33 @@
1
+ // War.app mods whose published source has been read, and what each changes (#165's mods warning made
2
+ // mod-aware). A mod listed here with `turnRules: false` changes no rule the planner models while turns are
3
+ // played, so a plan in a game running only such mods does not say its rules may not hold. Every other mod
4
+ // id keeps the general warning. Pure.
5
+ /** The Local Deployment Helper mod's id (game 45736172's settings: `Mods[].ModID` "336"). */
6
+ export const LOCAL_DEPLOYMENT_HELPER = 336;
7
+ /**
8
+ * Read 2026-11-23 from the published source (JustMe003/WarzoneMods, `Local_Deployment_Helper` and
9
+ * `LDHelper2`, ModVersion 3.0): it has no server turn hook (no `Server_AdvanceTurn_*`), only
10
+ * `Server_Created` (at game creation: turns Local Deployment on, optionally "attack by percentage", and —
11
+ * its default "bonus overrider" — sets to 0 every bonus on a territory that is in more than one non-zero
12
+ * bonus except the one with fewest territories, so Local Deployment's pools never overlap; those values
13
+ * reach us as the game's `OverriddenBonuses`, which the model applies), `Server_GameCustomMessage` (saves a
14
+ * player's helper inputs) and web-client hooks: at a new turn, with the order list empty, its default
15
+ * `AutoDeploy` adds last turn's orders and updated deploys to the client's list (only in the web client; a
16
+ * `warapp_submit_turn` send replaces the whole list), and a marker custom order `[LDH_V3]` it removes again
17
+ * before a commit.
18
+ */
19
+ const MODS = [
20
+ {
21
+ id: LOCAL_DEPLOYMENT_HELPER,
22
+ name: 'Local Deployment Helper',
23
+ turnRules: false,
24
+ note: 'This game runs the Local Deployment Helper (mod 336), which changes no rule during a turn (its published ' +
25
+ 'source has no turn hook). At creation it turned Local Deployment on and set to 0 every bonus but the ' +
26
+ 'smallest on a territory in more than one bonus — those are the game\'s overridden bonuses, which this plan ' +
27
+ 'applies: a 0-value bonus has no deploy pool, so only the free income (the base income — MinimumArmyBonus, or ' +
28
+ 'territories ÷ BonusArmyPer when larger — and card armies) lands on its territories. In the web client it may add last ' +
29
+ "turn's orders to an empty order list when the game is opened there; a warapp_submit_turn send replaces the " +
30
+ 'whole list. Read from its source version 3.0; a later version may differ.',
31
+ },
32
+ ];
33
+ export const KNOWN_MODS = new Map(MODS.map((m) => [m.id, m]));
package/dist/map-stats.js CHANGED
@@ -1,3 +1,20 @@
1
+ // Per-map statistics from finished games (S6). Pure and deterministic: no I/O,
2
+ // ties on ascending id.
3
+ //
4
+ // A finished game is first reduced to a compact {@link GameRecord} (what the
5
+ // stats cache stores — ids, wins and turn numbers, never a name), and
6
+ // {@link mapStats} aggregates records per map: the most-picked starting
7
+ // territories, the win rate by starting bonus (the bonus a player's picks
8
+ // anchored), the turn of each player's first bonus completion, and the sample
9
+ // size. A sample of fewer than {@link MIN_SAMPLE} games, and a bonus win rate on
10
+ // fewer than {@link MIN_RATE_SAMPLE} players, is always flagged.
11
+ //
12
+ // The history shape is UNVERIFIED (docs/WARAPP-API.md "Board state"): records
13
+ // are read with the same loose parser as the planner's trend
14
+ // (`historyBoards`), and a game whose history does not parse still records its
15
+ // winner, with no starts. Such a game says nothing about starts or bonuses, so
16
+ // {@link mapStats} leaves it out of every figure and counts it apart (#132).
17
+ import { applyBonusOverrides } from './analysis/overrides.js';
1
18
  import { historyBoards, historyReport } from './trend.js';
2
19
  /** Below this many games a rate is reported only with a warning. */
3
20
  export const MIN_SAMPLE = 5;
@@ -18,8 +35,13 @@ const ownedBy = (board, playerId) => new Set(board.territories
18
35
  .map((t) => t.territoryId));
19
36
  /** Positive bonuses with territory members (superbonus members are not counted). */
20
37
  const scoringBonuses = (map) => map.bonuses.filter((b) => b.value > 0 && b.territoryIds.length > 0).sort((a, b) => a.id - b.id);
21
- /** Reduce a finished game (with `GetHistory`) to its stats record. Never throws on a bad history. */
22
- export function recordFromGame(game, map) {
38
+ /**
39
+ * Reduce a finished game (with `GetHistory`) to its stats record. Never throws on a bad history.
40
+ * `map` carries the map's own values; the game's `OverriddenBonuses` are applied here, so a bonus
41
+ * the game made worthless is neither an anchor nor a first completion.
42
+ */
43
+ export function recordFromGame(game, base) {
44
+ const map = applyBonusOverrides(base, game.settings);
23
45
  const boards = historyBoards(game.history, game.players, game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {});
24
46
  const start = boards.find(({ board }) => board.territories.some((t) => t.owner.kind === 'player'));
25
47
  const later = start ? boards.filter((b) => b.turn >= start.turn) : [];
@@ -0,0 +1,217 @@
1
+ // The "Diplomacy 2" mod's alliances (mod 191), read from the game details. UNVERIFIED live: no game this
2
+ // account plays had an alliance to read on 2026-11-23 (the one mod-191 game was a lobby, where the mod
3
+ // had written nothing yet).
4
+ //
5
+ // Where the data lives (read from the client bundle; the location VERIFIED live 2026-11-23 on a lobby, with
6
+ // another mod's table in it): GameRefresh (40) asked with `nonChat` answers `GameDetailsAndChat`, whose
7
+ // fourth field (0-based 3) is MY player data of each mod (a dict of mod id → XML text, the client's
8
+ // `Mod.PlayerGameData`), and whose game (`GameWL`, field 1) carries every mod's public data at field 8
9
+ // (the same dict shape, `Mod.PublicGameData`). The XML is the client's mod-table format (src/mod-data.ts).
10
+ //
11
+ // What the mod keeps (its published source, FizzerWL/ExampleMods `Diplomacy2Mod`; that the mod running
12
+ // as 191 is that source is UNVERIFIED):
13
+ // - public `Alliances`: a Lua array of { ID, PlayerOne (the proposer), PlayerTwo (who accepted) }, in-game
14
+ // player ids. No turn is kept: `ID` (from the mod's one counter, shared with proposals) orders them.
15
+ // - my `PendingProposals`: proposals TO me only ({ ID, PlayerOne = from, PlayerTwo = me }); a proposal I
16
+ // sent sits in the other player's private data, which I cannot read.
17
+ // - my `Alerts`: { ID, Message } — "<name> has broken their alliance with you", until the web client shows them.
18
+ // Its rules: an attack (GameOrderAttackTransfer) between two players allied at the START of the turn is
19
+ // skipped by the game, both ways; a break is a custom order in the breaker's own orders
20
+ // ("Diplomacy2_BreakAlliance_<other in-game id>"), applied at the END of that turn — so the alliance holds
21
+ // through the turn the break is entered, and either side can attack from the next. Nobody but the breaker
22
+ // can see a break before it applies. Bombs and other cards are not stopped by it.
23
+ //
24
+ // Pure. Never throws: a shape this server does not understand is `undefined` (unknown).
25
+ import { fields, isObj } from './protocol/decoded.js';
26
+ import { GAME_DETAILS_AND_CHAT } from './chat.js';
27
+ import { GAME_WL, GAME_WL_FIELDS } from './surrender-pending.js';
28
+ import { intField, luaArray, parseModTable } from './mod-data.js';
29
+ /** The "Diplomacy 2" mod's id (GameFeed settings `Mods[].ModID`, VERIFIED live on game 45736172's settings). */
30
+ export const DIPLOMACY2_MOD_ID = 191;
31
+ /** The custom-order payload of a break, before the other player's in-game id. */
32
+ export const BREAK_PAYLOAD_PREFIX = 'Diplomacy2_BreakAlliance_';
33
+ /** GameDetailsAndChat: where my mod data is (0-based, read order). */
34
+ const GDC_PLAYER_MOD_DATA = 3;
35
+ /** GameWL: where the public mod data is (0-based, read order). */
36
+ const GW_PUBLIC_MOD_DATA = 8;
37
+ /** A dict of int → string as decoded (pairs), `null` read as empty; `undefined` when it is not one. */
38
+ function intStringDict(v) {
39
+ if (v === null)
40
+ return new Map();
41
+ if (!Array.isArray(v))
42
+ return undefined;
43
+ const out = new Map();
44
+ for (const pair of v) {
45
+ if (!Array.isArray(pair) || pair.length !== 2 || !Number.isInteger(pair[0]))
46
+ return undefined;
47
+ if (pair[1] === null)
48
+ continue;
49
+ if (typeof pair[1] !== 'string')
50
+ return undefined;
51
+ out.set(pair[0], pair[1]);
52
+ }
53
+ return out;
54
+ }
55
+ /**
56
+ * The mod data of a GameRefresh reply asked with `nonChat` (the body at the result-present flag);
57
+ * `undefined` without a result or game, or in a shape this server does not know. Never throws.
58
+ */
59
+ export function readModData(bundle, body) {
60
+ try {
61
+ if (!body.bool())
62
+ return undefined;
63
+ const ret = bundle.readClass(GAME_DETAILS_AND_CHAT, body);
64
+ if (!isObj(ret) || ret.$type !== GAME_DETAILS_AND_CHAT)
65
+ return undefined;
66
+ const rf = fields(ret);
67
+ const game = rf[1];
68
+ if (!isObj(game) || game.$type !== GAME_WL)
69
+ return undefined;
70
+ const gf = fields(game);
71
+ if (gf.length !== GAME_WL_FIELDS)
72
+ return undefined;
73
+ const pub = intStringDict(gf[GW_PUBLIC_MOD_DATA]);
74
+ const mine = rf.length > GDC_PLAYER_MOD_DATA ? intStringDict(rf[GDC_PLAYER_MOD_DATA]) : undefined;
75
+ if (!pub || !mine)
76
+ return undefined;
77
+ return { public: pub, mine };
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ }
83
+ const tableOrEmpty = (xml) => (xml === undefined ? new Map() : parseModTable(xml));
84
+ /** The entries of an optional Lua array field; `undefined` when it is there but not an array of tables. */
85
+ function records(t, key) {
86
+ const v = t.get(key);
87
+ if (v === undefined || v === null)
88
+ return [];
89
+ const list = luaArray(v);
90
+ if (!list?.every((x) => x instanceof Map))
91
+ return undefined;
92
+ return list;
93
+ }
94
+ /**
95
+ * Diplomacy 2's state from one read (`undefined`: a table this server does not understand). No data for
96
+ * the mod means it stored nothing yet: no alliance, proposal or alert.
97
+ */
98
+ export function diplomacy2From(read) {
99
+ const pub = tableOrEmpty(read.public.get(DIPLOMACY2_MOD_ID));
100
+ const mine = tableOrEmpty(read.mine.get(DIPLOMACY2_MOD_ID));
101
+ if (!pub || !mine)
102
+ return undefined;
103
+ const a = records(pub, 'Alliances');
104
+ const p = records(mine, 'PendingProposals');
105
+ const al = records(mine, 'Alerts');
106
+ if (!a || !p || !al)
107
+ return undefined;
108
+ const alliances = [];
109
+ for (const r of a) {
110
+ const id = intField(r, 'ID');
111
+ const proposer = intField(r, 'PlayerOne');
112
+ const accepter = intField(r, 'PlayerTwo');
113
+ if (id === undefined || proposer === undefined || accepter === undefined)
114
+ return undefined;
115
+ alliances.push({ id, proposer, accepter });
116
+ }
117
+ const proposalsToMe = [];
118
+ for (const r of p) {
119
+ const id = intField(r, 'ID');
120
+ const from = intField(r, 'PlayerOne');
121
+ if (id === undefined || from === undefined)
122
+ return undefined;
123
+ proposalsToMe.push({ id, from });
124
+ }
125
+ const alerts = [];
126
+ for (const r of al) {
127
+ const id = intField(r, 'ID');
128
+ const message = r.get('Message');
129
+ if (id === undefined || typeof message !== 'string')
130
+ return undefined;
131
+ alerts.push({ id, message });
132
+ }
133
+ return { alliances, proposalsToMe, alerts };
134
+ }
135
+ /**
136
+ * The players my own orders this turn break an alliance with (in-game ids): every `GameOrderCustom` in the
137
+ * decoded order list carrying the mod's break payload. Its field layout is not read: any string field with
138
+ * the payload counts. `[]` for none.
139
+ */
140
+ export function breaksInOrders(orders) {
141
+ const out = new Set();
142
+ for (const o of orders) {
143
+ if (!isObj(o) || typeof o.$type !== 'string' || !o.$type.endsWith('GameOrderCustom'))
144
+ continue;
145
+ for (const v of fields(o)) {
146
+ if (typeof v !== 'string' || !v.startsWith(BREAK_PAYLOAD_PREFIX))
147
+ continue;
148
+ const id = Number(v.slice(BREAK_PAYLOAD_PREFIX.length));
149
+ if (Number.isInteger(id) && id > 0)
150
+ out.add(id);
151
+ }
152
+ }
153
+ return [...out].sort((x, y) => x - y);
154
+ }
155
+ /** Every pair, alliances first (by id), then proposals to me. `turn`: this turn; `breaksByMe`: in-game ids. */
156
+ export function modPairs(state, me, turn, breaksByMe = []) {
157
+ const out = [];
158
+ for (const a of [...state.alliances].sort((x, y) => x.id - y.id)) {
159
+ const other = a.proposer === me ? a.accepter : a.accepter === me ? a.proposer : undefined;
160
+ const breaking = other !== undefined && breaksByMe.includes(other) && turn !== null;
161
+ out.push({
162
+ players: [a.proposer, a.accepter],
163
+ state: breaking ? 'breaking' : 'allied',
164
+ proposer: a.proposer,
165
+ id: a.id,
166
+ ...(breaking ? { endsTurn: turn + 1 } : {}),
167
+ });
168
+ }
169
+ for (const p of [...state.proposalsToMe].sort((x, y) => x.id - y.id)) {
170
+ if (me === undefined)
171
+ continue;
172
+ out.push({ players: [p.from, me], state: 'pending', proposer: p.from, id: p.id });
173
+ }
174
+ return out;
175
+ }
176
+ /** My allies (in-game ids), ascending. */
177
+ export function myAllies(state, me) {
178
+ const out = new Set();
179
+ for (const a of state.alliances) {
180
+ if (a.proposer === me && a.accepter !== me)
181
+ out.add(a.accepter);
182
+ else if (a.accepter === me && a.proposer !== me)
183
+ out.add(a.proposer);
184
+ }
185
+ return [...out].sort((x, y) => x - y);
186
+ }
187
+ /** The alerts that report a break of an alliance with me (the mod's own wording). */
188
+ export const breakAlerts = (state) => state.alerts.filter((a) => / has broken their alliance with you$/.test(a.message));
189
+ /** Whether a game's mods (GameFeed settings, `modIds`) include Diplomacy 2. */
190
+ export const runsDiplomacy2 = (modIds) => (modIds ?? []).includes(DIPLOMACY2_MOD_ID);
191
+ /**
192
+ * The moves that attack a territory an ally holds at the start of the turn (`ownerAt`: the owner on this
193
+ * turn's board, `undefined` when hidden or not a player). A transfer-only move attacks nothing. Pure.
194
+ */
195
+ export function allyAttacksIn(moves, allies, ownerAt) {
196
+ if (!allies.size)
197
+ return [];
198
+ return moves.flatMap((m, index) => {
199
+ if (m.mode === 'transfer-only')
200
+ return [];
201
+ const owner = ownerAt(m.to);
202
+ return owner !== undefined && allies.has(owner) ? [{ index, from: m.from, to: m.to, ally: owner }] : [];
203
+ });
204
+ }
205
+ /**
206
+ * Where the mod and the ledger disagree: an ally with no agreement active or in notice, and an agreement active
207
+ * or in notice with a player the mod does not ally me with. By player, then kind. Pure.
208
+ */
209
+ export function allianceMismatches(allies, live) {
210
+ const allied = new Set(allies);
211
+ const recorded = new Set(live.map((a) => a.with));
212
+ const out = [
213
+ ...[...allied].filter((p) => !recorded.has(p)).map((player) => ({ player, kind: 'mod-only' })),
214
+ ...live.filter((a) => !allied.has(a.with)).map((a) => ({ player: a.with, kind: 'ledger-only', agreement: a.id })),
215
+ ];
216
+ return out.sort((x, y) => x.player - y.player || x.kind.localeCompare(y.kind));
217
+ }
@@ -0,0 +1,160 @@
1
+ // A war.app mod's stored data (`Mod.PublicGameData`, `Mod.PlayerGameData`), as the web client keeps it:
2
+ // one XML string per mod id. Read from the client bundle (its mod-table serializer and parser), the
3
+ // format VERIFIED live 2026-11-23 on a lobby's public data (mod 336's table):
4
+ //
5
+ // <m><e k="s|ModVersion" v="s|3.0" /><e k="s|Map"><v><e k="d|2.0" v="d|665.0" /></v></e></m>
6
+ //
7
+ // Each `<e>` is one key and value of a Lua table: a scalar in an attribute (`s|` text, `i|` integer,
8
+ // `d|`/`f|` number, `b|1`/`b|0` a bool, `null`), or a nested table as a child element (`<v>`, or `<k>`
9
+ // for a table key) holding its own `<e>` entries. Lua arrays are tables keyed 1..n.
10
+ //
11
+ // Pure. Never throws: a document this parser does not understand is `undefined` (unknown).
12
+ const ENTITY = { quot: '"', amp: '&', lt: '<', gt: '>', apos: "'" };
13
+ /** An attribute value with its XML escapes undone; `undefined` on an escape this parser does not know. */
14
+ function unescapeXml(s) {
15
+ let bad = false;
16
+ const out = s.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);/g, (_, e) => {
17
+ if (e.startsWith('#x'))
18
+ return String.fromCodePoint(parseInt(e.slice(2), 16));
19
+ if (e.startsWith('#'))
20
+ return String.fromCodePoint(parseInt(e.slice(1), 10));
21
+ const v = ENTITY[e];
22
+ if (v === undefined)
23
+ bad = true;
24
+ return v ?? '';
25
+ });
26
+ // A bare `&` (no entity after it) is not well-formed XML.
27
+ if (bad || /&(?!(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);)/.test(s))
28
+ return undefined;
29
+ return out;
30
+ }
31
+ /** The element tree of `xml` (its root), or `undefined` when it is not well formed as far as this reads. */
32
+ function parseXml(xml) {
33
+ const tag = /<\?[^>]*\?>|<(\/?)([A-Za-z_][\w.-]*)((?:\s+[A-Za-z_][\w.-]*\s*=\s*"[^"]*")*)\s*(\/?)>|([^<]+)/gy;
34
+ const attr = /([A-Za-z_][\w.-]*)\s*=\s*"([^"]*)"/g;
35
+ const stack = [];
36
+ let root;
37
+ let m;
38
+ let at = 0;
39
+ while (at < xml.length) {
40
+ tag.lastIndex = at;
41
+ m = tag.exec(xml);
42
+ if (!m)
43
+ return undefined;
44
+ at = tag.lastIndex;
45
+ if (m[0].startsWith('<?'))
46
+ continue;
47
+ if (m[5] !== undefined) {
48
+ // Text between elements: only whitespace belongs in this format.
49
+ if (m[5].trim())
50
+ return undefined;
51
+ continue;
52
+ }
53
+ const [, close, name, attrs, self] = m;
54
+ if (close) {
55
+ const top = stack.pop();
56
+ if (!top || top.name !== name)
57
+ return undefined;
58
+ if (!stack.length) {
59
+ if (root)
60
+ return undefined;
61
+ root = top;
62
+ }
63
+ continue;
64
+ }
65
+ const node = { name: name, attrs: new Map(), children: [] };
66
+ for (const a of attrs.matchAll(attr)) {
67
+ const v = unescapeXml(a[2]);
68
+ if (v === undefined)
69
+ return undefined;
70
+ node.attrs.set(a[1], v);
71
+ }
72
+ if (stack.length)
73
+ stack[stack.length - 1].children.push(node);
74
+ if (self) {
75
+ if (!stack.length) {
76
+ if (root)
77
+ return undefined;
78
+ root = node;
79
+ }
80
+ }
81
+ else
82
+ stack.push(node);
83
+ }
84
+ return stack.length ? undefined : root;
85
+ }
86
+ const NOT = Symbol('not understood');
87
+ /** One scalar as the client's parser reads it. */
88
+ function scalar(s) {
89
+ if (s === 'null')
90
+ return null;
91
+ const kind = s.slice(0, 2);
92
+ const body = s.slice(2);
93
+ if (kind === 's|')
94
+ return body;
95
+ if (kind === 'i|') {
96
+ const n = Number.parseInt(body, 10);
97
+ return Number.isFinite(n) ? n : NOT;
98
+ }
99
+ if (kind === 'd|' || kind === 'f|') {
100
+ const n = Number(body);
101
+ return body.trim() !== '' && Number.isFinite(n) ? n : NOT;
102
+ }
103
+ if (kind === 'b|')
104
+ return s === 'b|1';
105
+ return NOT;
106
+ }
107
+ /** A table element's `<e>` entries, as the client's parser reads them. */
108
+ function tableOf(node) {
109
+ const out = new Map();
110
+ for (const e of node.children) {
111
+ if (e.name !== 'e')
112
+ continue;
113
+ const part = (n) => {
114
+ const a = e.attrs.get(n);
115
+ if (a !== undefined)
116
+ return scalar(a);
117
+ const child = e.children.find((c) => c.name === n);
118
+ if (!child)
119
+ return NOT;
120
+ return tableOf(child) ?? NOT;
121
+ };
122
+ const k = part('k');
123
+ const v = part('v');
124
+ if (k === NOT || v === NOT)
125
+ return undefined;
126
+ if (typeof k !== 'string' && typeof k !== 'number')
127
+ return undefined;
128
+ out.set(k, v);
129
+ }
130
+ return out;
131
+ }
132
+ /** A mod's stored table from its XML; `undefined` when the text is not one this parser understands. */
133
+ export function parseModTable(xml) {
134
+ try {
135
+ const root = parseXml(xml);
136
+ if (root?.name !== 'm')
137
+ return undefined;
138
+ return tableOf(root);
139
+ }
140
+ catch {
141
+ return undefined;
142
+ }
143
+ }
144
+ /** A Lua array (a table keyed 1..n) as a list; `undefined` when `v` is no such table. An empty table is `[]`. */
145
+ export function luaArray(v) {
146
+ if (!(v instanceof Map))
147
+ return undefined;
148
+ const out = [];
149
+ for (let i = 1; i <= v.size; i++) {
150
+ if (!v.has(i))
151
+ return undefined;
152
+ out.push(v.get(i));
153
+ }
154
+ return out;
155
+ }
156
+ /** A table's integer field; `undefined` when absent or not an integer. */
157
+ export function intField(t, key) {
158
+ const v = t.get(key);
159
+ return typeof v === 'number' && Number.isInteger(v) ? v : undefined;
160
+ }