@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
@@ -0,0 +1,357 @@
1
+ // The end-of-game records (#312 E1; owner decisions P2–P4 of 2026-11-16): one file per finished game
2
+ // the account played, `<dataDir>/finished/<key>.json`, the key an HMAC of my account and the game
3
+ // under the one shared salt (`finishedGameKey`, src/player-record-store.ts), so no file name holds an
4
+ // id. NAME-FREE inside too: players by the deal record's `playerKey` under the same salt, never an id
5
+ // or a name; territory, bonus and map ids are the map's own, public data. No clock is kept.
6
+ // A captured record also keeps the history's boards (owners by key, delta-encoded), which the calibration
7
+ // harness (#318, scripts/calibrate.mjs) reads as its truth: it never reads a history of its own.
8
+ //
9
+ // The file is also the "processed" mark: the end-of-game pass (src/tools/end-of-game.ts) runs once per
10
+ // game, and a file of any status means it ran. `captured` holds the history's capture; `history-unreadable`
11
+ // (with #315's reason) and `read-failed` (the request failed) record a pass whose history did not come,
12
+ // and are never retried automatically (an explicit warapp_get_game with `include_history` may).
13
+ //
14
+ // The record bound would drop a processed mark, so every pass that spent its history read (its own
15
+ // request, or the history a caller read and handed it) also leaves a mark in
16
+ // `<dataDir>/finished/processed.json` (`markProcessed`): the record keys only (hashed, no id),
17
+ // at most `MAX_PROCESSED_KEYS` (ten times the record bound), the least recently marked dropped first. A
18
+ // game with a mark is never read again by a trigger even once its record is pruned (P2). The one
19
+ // remaining exception: a game whose record AND mark have both aged out (over 5000 later passes) reads
20
+ // again if a trigger names it. A marks file that does not parse is never overwritten (marks then rely
21
+ // on the records alone).
22
+ //
23
+ // A captured record keeps at most `MAX_RECORD_BOARDS_HEAD` opening boards and `MAX_RECORD_BOARDS_TAIL`
24
+ // closing ones (the opening benchmark reads the first, the calibration the turns the board cache kept,
25
+ // the last ten); `boardsOmitted` counts the boards between them that were left out.
26
+ //
27
+ // Same guarantees as the profile stores: 0600 files in a 0700 folder, atomic writes, best effort; at
28
+ // most `MAX_FINISHED_RECORDS` files, the least recently written (or refreshed by the sweep) dropped first, never
29
+ // one the writer protects (the sweep's window: its newest finished games, half the bound, so a processed
30
+ // game it lists never loses its mark and is never read again); a file that exists but
31
+ // does not parse (not JSON, not an object, another version) is never overwritten. `WARAPP_PLAYER_PROFILE=off`
32
+ // switches the pass off (nothing read or written).
33
+ import { readdir, readFile, stat, unlink, utimes } from 'node:fs/promises';
34
+ import { join } from 'node:path';
35
+ import { profileFormatOf } from './analysis/opponent-profile.js';
36
+ import { writeJsonAtomic } from './map-store.js';
37
+ import { finishedGameKey, playerKey } from './player-record-store.js';
38
+ import { holdsSeat } from './player-states.js';
39
+ import { withPathLock } from './path-lock.js';
40
+ export const MAX_FINISHED_RECORDS = 500;
41
+ /** The processed marks kept: ten times the record bound. */
42
+ export const MAX_PROCESSED_KEYS = 5000;
43
+ /** The opening boards a captured record keeps. */
44
+ export const MAX_RECORD_BOARDS_HEAD = 30;
45
+ /** The closing boards a captured record keeps. */
46
+ export const MAX_RECORD_BOARDS_TAIL = 30;
47
+ const VERSION = 1;
48
+ const FILE = /^[0-9a-f]{32}\.json$/;
49
+ export const finishedDir = (dir) => join(dir, 'finished');
50
+ export const finishedPath = (dir, salt, me, gameId) => join(finishedDir(dir), `${finishedGameKey(salt, me, gameId)}.json`);
51
+ /** The processed marks: not a record (its name is no key), so the prune and the record list skip it. */
52
+ export const processedPath = (dir) => join(finishedDir(dir), 'processed.json');
53
+ const KEY = /^[0-9a-f]{32}$/;
54
+ export const OWNER_NEUTRAL = -1;
55
+ export const OWNER_AVAILABLE = -2;
56
+ /** Fogged, or an owner that is no seated player's (its raw value is never kept). */
57
+ export const OWNER_UNKNOWN = -3;
58
+ const FOG_WORD = /^[A-Za-z0-9]{1,20}$/;
59
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
60
+ const STATUSES = new Set(['captured', 'history-unreadable', 'read-failed']);
61
+ /**
62
+ * The record at `path`: `missing`, `unreadable` (exists, but not JSON, not an object, another version
63
+ * or an unknown status: never overwritten), or its status. Never throws.
64
+ */
65
+ export async function readFinishedState(path) {
66
+ let text;
67
+ try {
68
+ text = await readFile(path, 'utf8');
69
+ }
70
+ catch (e) {
71
+ return e.code === 'ENOENT' ? 'missing' : 'unreadable';
72
+ }
73
+ try {
74
+ const v = JSON.parse(text);
75
+ if (!isRec(v) || v.version !== VERSION || typeof v.status !== 'string' || !STATUSES.has(v.status))
76
+ return 'unreadable';
77
+ return { status: v.status };
78
+ }
79
+ catch {
80
+ return 'unreadable';
81
+ }
82
+ }
83
+ /**
84
+ * Write a record atomically (0600), then keep the newest {@link MAX_FINISHED_RECORDS}: never a path in
85
+ * `protect` (the sweep's window, src/tools/end-of-game.ts), nor the one just written. Throws on a failed write.
86
+ */
87
+ export async function writeFinishedRecord(dir, path, body, keep = MAX_FINISHED_RECORDS, protect) {
88
+ await writeJsonAtomic(path, finishedDir(dir), body);
89
+ await pruneFinished(dir, keep, new Set([...(protect ?? []), path])).catch(() => undefined);
90
+ }
91
+ /** Mark a record most recently used (a prune drops the least recently written or touched first). Never throws. */
92
+ export async function touchFinished(path) {
93
+ const now = new Date();
94
+ await utimes(path, now, now).catch(() => undefined);
95
+ }
96
+ /**
97
+ * The processed marks: the record keys of every game whose pass spent its history read, oldest first.
98
+ * Missing: none. `unreadable`: the file exists but does not parse (never overwritten). Never throws.
99
+ */
100
+ export async function readProcessed(dir) {
101
+ const keys = await readProcessedKeys(dir);
102
+ return keys === 'unreadable' ? keys : new Set(keys);
103
+ }
104
+ async function readProcessedKeys(dir) {
105
+ let text;
106
+ try {
107
+ text = await readFile(processedPath(dir), 'utf8');
108
+ }
109
+ catch (e) {
110
+ return e.code === 'ENOENT' ? [] : 'unreadable';
111
+ }
112
+ try {
113
+ const v = JSON.parse(text);
114
+ if (!isRec(v) || v.version !== VERSION || !Array.isArray(v.keys) || !v.keys.every((k) => typeof k === 'string' && KEY.test(k)))
115
+ return 'unreadable';
116
+ return v.keys;
117
+ }
118
+ catch {
119
+ return 'unreadable';
120
+ }
121
+ }
122
+ /**
123
+ * Mark `key` (a `finishedGameKey`) processed, newest, keeping at most `limit` marks (0600, atomic,
124
+ * under the path lock). `false` when the marks file does not parse (left as it is) or the write failed. Never throws.
125
+ */
126
+ export async function markProcessed(dir, key, limit = MAX_PROCESSED_KEYS) {
127
+ if (!KEY.test(key))
128
+ return false;
129
+ const path = processedPath(dir);
130
+ try {
131
+ return await withPathLock(path, async () => {
132
+ const keys = await readProcessedKeys(dir);
133
+ if (keys === 'unreadable')
134
+ return false;
135
+ const next = [...keys.filter((k) => k !== key), key];
136
+ await writeJsonAtomic(path, finishedDir(dir), { version: VERSION, keys: next.slice(Math.max(0, next.length - limit)) });
137
+ return true;
138
+ });
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ /** Every record file under `dir` (the marks file aside), by path, sorted. Never throws. */
145
+ export async function listFinishedRecords(dir) {
146
+ const names = await readdir(finishedDir(dir)).catch(() => []);
147
+ return names
148
+ .filter((n) => FILE.test(n))
149
+ .sort()
150
+ .map((n) => join(finishedDir(dir), n));
151
+ }
152
+ async function pruneFinished(dir, keep, protect) {
153
+ const folder = finishedDir(dir);
154
+ const files = [];
155
+ for (const name of await readdir(folder)) {
156
+ if (!FILE.test(name))
157
+ continue;
158
+ const path = join(folder, name);
159
+ try {
160
+ files.push({ path, at: (await stat(path)).mtimeMs });
161
+ }
162
+ catch {
163
+ // Gone already.
164
+ }
165
+ }
166
+ if (files.length <= keep)
167
+ return;
168
+ files.sort((a, b) => b.at - a.at || a.path.localeCompare(b.path));
169
+ let over = files.length - keep;
170
+ for (const f of [...files].reverse()) {
171
+ if (over <= 0)
172
+ break;
173
+ if (protect.has(f.path))
174
+ continue;
175
+ await unlink(f.path).catch(() => undefined);
176
+ over--;
177
+ }
178
+ }
179
+ /** The stored record: every player id replaced by its `playerKey`. Pure. */
180
+ export function finishedRecordOf(p) {
181
+ const key = (id) => playerKey(p.salt, id);
182
+ const owner = (o) => (typeof o === 'number' ? key(o) : o);
183
+ const keyed = (m) => Object.fromEntries([...m].map(([id, v]) => [key(id), v]));
184
+ const game = p.game;
185
+ const c = p.capture;
186
+ // The history's own parts only when it read.
187
+ const h = p.status === 'captured' ? c : undefined;
188
+ const kept = p.status === 'captured' && p.boards ? boundedBoards(p.boards) : undefined;
189
+ const stored = kept ? storeBoards(kept.boards, p.game?.players.map((x) => x.id) ?? [p.me], key) : undefined;
190
+ return {
191
+ version: VERSION,
192
+ status: p.status,
193
+ ...(p.failure ? { failure: p.failure } : {}),
194
+ ...(p.layout ? { layout: p.layout } : {}),
195
+ ...(p.mapId !== undefined ? { mapId: p.mapId } : {}),
196
+ ...(p.noMap ? { noMap: true } : {}),
197
+ ...(game ? { format: profileFormatOf(game.players), seats: game.players.filter((x) => holdsSeat(x.state)).length } : {}),
198
+ ...(p.settings ? { settings: p.settings } : {}),
199
+ me: key(p.me),
200
+ ...(game
201
+ ? {
202
+ players: game.players
203
+ .filter((x) => holdsSeat(x.state))
204
+ .map((x) => ({
205
+ key: key(x.id),
206
+ ai: x.isAI,
207
+ ...(x.humanTurnedIntoAI ? { turnedAI: true } : {}),
208
+ ...(x.team !== undefined && x.team !== null ? { team: x.team } : {}),
209
+ ...(x.state ? { state: x.state } : {}),
210
+ })),
211
+ }
212
+ : {}),
213
+ ...(c ? { outcome: { ...c.outcome, winners: c.outcome.winners.map(key) } } : {}),
214
+ ...(p.outlook ? { outlook: p.outlook } : {}),
215
+ ...(p.picks !== undefined ? { picks: p.picks } : {}),
216
+ ...(h ? { starts: keyed(h.starts) } : {}),
217
+ ...(h ? { turns: h.turns.map((t) => ({ afterTurn: t.afterTurn, players: keyed(t.players) })) } : {}),
218
+ ...(h
219
+ ? {
220
+ failedAttacks: h.failedAttacks.map((f) => ({
221
+ ...f,
222
+ before: { owner: owner(f.before.owner), armies: f.before.armies },
223
+ after: { owner: owner(f.after.owner), armies: f.after.armies },
224
+ })),
225
+ }
226
+ : {}),
227
+ ...(stored ?? {}),
228
+ ...(kept?.omitted ? { boardsOmitted: kept.omitted } : {}),
229
+ };
230
+ }
231
+ /** The opening and closing boards a record keeps, and how many between them it leaves out. Pure. */
232
+ function boundedBoards(boards) {
233
+ const max = MAX_RECORD_BOARDS_HEAD + MAX_RECORD_BOARDS_TAIL;
234
+ if (boards.length <= max)
235
+ return { boards, omitted: 0 };
236
+ return { boards: [...boards.slice(0, MAX_RECORD_BOARDS_HEAD), ...boards.slice(boards.length - MAX_RECORD_BOARDS_TAIL)], omitted: boards.length - max };
237
+ }
238
+ /** The boards in their stored shape: owners by key (only the game's players; any other owner is unknown). Pure. */
239
+ function storeBoards(boards, ids, key) {
240
+ const known = new Set(ids);
241
+ const index = new Map();
242
+ const owners = [];
243
+ const ownerOf = (o) => {
244
+ if (o.kind === 'neutral')
245
+ return OWNER_NEUTRAL;
246
+ if (o.kind === 'available')
247
+ return OWNER_AVAILABLE;
248
+ if (o.kind !== 'player' || !known.has(o.playerId))
249
+ return OWNER_UNKNOWN;
250
+ let i = index.get(o.playerId);
251
+ if (i === undefined) {
252
+ i = owners.push(key(o.playerId)) - 1;
253
+ index.set(o.playerId, i);
254
+ }
255
+ return i;
256
+ };
257
+ const rowOf = (x) => {
258
+ const row = [x.territoryId, ownerOf(x.owner), x.armies];
259
+ return x.fogLevel && x.fogLevel !== 'Visible' && FOG_WORD.test(x.fogLevel) ? [...row, x.fogLevel] : row;
260
+ };
261
+ let prev;
262
+ const out = [];
263
+ for (const { turn, board } of boards) {
264
+ const rows = board.territories.map(rowOf);
265
+ const before = prev;
266
+ const sameList = before !== undefined && before.length === rows.length && rows.every((r, i) => r[0] === before[i][0]);
267
+ out.push(sameList ? { turn, d: true, t: rows.filter((r, i) => JSON.stringify(r) !== JSON.stringify(before[i])) } : { turn, t: rows });
268
+ prev = rows;
269
+ }
270
+ return { boardOwners: owners, boards: out };
271
+ }
272
+ /**
273
+ * The record at `path`: `missing`, `unreadable` (as {@link readFinishedState}), or the record itself.
274
+ * Never throws. The harness's reader (scripts/calibrate.mjs); the pass needs only the state.
275
+ */
276
+ export async function readFinishedRecord(path) {
277
+ const state = await readFinishedState(path);
278
+ if (typeof state === 'string')
279
+ return state;
280
+ try {
281
+ return JSON.parse(await readFile(path, 'utf8'));
282
+ }
283
+ catch {
284
+ return 'unreadable';
285
+ }
286
+ }
287
+ /**
288
+ * The history a captured record keeps, its keys matched against `ids` (the players the caller already
289
+ * knows by id: a key is never reversed). `no-boards`: not captured, or captured without its boards;
290
+ * `unmatched`: my key is none of `ids`. A seat matching none is left out, and land it owned reads as
291
+ * an unknown owner. Pure.
292
+ */
293
+ export function historyOfRecord(rec, salt, ids) {
294
+ if (!hasBoards(rec))
295
+ return 'no-boards';
296
+ const byKey = new Map(ids.map((id) => [playerKey(salt, id), id]));
297
+ if (!byKey.has(rec.me))
298
+ return 'unmatched';
299
+ return decodeHistory(rec, byKey);
300
+ }
301
+ /**
302
+ * The history a captured record keeps when the ids of its game are not known (#318: the game's settings
303
+ * record aged out): each player labelled by position, me 1, then the seats in the record's order, then
304
+ * any other board owner. A key is never reversed: the labels say who is who within the record only. Pure.
305
+ */
306
+ export function anonymousHistoryOfRecord(rec) {
307
+ if (!hasBoards(rec))
308
+ return 'no-boards';
309
+ const byKey = new Map();
310
+ for (const k of [rec.me, ...(rec.players ?? []).map((p) => p.key), ...rec.boardOwners])
311
+ if (!byKey.has(k))
312
+ byKey.set(k, byKey.size + 1);
313
+ const h = decodeHistory(rec, byKey);
314
+ // Me first among the players.
315
+ h.players.sort((a, b) => a.id - b.id);
316
+ return h;
317
+ }
318
+ const hasBoards = (rec) => rec.status === 'captured' && Array.isArray(rec.boards) && Array.isArray(rec.boardOwners);
319
+ function decodeHistory(rec, byKey) {
320
+ const me = byKey.get(rec.me);
321
+ const owners = rec.boardOwners.map((k) => byKey.get(k));
322
+ const ownerOf = (o) => {
323
+ if (o === OWNER_NEUTRAL)
324
+ return { kind: 'neutral' };
325
+ if (o === OWNER_AVAILABLE)
326
+ return { kind: 'available' };
327
+ const id = owners[o];
328
+ return id === undefined ? { kind: 'unknown' } : { kind: 'player', playerId: id };
329
+ };
330
+ const players = [];
331
+ for (const p of rec.players ?? []) {
332
+ const id = byKey.get(p.key);
333
+ if (id === undefined)
334
+ continue;
335
+ players.push({ id, isAI: p.ai, ...(p.team !== undefined ? { team: p.team } : {}), ...(p.state !== undefined ? { state: p.state } : {}) });
336
+ }
337
+ const territoryOf = ([territoryId, owner, armies, fogLevel]) => ({
338
+ territoryId,
339
+ owner: ownerOf(owner),
340
+ armies,
341
+ ...(fogLevel !== undefined ? { fogLevel } : {}),
342
+ });
343
+ const boards = [];
344
+ let prev;
345
+ for (const { turn, d, t } of rec.boards) {
346
+ let territories;
347
+ if (d && prev) {
348
+ const changed = new Map(t.map((row) => [row[0], territoryOf(row)]));
349
+ territories = prev.map((x) => changed.get(x.territoryId) ?? { ...x });
350
+ }
351
+ else
352
+ territories = t.map(territoryOf);
353
+ boards.push({ turn, board: { source: 'gamefeed', verified: false, territories } });
354
+ prev = territories;
355
+ }
356
+ return { me, numberOfTurns: rec.outcome?.turn ?? null, players, boards };
357
+ }
@@ -0,0 +1,65 @@
1
+ // The local secret mixed into the border guess's seed (src/analysis/guess.ts `guessSeed`). The code
2
+ // is public, so a seed from the game id and turn alone could be reproduced by an opponent who reads
3
+ // it; with this salt the draw stays the same when a turn is planned again here, and unreadable
4
+ // elsewhere. Kept at `<dataDir>/guess-salt` (0600, atomic); without a data directory, or when it
5
+ // cannot be written, a salt for this process only. Never logged, never in a tool result.
6
+ import { randomBytes } from 'node:crypto';
7
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ const SALT = /^[0-9a-f]{32}$/;
10
+ let processSalt;
11
+ const cached = new Map();
12
+ export const guessSaltPath = (dir) => join(dir, 'guess-salt');
13
+ /**
14
+ * The salt {@link guessSalt} would return, without creating one: `undefined` when none exists yet (no
15
+ * guess has been drawn with it). For a reader that must write nothing (#275 pattern 3). Never throws.
16
+ */
17
+ export async function peekGuessSalt(dir) {
18
+ if (!dir)
19
+ return processSalt;
20
+ const hit = cached.get(dir);
21
+ if (hit)
22
+ return hit;
23
+ try {
24
+ const text = (await readFile(guessSaltPath(dir), 'utf8')).trim();
25
+ if (SALT.test(text))
26
+ return text;
27
+ }
28
+ catch {
29
+ // Not there.
30
+ }
31
+ // A salt that could not be kept falls back to this process's (guessSalt).
32
+ return processSalt;
33
+ }
34
+ /** The salt for `dir` (created on first use), else this process's. Never throws. */
35
+ export async function guessSalt(dir) {
36
+ const fallback = () => (processSalt ??= randomBytes(16).toString('hex'));
37
+ if (!dir)
38
+ return fallback();
39
+ const hit = cached.get(dir);
40
+ if (hit)
41
+ return hit;
42
+ const path = guessSaltPath(dir);
43
+ try {
44
+ const text = (await readFile(path, 'utf8')).trim();
45
+ if (SALT.test(text)) {
46
+ cached.set(dir, text);
47
+ return text;
48
+ }
49
+ }
50
+ catch {
51
+ // Not there yet.
52
+ }
53
+ const salt = randomBytes(16).toString('hex');
54
+ try {
55
+ await mkdir(dir, { recursive: true, mode: 0o700 });
56
+ const tmp = `${path}.${process.pid}.tmp`;
57
+ await writeFile(tmp, salt, { mode: 0o600 });
58
+ await rename(tmp, path);
59
+ cached.set(dir, salt);
60
+ return salt;
61
+ }
62
+ catch {
63
+ return fallback();
64
+ }
65
+ }
package/dist/hosted.js ADDED
@@ -0,0 +1,24 @@
1
+ // Is this process a hosted child (mcp-host), not a local install?
2
+ //
3
+ // mcp-host gives this server no explicit "hosted" flag, so a hosted child is
4
+ // recognised by the variables only the host sets ({@link HOSTED_MARKERS}).
5
+ // Consulted by the map statistics (always off when hosted, src/stats.ts) and by
6
+ // the direct transport, which is LOCAL-ONLY: when hosted the session store
7
+ // reads as empty and refuses writes (src/direct/session.ts), the router is
8
+ // pinned to the browser bridge (src/direct/transport.ts), and
9
+ // warapp_link_session is not registered (src/tools/session.ts).
10
+ import { readEnvVar } from '@chrischall/mcp-utils';
11
+ /**
12
+ * Variables only a hosted child sees: mcp-host's own (its child-env contract —
13
+ * the byte-meter file, the confirm-token key, the blob store) and the
14
+ * platform's machine id. Any one of them set means hosted.
15
+ */
16
+ export const HOSTED_MARKERS = [
17
+ 'MCP_HOST_METER_FILE',
18
+ 'MCP_HOST_CONFIRM_SECRET',
19
+ 'MCP_BLOB_BASE_URL',
20
+ 'FLY_MACHINE_ID',
21
+ ];
22
+ export function isHosted(env = process.env) {
23
+ return HOSTED_MARKERS.some((k) => readEnvVar(k, { env }) !== undefined);
24
+ }
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ // warapp-mcp entrypoint.
3
+ //
4
+ // war.app (Warzone) exposes a per-player GameFeed API authenticated by the
5
+ // player's email + API token. Credentials come from the host env, or from an
6
+ // optional dotenv file (WARAPP_ENV_FILE, default ~/.config/warapp-mcp/.env)
7
+ // whose values never override the host's.
8
+ //
9
+ // Deferred config: the server boots and answers tools/list with no
10
+ // credentials; a missing credential surfaces on the first call that needs it.
11
+ //
12
+ // The live-game tools also speak the web-client protocol, relayed through the
13
+ // user's signed-in war.app tab by the fetchproxy bridge (src/transport-bridge.ts).
14
+ // One bridge per process, started at boot; start() only loads the identity —
15
+ // the port binds on the first request.
16
+ import { loadDotenvSafely, runMcp } from '@chrischall/mcp-utils';
17
+ import { envFilePath } from './config.js';
18
+ import { registerAllTools } from './tools/index.js';
19
+ import { createWarappBridge } from './transport-bridge.js';
20
+ import { VERSION } from './version.js';
21
+ await loadDotenvSafely({ path: envFilePath() });
22
+ const bridge = createWarappBridge();
23
+ // A failed start (e.g. an unwritable identity dir) is not a boot failure: the
24
+ // lazy transport forgets it, and the first bridged call retries and reports it.
25
+ bridge.ready().catch(() => undefined);
26
+ await runMcp({
27
+ name: 'warapp-mcp',
28
+ version: VERSION,
29
+ tools: [(server) => registerAllTools(server, { bridge })],
30
+ 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. ` +
32
+ 'This project was developed and is maintained by AI (Claude). Use at your own discretion.',
33
+ });
@@ -0,0 +1,140 @@
1
+ // The colour a join sends. war.app refuses AcceptOpenSeat without one (verified
2
+ // live: server error 1, "color is null"), so warapp_join_game resolves it the way
3
+ // the web client does (verified from the client bundle, docs/WEB-PROTOCOL.md):
4
+ // the account's preferred colour, else its secondary colour — each only when no
5
+ // player in the lobby has it — else a standard colour still free.
6
+ //
7
+ // The account's colours come from the page itself: every war.app page that runs
8
+ // the client starts it with its startup parameters (`warlight.shared.InitParameters`)
9
+ // as one string of two characters per byte, and those carry the signed-in
10
+ // `warlight.shared.Player`. The Player record is read with the bundle's own reader;
11
+ // only its two GameColor fields are kept (the parameters also carry the session's
12
+ // auth string — never read out, never reported).
13
+ import { Reader } from './protocol/codec.js';
14
+ import { fields, isObj } from './protocol/decoded.js';
15
+ import { GAME_COLOR_COUNT } from './protocol/methods.js';
16
+ const GAME_COLOR = 'warlight.shared.GameColor';
17
+ const PLAYER = 'warlight.shared.Player';
18
+ const INIT_PARAMETERS = 'warlight.shared.InitParameters';
19
+ /** Colours 0..23 are the standard ones (no unlock needed); the client offers these first. */
20
+ export const STANDARD_COLORS = 24;
21
+ /** Player field positions in read order (each checked for its type): the two GameColor fields. */
22
+ const PL = { secondary: 18, preferred: 32 };
23
+ const PL_MIN_FIELDS = 33;
24
+ /** The startup string's alphabet: `>` (62) is 0, `M` (77) is 15. */
25
+ const BASE = 62;
26
+ const RUN_RE = /[>-M]{64,}/g;
27
+ /** How many candidate runs a page is searched for (longest first). */
28
+ const MAX_CANDIDATES = 8;
29
+ /**
30
+ * The client's startup-string decoding: two characters per byte, each `code - 62`
31
+ * a nibble; the first carries the byte's even bits (0, 2, 4, 6), the second its odd
32
+ * bits (1, 3, 5, 7). `undefined` for an odd length or a character outside `>`..`M`.
33
+ */
34
+ export function decodeStartupBytes(s) {
35
+ if (s.length % 2 !== 0)
36
+ return undefined;
37
+ const out = new Uint8Array(s.length / 2);
38
+ for (let i = 0; i < out.length; i++) {
39
+ const g = s.charCodeAt(2 * i) - BASE;
40
+ const f = s.charCodeAt(2 * i + 1) - BASE;
41
+ if (g < 0 || g > 15 || f < 0 || f > 15)
42
+ return undefined;
43
+ let b = 0;
44
+ for (let bit = 0; bit < 4; bit++) {
45
+ b |= ((g >> bit) & 1) << (2 * bit);
46
+ b |= ((f >> bit) & 1) << (2 * bit + 1);
47
+ }
48
+ out[i] = b;
49
+ }
50
+ return out;
51
+ }
52
+ /** The inverse of {@link decodeStartupBytes} (for synthetic pages in tests). */
53
+ export function encodeStartupBytes(bytes) {
54
+ let s = '';
55
+ for (const b of bytes) {
56
+ let g = 0;
57
+ let f = 0;
58
+ for (let bit = 0; bit < 4; bit++) {
59
+ g |= ((b >> (2 * bit)) & 1) << bit;
60
+ f |= ((b >> (2 * bit + 1)) & 1) << bit;
61
+ }
62
+ s += String.fromCharCode(BASE + g, BASE + f);
63
+ }
64
+ return s;
65
+ }
66
+ /** A GameColor record's index; `null` for an absent colour; `undefined` when it is neither. */
67
+ export function colorIndexOf(v) {
68
+ if (v === null)
69
+ return null;
70
+ if (!isObj(v) || v.$type !== GAME_COLOR)
71
+ return undefined;
72
+ const [index] = fields(v);
73
+ return typeof index === 'number' && Number.isInteger(index) && index >= 0 && index < GAME_COLOR_COUNT
74
+ ? index
75
+ : undefined;
76
+ }
77
+ function colorsOfPlayer(p) {
78
+ const f = fields(p);
79
+ if (f.length < PL_MIN_FIELDS)
80
+ return undefined;
81
+ const secondary = colorIndexOf(f[PL.secondary]);
82
+ const preferred = colorIndexOf(f[PL.preferred]);
83
+ if (secondary === undefined || preferred === undefined)
84
+ return undefined;
85
+ return { ...(preferred !== null ? { preferred } : {}), ...(secondary !== null ? { secondary } : {}) };
86
+ }
87
+ /** The account colours in one candidate startup string, or `undefined`. */
88
+ function colorsIn(run, bundle) {
89
+ const bytes = decodeStartupBytes(run);
90
+ if (!bytes)
91
+ return undefined;
92
+ let params;
93
+ try {
94
+ params = bundle.readClass(INIT_PARAMETERS, new Reader(bytes));
95
+ }
96
+ catch {
97
+ return undefined;
98
+ }
99
+ if (!isObj(params) || params.$type !== INIT_PARAMETERS)
100
+ return undefined;
101
+ const player = fields(params).find((v) => isObj(v) && v.$type === PLAYER);
102
+ return player ? colorsOfPlayer(player) : undefined;
103
+ }
104
+ /**
105
+ * The signed-in account's preferred and secondary colours, from the client
106
+ * startup parameters a war.app page carries; `undefined` when the page has none
107
+ * that read (signed out, or the client changed). Never throws.
108
+ */
109
+ export function readAccountColors(html, bundle) {
110
+ const runs = [...html.matchAll(RUN_RE)].map((m) => m[0]);
111
+ runs.sort((a, b) => b.length - a.length);
112
+ for (const run of runs.slice(0, MAX_CANDIDATES)) {
113
+ // A run can pick up a neighbouring `>` (a tag's end): try it trimmed on either side.
114
+ const tries = run.length % 2 === 0 ? [run] : [run.slice(1), run.slice(0, -1)];
115
+ for (const t of tries) {
116
+ const colors = colorsIn(t, bundle);
117
+ if (colors)
118
+ return colors;
119
+ }
120
+ }
121
+ return undefined;
122
+ }
123
+ /**
124
+ * The colour to join with, as the web client picks it: the preferred colour when
125
+ * no lobby player has it, else the secondary, else the first standard colour
126
+ * (0..23) still free. `undefined` when every standard colour is taken.
127
+ */
128
+ export function chooseJoinColor(account, taken) {
129
+ const used = new Set(taken);
130
+ if (account?.preferred !== undefined && !used.has(account.preferred)) {
131
+ return { color: account.preferred, source: 'preferred' };
132
+ }
133
+ if (account?.secondary !== undefined && !used.has(account.secondary)) {
134
+ return { color: account.secondary, source: 'secondary' };
135
+ }
136
+ for (let c = 0; c < STANDARD_COLORS; c++)
137
+ if (!used.has(c))
138
+ return { color: c, source: 'free' };
139
+ return undefined;
140
+ }