@chrischall/warapp-mcp 0.1.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 (74) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +28 -17
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +12392 -9245
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/finished-store.js +357 -0
  22. package/dist/index.js +1 -1
  23. package/dist/lessons-store.js +356 -0
  24. package/dist/live.js +9 -0
  25. package/dist/map-details.js +127 -0
  26. package/dist/map-stats.js +14 -6
  27. package/dist/map-store.js +44 -6
  28. package/dist/my-games.js +44 -6
  29. package/dist/normalize.js +34 -2
  30. package/dist/notifications.js +143 -0
  31. package/dist/outlook-log.js +28 -1
  32. package/dist/player-record-store.js +2 -0
  33. package/dist/profile-store.js +61 -11
  34. package/dist/protocol/methods.js +86 -2
  35. package/dist/replay.js +16 -4
  36. package/dist/stats.js +26 -4
  37. package/dist/strategy/notes.js +64 -9
  38. package/dist/surrender-pending.js +126 -0
  39. package/dist/tools/accept-surrender.js +311 -0
  40. package/dist/tools/chat-inbox.js +17 -5
  41. package/dist/tools/chat-read-mark.js +179 -0
  42. package/dist/tools/chat.js +50 -8
  43. package/dist/tools/check-plan.js +1 -0
  44. package/dist/tools/commander-check.js +1 -0
  45. package/dist/tools/end-of-game.js +384 -0
  46. package/dist/tools/game.js +31 -6
  47. package/dist/tools/index.js +15 -5
  48. package/dist/tools/live-context.js +1 -1
  49. package/dist/tools/map-details.js +88 -0
  50. package/dist/tools/map-stats.js +15 -2
  51. package/dist/tools/map.js +10 -2
  52. package/dist/tools/my-games.js +77 -7
  53. package/dist/tools/notifications.js +484 -0
  54. package/dist/tools/opponents.js +14 -2
  55. package/dist/tools/past-games.js +94 -0
  56. package/dist/tools/picks.js +15 -2
  57. package/dist/tools/profile-opponents.js +1 -1
  58. package/dist/tools/profile-reads.js +3 -3
  59. package/dist/tools/push.js +72 -12
  60. package/dist/tools/strategy.js +65 -8
  61. package/dist/tools/stress-opponents.js +1 -1
  62. package/dist/tools/surrender-pending.js +74 -0
  63. package/dist/tools/surrender.js +10 -3
  64. package/dist/tools/team.js +1 -5
  65. package/dist/tools/turn.js +79 -15
  66. package/dist/tools/where.js +42 -17
  67. package/dist/tools/write-kit.js +6 -0
  68. package/dist/trend.js +145 -20
  69. package/dist/version.js +1 -1
  70. package/manifest.json +22 -2
  71. package/mint.yaml +14 -9
  72. package/package.json +1 -1
  73. package/server.json +2 -2
  74. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -0,0 +1,75 @@
