@chrischall/warapp-mcp 0.0.0 → 0.1.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 (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,123 @@
1
+ // warapp_my_games: the signed-in account's games through the web client's
2
+ // GetMyGames, with which ones are waiting on me — the group's canonical
3
+ // "what's new" tool, so it also answers `view: 'brief'`.
4
+ //
5
+ // The whole list (#260): the client's default filters (`Default`, 10 games) are the dashboard's
6
+ // short list, so every caller asks `All` with a count, widened while war.app fills it
7
+ // (MY_GAMES_WINDOWS). The client itself never pages GetMyGames (its writer sends the int32 after
8
+ // the filters as a constant 0, and the one other list it asks takes `count` 100), so a wider
9
+ // count is how the whole list is read. UNVERIFIED live: that `All` lists lobbies and finished
10
+ // games together and that the server honours a count above 10.
11
+ import { untrustedEnvelope } from '@chrischall/mcp-utils';
12
+ import { z } from 'zod';
13
+ import { briefGameLine, isFinished, readMyGames, summarizeMyGames } from '../my-games.js';
14
+ import { Method, MY_GAMES_DEFAULT_SORT, MyGamesFilterType, writeGetMyGamesParams } from '../protocol/methods.js';
15
+ import { readAnnotations, respond, untrustedDescription, WARAPP_UNTRUSTED_NOTE } from './common.js';
16
+ import { canonicalMeta } from './hints.js';
17
+ import { BRIDGE_NOTE } from './live.js';
18
+ import { accountUnknown } from './write-kit.js';
19
+ const VIEWS = ['compact', 'brief'];
20
+ /** The note line a brief answer ends with when the list may be partial (a `-- ` line is never a game). */
21
+ const partialLine = (listed) => `-- the list may be partial: war.app returned ${listed} games, the most this server asks for`;
22
+ function briefResult(games, partialOf) {
23
+ const lines = games.length ? games.map(briefGameLine) : ['-- none'];
24
+ if (partialOf !== undefined)
25
+ lines.push(partialLine(partialOf));
26
+ return { content: [{ type: 'text', text: JSON.stringify(untrustedEnvelope(lines, { note: WARAPP_UNTRUSTED_NOTE })) }] };
27
+ }
28
+ /**
29
+ * The counts GetMyGames is asked for, in turn (#260): a reply that fills its count may have left games out,
30
+ * so the list is asked again with the next; one that fills the last is reported as possibly partial.
31
+ */
32
+ export const MY_GAMES_WINDOWS = [100, 400, 1600];
33
+ /**
34
+ * Every game of the account through `read` (one GetMyGames request with these filters): `All` (lobbies, games
35
+ * being picked or played, finished games), asked with each count of `windows` in turn until a reply does not
36
+ * fill it. A failed first read throws; a failed wider read keeps the last list, as partial.
37
+ */
38
+ export async function listMyGames(read, windows = MY_GAMES_WINDOWS) {
39
+ let games = [];
40
+ let requests = 0;
41
+ for (const count of windows) {
42
+ const filters = { filterType: MyGamesFilterType.All, count, sort: MY_GAMES_DEFAULT_SORT };
43
+ requests++;
44
+ if (requests === 1)
45
+ games = await read(filters);
46
+ else {
47
+ try {
48
+ games = await read(filters);
49
+ }
50
+ catch {
51
+ return { games, partial: true, requests };
52
+ }
53
+ }
54
+ if (games.length < count)
55
+ return { games, partial: false, requests };
56
+ }
57
+ return { games, partial: true, requests };
58
+ }
59
+ /** The signed-in account's in-game id; refuses when it cannot be read. */
60
+ async function myInGameId(ctx) {
61
+ const me = await ctx.myInGameId();
62
+ if (me === undefined) {
63
+ throw accountUnknown(ctx.hosted, 'its games cannot be listed');
64
+ }
65
+ return me;
66
+ }
67
+ /** The signed-in account's in-game id and every game of its, through GetMyGames ({@link listMyGames}). */
68
+ export async function fetchMyGames(ctx) {
69
+ const read = async (filters) => {
70
+ const env = await ctx.rpc.call('GetMyGames', Method.GetMyGames, (w) => writeGetMyGamesParams(w, filters));
71
+ return readMyGames(await ctx.bundle(), env.body);
72
+ };
73
+ const [me, list] = await Promise.all([myInGameId(ctx), listMyGames(read)]);
74
+ return { me, ...list };
75
+ }
76
+ export function registerMyGamesTool(server, ctx) {
77
+ server.registerTool('warapp_my_games', {
78
+ title: 'List my war.app games and which need me',
79
+ description: untrustedDescription('Your war.app (Warzone) games, games waiting on you first: each with its id, name, state ' +
80
+ '(WaitingForPlayers, DistributingTerritories, Playing, Finished), turn, players (name, state, whether ' +
81
+ 'they have committed this turn) and waitingOnYou — true when the game is being played or distributing ' +
82
+ 'territories, you are still playing, and you have not committed. Finished games are left out unless ' +
83
+ '`include_finished` (`finishedLeftOut` counts them). `listed` is how many games war.app returned and ' +
84
+ '`complete` false (with a `warning`) means the list may be partial. Use the id with the other warapp tools. ' +
85
+ `${BRIDGE_NOTE} Read-only.`),
86
+ _meta: canonicalMeta('whats-new', ['my games', 'warzone', 'whose turn', 'games waiting on me', 'which games need me']),
87
+ annotations: readAnnotations('List my war.app games'),
88
+ inputSchema: z.object({
89
+ view: z
90
+ .enum(VIEWS)
91
+ .optional()
92
+ .describe('"compact" (default): the games as described. "brief": one line per game — name — "turn N" (or the ' +
93
+ 'state when not being played) — "waiting on you" or "waiting on others", inside the untrusted-data ' +
94
+ 'envelope as data: string[]; "-- none" when there are no games, and a last "-- the list may be ' +
95
+ 'partial…" line when it may be.'),
96
+ include_finished: z
97
+ .boolean()
98
+ .optional()
99
+ .describe('List finished games too (default false: lobbies and games being picked or played).'),
100
+ }),
101
+ }, async ({ view, include_finished }) => {
102
+ const { me, games: raw, partial } = await fetchMyGames(ctx);
103
+ const kept = include_finished ? raw : raw.filter((g) => !isFinished(g));
104
+ const games = summarizeMyGames(kept, me);
105
+ if (view === 'brief')
106
+ return briefResult(games, partial ? raw.length : undefined);
107
+ const finishedLeftOut = raw.length - kept.length;
108
+ return respond(undefined, ['compact'], () => ({
109
+ games,
110
+ count: games.length,
111
+ waitingOnYou: games.filter((g) => g.waitingOnYou).length,
112
+ listed: raw.length,
113
+ ...(finishedLeftOut ? { finishedLeftOut } : {}),
114
+ complete: !partial,
115
+ ...(partial
116
+ ? {
117
+ warning: `The list may be partial: war.app returned ${raw.length} games, the most this server asks for. ` +
118
+ 'A game missing here can still be read by id with warapp_get_game.',
119
+ }
120
+ : {}),
121
+ }));
122
+ });
123
+ }
@@ -0,0 +1,104 @@
1
+ // warapp_list_open_games: the open games war.app's OpenGames page lists, decoded
2
+ // from the page's embedded payload (src/open-games.ts) — a page GET, so it works
3
+ // over the direct transport with no browser. Read-only.
4
+ import { McpToolError } from '@chrischall/mcp-utils';
5
+ import { z } from 'zod';
6
+ import { filterOpenGames, joiningPolicy, lotteryOf, lotteryShape, markJoined, withLottery, OPEN_GAMES_URL, parseOpenGamesPage, } from '../open-games.js';
7
+ import { readAnnotations, respond, untrustedDescription } from './common.js';
8
+ import { noBrowserNote } from './session.js';
9
+ import { lookupMeta } from './hints.js';
10
+ /** The OpenGames page as text, or a tool error with a hint. */
11
+ export async function openGamesPage(ctx) {
12
+ try {
13
+ return await ctx.fetchPage(OPEN_GAMES_URL);
14
+ }
15
+ catch (e) {
16
+ throw new McpToolError(`Could not read war.app's open games page: ${e instanceof Error ? e.message : String(e)}`, {
17
+ kind: 'unknown',
18
+ hint: (ctx.hosted ? 'Make sure' : 'Link a session with warapp_link_session to read it without a browser, or make sure') +
19
+ ' a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.',
20
+ cause: e,
21
+ });
22
+ }
23
+ }
24
+ /** At most this many lobbies' maps are fetched from GameFeed per call to tell a lottery (#217). */
25
+ export const LOTTERY_LOOKUPS = 5;
26
+ /** A lobby's map size: the cached map, else (when `fetch`) GameFeed's; undefined when unread. */
27
+ async function territoryCount(ctx, game, fetch) {
28
+ const cached = ctx.client.cachedMap(game.mapId);
29
+ if (cached)
30
+ return cached.territories.length;
31
+ if (!fetch)
32
+ return undefined;
33
+ try {
34
+ return (await ctx.client.getGame(game.id))?.map?.territories.length;
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ /**
41
+ * `games` with `lottery` / `lotteryBasis` set where the data says so (#217, {@link lotteryOf}): a
42
+ * cached map is used for every game; GameFeed is asked (map included) only for lobbies whose
43
+ * settings fit the lottery shape, at most {@link LOTTERY_LOOKUPS} per call. Never throws.
44
+ */
45
+ export async function markLotteries(ctx, games) {
46
+ let lookups = 0;
47
+ const fetchFor = games.map((g) => lotteryShape(g) && !ctx.client.cachedMap(g.mapId) && lookups++ < LOTTERY_LOOKUPS);
48
+ return Promise.all(games.map(async (g, i) => {
49
+ const verdict = lotteryOf(g, await territoryCount(ctx, g, fetchFor[i]));
50
+ return verdict ? withLottery(g, verdict) : g;
51
+ }));
52
+ }
53
+ export function registerOpenGamesTool(server, ctx) {
54
+ server.registerTool('warapp_list_open_games', {
55
+ title: 'List open war.app games to join',
56
+ description: untrustedDescription('Open war.app (Warzone) games you could join, from war.app\'s Open Games page: each with its id, name, url, ' +
57
+ 'pace (multi-day or real-time), boot time, players seated, open seats, seats in all, team game or not, ' +
58
+ 'map id, entry fee and prize in coins, cards, rules (the settings flags the game carries, in war.app\'s ' +
59
+ 'wording) and plannerGaps — rules the turn planner does not model yet. joined: true marks a game you ' +
60
+ 'already hold a seat in (when the signed-in account can be told). By default only free, multi-day, ' +
61
+ 'no-team games. policyBreaks lists the joining-policy rules a game breaks (Commerce, mods, custom ' +
62
+ 'scenarios, more than four seats, a boot time under 12 hours, a lottery (a likely one too)); the neutral cost is checked by ' +
63
+ 'warapp_join_game\'s preview. lottery: true marks a lottery from the data, never the name — a map of at ' +
64
+ 'most four territories (its size read from GameFeed for lobbies with base income 0 and overridden ' +
65
+ 'bonuses, or from a map already cached); lottery: null is that settings shape with the map size unread; ' +
66
+ 'lotteryBasis says which. hiddenByPrerequisites counts games war.app hides from this account.' +
67
+ `${noBrowserNote(ctx.hosted)} Read-only.`),
68
+ _meta: lookupMeta(['open games', 'find a game', 'join a game', 'new warzone game', 'games to join']),
69
+ annotations: readAnnotations('List open war.app games'),
70
+ inputSchema: z.object({
71
+ pace: z
72
+ .enum(['multi-day', 'real-time', 'both'])
73
+ .optional()
74
+ .describe('Game pace (default multi-day).'),
75
+ max_players: z.number().int().positive().optional().describe('At most this many seats in the game.'),
76
+ free_only: z.boolean().optional().describe('Only games without a coin entry fee (default true).'),
77
+ exclude_teams: z.boolean().optional().describe('Leave out team games (default true).'),
78
+ limit: z.number().int().positive().max(200).optional().describe('At most this many games (default 25).'),
79
+ }),
80
+ }, async ({ pace, max_players, free_only, exclude_teams, limit }) => {
81
+ const [html, myId] = await Promise.all([openGamesPage(ctx), ctx.myInGameId()]);
82
+ const parsed = parseOpenGamesPage(html, await ctx.bundle());
83
+ const marked = myId === undefined ? parsed.games : markJoined(parsed.games, parsed.lobbies, myId);
84
+ const filtered = filterOpenGames(marked, {
85
+ ...(pace ? { pace } : {}),
86
+ ...(max_players !== undefined ? { max_players } : {}),
87
+ ...(free_only !== undefined ? { free_only } : {}),
88
+ ...(exclude_teams !== undefined ? { exclude_teams } : {}),
89
+ limit: limit ?? 25,
90
+ });
91
+ // #134: advisory — the neutral-cost part needs each lobby's GameFeed settings, so only the join preview has it.
92
+ const games = (await markLotteries(ctx, filtered)).map((g) => {
93
+ const { breaks } = joiningPolicy(g, null);
94
+ return breaks.length ? { ...g, policyBreaks: breaks } : g;
95
+ });
96
+ return respond(undefined, ['compact'], () => ({
97
+ games,
98
+ count: games.length,
99
+ listed: parsed.games.length,
100
+ ...(parsed.hiddenByPrerequisites !== undefined ? { hiddenByPrerequisites: parsed.hiddenByPrerequisites } : {}),
101
+ ...(parsed.note ? { warning: parsed.note } : {}),
102
+ }));
103
+ });
104
+ }
@@ -0,0 +1,151 @@
1
+ import { z } from 'zod';
2
+ import { INFER_REACH, MAX_LISTED_COMBINATIONS, TRACKED_MIN_TURNS, trackGame, trackOpponents } from '../analysis/index.js';
3
+ import { boardStateFromLive } from '../live.js';
4
+ import { CACHED_TURNS, writeBoardCache } from '../trend.js';
5
+ import { writeGameRecord } from '../replay.js';
6
+ import { gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, viewArg } from './common.js';
7
+ import { lookupMeta } from './hints.js';
8
+ import { loadLiveGame } from './live-context.js';
9
+ import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
10
+ import { mapOf } from './map.js';
11
+ import { recordProfile } from './profile-hook.js';
12
+ import { boardHistory, currentTurn, plannerSettings, requireTurnPhase } from './turn.js';
13
+ import { resolveTeamsFor } from './team-source.js';
14
+ const VIEWS = ['compact', 'full'];
15
+ export function registerOpponentsTool(server, ctx, deps = {}) {
16
+ server.registerTool('warapp_track_opponents', {
17
+ title: 'Track my opponents in a war.app game',
18
+ description: untrustedDescription('Track each opponent of an in-progress war.app (Warzone) game over your own board history (the boards ' +
19
+ `warapp_plan_turn and this tool have read, the last ${CACHED_TURNS} turns, or the game history when war.app sends it): ` +
20
+ 'per opponent, by name, its observed deploy each turn (the net change of its armies on territories visible ' +
21
+ 'both turns plus what its captures cost; a stack that only came out of the fog is not income, and no turn ' +
22
+ 'exceeds what it could earn), its income estimate (each observed deploy is a lower bound under fog, so: the ' +
23
+ 'largest of its last three observed turns, or its visible army growth plus losses per turn (stacks out of the fog left out) when more, capped ' +
24
+ 'at what it could earn and at least its base income plus the bonuses it visibly holds; it never decays: an ' +
25
+ 'earlier figure is carried until a bonus it visibly held is visibly broken; orders you sent through warapp_submit_turn count as measurements; with the method used ' +
26
+ 'and the observed range; a turn whose armies could read two ways — a stack walking in from the fog or a deploy, ' +
27
+ 'a capture reinforced on its visible attacker or a stack out of the fog, my emptied territory taken — gives its ' +
28
+ 'low–high range), its unexplainedArmies (income earned since first seen minus its visible army change, losses ' +
29
+ 'and likely combat deaths: in the fog, spent there, or a misread) and inferred bonuses (the ' +
30
+ 'combinations of bonuses it could hold whose values best explain the gap between that income and what it ' +
31
+ `visibly earns, only those within ${INFER_REACH} hops of its territories that it could have paid for, nearest first — ` +
32
+ `as candidates, none listed when more than ${MAX_LISTED_COMBINATIONS} fit). Once an opponent has ${TRACKED_MIN_TURNS}+ ` +
33
+ "observed turns, warapp_plan_turn uses this income in place of the single-turn observed figure. Every opponent " +
34
+ 'still playing is listed, even with no territory in view (visible, turnsUnseen); one with nothing in view gets ' +
35
+ 'earnedAtLeast (its starting armies plus the base income every turn so far: a lower bound on armies received, ' +
36
+ 'not held) and a warning when that beats your largest stack or your total visible armies. Notes say how ' +
37
+ 'confident each figure is (turns used, missing turns, caps, fog reveals). Only consecutive turns are ' +
38
+ `compared. Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it caches the board it read.`),
39
+ _meta: lookupMeta(['track opponents', 'enemy income', 'what is my opponent earning', 'hidden bonuses']),
40
+ annotations: readAnnotations('Track war.app opponents'),
41
+ inputSchema: z.object({
42
+ game_id: gameIdArg,
43
+ player: playerArg,
44
+ view: viewArg(VIEWS, 'compact (default) gives each opponent\'s per-turn deploys (with a low–high range when ambiguous), income, unexplained armies, inferred bonuses and notes; "full" adds the territories each turn counted, captured (and which captures came out of the fog, were reinforced, or were mine emptied), grew next to the fog, and skipped as fog reveals, and its army change, losses and likely combat deaths.'),
45
+ }),
46
+ }, async ({ game_id, player, view }) => {
47
+ const feed = await ctx.client.getGame(game_id, { settings: true });
48
+ requireTurnPhase(feed);
49
+ const seat = await resolveMe(ctx, feed.players, player);
50
+ // The teams, once my seat is found: GameFeed's, else the game list's (asked once per game, kept).
51
+ const { game, me, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
52
+ const map = mapOf(game);
53
+ const { territories } = await loadLiveGame(ctx, game);
54
+ const graph = graphOf(map);
55
+ const board = boardStateFromLive(territories, me, game.players);
56
+ const settings = plannerSettings(game.settings);
57
+ const turn = currentTurn(game);
58
+ const history = await boardHistory(ctx, game, me, turn);
59
+ const boards = turn !== null ? [...history.boards, { turn, board }] : [{ turn: 0, board }];
60
+ const tracks = trackOpponents(graph, boards, me.id, settings, trackGame(game.players, game.settings, map, game.endRules));
61
+ if (ctx.dataDir && turn !== null) {
62
+ await writeBoardCache(ctx.dataDir, game.id, me.id, turn, board);
63
+ await writeGameRecord(ctx.dataDir, game);
64
+ await recordProfile(ctx.dataDir, deps.env, game, me, boards, teamsKnown);
65
+ }
66
+ const name = namer(map);
67
+ const players = new Map(game.players.map((p) => [p.id, p.name]));
68
+ const bonusOf = (id) => {
69
+ const b = map.bonuses.find((x) => x.id === id);
70
+ return { id, name: b?.name ?? String(id), value: b?.value ?? 0 };
71
+ };
72
+ return respond(view, VIEWS, (rung) => {
73
+ const turnView = (x) => ({
74
+ turn: x.from,
75
+ deploy: x.observed,
76
+ ...(x.raw !== x.observed ? { uncapped: x.raw, cap: x.cap } : {}),
77
+ visibleIncome: x.visibleIncome,
78
+ // #119: what my own orders that turn measured (defenders my failed attacks killed, …).
79
+ ...(x.measured ? { measured: x.measured } : {}),
80
+ ...(x.broken.length ? { brokenBonuses: x.broken.map(bonusOf) } : {}),
81
+ // #123: an ambiguous turn reads between these (fog moves vs deploys, my emptied stacks).
82
+ ...(x.low !== x.high ? { range: { low: x.low, high: x.high } } : {}),
83
+ // #271: a failed attack on a hold of mine bounds the turn's deploy; a pattern of captures that
84
+ // needed attackers out of sight is income.
85
+ ...(x.repelled && x.repelledFloor ? { repelled: { territories: x.repelled.territories.map(name), attackers: x.repelled.attackers, besideStacks: x.repelled.supply, deployAtLeast: x.repelledFloor } } : {}),
86
+ ...(x.fogCaptures ? { fogCaptures: x.fogCaptures } : {}),
87
+ ...(rung === 'full'
88
+ ? {
89
+ counted: x.counted.map(name),
90
+ captured: x.captured.map(name),
91
+ fromFog: x.fromFog.map(name),
92
+ ...(x.reinforced.length ? { reinforced: x.reinforced.map(name) } : {}),
93
+ ...(x.grewFromFog.length ? { grewFromFog: x.grewFromFog.map(name) } : {}),
94
+ ...(x.emptied.length ? { emptied: x.emptied.map(name) } : {}),
95
+ ...(x.unseenAttackers?.length ? { unseenAttackers: x.unseenAttackers.map(name), unseenAttackerArmies: x.unseenAttackerArmies } : {}),
96
+ ...(x.arrivals ? { arrivals: x.arrivals } : {}),
97
+ reveals: x.reveals.map(name),
98
+ armyChange: x.net,
99
+ losses: x.losses,
100
+ earned: x.earned,
101
+ ...(x.combat ? { combat: x.combat } : {}),
102
+ }
103
+ : {}),
104
+ });
105
+ return {
106
+ game: { id: game.id, name: game.name ?? null, turn },
107
+ player: { id: me.id, name: me.name },
108
+ turns: boards.map((b) => b.turn).sort((a, b) => a - b),
109
+ // #94: every opponent out of sight whose received armies beat my largest stack or my total.
110
+ warnings: tracks.flatMap((t) => t.warnings),
111
+ opponents: tracks.map((t) => ({
112
+ player: { id: t.playerId, name: players.get(t.playerId) ?? String(t.playerId) },
113
+ firstSeen: t.firstSeen,
114
+ visible: t.visible,
115
+ turnsUnseen: t.turnsUnseen,
116
+ turnsUnseenAtLeast: t.turnsUnseenAtLeast,
117
+ earnedAtLeast: t.earnedAtLeast,
118
+ warnings: t.warnings,
119
+ observed: t.turns.map(turnView),
120
+ income: {
121
+ estimate: t.income,
122
+ visible: t.visibleIncome,
123
+ base: t.base,
124
+ visibleBonuses: t.bonusIncome,
125
+ turns: t.incomeTurns,
126
+ // #99: which term set the estimate, and the spread of what it was observed to deploy.
127
+ method: t.incomeMethod,
128
+ ...(t.incomeLowered ? { lowered: t.incomeLowered } : {}),
129
+ observedRange: t.observedRange,
130
+ usedByPlanner: t.income !== null && t.turns.length >= TRACKED_MIN_TURNS,
131
+ // #250: set by one turn far above the turns before it, with what the boards say of it.
132
+ ...(t.incomeJump ? { jump: t.incomeJump } : {}),
133
+ },
134
+ unexplainedArmies: t.unexplained,
135
+ // #164: large stacks last seen on a territory hidden since (the planner counts each where it can reach).
136
+ ...(t.lostStacks?.length ? { lostStacks: t.lostStacks } : {}),
137
+ inferredBonuses: t.inferred
138
+ ? {
139
+ gap: t.inferred.gap,
140
+ exact: t.inferred.exact,
141
+ candidates: t.inferred.candidates.map((c) => ({ bonuses: c.bonusIds.map(bonusOf), total: c.total, hops: c.hops })),
142
+ ...(t.inferred.more ? { more: t.inferred.more } : {}),
143
+ ...(t.inferred.implausible ? { implausible: t.inferred.implausible } : {}),
144
+ }
145
+ : null,
146
+ notes: t.notes,
147
+ })),
148
+ };
149
+ });
150
+ });
151
+ }
@@ -0,0 +1,135 @@
1
+ // The options an attack/transfer order can carry (#165): Transfer Only, Attack Only, a percentage
2
+ // of the armies, the commander, and attacking teammates. Each is refused unless the game allows
3
+ // it — war.app's own validator refuses a percentage order (error 360), Transfer Only (361) and
4
+ // Attack Only (362) when the setting is off (read from the client bundle) — and every one is
5
+ // UNVERIFIED against a live commit: the encoding follows the client's writer (docs/WEB-PROTOCOL.md).
6
+ import { McpToolError } from '@chrischall/mcp-utils';
7
+ import { percentOf } from '../analysis/turn-sim.js';
8
+ import { untrustedText } from './common.js';
9
+ /** A move's mode, as warapp_submit_turn takes it. */
10
+ export const MOVE_MODES = ['attack-transfer', 'attack-only', 'transfer-only'];
11
+ /** Options used, said once per preview: none of them has been sent in a live commit yet. */
12
+ const OPTIONS_UNVERIFIED = 'Order options (Transfer Only, Attack Only, percentage, the commander, attack teammates) follow the war.app ' +
13
+ "client's own encoding but are not yet verified by a live commit: check the orders in the game after sending.";
14
+ const label = (t) => `${untrustedText(t.name)} (${t.id})`;
15
+ const move = (m) => `${label(m.from)} → ${label(m.to)}`;
16
+ /**
17
+ * Check each move's options against the game's settings and the live board at the start of the
18
+ * turn; throws a clear refusal on the first that cannot be sent, else returns warnings, the
19
+ * commander each commander move takes, and what each percentage order would send now.
20
+ */
21
+ export function checkMoveOptions(args) {
22
+ const { moves, board, myInGameId: me, teammates } = args;
23
+ const s = args.settings;
24
+ const standing = new Map(board.map((t) => [t.territoryId, t]));
25
+ const ownerOf = (id) => {
26
+ const t = standing.get(id);
27
+ return t && !t.fogged ? t.owner : undefined;
28
+ };
29
+ const warnings = [];
30
+ const commanders = new Map();
31
+ const estimates = new Map();
32
+ let used = false;
33
+ /** Where my commander stands at the start of the turn. */
34
+ const home = board.find((t) => !t.fogged && t.specialUnits?.some((u) => u.kind === 'commander' && u.owner === me));
35
+ const myCommander = home?.specialUnits?.find((u) => u.kind === 'commander' && u.owner === me);
36
+ /** Where my commander is after the commander moves so far. */
37
+ let commanderAt = home?.territoryId;
38
+ let commanderMoves = 0;
39
+ moves.forEach((m, i) => {
40
+ if (m.mode === 'transfer-only' || m.mode === 'attack-only')
41
+ used = true;
42
+ if (m.mode === 'transfer-only' && s?.allowTransferOnly !== true) {
43
+ throw new McpToolError(`Transfer Only orders are off in this game (AllowTransferOnly; war.app refuses one, error 361): ${move(m)}.`, {
44
+ hint: 'Send it without `mode`: an ordinary attack/transfer.',
45
+ });
46
+ }
47
+ if (m.mode === 'attack-only' && s?.allowAttackOnly !== true) {
48
+ throw new McpToolError(`Attack Only orders are off in this game (AllowAttackOnly; war.app refuses one, error 362): ${move(m)}.`, {
49
+ hint: 'Send it without `mode`: an ordinary attack/transfer.',
50
+ });
51
+ }
52
+ const target = ownerOf(m.to.id);
53
+ const friendly = target === me || (target !== undefined && teammates.has(target) && !m.attackTeammates);
54
+ if (m.mode === 'transfer-only' && !friendly) {
55
+ warnings.push(`Transfer Only ${move(m)}: ${label(m.to)} is not yours at the start of the turn, so the order does nothing unless it is yours (or a teammate's) when it runs.`);
56
+ }
57
+ if (m.mode === 'attack-only' && target === me) {
58
+ warnings.push(`Attack Only ${move(m)}: ${label(m.to)} is yours, so the order fires only if it has fallen by the time it runs; otherwise nothing moves.`);
59
+ }
60
+ if (m.percent) {
61
+ used = true;
62
+ if (s?.allowPercentageAttacks !== true) {
63
+ throw new McpToolError(`Percentage orders are off in this game (AllowPercentageAttacks; war.app refuses one, error 360): ${move(m)}.`, {
64
+ hint: 'Send a number of armies instead (leave `percent` out).',
65
+ });
66
+ }
67
+ if (m.armies < 1 || m.armies > 100) {
68
+ throw new McpToolError(`${move(m)} asks for ${m.armies}%: a percentage order sends 1 to 100 percent.`, {
69
+ hint: 'With `percent`, `armies` is the percentage of the armies the territory can move when the order runs.',
70
+ });
71
+ }
72
+ const guard = s?.oneArmyStandsGuard === false ? 0 : 1;
73
+ const now = Math.max(0, (standing.get(m.from.id)?.armies ?? 0) + (args.deployedOn.get(m.from.id) ?? 0) - guard);
74
+ const est = percentOf(m.armies, now);
75
+ estimates.set(i, est);
76
+ warnings.push(`${move(m)} sends ${m.armies}% of the armies ${label(m.from)} can move when it runs: about ${est} now (worked out when the order runs, so it scales with what is left).`);
77
+ }
78
+ else if (m.armies === 0 && !m.commander) {
79
+ throw new McpToolError(`${move(m)} sends no armies.`, {
80
+ hint: 'Send at least one army; 0 is only for a commander moving alone (`commander: true`).',
81
+ });
82
+ }
83
+ if (m.attackTeammates) {
84
+ used = true;
85
+ if (!teammates.size) {
86
+ throw new McpToolError(`${move(m)} sets attack_teammates, but you have no teammates in this game.`, {
87
+ hint: 'Leave attack_teammates out: outside a team game every territory not yours is attacked anyway.',
88
+ });
89
+ }
90
+ if (target === undefined || !teammates.has(target)) {
91
+ warnings.push(`${move(m)} attacks teammates, but ${label(m.to)} is not a teammate's at the start of the turn: the flag matters only if it is one when the order runs.`);
92
+ }
93
+ }
94
+ if (m.commander) {
95
+ used = true;
96
+ if (s?.commanders !== true) {
97
+ throw new McpToolError(`This game has no commanders, so ${move(m)} cannot take one along.`, { hint: 'Leave `commander` out.' });
98
+ }
99
+ if (!home || !myCommander) {
100
+ throw new McpToolError(`No commander of yours is on the live board, so ${move(m)} cannot take one along.`, {
101
+ hint: 'Leave `commander` out; warapp_get_live_board shows your commander when you have one.',
102
+ });
103
+ }
104
+ if (commanderMoves > 0 && !(s?.multiAttack && m.from.id === commanderAt)) {
105
+ throw new McpToolError(`Your commander moves once a turn, and ${move(m)} would move it again.`, {
106
+ hint: 'Take the commander along on one move only (under Multi-Attack it may go on from the territory it just took).',
107
+ });
108
+ }
109
+ if (m.from.id !== commanderAt) {
110
+ throw new McpToolError(`Your commander is not on ${label(m.from)}: it stands on territory ${commanderAt} at the start of the turn.`, {
111
+ hint: 'Take it along on a move from the territory it stands on.',
112
+ });
113
+ }
114
+ commanders.set(i, { id: myCommander.id, owner: me });
115
+ commanderMoves += 1;
116
+ const ontoTeammate = target !== undefined && target !== me && teammates.has(target) && !m.attackTeammates;
117
+ // It reaches m.to only when the order surely carries it there: not onto a teammate's land
118
+ // (it stays home), not an Attack Only onto my own territory or a Transfer Only onto one not
119
+ // mine (either may not fire). Otherwise it is held where it stood, so a Multi-Attack chain
120
+ // from m.to is refused rather than assumed.
121
+ const mayNotFire = (m.mode === 'attack-only' && target === me) || (m.mode === 'transfer-only' && target !== undefined && !friendly);
122
+ if (!ontoTeammate && !mayNotFire)
123
+ commanderAt = m.to.id;
124
+ if (ontoTeammate) {
125
+ warnings.push(`${move(m)} goes to a teammate's territory: a commander does not move onto a teammate's land, so your commander stays on ${label(m.from)}.`);
126
+ }
127
+ else if (!friendly) {
128
+ warnings.push(`Your commander goes with ${move(m)}: it fights as 7 armies after the ones with it, and if it dies (7 damage left over in the battle) you are eliminated.`);
129
+ }
130
+ }
131
+ });
132
+ if (used)
133
+ warnings.push(OPTIONS_UNVERIFIED);
134
+ return { warnings, commanders, estimates };
135
+ }