@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,404 @@
1
+ // Live-game tools over the web-client protocol (through the user's signed-in
2
+ // war.app tab): the current board, the player's territory picks, and — gated
3
+ // on the user's confirmation — submitting picks.
4
+ import { CONFIRM_INJECTION_RULE, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
5
+ import { z } from 'zod';
6
+ import { clientPickLimits } from '../analysis/picks.js';
7
+ import { isTeamGame } from '../teams.js';
8
+ import { parseGameId } from '../client.js';
9
+ import { FOG_LEVEL_NAMES, inGameId, OWNER_NEUTRAL, OWNER_PICKABLE, playersByInGameId, } from '../live.js';
10
+ import { pickingNeutrals, writePickable, writePickList } from '../pick-list.js';
11
+ import { Method, writeSendTerritoryPicksParams } from '../protocol/methods.js';
12
+ import { currentTurn, gameIdArg, namer, readAnnotations, respond, shownAccount, turnsCompleted, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, UNTRUSTED_LIST_MAX, untrustedList, untrustedText, viewArg, } from './common.js';
13
+ import { lookupMeta, mintMeta } from './hints.js';
14
+ import { loadLiveTerritories, loadPicks, requireApprovedAccount, writeAccount } from './live-context.js';
15
+ import { mapOf } from './map.js';
16
+ import { resolvePlayer, resolveTerritory } from './resolve.js';
17
+ import { defineGatedWrite, requireMySeat, sendAndVerify } from './write-kit.js';
18
+ import { resolveTeamsFor } from './team-source.js';
19
+ const VIEWS = ['compact', 'full'];
20
+ const MAX_PICK_ARGS = 200;
21
+ export const BRIDGE_NOTE = 'Reads through your signed-in war.app tab (ContextMint Bridge), so it sees exactly what you see — fog included.';
22
+ export const playerArg = z
23
+ .union([z.string(), z.number()])
24
+ .optional()
25
+ .describe('You in this game: your war.app name (or part of it) or GameFeed player id. Omit to use the signed-in account.');
26
+ /** `player` when given; else the signed-in account (its invite token is its GameFeed id). */
27
+ export async function resolveMe(ctx, players, input, opts = {}) {
28
+ if (input === undefined || String(input).trim() === '') {
29
+ const token = await ctx.myInviteToken(opts);
30
+ const me = token === undefined ? undefined : players.find((p) => p.id === token);
31
+ if (me)
32
+ return me;
33
+ }
34
+ return resolvePlayer(players, input);
35
+ }
36
+ /** A territory's owner as a person reads it. */
37
+ function ownerLabel(t, byInGame) {
38
+ if (t.fogged)
39
+ return 'fogged';
40
+ if (t.owner === OWNER_NEUTRAL)
41
+ return 'neutral';
42
+ if (t.owner === OWNER_PICKABLE)
43
+ return 'pickable';
44
+ if (t.owner > 0)
45
+ return byInGame.get(t.owner)?.name ?? `player ${t.owner}`;
46
+ return 'unknown';
47
+ }
48
+ /** A unit owner's name, as {@link ownerLabel} names a territory's player owner. */
49
+ function playerLabel(id, byInGame) {
50
+ return byInGame.get(id)?.name ?? `player ${id}`;
51
+ }
52
+ /** The commander(s) on a territory, by owner name; `undefined` when there is none. */
53
+ function commanderOn(t, byInGame) {
54
+ const owners = (t.specialUnits ?? []).filter((u) => u.kind === 'commander').map((u) => playerLabel(u.owner, byInGame));
55
+ return owners.length ? owners.join(', ') : undefined;
56
+ }
57
+ const nameIn = (map) => {
58
+ const name = namer(map);
59
+ return (id) => name(id).name;
60
+ };
61
+ /**
62
+ * The most territory picks war.app's client lets a player list (players × territories per
63
+ * player, #129), when the settings say; `pickable` (the live board's count) can lower it.
64
+ */
65
+ export function maxPicks(game, pickable) {
66
+ return clientPickLimits({ territoryLimit: game.settings?.territoryLimit, players: game.players.length, pickable })?.max ?? null;
67
+ }
68
+ /** The selected territories of `list`, and the page block when paged. */
69
+ function select(list, sel) {
70
+ const matched = list.filter((t) => (sel.ids === undefined || sel.ids.has(t.territoryId)) && (sel.owner === undefined || (!t.fogged && t.owner === sel.owner)));
71
+ if (sel.limit === undefined && sel.offset === undefined)
72
+ return { shown: matched };
73
+ const offset = sel.offset ?? 0;
74
+ const limit = sel.limit ?? matched.length;
75
+ const shown = matched.slice(offset, offset + limit);
76
+ const next = offset + shown.length;
77
+ return { shown, page: { offset, limit, matched: matched.length, nextOffset: next < matched.length ? next : null } };
78
+ }
79
+ function liveBoardView(game, territories, rung, sel = {}) {
80
+ const map = mapOf(game);
81
+ const name = nameIn(map);
82
+ const byInGame = playersByInGameId(game.players);
83
+ const stats = new Map();
84
+ for (const t of territories) {
85
+ if (t.fogged || t.owner <= 0)
86
+ continue;
87
+ const s = stats.get(t.owner) ?? { territories: 0, armies: 0 };
88
+ s.territories++;
89
+ s.armies += t.armies ?? 0;
90
+ stats.set(t.owner, s);
91
+ }
92
+ const header = {
93
+ game: { id: game.id, name: game.name ?? null, state: game.state, turn: currentTurn(game), turnsCompleted: turnsCompleted(game) },
94
+ map: { id: map.id, name: map.name },
95
+ };
96
+ const players = game.players.map((p) => {
97
+ let id = null;
98
+ try {
99
+ id = inGameId(p);
100
+ }
101
+ catch {
102
+ // not a wrapped id
103
+ }
104
+ const s = id === null ? undefined : stats.get(id);
105
+ const row = {
106
+ id: p.id,
107
+ name: p.name,
108
+ visibleTerritories: s?.territories ?? 0,
109
+ visibleArmies: s?.armies ?? 0,
110
+ };
111
+ if (rung === 'full')
112
+ row.inGameId = id;
113
+ return row;
114
+ });
115
+ const pickable = territories.filter((t) => !t.fogged && t.owner === OWNER_PICKABLE).length;
116
+ if (rung === 'full') {
117
+ const { shown, page } = select(territories, sel);
118
+ return {
119
+ ...header,
120
+ players,
121
+ ...(page ? { page } : {}),
122
+ territories: shown.map((t) => ({
123
+ id: t.territoryId,
124
+ name: name(t.territoryId),
125
+ owner: ownerLabel(t, byInGame),
126
+ ownerId: t.owner,
127
+ armies: t.armies,
128
+ fogged: t.fogged,
129
+ fogLevel: FOG_LEVEL_NAMES[t.fogLevel] ?? t.fogLevel,
130
+ specialUnits: (t.specialUnits ?? []).map((u) => ({
131
+ kind: u.kind,
132
+ ...(u.type ? { type: u.type } : {}),
133
+ id: u.id,
134
+ owner: playerLabel(u.owner, byInGame),
135
+ ownerId: u.owner,
136
+ })),
137
+ })),
138
+ };
139
+ }
140
+ const visible = territories.filter((t) => !t.fogged);
141
+ const { shown, page } = select(visible, sel);
142
+ return {
143
+ ...header,
144
+ players,
145
+ ...(page ? { page } : {}),
146
+ territories: shown.map((t) => {
147
+ const commander = commanderOn(t, byInGame);
148
+ return {
149
+ id: t.territoryId,
150
+ name: name(t.territoryId),
151
+ owner: ownerLabel(t, byInGame),
152
+ armies: t.armies,
153
+ ...(commander ? { commander } : {}),
154
+ };
155
+ }),
156
+ counts: { territories: territories.length, visible: visible.length, fogged: territories.length - visible.length, pickable },
157
+ };
158
+ }
159
+ const FALLBACK_NOTE = "Decoded by a cached copy of war.app's client: the current version could not be looked up (a frozen or " +
160
+ 'signed-out tab?). Reload or focus a war.app tab; warapp_session_status shows the decoder.';
161
+ export function registerLiveTools(server, ctx) {
162
+ server.registerTool('warapp_get_live_board', {
163
+ title: 'Get the live board of a war.app game',
164
+ description: untrustedDescription('The current board of a war.app (Warzone) game as the web client shows it: every territory by name with ' +
165
+ 'its owner (a player name, "neutral", or "pickable" while territories are being picked), its armies, ' +
166
+ 'whether it is fogged and, in a Commanders game, whose commander stands on it (losing your commander ' +
167
+ 'eliminates you); plus each player\'s visible territory and army totals. Works in the pick ' +
168
+ 'phase and mid-game, where GameFeed has no board. On a large map, narrow it with `owner`, `territories` or ' +
169
+ `\`limit\`/\`offset\` paging (the counts stay whole-board). ${BRIDGE_NOTE} Read-only.`),
170
+ _meta: lookupMeta(['warzone board', 'live board', 'who owns what', 'pickable territories', 'where is my commander']),
171
+ annotations: readAnnotations('Get a war.app live board'),
172
+ inputSchema: z.object({
173
+ game_id: gameIdArg,
174
+ view: viewArg(VIEWS, 'compact (default) lists the territories you can see (owner by name, armies, `commander` naming the owner of ' +
175
+ 'a commander standing there) with counts of fogged and pickable ones; "full" lists every territory with raw ' +
176
+ 'owner ids, fog flags and fog levels, its special units (commanders, bosses) with owners, and in-game player ids.'),
177
+ owner: z
178
+ .union([z.string(), z.number()])
179
+ .optional()
180
+ .describe('Only territories owned by: "me", "neutral", "pickable", or a player (name or GameFeed id).'),
181
+ territories: z
182
+ .array(z.union([z.string(), z.number()]))
183
+ .min(1)
184
+ .max(MAX_PICK_ARGS)
185
+ .optional()
186
+ .describe('Only these territories (ids or names).'),
187
+ limit: z.coerce.number().int().min(1).max(5000).optional().describe('Page size; omit for every match.'),
188
+ offset: z.coerce.number().int().min(0).optional().describe('Skip this many matches (from a previous `page.nextOffset`).'),
189
+ }),
190
+ }, async ({ game_id, view, owner, territories: only, limit, offset }) => {
191
+ const game = await ctx.client.getGame(game_id, { settings: true });
192
+ const sel = {
193
+ ...(limit !== undefined ? { limit } : {}),
194
+ ...(offset !== undefined ? { offset } : {}),
195
+ };
196
+ if (only)
197
+ sel.ids = new Set(only.map((t) => resolveTerritory(mapOf(game), t).id));
198
+ if (owner !== undefined && String(owner).trim() !== '') {
199
+ const o = String(owner).trim().toLowerCase();
200
+ sel.owner =
201
+ o === 'neutral'
202
+ ? OWNER_NEUTRAL
203
+ : o === 'pickable'
204
+ ? OWNER_PICKABLE
205
+ : inGameId(await resolveMe(ctx, game.players, o === 'me' ? undefined : owner));
206
+ }
207
+ const territories = await loadLiveTerritories(ctx, game);
208
+ const decoder = ctx.decoderReport();
209
+ return respond(view, VIEWS, (rung) => {
210
+ const out = liveBoardView(game, territories, rung, sel);
211
+ // What the decoding rests on (#148): always on full; on compact only when a stand-in decoded it.
212
+ if (!decoder || (rung !== 'full' && !decoder.fallback))
213
+ return out;
214
+ return {
215
+ ...out,
216
+ decoder: rung === 'full'
217
+ ? decoder
218
+ : { bundleVersion: decoder.bundleVersion, fallback: true, note: FALLBACK_NOTE },
219
+ };
220
+ });
221
+ });
222
+ server.registerTool('warapp_get_my_picks', {
223
+ title: 'Get my territory picks in a war.app game',
224
+ description: untrustedDescription('The territory picks you have submitted for a war.app (Warzone) game in manual distribution, in priority ' +
225
+ "order and by name, with the most war.app's client lets a player list (players × the territory limit). " +
226
+ `${BRIDGE_NOTE} Read-only; use warapp_submit_picks to change them.`),
227
+ _meta: lookupMeta(['my picks', 'territory picks', 'what did i pick']),
228
+ annotations: readAnnotations('Get my war.app picks'),
229
+ inputSchema: z.object({ game_id: gameIdArg, player: playerArg }),
230
+ }, async ({ game_id, player }) => {
231
+ const game = await ctx.client.getGame(game_id, { settings: true });
232
+ const me = await resolveMe(ctx, game.players, player);
233
+ const picks = await loadPicks(ctx, game.id, inGameId(me));
234
+ // Kept while territories are being distributed, so the award can be read from it later (#166):
235
+ // only for the signed-in account (no `player` given), the one war.app answers for.
236
+ if (ctx.dataDir && player === undefined && game.state === 'DistributingTerritories' && picks.length)
237
+ await writePickList(ctx.dataDir, game.id, me.id, picks);
238
+ const name = nameIn(mapOf(game));
239
+ return respond(undefined, ['compact'], () => ({
240
+ game: { id: game.id, state: game.state },
241
+ player: { id: me.id, name: me.name },
242
+ picks: picks.map((id, i) => ({ priority: i + 1, id, name: name(id) })),
243
+ count: picks.length,
244
+ maxPicks: maxPicks(game),
245
+ }));
246
+ });
247
+ const submitSchema = z.object({
248
+ game_id: gameIdArg,
249
+ player: playerArg,
250
+ territories: z
251
+ .array(z.union([z.string(), z.number()]))
252
+ .min(1)
253
+ .max(MAX_PICK_ARGS)
254
+ .describe('Your picks in priority order (first = most wanted): territory ids or names. Replaces any picks already submitted.'),
255
+ });
256
+ defineGatedWrite(server, {
257
+ title: 'Submit territory picks in a war.app game',
258
+ _meta: mintMeta('change', ['submit my picks', 'pick territories', 'choose starting territories']),
259
+ }, {
260
+ name: 'warapp_submit_picks',
261
+ description: 'Submit your territory picks for a war.app (Warzone) game in manual distribution, in priority order — ' +
262
+ 'they replace any picks you submitted before. Every territory must be pickable on the live board; a list ' +
263
+ "longer than war.app's client allows (players × territories per player) or shorter than the territories " +
264
+ 'each player is granted is warned about in the preview. After sending, the picks are read back and ' +
265
+ `reported verified only if they match exactly. ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
266
+ annotations: toolAnnotations({
267
+ title: 'Submit war.app picks',
268
+ readOnly: false,
269
+ destructive: true,
270
+ idempotent: true,
271
+ openWorld: true,
272
+ }),
273
+ inputSchema: submitSchema,
274
+ async plan({ game_id, player, territories }) {
275
+ const feed = await ctx.client.getGame(parseGameId(game_id), { settings: true });
276
+ const map = mapOf(feed);
277
+ // A write through the bridge always acts as the signed-in account, whatever `player` says
278
+ // (issue #7): a different player, an unknown account and an account without a seat are refused.
279
+ const seat = await requireMySeat(ctx, feed, { player, playing: false });
280
+ // The teams (the team-game warning): GameFeed's, else the game list's (asked once per game, kept).
281
+ const { game, me } = await resolveTeamsFor(ctx, feed, seat);
282
+ const picks = territories.map((t) => resolveTerritory(map, t));
283
+ const seen = new Set();
284
+ for (const t of picks) {
285
+ if (seen.has(t.id)) {
286
+ throw new McpToolError(`${untrustedText(t.name)} (${t.id}) is listed twice.`, { hint: 'List each territory once.' });
287
+ }
288
+ seen.add(t.id);
289
+ }
290
+ const board = await loadLiveTerritories(ctx, game);
291
+ const owner = new Map(board.map((t) => [t.territoryId, t]));
292
+ const unpickable = picks.filter((t) => {
293
+ const s = owner.get(t.id);
294
+ return !s || s.fogged || s.owner !== OWNER_PICKABLE;
295
+ });
296
+ if (unpickable.length) {
297
+ throw new McpToolError(`Not pickable on the live board: ${untrustedList(unpickable, UNTRUSTED_LIST_MAX, (t) => `${untrustedText(t.name)} (${t.id})`)}.`, {
298
+ hint: game.state === 'DistributingTerritories'
299
+ ? 'Pick only territories warapp_get_live_board lists as "pickable".'
300
+ : `Picks are only open while the game distributes territories (game state: ${game.state}).`,
301
+ });
302
+ }
303
+ // The list's length is checked against the client's own bounds (#129) as a warning:
304
+ // its picking UI stops at the maximum, and its validation rejects a list shorter
305
+ // than the minimum, but neither is verified against the server.
306
+ const pickable = board.filter((t) => !t.fogged && t.owner === OWNER_PICKABLE).map((t) => t.territoryId);
307
+ const pickableCount = pickable.length;
308
+ // Kept for the turns to come: where a player could have started (warapp_locate_opponents).
309
+ // #201: with the picking board's neutrals, so a fogged one keeps its size later.
310
+ if (ctx.dataDir)
311
+ await writePickable(ctx.dataDir, game.id, me.id, pickable, pickingNeutrals(board));
312
+ const bounds = clientPickLimits({
313
+ territoryLimit: game.settings?.territoryLimit,
314
+ players: game.players.length,
315
+ pickable: pickableCount,
316
+ });
317
+ const lengthWarnings = [];
318
+ if (bounds && picks.length > bounds.max)
319
+ lengthWarnings.push(`war.app's client lets a player list at most ${bounds.max} picks here (${game.players.length} players × ${bounds.perPlayer} territories each); got ${picks.length}. The extra picks may be ignored.`);
320
+ // A team game (C2): my list and my teammate's are not agreed, so a pick we both list goes to one of
321
+ // us; a list as long as the client allows (starts × all players) is the one that cannot run out.
322
+ if (bounds && isTeamGame(game.players) && picks.length < bounds.max)
323
+ lengthWarnings.push(`In a team game your list and your teammate's are not agreed: a pick you both list goes to one of you. ` +
324
+ `A list of ${bounds.max} picks (${game.players.length} players × ${bounds.perPlayer} each) cannot run out; got ${picks.length}. ` +
325
+ "A shorter list is safe only when no teammate lists any of its picks (warapp_plan_picks shortens it only then).");
326
+ if (bounds && picks.length < bounds.min)
327
+ lengthWarnings.push(`war.app expects at least ${bounds.min} picks here (the territories each player is granted); got ${picks.length}, which it may reject.`);
328
+ const playerId = inGameId(me);
329
+ const territoryIds = picks.map((t) => t.id);
330
+ const named = picks.map((t) => ({ id: t.id, name: t.name }));
331
+ return {
332
+ gate: {
333
+ action: 'warapp.submit_picks',
334
+ // By id only: player and territory names are other people's words and go,
335
+ // delimited, in labelled fields.
336
+ summary: `Submit ${picks.length} territory pick${picks.length === 1 ? '' : 's'} for player ${me.id} in game ${game.id}`,
337
+ account: writeAccount(me.id),
338
+ target: game.id,
339
+ payload: { method: 'SendTerritoryPicks', gameId: game.id, playerId, territoryIds },
340
+ willSend: {
341
+ game: game.id,
342
+ player: untrustedText(me.name),
343
+ picksInPriorityOrder: named.map((t) => ({ id: t.id, name: untrustedText(t.name) })),
344
+ },
345
+ preview: {
346
+ account: shownAccount(me.name, me.id),
347
+ note: 'Replaces any picks already submitted for this game.',
348
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
349
+ ...(lengthWarnings.length ? { warnings: lengthWarnings } : {}),
350
+ },
351
+ },
352
+ state: { gameId: game.id, playerId, picks: named, me: me.id },
353
+ };
354
+ },
355
+ async execute({ gameId, playerId, picks, me }) {
356
+ await requireApprovedAccount(ctx, writeAccount(me));
357
+ const ids = picks.map((p) => p.id);
358
+ const base = { game: gameId, picks };
359
+ return sendAndVerify({
360
+ send: async () => {
361
+ await ctx.rpc.call('SendTerritoryPicks', Method.SendTerritoryPicks, (w) => writeSendTerritoryPicksParams(w, gameId, ids));
362
+ },
363
+ unanswered: (failure) => ({
364
+ status: 'unknown',
365
+ outcome: 'unknown',
366
+ verified: false,
367
+ ...base,
368
+ readBack: null,
369
+ warning: `war.app did not confirm the picks (${failure}), so they may already have been saved. ` +
370
+ 'Check warapp_get_my_picks before resubmitting.',
371
+ }),
372
+ readBack: () => loadPicks(ctx, gameId, playerId),
373
+ // The send went through: a failed read-back must not hide that (#130).
374
+ unreadable: (failure) => ({
375
+ status: 'unconfirmed',
376
+ outcome: 'unconfirmed',
377
+ sent: true,
378
+ verified: false,
379
+ ...base,
380
+ readBack: null,
381
+ readBackError: failure,
382
+ warning: 'war.app accepted the picks, but reading them back failed. Check warapp_get_my_picks before resubmitting.',
383
+ }),
384
+ classify: async (readBack) => {
385
+ // What war.app holds is the list the award will use: kept to read the award from (#166).
386
+ if (ctx.dataDir && readBack.length)
387
+ await writePickList(ctx.dataDir, gameId, me, readBack);
388
+ const verified = readBack.length === ids.length && readBack.every((id, i) => id === ids[i]);
389
+ return verified
390
+ ? { status: 'verified', outcome: 'confirmed', sent: true, verified, ...base, readBack }
391
+ : {
392
+ status: 'unconfirmed',
393
+ outcome: 'unconfirmed',
394
+ sent: true,
395
+ verified,
396
+ ...base,
397
+ readBack,
398
+ warning: 'war.app did not read back exactly these picks. Check warapp_get_my_picks before resubmitting.',
399
+ };
400
+ },
401
+ });
402
+ },
403
+ });
404
+ }
@@ -0,0 +1,88 @@
1
+ // A map's distribution modes with the territories each lets a player start on (#328), read lazily from war.app's
2
+ // map details (GetMapDetails, method 73, no auth) through the web-client channel and kept with the map
3
+ // (src/map-store.ts). Asked only when a caller needs a mode's territories and the map lacks them, at most once
4
+ // per map per process (a failure is never retried in a loop); a failure leaves them unknown (`null`), never `[]`.
5
+ // UNVERIFIED live beyond #328's trace (src/map-details.ts).
6
+ import { applyModeTerritories, readMapDetailsModes } from '../map-details.js';
7
+ import { Method, writeGetMapDetailsParams } from '../protocol/methods.js';
8
+ import { failureText } from './live-context.js';
9
+ const known = (d) => Array.isArray(d.territories);
10
+ /** `map` with every mode not known marked unknown (`null`). */
11
+ const unknownRest = (map) => ({
12
+ ...map,
13
+ distributionModes: map.distributionModes.map((d) => (known(d) ? d : { ...d, territories: null })),
14
+ });
15
+ const UNKNOWN = (map, why) => `The starting territories of map ${map.id}'s distribution modes could not be read from war.app's map details (${why}); ` +
16
+ 'they stay unknown and are not asked again until the server restarts.';
17
+ /**
18
+ * `map` (the game's, overrides applied or not) with its modes' territories: what the cached map already has,
19
+ * else read from war.app's map details and kept (the cached base map and the store). Never throws.
20
+ */
21
+ export async function withModeTerritories(ctx, map) {
22
+ if (map.distributionModes.every(known))
23
+ return { map, warnings: [] };
24
+ if (ctx.client.mapDetailsTried(map.id)) {
25
+ return { map: unknownRest(map), warnings: [UNKNOWN(map, 'an earlier read this session did not give them')] };
26
+ }
27
+ ctx.client.markMapDetailsTried(map.id);
28
+ let byMode;
29
+ try {
30
+ const env = await ctx.rpc.call('GetMapDetails', Method.GetMapDetails, (w) => writeGetMapDetailsParams(w, map.id));
31
+ byMode = readMapDetailsModes(await ctx.bundle(), env.body);
32
+ }
33
+ catch (e) {
34
+ return { map: unknownRest(map), warnings: [UNKNOWN(map, failureText(e))] };
35
+ }
36
+ if (byMode === null)
37
+ return { map: unknownRest(map), warnings: [UNKNOWN(map, 'the reply carried no result')] };
38
+ const read = applyModeTerritories(map, byMode);
39
+ if (read.found.size)
40
+ await ctx.client.keepModeTerritories(map.id, read.found).catch(() => { });
41
+ const missing = read.map.distributionModes.filter((d) => d.territories === null).map((d) => d.id);
42
+ const warnings = [...read.warnings];
43
+ if (missing.length)
44
+ warnings.push(UNKNOWN(map, `none listed for mode${missing.length === 1 ? '' : 's'} ${missing.join(', ')}`));
45
+ return { map: read.map, warnings };
46
+ }
47
+ /** One mode as warapp_get_map's full view lists it: its territory count and ids, `null` both when unknown. */
48
+ export function modeRow(d) {
49
+ const ids = Array.isArray(d.territories) ? d.territories : null;
50
+ return {
51
+ id: d.id,
52
+ name: d.name,
53
+ ...(d.type !== undefined ? { type: d.type } : {}),
54
+ territoryCount: ids ? ids.length : null,
55
+ territories: ids,
56
+ };
57
+ }
58
+ /**
59
+ * The map distribution mode an automatically distributed game dealt its starts from (#328): its settings say
60
+ * `AutomaticTerritoryDistribution` "Automatic" and name, as `DistributionMode`, a mode of the map. `undefined`
61
+ * otherwise — manual picks (the live board's pickable territories say where then), full distribution (-1),
62
+ * random or custom distributions (no map mode), or settings that do not say.
63
+ */
64
+ export function dealtMode(settings, map) {
65
+ if (settings?.raw.AutomaticTerritoryDistribution !== 'Automatic' || settings.distributionMode === undefined)
66
+ return undefined;
67
+ return map.distributionModes.find((d) => d.id === settings.distributionMode);
68
+ }
69
+ /**
70
+ * The territories `mode` (a mode of `map`) dealt starts among: what the map already has, else read once from
71
+ * war.app's map details ({@link withModeTerritories}). Unknown (`null`, with the reasons) when the read failed or
72
+ * listed none for it. Never throws.
73
+ */
74
+ export async function modeStarts(ctx, map, mode) {
75
+ const read = await withModeTerritories(ctx, map);
76
+ const ids = read.map.distributionModes.find((d) => d.id === mode)?.territories;
77
+ if (Array.isArray(ids) && ids.length)
78
+ return { mode, territories: ids };
79
+ return {
80
+ mode,
81
+ territories: null,
82
+ warnings: [
83
+ `The game dealt its starts automatically from the map's distribution mode ${mode}, whose territories are unknown, ` +
84
+ 'so they are not used as start candidates.',
85
+ ...read.warnings,
86
+ ],
87
+ };
88
+ }
@@ -0,0 +1,130 @@
1
+ // warapp_map_stats: what has worked on a map, learned from finished ladder
2
+ // games — OPT-IN (WARAPP_STATS=1) and never on a hosted server. See
3
+ // src/stats.ts (collection, throttle, cache) and src/map-stats.ts (the pure
4
+ // aggregation).
5
+ import { McpToolError } from '@chrischall/mcp-utils';
6
+ import { z } from 'zod';
7
+ import { MIN_RATE_SAMPLE, MIN_SAMPLE, mapStats } from '../map-stats.js';
8
+ import { DEFAULT_NEW_GAMES, MAX_NEW_GAMES, STATS_ENV, statsGate } from '../stats.js';
9
+ import { readAnnotations, respond, untrustedDescription } from './common.js';
10
+ import { lookupMeta } from './hints.js';
11
+ import { mapRecordFor, mapRecordView } from './past-games.js';
12
+ function refusal(gate) {
13
+ if (gate.reason === 'hosted') {
14
+ return new McpToolError('Map statistics are off on a hosted server.', {
15
+ hint: 'They make many war.app requests and keep a cache on disk, so they run only on a local install with ' +
16
+ `${STATS_ENV}=1 set. Use warapp_get_map for the map's bonuses meanwhile.`,
17
+ });
18
+ }
19
+ return new McpToolError('Map statistics are off (opt-in).', {
20
+ hint: `Set ${STATS_ENV}=1 in this server's environment (or its .env file) on a local install and restart it. ` +
21
+ `Each call then fetches up to ${DEFAULT_NEW_GAMES} new finished ladder games (at most ${MAX_NEW_GAMES}), ` +
22
+ 'one request a second, and caches them forever.',
23
+ });
24
+ }
25
+ /** Attach territory and bonus names when the map is known (cached this process). */
26
+ function named(stats, map) {
27
+ const territory = new Map(map?.territories.map((t) => [t.id, t.name]));
28
+ const bonus = new Map(map?.bonuses.map((b) => [b.id, b.name]));
29
+ return {
30
+ ...stats,
31
+ mostPicked: stats.mostPicked.map(({ territoryId, ...rest }) => ({
32
+ territoryId,
33
+ ...(territory.has(territoryId) ? { name: territory.get(territoryId) } : {}),
34
+ ...rest,
35
+ })),
36
+ winRateByStartingBonus: stats.winRateByStartingBonus.map(({ bonusId, ...rest }) => ({
37
+ bonusId,
38
+ ...(bonus.has(bonusId) ? { name: bonus.get(bonusId) } : {}),
39
+ ...rest,
40
+ })),
41
+ };
42
+ }
43
+ export function registerMapStatsTool(server, deps) {
44
+ server.registerTool('warapp_map_stats', {
45
+ title: 'war.app map statistics',
46
+ description: untrustedDescription('Statistics for a war.app (Warzone) map learned from finished ladder games: the most-picked starting ' +
47
+ 'territories (and how often their pickers won), the win rate by every bonus a player started in, the ' +
48
+ 'turn of each player’s first bonus completion, and the sample size — a sample under ' +
49
+ `${MIN_SAMPLE} games and a bonus rate under ${MIN_RATE_SAMPLE} players are flagged, and games whose history ` +
50
+ 'could not be read are counted apart, never cached. Each call reads the ladder’s game-ID feed and fetches up to ' +
51
+ `max_new_games new games (default ${DEFAULT_NEW_GAMES}, max ${MAX_NEW_GAMES}, one request a second); ` +
52
+ 'finished games are cached forever, so stats grow across calls. OPT-IN: off unless the server runs ' +
53
+ `locally with ${STATS_ENV}=1, and always off when hosted. ` +
54
+ '`myGames` adds your own finished games on the map, from their histories (no request): results, your results by start bonus, the ' +
55
+ "bonuses winners started in, and the pace — the median income after turns 4 and 8 of the winners and of you. Read-only."),
56
+ _meta: lookupMeta(['map stats', 'best starting picks', 'ladder statistics', 'which bonus wins']),
57
+ annotations: readAnnotations('war.app map statistics'),
58
+ inputSchema: z.object({
59
+ map_id: z.number().int().positive().describe('The map id (warapp_get_game names it under settings.mapId).'),
60
+ ladder_id: z
61
+ .number()
62
+ .int()
63
+ .min(0)
64
+ .optional()
65
+ .describe('The ladder whose games to learn from: 1v1 is 0 (default), 2v2 is 1, 3v3 is 4.'),
66
+ max_new_games: z
67
+ .number()
68
+ .int()
69
+ .min(0)
70
+ .max(MAX_NEW_GAMES)
71
+ .optional()
72
+ .describe(`New games to fetch this call (default ${DEFAULT_NEW_GAMES}, max ${MAX_NEW_GAMES}); 0 reads the cache only.`),
73
+ }),
74
+ }, async ({ map_id, ladder_id, max_new_games }) => {
75
+ const gate = statsGate(deps.env);
76
+ if (!gate.enabled)
77
+ throw refusal(gate);
78
+ const ladderId = ladder_id ?? 0;
79
+ // 0 reads the cache only: no feed request, so no throttle either.
80
+ let collected = { ladderId, cacheOnly: true };
81
+ let warning;
82
+ let feedError;
83
+ if (max_new_games !== 0) {
84
+ try {
85
+ collected = await deps.collector.collect(ladderId, max_new_games ?? DEFAULT_NEW_GAMES);
86
+ }
87
+ catch (e) {
88
+ collected = undefined;
89
+ feedError = e;
90
+ }
91
+ }
92
+ const records = await deps.collector.records(map_id);
93
+ if (feedError !== undefined) {
94
+ // The feed failed: the cache can still answer; with nothing cached the error stands.
95
+ if (records.length === 0)
96
+ throw feedError;
97
+ const why = feedError instanceof Error ? feedError.message : String(feedError);
98
+ warning = `The game-ID feed failed (${why}), so no new games were collected; these stats are from the cache.`;
99
+ }
100
+ const [stats] = mapStats(records);
101
+ const map = deps.mapCache.get(map_id);
102
+ // #312 E3: my own finished games on the map (the end-of-game record; no request).
103
+ const mine = await mapRecordFor(deps.dataDir?.(), deps.env, map_id);
104
+ const names = new Map(map?.bonuses.map((b) => [b.id, b.name]));
105
+ return respond(undefined, ['compact'], () => ({
106
+ map: map ? { id: map.id, name: map.name } : { id: map_id },
107
+ ...(collected ? { collected } : {}),
108
+ ...(warning ? { warning } : {}),
109
+ ...(mine
110
+ ? {
111
+ myGames: mine === 'unreadable'
112
+ ? mine
113
+ : mapRecordView(mine, { bonusName: (id) => ({ id, name: names.get(id) ?? String(id) }), full: true }),
114
+ }
115
+ : {}),
116
+ ...(stats
117
+ ? { stats: named(stats, map) }
118
+ : {
119
+ message: `No finished games on map ${map_id} are cached yet. Ladder games use many maps: call again to ` +
120
+ 'collect more, or try the ladder this map is played on.',
121
+ }),
122
+ assumptions: 'Starting territories are read from the first history board where players hold land (a game with no ' +
123
+ 'such board is left out of every figure and never cached; `collected.unreadable` says how many this call skipped, ' +
124
+ 'across the ladder, and `collected.unreadableGames` why, by key name), a player counts toward every bonus holding one ' +
125
+ 'of its starts, and a bonus ' +
126
+ 'turn is the history entry (completed turns) on which a player first held a whole positive bonus. ' +
127
+ 'The game-ID feed and history shapes are unverified (docs/WARAPP-API.md).',
128
+ }));
129
+ });
130
+ }