1
+ import { normalizeSettings } from './normalize.js';
2
+ import { anonymousHistoryOfRecord, finishedPath, historyOfRecord, listFinishedRecords, readFinishedRecord } from './finished-store.js';
3
+ import { readStoredMap } from './map-store.js';
4
+ import { playerRecordSalt } from './player-record-store.js';
5
+ import { gamesDir, loadReplay } from './replay.js';
6
+ import { readdir } from 'node:fs/promises';
7
+ const count = (o, k) => {
8
+ o[k] = (o[k] ?? 0) + 1;
9
+ };
10
+ async function settingsRecordIds(dir) {
11
+ const names = await readdir(gamesDir(dir)).catch(() => []);
12
+ return names
13
+ .filter((n) => /^\d+\.json$/.test(n))
14
+ .map((n) => Number(n.slice(0, -5)))
15
+ .sort((a, b) => a - b);
16
+ }
17
+ /** Every finished game the data directory can score, and what it cannot. Never throws. */
18
+ export async function calibrationSources(dir) {
19
+ const out = { inputs: [], statuses: {}, skipped: {} };
20
+ const salt = await playerRecordSalt(dir).catch(() => undefined);
21
+ // The settings records by the record path they would match.
22
+ const byPath = new Map();
23
+ for (const id of await settingsRecordIds(dir)) {
24
+ const replay = await loadReplay(dir, id);
25
+ if (!salt || !replay || replay.playerId === undefined) {
26
+ count(out.statuses, 'missing');
27
+ continue;
28
+ }
29
+ byPath.set(finishedPath(dir, salt, replay.playerId, id), replay);
30
+ }
31
+ const paths = salt ? await listFinishedRecords(dir) : [];
32
+ const seen = new Set();
33
+ for (const path of paths) {
34
+ seen.add(path);
35
+ const rec = await readFinishedRecord(path);
36
+ if (typeof rec === 'string') {
37
+ count(out.statuses, rec);
38
+ continue;
39
+ }
40
+ count(out.statuses, rec.status);
41
+ if (rec.status !== 'captured')
42
+ continue;
43
+ const replay = byPath.get(path);
44
+ const matched = replay ? historyOfRecord(rec, salt, [replay.playerId, ...replay.game.players.map((p) => p.id)]) : undefined;
45
+ const history = matched && typeof matched === 'object' ? matched : anonymousHistoryOfRecord(rec);
46
+ if (typeof history === 'string') {
47
+ count(out.skipped, 'captured-without-boards');
48
+ continue;
49
+ }
50
+ const fromReplay = matched !== undefined && typeof matched === 'object';
51
+ const settings = fromReplay ? replay.settings : rec.settings ? normalizeSettings(rec.settings) : undefined;
52
+ if (!settings) {
53
+ count(out.skipped, 'no-settings');
54
+ continue;
55
+ }
56
+ const mapId = rec.mapId ?? settings.mapId;
57
+ const map = (fromReplay ? replay.map : undefined) ?? (mapId !== undefined ? await readStoredMap(dir, mapId, { maxAgeMs: Number.POSITIVE_INFINITY }) : undefined);
58
+ if (!map) {
59
+ count(out.skipped, 'no-map');
60
+ continue;
61
+ }
62
+ const cached = fromReplay && replay.playerId === history.me
63
+ ? replay.boards.map((b) => {
64
+ const o = replay.orders.get(b.turn);
65
+ return { turn: b.turn, board: b.board, ...(o ? { orders: o } : {}) };
66
+ })
67
+ : [];
68
+ out.inputs.push({ source: fromReplay ? 'settings-record' : 'record-only', history, settings, map, cached });
69
+ }
70
+ // A settings record whose game has no record: its pass has not run (or the record was pruned).
71
+ for (const path of byPath.keys())
72
+ if (!seen.has(path))
73
+ count(out.statuses, 'missing');
74
+ return out;
75
+ }
package/dist/chat.js CHANGED
@@ -58,6 +58,7 @@ function webLine(m) {
58
58
  }
59
59
  else if (group !== null) {
60
60
  line.channel = 'unknown';
61
+ line.group = group;
61
62
  }
62
63
  else if (channel === PUBLIC_CHANNEL) {
63
64
  line.channel = 'public';
@@ -126,6 +127,42 @@ export function readSendChatReply(bundle, body) {
126
127
  return undefined;
127
128
  }
128
129
  }
