@chrischall/warapp-mcp 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
package/dist/scout.js ADDED
@@ -0,0 +1,346 @@
1
+ // Scouting a war.app player from two server-rendered pages read through the
2
+ // bridge: Profile (stats) and CommonGames (head-to-head with the signed-in
3
+ // account). Both pages also carry personal details (e.g. a self-reported
4
+ // location); this module projects an ALLOWLIST of fields and never returns
5
+ // anything else. Parsing is loose: a block that is missing (a new player has no
6
+ // ranked games) reads as null, never a throw.
7
+ //
8
+ // The pages are untrusted input, and parts of them are written by the player
9
+ // being scouted (name, tagline, location). So: a page over MAX_PAGE_CHARS is not
10
+ // parsed at all; no pattern runs over the whole document (blocks are found by
11
+ // fixed markers and read through small anchored patterns on a bounded window, so
12
+ // parsing is linear in the page); and each stat is read only from its own block,
13
+ // where the page lays it out, never from the first place its wording appears.
14
+ // A value of the wrong shape is null.
15
+ //
16
+ // The anchor is war.app's own label markup (`<font class="text-muted">Joined:</font>
17
+ // value<br>`), which a player cannot write: Played is the one whole block (div, p, li or td) worded
18
+ // "Played in …" straight after a run of label rows, Level the whole block straight
19
+ // before them, Last seen and Booted the whole blocks straight after Played. No
20
+ // such block, or two, reads as null for all four. What this still relies on (the
21
+ // layout is not verified live): the page has at least one label row between the
22
+ // Level and Played blocks, and no player-written block sits directly before that
23
+ // run (in place of a missing Level block) or directly after Played (in place of
24
+ // a missing Last seen or Booted block).
25
+ import { McpToolError } from '@chrischall/mcp-utils';
26
+ /**
27
+ * Larger than any real Profile or CommonGames page (tens of kilobytes). A bigger
28
+ * page is not parsed: every block reads as missing.
29
+ */
30
+ export const MAX_PAGE_CHARS = 1 << 20;
31
+ /** Text longer than this is never a stat block, a label or a title. */
32
+ const MAX_NODE_CHARS = 1024;
33
+ /** A tag is classified from at most this many characters. */
34
+ const MAX_TAG_CHARS = 512;
35
+ /** How far a common-games row's next cell may be from the last. */
36
+ const CELL_WINDOW = 2048;
37
+ /** Label rows (Location, Joined, …) that may sit between the Level and Played blocks. */
38
+ const MAX_LABEL_ROWS = 16;
39
+ const MAX_FORMATS = 64;
40
+ /** More common games than anyone plays against one player; the rest of a bigger page is dropped. */
41
+ const MAX_GAMES = 1000;
42
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
43
+ function decodeEntities(s) {
44
+ return s.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{1,8});/gi, (m, e) => {
45
+ if (e[0] === '#') {
46
+ const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
47
+ return Number.isInteger(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;
48
+ }
49
+ return ENTITIES[e.toLowerCase()] ?? m;
50
+ });
51
+ }
52
+ const clean = (s) => decodeEntities(s).replace(/\s+/g, ' ').trim();
53
+ /** Text of a (bounded) HTML fragment: tags dropped, entities decoded, whitespace collapsed. */
54
+ const textOf = (html) => clean(html.replace(/<[^<>]*>/g, ' '));
55
+ // Values are validated by shape: an integer (thousands separators allowed), a percentage.
56
+ const INT = '(\\d{1,3}(?:,\\d{3})+|\\d{1,12})';
57
+ const PCT = '(\\d{1,3}(?:\\.\\d{1,2})?)';
58
+ const int = (s) => {
59
+ const n = Number(s.replace(/,/g, ''));
60
+ return Number.isSafeInteger(n) ? n : null;
61
+ };
62
+ const pct = (s) => {
63
+ const n = Number(s);
64
+ return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null;
65
+ };
66
+ /** Every value of a block, or null when any of them has the wrong shape. */
67
+ const values = (v) => (v.every((x) => x !== null) ? v : null);
68
+ const LEVEL = new RegExp(`^Level ${INT}$`);
69
+ const PLAYED = new RegExp(`^Played in ${INT} multi-player games \\(${PCT}% real-time\\)$`);
70
+ // war.app's own phrasing only, e.g. "less than 15 minutes ago", "3 days ago".
71
+ const SEEN = /^Last seen ((?:less than )?\d{1,4} (?:second|minute|hour|day|week|month|year)s? ago)$/i;
72
+ const SEEN_BLOCK = /^Last seen\b/i;
73
+ const PLAYED_BLOCK = /^Played in\b/i;
74
+ const BOOTED = new RegExp(`^Booted ${INT} times? \\(${PCT}% of their last 100\\)$`);
75
+ const RANKED = new RegExp(`^${INT} ranked games \\(${INT} / ${INT}\\)$`);
76
+ const FORMAT_LABEL = /^([^:]{1,60}):$/;
77
+ const FORMAT_ROW = new RegExp(`^${INT} ?/ ?${INT} ?\\( ?${PCT} ?% ?\\)$`);
78
+ const MUTED = /^<font\b[^>]*\bclass\s*=\s*["']?text-muted\b/i;
79
+ const BLOCK_OPEN = /^<(div|p|li|td)\b/i;
80
+ const BLOCK_CLOSE = /^<\/(div|p|li|td)\s*>/i;
81
+ /**
82
+ * The non-empty text nodes of `html` from `from` on, in one linear pass. Script and
83
+ * style bodies are skipped; an over-long node keeps its place but matches nothing.
84
+ */
85
+ function textNodes(html, from) {
86
+ const nodes = [];
87
+ let open = '';
88
+ let pos = from;
89
+ while (pos < html.length) {
90
+ const lt = html.indexOf('<', pos);
91
+ const end = lt < 0 ? html.length : lt;
92
+ const raw = html.slice(pos, end);
93
+ const text = raw.length > MAX_NODE_CHARS ? '\u0000' : clean(raw);
94
+ const gt = lt < 0 ? -1 : html.indexOf('>', lt + 1);
95
+ const close = gt < 0 ? '' : html.slice(lt, Math.min(gt + 1, lt + MAX_TAG_CHARS));
96
+ if (text)
97
+ nodes.push({ text, open, close });
98
+ if (gt < 0)
99
+ break;
100
+ open = close;
101
+ pos = gt + 1;
102
+ const body = /^<(script|style)\b/i.exec(close);
103
+ if (body && !close.endsWith('/>')) {
104
+ const shut = new RegExp(`</${body[1]}\\s*>`, 'gi');
105
+ shut.lastIndex = pos;
106
+ const m = shut.exec(html);
107
+ if (!m)
108
+ break;
109
+ pos = m.index;
110
+ }
111
+ }
112
+ return nodes;
113
+ }
114
+ /** A label in war.app's own markup, `<font class="text-muted">LABEL</font>`. */
115
+ const isMuted = (n) => !!n && MUTED.test(n.open) && /^<\/font\s*>/i.test(n.close);
116
+ const isLabel = (n) => isMuted(n) && n.text.endsWith(':');
117
+ /** A label's value: the text straight after the label's `</font>`, never a block of its own. */
118
+ const isLabelValue = (label, n) => isLabel(label) && !!n && /^<\/font\s*>/i.test(n.open);
119
+ /** A whole block: all the text of a `<div>` (or p, li, td) with no tag inside it. */
120
+ const isBlock = (n) => {
121
+ const o = n ? BLOCK_OPEN.exec(n.open) : null;
122
+ const c = o ? BLOCK_CLOSE.exec(n.close) : null;
123
+ return !!c && c[1].toLowerCase() === o[1].toLowerCase();
124
+ };
125
+ /** The first match of `re` (anchored, not global) in the `window` characters from `from`, as offsets. */
126
+ function near(html, from, re, window = CELL_WINDOW) {
127
+ const m = re.exec(html.slice(from, from + window));
128
+ return m ? { start: from + m.index, end: from + m.index + m[0].length } : null;
129
+ }
130
+ const EMPTY_PROFILE = {
131
+ name: null,
132
+ level: null,
133
+ multiplayerGames: null,
134
+ realTimePct: null,
135
+ lastSeen: null,
136
+ boots: null,
137
+ bootRatePct: null,
138
+ ranked: null,
139
+ formats: [],
140
+ };
141
+ export function parseProfile(html) {
142
+ if (html.length > MAX_PAGE_CHARS)
143
+ return { ...EMPTY_PROFILE, formats: [] };
144
+ // The name comes from the title only; the stats are read after it and after the
145
+ // name heading, both of which the player writes.
146
+ let name = null;
147
+ let start = 0;
148
+ const title = /<title\b[^<>]{0,200}>/i.exec(html);
149
+ if (title) {
150
+ const from = title.index + title[0].length;
151
+ const shut = near(html, from, /<\/title\s*>/i, MAX_NODE_CHARS);
152
+ if (shut) {
153
+ const titleText = textOf(html.slice(from, shut.start));
154
+ const nameMatch = / - War\.app\b/i.exec(titleText);
155
+ name = nameMatch && nameMatch.index > 0 ? titleText.slice(0, nameMatch.index).trim() : null;
156
+ start = shut.end;
157
+ }
158
+ }
159
+ const heading = /<\/h1\s*>/i.exec(html.slice(start));
160
+ if (heading)
161
+ start += heading.index + heading[0].length;
162
+ const nodes = textNodes(html, start);
163
+ const at = (i) => nodes[i]?.text ?? '';
164
+ const isValue = (i) => isLabelValue(nodes[i - 1], nodes[i]);
165
+ /** The node just before the run of label rows that ends right before node `i`; null when no label row is there. */
166
+ const beforeLabels = (i) => {
167
+ let j = i - 1;
168
+ for (let rows = 0; j >= 0 && rows < MAX_LABEL_ROWS; rows++) {
169
+ if (isLabel(nodes[j]))
170
+ j -= 1;
171
+ else if (isValue(j))
172
+ j -= 2;
173
+ else
174
+ break;
175
+ }
176
+ return j < i - 1 ? j : null;
177
+ };
178
+ // Played: the one whole block worded "Played in …" that follows war.app's label rows
179
+ // (Location, Joined, …) — the player cannot write that markup, only the text in it.
180
+ // Two such blocks, or one of the wrong shape, read as null, and so does everything
181
+ // anchored to it: never an imitation from elsewhere on the page.
182
+ const candidates = [];
183
+ for (let i = 0; i < nodes.length && candidates.length < 2; i++) {
184
+ if (PLAYED_BLOCK.test(at(i)) && isBlock(nodes[i]) && beforeLabels(i) !== null)
185
+ candidates.push(i);
186
+ }
187
+ let p = -1;
188
+ let played = null;
189
+ if (candidates.length === 1) {
190
+ const m = PLAYED.exec(at(candidates[0]));
191
+ played = m ? values([int(m[1]), pct(m[2])]) : null;
192
+ if (played)
193
+ p = candidates[0];
194
+ }
195
+ // Level: the whole block just before those label rows.
196
+ let level = null;
197
+ if (p >= 0) {
198
+ const j = beforeLabels(p);
199
+ const m = j >= 0 && isBlock(nodes[j]) ? LEVEL.exec(at(j)) : null;
200
+ level = m ? int(m[1]) : null;
201
+ }
202
+ // Last seen, then Booted: the whole blocks right after Played.
203
+ let lastSeen = null;
204
+ let booted = null;
205
+ if (p >= 0) {
206
+ let k = p + 1;
207
+ if (SEEN_BLOCK.test(at(k)) && isBlock(nodes[k])) {
208
+ lastSeen = SEEN.exec(at(k))?.[1] ?? null;
209
+ k++;
210
+ }
211
+ const m = isBlock(nodes[k]) ? BOOTED.exec(at(k)) : null;
212
+ booted = m ? values([int(m[1]), pct(m[2])]) : null;
213
+ }
214
+ // Ranked: war.app's `Completed` label and its value, then the per-format label rows.
215
+ let ranked = null;
216
+ const formats = [];
217
+ for (let i = 0; i < nodes.length - 1 && !ranked; i++) {
218
+ if (!isMuted(nodes[i]) || at(i) !== 'Completed')
219
+ continue;
220
+ const m = RANKED.exec(at(i + 1));
221
+ const v = m ? values([int(m[1]), int(m[2]), int(m[3])]) : null;
222
+ if (!v)
223
+ continue;
224
+ ranked = { completed: v[0], wins: v[1], games: v[2] };
225
+ for (let r = i + 2; r + 1 < nodes.length && formats.length < MAX_FORMATS; r += 2) {
226
+ const label = isLabel(nodes[r]) ? FORMAT_LABEL.exec(at(r)) : null;
227
+ const row = label ? FORMAT_ROW.exec(at(r + 1)) : null;
228
+ const rv = row ? values([int(row[1]), int(row[2]), pct(row[3])]) : null;
229
+ if (!rv)
230
+ break;
231
+ formats.push({ format: label[1].trim(), wins: rv[0], games: rv[1], pct: rv[2] });
232
+ }
233
+ }
234
+ return {
235
+ // A page with neither a level nor games played is not a profile (signed out, no such player).
236
+ name: level !== null || played ? name : null,
237
+ level,
238
+ multiplayerGames: played ? played[0] : null,
239
+ realTimePct: played ? played[1] : null,
240
+ lastSeen,
241
+ boots: booted ? booted[0] : null,
242
+ bootRatePct: booted ? booted[1] : null,
243
+ ranked,
244
+ formats,
245
+ };
246
+ }
247
+ /**
248
+ * Whether a page parsed as a profile is one: every player's profile shows a level and the
249
+ * multi-player games played (a new player's say 0), while a sign-in page or an unknown player's
250
+ * page has neither (#130).
251
+ */
252
+ export function isProfile(p) {
253
+ return p.level !== null || p.multiplayerGames !== null;
254
+ }
255
+ /** Whether a common game's teams column has teams: a side of more than one player ("2v2", "3v3v3", "Teams"). */
256
+ export function isTeamGame(teams) {
257
+ if (/\bteams?\b/i.test(teams))
258
+ return true;
259
+ const sides = /^\s*\d+(?:\s*v\s*\d+)+\s*$/i.test(teams) ? teams.split(/v/i).map((x) => Number(x.trim())) : [];
260
+ return sides.some((n) => n > 1);
261
+ }
262
+ /** My state in a common game, as a win, a loss, still going, or none of those (declined, …). */
263
+ function outcomeOf(state) {
264
+ if (/^won\b/i.test(state))
265
+ return 'win';
266
+ if (/eliminated|booted|surrender|lost/i.test(state))
267
+ return 'loss';
268
+ if (/playing|invited|waiting/i.test(state))
269
+ return 'inProgress';
270
+ return undefined;
271
+ }
272
+ const HEADER = new RegExp(`^\\s*${INT}\\s+Common Games?\\b`, 'i');
273
+ const GAME_LINK = /(?:^|\/)MultiPlayer\?GameID=(\d{1,12})(?!\d)/i;
274
+ /** One table row from the game link's tag end at `from`: its four cells and where it ends. */
275
+ function rowAt(html, from) {
276
+ const a = near(html, from, /<\/a\s*>/i);
277
+ if (!a)
278
+ return null;
279
+ const cells = [html.slice(from, a.start)];
280
+ const first = near(html, a.end, /^\s*<\/td\s*>/i, MAX_TAG_CHARS);
281
+ if (!first)
282
+ return null;
283
+ let pos = first.end;
284
+ for (let c = 0; c < 3; c++) {
285
+ const td = near(html, pos, /^\s*<td\b[^<>]{0,200}>/i, MAX_TAG_CHARS);
286
+ if (!td)
287
+ return null;
288
+ const shut = near(html, td.end, /<\/td\s*>/i);
289
+ if (!shut)
290
+ return null;
291
+ cells.push(html.slice(td.end, shut.start));
292
+ pos = shut.end;
293
+ }
294
+ return { cells, end: pos };
295
+ }
296
+ export function parseCommonGames(html) {
297
+ const games = [];
298
+ let count = null;
299
+ if (html.length <= MAX_PAGE_CHARS) {
300
+ const h1 = /<h1\b[^<>]{0,200}>/gi;
301
+ for (let m = h1.exec(html); m && count === null; m = h1.exec(html)) {
302
+ const head = HEADER.exec(html.slice(h1.lastIndex, h1.lastIndex + 256));
303
+ if (head)
304
+ count = int(head[1]);
305
+ }
306
+ const link = /<a\b[^<>]{0,500}>/gi;
307
+ for (let m = link.exec(html); m && games.length < MAX_GAMES; m = link.exec(html)) {
308
+ const href = /\bhref\s*=\s*(?:"([^"]{0,300})"|'([^']{0,300})'|([^\s"'>]{1,300}))/i.exec(m[0]);
309
+ const id = href ? GAME_LINK.exec(href[1] ?? href[2] ?? href[3]) : null;
310
+ const row = id ? rowAt(html, link.lastIndex) : null;
311
+ if (!id || !row)
312
+ continue;
313
+ const [name, started, teams, state] = row.cells.map(textOf);
314
+ games.push({ id: Number(id[1]), name, started, teams, myState: state });
315
+ link.lastIndex = row.end;
316
+ }
317
+ }
318
+ const tally = { win: 0, loss: 0, inProgress: 0 };
319
+ let teamGames = 0;
320
+ for (const g of games) {
321
+ const o = outcomeOf(g.myState);
322
+ const team = isTeamGame(g.teams);
323
+ if (team)
324
+ teamGames++;
325
+ if (o === 'inProgress' || (o && !team))
326
+ tally[o]++;
327
+ }
328
+ return {
329
+ count: count ?? (games.length ? games.length : null),
330
+ wins: tally.win,
331
+ losses: tally.loss,
332
+ inProgress: tally.inProgress,
333
+ teamGames,
334
+ games,
335
+ };
336
+ }
337
+ function checkToken(token) {
338
+ if (!/^\d{5,20}$/.test(token)) {
339
+ throw new McpToolError(`${JSON.stringify(token)} is not a war.app invite token (a GameFeed player id).`, {
340
+ hint: 'Pass the player id from warapp_get_game, or game_id plus the player name.',
341
+ });
342
+ }
343
+ return token;
344
+ }
345
+ export const profileUrl = (token) => `https://war.app/Profile?p=${checkToken(token)}`;
346
+ export const commonGamesUrl = (token) => `https://war.app/CommonGames?p=${checkToken(token)}`;
package/dist/stats.js ADDED
@@ -0,0 +1,291 @@
1
+ // Opt-in per-map statistics: collect finished games, cache them forever (S6).
2
+ //
3
+ // OFF unless `WARAPP_STATS` is truthy, and ALWAYS off on a hosted child: a
4
+ // hosted server makes requests on someone else's machine and quota, and its
5
+ // dataDir is not the user's to fill. mcp-host gives this server no explicit
6
+ // "hosted" flag, so a hosted child is recognised by the variables only the host
7
+ // sets (`HOSTED_MARKERS`, src/hosted.ts); mint.yaml never sets WARAPP_STATS either
8
+ // (pinned by tests/packaging.test.ts).
9
+ //
10
+ // Source: war.app's game-ID feed for a ladder (`WarappClient.getGameIds`), then
11
+ // GameFeed with `GetHistory=true` per game (`WarappClient.getGame`, without the map: a map
12
+ // already cached — in memory or in the shared map store, `<dataDir>/maps/` — is attached by its id, and only a finished game on an uncached map costs one more
13
+ // request, for the map) — every request through WarappClient. At most `maxNewGames` new games per call, at
14
+ // least {@link MIN_GAP_MS} between requests, and a finished game is cached
15
+ // forever at `<dataDir>/stats/<mapId>/<gameId>.json` (its compact
16
+ // {@link GameRecord}: ids, wins and turn numbers, no names), so a cache hit
17
+ // costs no request. A failing game is skipped and counted, never fatal. A finished
18
+ // game whose history does not parse is counted and not cached (#132): cached, it
19
+ // would sit in every denominator forever, and a later parser could read it.
20
+ import { randomUUID } from 'node:crypto';
21
+ import { mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
22
+ import { join } from 'node:path';
23
+ import { readEnvVar } from '@chrischall/mcp-utils';
24
+ import { isHosted } from './hosted.js';
25
+ import { RETIRED_LAYOUTS, readableRecord, recordFromGame } from './map-stats.js';
26
+ import { historyReport, safeKeys } from './trend.js';
27
+ // The hosted check is shared (src/hosted.ts); re-exported for existing imports.
28
+ export { HOSTED_MARKERS, isHosted } from './hosted.js';
29
+ /** The opt-in switch. */
30
+ export const STATS_ENV = 'WARAPP_STATS';
31
+ export const DEFAULT_NEW_GAMES = 10;
32
+ export const MAX_NEW_GAMES = 50;
33
+ /** The least time between two requests the collector makes. */
34
+ export const MIN_GAP_MS = 1000;
35
+ /** At most this many unreadable games are listed with their reason (#302). */
36
+ export const MAX_UNREADABLE_LISTED = 10;
37
+ /** How long a game seen unfinished is skipped before it is fetched again. */
38
+ export const UNFINISHED_RETRY_MS = 60 * 60 * 1000;
39
+ const truthy = (v) => v !== undefined && /^(1|true|yes|on)$/i.test(v.trim());
40
+ /** Whether map statistics may run here. */
41
+ export function statsGate(env = process.env) {
42
+ if (isHosted(env))
43
+ return { enabled: false, reason: 'hosted' };
44
+ return truthy(readEnvVar(STATS_ENV, { env })) ? { enabled: true } : { enabled: false, reason: 'off' };
45
+ }
46
+ const statsDir = (dir) => join(dir, 'stats');
47
+ export const recordPath = (dir, mapId, gameId) => join(statsDir(dir), String(mapId), `${gameId}.json`);
48
+ const isRecord = (v) => {
49
+ if (!v || typeof v !== 'object')
50
+ return false;
51
+ const r = v;
52
+ return (typeof r.gameId === 'number' &&
53
+ typeof r.mapId === 'number' &&
54
+ typeof r.turnsSeen === 'number' &&
55
+ (r.layout === undefined || typeof r.layout === 'string') &&
56
+ Array.isArray(r.players) &&
57
+ r.players.every((p) => !!p &&
58
+ typeof p === 'object' &&
59
+ typeof p.playerId === 'number' &&
60
+ typeof p.won === 'boolean' &&
61
+ Array.isArray(p.starts)));
62
+ };
63
+ /** One cached record: `undefined` when the file is not there, `null` when it is not a usable record. */
64
+ async function parseRecord(path) {
65
+ let text;
66
+ try {
67
+ text = await readFile(path, 'utf8');
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ let r;
73
+ try {
74
+ r = JSON.parse(text);
75
+ }
76
+ catch {
77
+ r = undefined;
78
+ }
79
+ return isRecord(r) && readableRecord(r) ? r : null;
80
+ }
81
+ /**
82
+ * Read one cached record. A file that reads but is not a valid record is
83
+ * deleted: its name alone counts as a cache hit, so left in place it would
84
+ * never be fetched again and never be counted.
85
+ */
86
+ async function readRecord(path) {
87
+ const r = await parseRecord(path);
88
+ if (r)
89
+ return r;
90
+ // An unreadable game cached by an older version is dropped too, so it is fetched again (#132).
91
+ if (r === null)
92
+ await unlink(path).catch(() => undefined);
93
+ return undefined;
94
+ }
95
+ /** The record files cached for `mapId` (`<dir>/stats/<mapId>/<gameId>.json`), by name. */
96
+ async function recordFiles(dir, mapId) {
97
+ const folder = join(statsDir(dir), String(mapId));
98
+ return (await names(folder))
99
+ .filter((f) => /^\d+\.json$/.test(f))
100
+ .sort()
101
+ .map((f) => join(folder, f));
102
+ }
103
+ /**
104
+ * Every usable record already cached for `mapId` under `dir`, ascending by game id. The cache
105
+ * alone: no request is made, and nothing is written or deleted (a file that is not a usable
106
+ * record is skipped where it is — the collector drops it). For readers outside the collector
107
+ * (warapp_locate_opponents), which call it only when {@link statsGate} allows statistics.
108
+ */
109
+ export async function cachedRecords(dir, mapId) {
110
+ const out = [];
111
+ for (const file of await recordFiles(dir, mapId)) {
112
+ const r = await parseRecord(file);
113
+ if (r && r.mapId === mapId)
114
+ out.push(r);
115
+ }
116
+ return out.sort((a, b) => a.gameId - b.gameId);
117
+ }
118
+ async function names(path) {
119
+ try {
120
+ return await readdir(path);
121
+ }
122
+ catch {
123
+ return [];
124
+ }
125
+ }
126
+ /** Every cached game id → its map id, from the file names alone. */
127
+ async function cacheIndex(dir) {
128
+ const out = new Map();
129
+ for (const m of await names(statsDir(dir))) {
130
+ if (!/^\d+$/.test(m))
131
+ continue;
132
+ for (const f of await names(join(statsDir(dir), m))) {
133
+ const g = /^(\d+)\.json$/.exec(f);
134
+ if (g)
135
+ out.set(Number(g[1]), Number(m));
136
+ }
137
+ }
138
+ return out;
139
+ }
140
+ async function writeRecord(dir, r) {
141
+ const path = recordPath(dir, r.mapId, r.gameId);
142
+ await mkdir(join(statsDir(dir), String(r.mapId)), { recursive: true, mode: 0o700 });
143
+ // Unique per write, so overlapping writes of one record never share (and lose) a temp file.
144
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
145
+ await writeFile(tmp, JSON.stringify(r), { mode: 0o600 });
146
+ await rename(tmp, path);
147
+ }
148
+ /** Collects finished games into the cache. One per process, so the throttle spans calls. */
149
+ export class StatsCollector {
150
+ #client;
151
+ #dir;
152
+ #now;
153
+ #sleep;
154
+ /** Games seen unfinished → when: not worth a request again until {@link UNFINISHED_RETRY_MS} has passed. */
155
+ #unfinished = new Map();
156
+ /** Games that failed this process: tried again only after every untried game. */
157
+ #failed = new Set();
158
+ /** Finished games whose history did not parse this process, with why (#302): not fetched again. */
159
+ #unreadable = new Map();
160
+ #last;
161
+ /** The request queue: each throttle waits for the one before it, so overlapping calls never share a slot. */
162
+ #queue = Promise.resolve();
163
+ constructor(opts) {
164
+ this.#client = opts.client;
165
+ this.#dir = opts.dir;
166
+ this.#now = opts.now ?? Date.now;
167
+ this.#sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
168
+ }
169
+ /**
170
+ * Wait until {@link MIN_GAP_MS} has passed since the previous request, then
171
+ * mark this one. Slots are granted one at a time through {@link #queue}, so
172
+ * two overlapping `collect()` calls cannot read the same `#last` and wake together.
173
+ */
174
+ #throttle() {
175
+ const turn = this.#queue.then(async () => {
176
+ if (this.#last !== undefined) {
177
+ const wait = this.#last + MIN_GAP_MS - this.#now();
178
+ if (wait > 0)
179
+ await this.#sleep(wait);
180
+ }
181
+ this.#last = this.#now();
182
+ });
183
+ this.#queue = turn.catch(() => undefined);
184
+ return turn;
185
+ }
186
+ /** Pull up to `maxNewGames` uncached games from a ladder's feed into the cache. */
187
+ async collect(ladderId, maxNewGames = DEFAULT_NEW_GAMES) {
188
+ const budget = Math.max(0, Math.min(MAX_NEW_GAMES, Math.floor(maxNewGames)));
189
+ const dir = this.#dir();
190
+ await this.#throttle();
191
+ const ids = await this.#client.getGameIds({ ladderId });
192
+ const index = await cacheIndex(dir);
193
+ const res = {
194
+ ladderId,
195
+ feedGames: ids.length,
196
+ cacheHits: 0,
197
+ fetched: 0,
198
+ newlyCached: 0,
199
+ notFinished: 0,
200
+ failed: 0,
201
+ unreadable: 0,
202
+ remaining: 0,
203
+ };
204
+ // Newest first, but a game that already failed this process goes last, so a
205
+ // permanently broken game at the head of the feed cannot eat the budget every call.
206
+ const listUnreadable = (gameId) => {
207
+ const why = this.#unreadable.get(gameId);
208
+ if (!why)
209
+ return;
210
+ const list = (res.unreadableGames ??= []);
211
+ if (list.length < MAX_UNREADABLE_LISTED)
212
+ list.push({ gameId, historyUnreadable: why });
213
+ };
214
+ const ordered = [...ids.filter((id) => !this.#failed.has(id)), ...ids.filter((id) => this.#failed.has(id))];
215
+ for (const id of ordered) {
216
+ if (index.has(id)) {
217
+ res.cacheHits++;
218
+ continue;
219
+ }
220
+ if (this.#unreadable.has(id)) {
221
+ res.unreadable++;
222
+ listUnreadable(id);
223
+ continue;
224
+ }
225
+ const seen = this.#unfinished.get(id);
226
+ if (seen !== undefined && this.#now() - seen < UNFINISHED_RETRY_MS) {
227
+ res.notFinished++;
228
+ continue;
229
+ }
230
+ if (res.fetched >= budget) {
231
+ res.remaining++;
232
+ continue;
233
+ }
234
+ res.fetched++;
235
+ try {
236
+ await this.#throttle();
237
+ // No map download (#148): WarappClient attaches a map it has cached for the game's map id
238
+ // (the settings name it), and an unfinished game needs none. Only a finished game on a map
239
+ // not cached yet costs a second request, for the map.
240
+ const game = await this.#client.getGame(id, { history: true, settings: true, map: false });
241
+ if (game.state !== 'Finished') {
242
+ this.#unfinished.set(id, this.#now());
243
+ res.notFinished++;
244
+ continue;
245
+ }
246
+ let map = game.map;
247
+ if (!map) {
248
+ await this.#throttle();
249
+ map = (await this.#client.getGame(id, { settings: true })).map;
250
+ }
251
+ if (!map)
252
+ throw new Error('no map');
253
+ const record = recordFromGame(game, map);
254
+ if (!readableRecord(record)) {
255
+ const report = historyReport(game, { needPlayerLand: true });
256
+ const keys = safeKeys(game.feedKeys ?? []);
257
+ this.#unreadable.set(id, 'unreadable' in report
258
+ ? report.unreadable
259
+ : record.layout !== undefined && RETIRED_LAYOUTS.has(record.layout)
260
+ ? // Read under a layout the live check found misnumbered (#302).
261
+ { reason: 'retired-layout', keys, turns: report.read.turns, layout: record.layout }
262
+ : // A history with player land that still yields no starts (the first board with land shows none of the game's players).
263
+ { reason: 'no-starts', keys, turns: report.read.turns });
264
+ listUnreadable(id);
265
+ this.#failed.delete(id);
266
+ res.unreadable++;
267
+ continue;
268
+ }
269
+ await writeRecord(dir, record);
270
+ this.#failed.delete(id);
271
+ this.#unfinished.delete(id);
272
+ res.newlyCached++;
273
+ }
274
+ catch {
275
+ this.#failed.add(id);
276
+ res.failed++;
277
+ }
278
+ }
279
+ return res;
280
+ }
281
+ /** Every cached record of `mapId`, ascending by game id. No request. */
282
+ async records(mapId) {
283
+ const out = [];
284
+ for (const file of await recordFiles(this.#dir(), mapId)) {
285
+ const r = await readRecord(file);
286
+ if (r && r.mapId === mapId)
287
+ out.push(r);
288
+ }
289
+ return out.sort((a, b) => a.gameId - b.gameId);
290
+ }
291
+ }