130
+ const MESSAGE_ID = /^\d{1,20}$/;
131
+ const higher = (a, b) => (a === undefined || BigInt(b) > BigInt(a) ? b : a);
132
+ /**
133
+ * The read marks of web-client `lines` on `channels` (pure): per channel the highest message id among
134
+ * them, mine included, as the client keeps it. A private conversation is keyed by its counterpart — the
135
+ * recipient of a message I sent, else its sender — and a game group (`unknown`) by its group. Lines
136
+ * without a message id (GameFeed's) mark nothing. `undefined` when nothing would be marked.
137
+ */
138
+ export function chatViewMarks(lines, meInGame, channels) {
139
+ const want = new Set(channels);
140
+ const out = { private: new Map(), groups: new Map(), channels: [] };
141
+ for (const l of lines) {
142
+ if (l.id === undefined || !MESSAGE_ID.test(l.id) || !want.has(l.channel))
143
+ continue;
144
+ if (l.channel === 'public')
145
+ out.public = higher(out.public, l.id);
146
+ else if (l.channel === 'team')
147
+ out.team = higher(out.team, l.id);
148
+ else if (l.channel === 'private') {
149
+ const other = l.sender === meInGame ? l.to : l.sender;
150
+ if (other === undefined || other === null)
151
+ continue;
152
+ out.private.set(other, higher(out.private.get(other), l.id));
153
+ }
154
+ else if (l.group !== undefined)
155
+ out.groups.set(l.group, higher(out.groups.get(l.group), l.id));
156
+ }
157
+ const has = {
158
+ public: out.public !== undefined,
159
+ team: out.team !== undefined,
160
+ private: out.private.size > 0,
161
+ unknown: out.groups.size > 0,
162
+ };
163
+ out.channels = CHAT_CHANNELS.filter((c) => has[c]);
164
+ return out.channels.length ? out : undefined;
165
+ }
129
166
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
130
167
  const pick = (r, keys) => {
131
168
  for (const k of keys)
@@ -190,3 +227,39 @@ export function feedChatLines(raw) {
190
227
  }
191
228
  return out;
192
229
  }
230
+ // ---------- A short web read, filled from GameFeed (#313) ----------
231
+ /** Two times this close (ms) are one message's: GameFeed may give whole seconds where the web client gives ms. */
232
+ const SAME_MESSAGE_MS = 1000;
233
+ const sameMessage = (web, feed) => {
234
+ if (web.sender !== feed.sender)
235
+ return false;
236
+ if (web.timeMs !== undefined && feed.timeMs !== undefined)
237
+ return Math.abs(web.timeMs - feed.timeMs) < SAME_MESSAGE_MS;
238
+ return web.text === feed.text;
239
+ };
240
+ /**
241
+ * The web client's `web` lines with GameFeed's `feed` lines that no web line matches (same sender, and
242
+ * times within a second — or the same text when either has no time), each match used once. The added
243
+ * lines keep GameFeed's `unknown` channel and go in by time (after every web line of the same or an
244
+ * earlier time); one with no time goes last. Pure: `added` is how many GameFeed lines were added.
245
+ */
246
+ export function fillFromFeed(web, feed) {
247
+ const used = new Set();
248
+ const extra = [];
249
+ for (const f of feed) {
250
+ const k = web.findIndex((w, i) => !used.has(i) && sameMessage(w, f));
251
+ if (k >= 0)
252
+ used.add(k);
253
+ else
254
+ extra.push({ ...f, channel: 'unknown' });
255
+ }
256
+ const lines = [...web];
257
+ for (const e of extra) {
258
+ const at = e.timeMs === undefined ? -1 : lines.findIndex((l) => l.timeMs !== undefined && l.timeMs > e.timeMs);
259
+ if (at < 0)
260
+ lines.push(e);
261
+ else
262
+ lines.splice(at, 0, e);
263
+ }
264
+ return { lines, added: extra.length };
265
+ }
package/dist/client.js CHANGED
@@ -25,9 +25,10 @@
25
25
  import { createApiClient, ERROR_REDACTION_INPUT_MAX, McpToolError, truncateErrorMessage, } from '@chrischall/mcp-utils';
26
26
  import { readCredentials, TOKEN_URL, WarappConfigError } from './config.js';
27
27
  import { feedErrorOf, normalizeGame, normalizeMap } from './normalize.js';
28
- import { readGameMapId, readStoredMap, rememberGameMap, touchStoredMap, writeStoredMap } from './map-store.js';
28
+ import { readGameMapId, readStoredMap, readStoredMapEntry, rememberGameMap, touchStoredMap, writeStoredMap, writeStoredModeTerritories } from './map-store.js';
29
29
  import { scrubSecrets } from './redact.js';
30
30
  import { asInt } from './scalars.js';
31
+ import { safeKeys } from './trend.js';
31
32
  const BASE_URL = 'https://war.app';
32
33
  const SERVICE = 'war.app';
33
34
  /** A game id war.app will not have: the largest positive int32. */
@@ -69,6 +70,7 @@ export class MapCache {
69
70
  #maps = new Map();
70
71
  #gameMaps = new Map();
71
72
  #refreshed = new Set();
73
+ #detailsTried = new Set();
72
74
  get(mapId) {
73
75
  return this.#maps.get(mapId);
74
76
  }
@@ -115,13 +117,67 @@ export class MapCache {
115
117
  */
116
118
  async store(map, dir, replace = false) {
117
119
  const known = this.#maps.has(map.id);
118
- this.set(map);
120
+ // #328: a map new to this process may already be stored with its modes' territories (read from war.app's
121
+ // map details, not GameFeed): the same map within its age, so they are kept rather than read again.
122
+ const carried = !known && !replace && dir !== undefined ? await this.#withStoredModes(map, dir) : undefined;
123
+ const kept = carried?.map ?? map;
124
+ this.set(kept);
119
125
  if (dir === undefined)
120
126
  return;
127
+ // Carried ids keep the age of the copy they were read with, so they age out on its clock, not this download's.
121
128
  if (!known || replace)
122
- await writeStoredMap(dir, map);
129
+ await writeStoredMap(dir, kept, carried?.storedAt);
123
130
  else
124
- await touchStoredMap(dir, map);
131
+ await touchStoredMap(dir, kept);
132
+ }
133
+ /**
134
+ * `map` with the mode territories its stored copy carries, where it has none of its own, and that copy's
135
+ * `storedAt`; `undefined` when nothing is carried. A mode whose stored ids are not all territories of
136
+ * `map` (its maker edited it since) is not carried: it reads as not read yet, so war.app is asked again
137
+ * and the fresh reply's ids are checked (and any the map lacks dropped with a warning) as on a first read.
138
+ */
139
+ async #withStoredModes(map, dir) {
140
+ const stored = await readStoredMapEntry(dir, map.id);
141
+ if (!stored || stored.storedAt === undefined)
142
+ return undefined;
143
+ const land = new Set(map.territories.map((t) => t.id));
144
+ const byMode = new Map(stored.map.distributionModes
145
+ .filter((d) => Array.isArray(d.territories) && d.territories.length > 0 && d.territories.every((id) => land.has(id)))
146
+ .map((d) => [d.id, d.territories]));
147
+ let any = false;
148
+ const distributionModes = map.distributionModes.map((d) => {
149
+ if (d.territories !== undefined || !byMode.has(d.id))
150
+ return d;
151
+ any = true;
152
+ return { ...d, territories: byMode.get(d.id) };
153
+ });
154
+ return any ? { map: { ...map, distributionModes }, storedAt: stored.storedAt } : undefined;
155
+ }
156
+ /**
157
+ * Lay the territories read for `mapId`'s modes (#328, by mode id) on the cached base map (a new object:
158
+ * the graph cache is keyed by map object) and keep them under `dir`. Nothing when the map is not cached.
159
+ */
160
+ async setModeTerritories(mapId, given, dir) {
161
+ const base = this.#maps.get(mapId);
162
+ if (!base)
163
+ return;
164
+ // An empty list is no knowledge (unknown is never `[]`): it is neither laid on the map nor kept.
165
+ const byMode = new Map([...given].filter(([, ids]) => ids.length > 0));
166
+ if (!byMode.size)
167
+ return;
168
+ this.set({
169
+ ...base,
170
+ distributionModes: base.distributionModes.map((d) => (byMode.has(d.id) ? { ...d, territories: [...byMode.get(d.id)] } : d)),
171
+ });
172
+ if (dir !== undefined)
173
+ await writeStoredModeTerritories(dir, mapId, byMode);
174
+ }
175
+ /** Whether war.app's map details were already asked for `mapId` this process (#328: once per map, never in a loop). */
176
+ mapDetailsTried(mapId) {
177
+ return this.#detailsTried.has(mapId);
178
+ }
179
+ markMapDetailsTried(mapId) {
180
+ this.#detailsTried.add(mapId);
125
181
  }
126
182
  /** Whether `mapId` was already downloaded again this process because the feed named land it lacked. */
127
183
  wasRefreshed(mapId) {
@@ -141,6 +197,7 @@ export class MapCache {
141
197
  this.#maps.clear();
142
198
  this.#gameMaps.clear();
143
199
  this.#refreshed.clear();
200
+ this.#detailsTried.clear();
144
201
  }
145
202
  }
146
203
  /** Whether the game's standing names a territory `map` does not have. */
@@ -158,16 +215,18 @@ export class WarappClient {
158
215
  #cache;
159
216
  #dataDir;
160
217
  #api;
218
+ /** The same client with no retry, for a request that must go out at most once (`noRetry`). */
219
+ #apiOnce;
161
220
  #secrets = [];
162
221
  constructor(opts = {}) {
163
222
  this.#env = opts.env;
164
223
  this.#cache = opts.mapCache ?? defaultMapCache;
165
224
  this.#dataDir = opts.dataDir;
166
- this.#api = createApiClient({
225
+ const build = (count) => createApiClient({
167
226
  baseUrl: BASE_URL,
168
227
  serviceName: SERVICE,
169
228
  baseHeaders: { accept: 'application/json' },
170
- retry: { count: 1, delayMs: 2000, statuses: [429, 500, 502, 503, 504], honorRetryAfter: true },
229
+ retry: { count, delayMs: 2000, statuses: [429, 500, 502, 503, 504], honorRetryAfter: true },
171
230
  redirect: 'same-origin',
172
231
  ...(opts.timeoutMs !== undefined ? { timeout: opts.timeoutMs } : {}),
173
232
  ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
@@ -179,6 +238,8 @@ export class WarappClient {
179
238
  }),
180
239
  onErrorResponse: ({ status, body }) => new McpToolError(`war.app GameFeed answered HTTP ${status}${body.trim() ? `: ${this.#redact(body)}` : ''}`, { kind: 'http', status }),
181
240
  });
241
+ this.#api = build(1);
242
+ this.#apiOnce = build(0);
182
243
  }
183
244
  #redact(text) {
184
245
  // Scrub by value before the shape redactor and the cut (as `values` would),
@@ -214,7 +275,8 @@ export class WarappClient {
214
275
  path += '&GetChat=true';
215
276
  if (flags.noMap)
216
277
  path += '&GetMap=false';
217
- const body = await this.#api.fetchJson('POST', path, {
278
+ const api = flags.noRetry ? this.#apiOnce : this.#api;
279
+ const body = await api.fetchJson('POST', path, {
218
280
  rawBody: new URLSearchParams({ Email: email, APIToken: token }).toString(),
219
281
  contentType: 'application/x-www-form-urlencoded',
220
282
  // A read sent as POST: safe to repeat.
@@ -265,6 +327,8 @@ export class WarappClient {
265
327
  const fresh = normalizeMap(rawMap);
266
328
  map = replace ? fresh : (this.#cache.get(fresh.id) ?? fresh);
267
329
  await this.#cache.store(map, dir, replace);
330
+ // The cache may hold it with what the store kept for it (#328: its modes' territories).
331
+ map = this.#cache.get(map.id) ?? map;
268
332
  }
269
333
  if (!map && game.settings?.mapId !== undefined)
270
334
  map = await this.#cache.load(game.settings.mapId, dir);
@@ -276,8 +340,22 @@ export class WarappClient {
276
340
  await this.#cache.storeGame(gameId, map.id, index ? dir : undefined);
277
341
  game.map = map;
278
342
  }
343
+ // #302: what came instead of a history that does not read, by key name only.
344
+ if (opts.history)
345
+ game.feedKeys = safeKeys(Object.keys(body));
279
346
  return game;
280
347
  }
348
+ /** Keep the territories read for a map's distribution modes (#328) on the cached map and in the store. */
349
+ async keepModeTerritories(mapId, byMode) {
350
+ await this.#cache.setModeTerritories(mapId, byMode, this.#dir());
351
+ }
352
+ /** Whether war.app's map details were already asked for `mapId` this process (#328). */
353
+ mapDetailsTried(mapId) {
354
+ return this.#cache.mapDetailsTried(mapId);
355
+ }
356
+ markMapDetailsTried(mapId) {
357
+ this.#cache.markMapDetailsTried(mapId);
358
+ }
281
359
  /** The data directory for the map store, or `undefined` (memory only); never throws. */
282
360
  #dir() {
283
361
  try {