@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,141 @@
1
+ import { McpToolError } from '@chrischall/mcp-utils';
2
+ import { z } from 'zod';
3
+ import { analyzeBonuses, applyBonusOverrides, findChokepoints } from '../analysis/index.js';
4
+ import { gameIdArg, graphOf, mapSummary, readAnnotations, respond, round2, untrustedDescription, untrustedText, viewArg } from './common.js';
5
+ import { lookupMeta } from './hints.js';
6
+ import { modeRow, withModeTerritories } from './map-details.js';
7
+ const VIEWS = ['compact', 'full'];
8
+ const DEFAULT_LIMIT = 25;
9
+ const COMPACT_CHOKEPOINTS = 20;
10
+ const SORTS = {
11
+ easiest: (a, b) => b.score - a.score || b.value - a.value || a.territoryIds.length - b.territoryIds.length || a.bonusId - b.bonusId,
12
+ value: (a, b) => b.value - a.value || b.score - a.score || a.bonusId - b.bonusId,
13
+ name: (a, b) => a.name.localeCompare(b.name) || a.bonusId - b.bonusId,
14
+ };
15
+ /**
16
+ * The game's map with the game's bonus values (its `OverriddenBonuses` applied —
17
+ * load the game with `settings: true`), or a clear error when the feed did not send one.
18
+ */
19
+ export function mapOf(game) {
20
+ if (game.map)
21
+ return applyBonusOverrides(game.map, game.settings);
22
+ throw new McpToolError(`war.app sent no map for game ${game.id}.`, {
23
+ hint: 'Try again in a moment; if it persists the game may not have a map assigned yet.',
24
+ });
25
+ }
26
+ const named = (g, ids) => ids.map((id) => ({ id, name: g.territoryById.get(id)?.name ?? String(id) }));
27
+ const row = (b) => ({
28
+ bonusId: b.bonusId,
29
+ name: b.name,
30
+ value: b.value,
31
+ territories: b.territoryIds.length,
32
+ borders: b.borderTerritoryIds.length,
33
+ entryPoints: b.entryPointIds.length,
34
+ valuePerTerritory: round2(b.valuePerTerritory),
35
+ score: round2(b.score),
36
+ });
37
+ function detail(g, b) {
38
+ const out = {
39
+ bonusId: b.bonusId,
40
+ name: b.name,
41
+ value: b.value,
42
+ territories: named(g, b.territoryIds),
43
+ borders: named(g, b.borderTerritoryIds),
44
+ entryPoints: named(g, b.entryPointIds),
45
+ valuePerTerritory: round2(b.valuePerTerritory),
46
+ valuePerBorder: round2(b.valuePerBorder),
47
+ score: round2(b.score),
48
+ };
49
+ if (b.isSuperbonus) {
50
+ out.memberBonuses = b.memberBonusIds.map((id) => ({ id, name: g.bonusById.get(id)?.name ?? String(id) }));
51
+ }
52
+ return out;
53
+ }
54
+ function chokepoints(g, limit) {
55
+ const all = findChokepoints(g);
56
+ const bonusName = (id) => (id === null ? null : (g.bonusById.get(id)?.name ?? String(id)));
57
+ return (limit === undefined ? all : all.slice(0, limit)).map((c) => ({
58
+ territoryId: c.territoryId,
59
+ name: c.name,
60
+ degree: c.degree,
61
+ reasons: c.reasons,
62
+ bonus: bonusName(c.bonusId),
63
+ connects: c.connectsBonusIds.map((id) => bonusName(id)),
64
+ }));
65
+ }
66
+ export function registerMapTool(server, client, live) {
67
+ server.registerTool('warapp_get_map', {
68
+ title: 'Get a war.app game map: bonuses and chokepoints',
69
+ description: untrustedDescription('Analyze the map of a war.app (Warzone) game: a bonus table ranked easiest-to-take first (army value, ' +
70
+ 'territory count, border territories to defend, entry points, value per territory, ease score) and the ' +
71
+ 'map\'s chokepoints (articulation points, bridges between regions, narrow connectors). Filter with ' +
72
+ '`bonus` (part of a bonus name) to see one bonus\'s territories, borders and entry points by name. ' +
73
+ 'View "full" also lists the map\'s distribution modes with the territories each lets a player start on ' +
74
+ '(read once from war.app\'s map details through the web-client channel (direct or bridge), then kept with the map; unknown is null). ' +
75
+ 'Map-only — needs no board, so it works in a lobby. Read-only.'),
76
+ _meta: lookupMeta(['warzone map', 'best bonuses', 'easiest bonus', 'chokepoints']),
77
+ annotations: readAnnotations('Get a war.app map'),
78
+ inputSchema: z.object({
79
+ game_id: gameIdArg,
80
+ bonus: z.string().optional().describe('Only bonuses whose name contains this (case-insensitive); rows list member territories by name.'),
81
+ sort: z
82
+ .enum(['easiest', 'value', 'name'])
83
+ .optional()
84
+ .describe('Bonus order: "easiest" (default — ease score = value / (territories + borders)), "value", or "name".'),
85
+ limit: z.coerce.number().int().min(1).max(1000).optional().describe(`Max bonus rows (default ${DEFAULT_LIMIT} on compact; all on full).`),
86
+ view: viewArg(VIEWS, `compact (default) keeps positive-value bonuses as one-line rows (counts, value per territory, score) and the top ${COMPACT_CHOKEPOINTS} chokepoints; ` +
87
+ '"full" lists every bonus (zero and negative included) with member, border and entry-point territories by name, every chokepoint, ' +
88
+ 'and each distribution mode with its starting territory count and ids.'),
89
+ }),
90
+ }, async ({ game_id, bonus, sort, limit, view }) => {
91
+ // Settings carry the game's overridden bonus values, which the bonus table reports.
92
+ const game = await client.getGame(game_id, { settings: true });
93
+ const map = mapOf(game);
94
+ const g = graphOf(map);
95
+ // #328: only the full table lists the modes' starting territories, so only it may ask war.app for them.
96
+ const modes = view === 'full' && !bonus?.trim() ? await withModeTerritories(live, map) : undefined;
97
+ const order = SORTS[sort ?? 'easiest'];
98
+ return respond(view, VIEWS, (rung) => {
99
+ const all = analyzeBonuses(g);
100
+ if (bonus?.trim()) {
101
+ const q = bonus.trim().toLowerCase();
102
+ const hits = all.filter((b) => b.name.toLowerCase().includes(q)).sort(order);
103
+ if (!hits.length) {
104
+ // The map name is map-maker text: delimited, since errors sit outside the untrusted envelope.
105
+ throw new McpToolError(`No bonus on map ${map.id} (${untrustedText(map.name)}) matches ${JSON.stringify(bonus)}.`, {
106
+ hint: 'Use part of the bonus name as the game spells it, or omit `bonus` to list the ranked table.',
107
+ });
108
+ }
109
+ const shown = hits.slice(0, limit ?? DEFAULT_LIMIT);
110
+ return { map: mapSummary(map), bonuses: shown.map((b) => detail(g, b)), bonusesShown: `${shown.length} of ${hits.length}` };
111
+ }
112
+ if (rung === 'full') {
113
+ const sorted = all.sort(order);
114
+ const shown = limit === undefined ? sorted : sorted.slice(0, limit);
115
+ return {
116
+ map: mapSummary(map),
117
+ bonuses: shown.map((b) => detail(g, b)),
118
+ bonusesShown: `${shown.length} of ${sorted.length}`,
119
+ chokepoints: chokepoints(g),
120
+ distributionModes: (modes?.map ?? map).distributionModes.map(modeRow),
121
+ ...(modes?.warnings.length ? { warnings: modes.warnings } : {}),
122
+ };
123
+ }
124
+ const positive = all.filter((b) => b.value >= 1).sort(order);
125
+ const shown = positive.slice(0, limit ?? DEFAULT_LIMIT);
126
+ const hidden = all.length - positive.length;
127
+ return {
128
+ map: mapSummary(map),
129
+ bonuses: shown.map(row),
130
+ bonusesShown: `${shown.length} of ${positive.length}`,
131
+ // #70: say what compact leaves out (the turn planner always counts every bonus).
132
+ ...(hidden
133
+ ? {
134
+ bonusesHidden: `${hidden} zero- or negative-value bonuses not listed (view "full" or a \`bonus\` filter shows them; the turn planner counts every bonus)`,
135
+ }
136
+ : {}),
137
+ chokepoints: chokepoints(g, COMPACT_CHOKEPOINTS),
138
+ };
139
+ });
140
+ });
141
+ }
@@ -0,0 +1,193 @@
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, gameStateName, 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, untrustedText, WARAPP_UNTRUSTED_NOTE } from './common.js';
16
+ import { canonicalMeta } from './hints.js';
17
+ import { BRIDGE_NOTE } from './live.js';
18
+ import { holdsSeat, playerStateName } from '../player-states.js';
19
+ import { sweepFinished } from './end-of-game.js';
20
+ import { accountUnknown } from './write-kit.js';
21
+ import { pendingSurrenders, surrenderOwed } from '../surrender-pending.js';
22
+ import { readDetailsSeats, SURRENDER_PENDING_NOTE, surrenderMayBePending } from './surrender-pending.js';
23
+ const VIEWS = ['compact', 'brief'];
24
+ /** The note line a brief answer ends with when the list may be partial (a `-- ` line is never a game). */
25
+ const partialLine = (listed) => `-- the list may be partial: war.app returned ${listed} games, the most this server asks for`;
26
+ function briefResult(games, partialOf) {
27
+ const lines = games.length ? games.map(briefGameLine) : ['-- none'];
28
+ if (partialOf !== undefined)
29
+ lines.push(partialLine(partialOf));
30
+ return { content: [{ type: 'text', text: JSON.stringify(untrustedEnvelope(lines, { note: WARAPP_UNTRUSTED_NOTE })) }] };
31
+ }
32
+ /**
33
+ * The counts GetMyGames is asked for, in turn (#260): a reply that fills its count may have left games out,
34
+ * so the list is asked again with the next; one that fills the last is reported as possibly partial.
35
+ */
36
+ export const MY_GAMES_WINDOWS = [100, 400, 1600];
37
+ /**
38
+ * Every game of the account through `read` (one GetMyGames request with these filters): `All` (lobbies, games
39
+ * being picked or played, finished games), asked with each count of `windows` in turn until a reply does not
40
+ * fill it. A failed first read throws; a failed wider read keeps the last list, as partial.
41
+ */
42
+ export async function listMyGames(read, windows = MY_GAMES_WINDOWS) {
43
+ let games = [];
44
+ let requests = 0;
45
+ for (const count of windows) {
46
+ const filters = { filterType: MyGamesFilterType.All, count, sort: MY_GAMES_DEFAULT_SORT };
47
+ requests++;
48
+ if (requests === 1)
49
+ games = await read(filters);
50
+ else {
51
+ try {
52
+ games = await read(filters);
53
+ }
54
+ catch {
55
+ return { games, partial: true, requests };
56
+ }
57
+ }
58
+ if (games.length < count)
59
+ return { games, partial: false, requests };
60
+ }
61
+ return { games, partial: true, requests };
62
+ }
63
+ /** The signed-in account's in-game id; refuses when it cannot be read. */
64
+ async function myInGameId(ctx) {
65
+ const me = await ctx.myInGameId();
66
+ if (me === undefined) {
67
+ throw accountUnknown(ctx.hosted, 'its games cannot be listed');
68
+ }
69
+ return me;
70
+ }
71
+ /** The signed-in account's in-game id and every game of its, through GetMyGames ({@link listMyGames}). */
72
+ export async function fetchMyGames(ctx) {
73
+ const read = async (filters) => {
74
+ const env = await ctx.rpc.call('GetMyGames', Method.GetMyGames, (w) => writeGetMyGamesParams(w, filters));
75
+ return readMyGames(await ctx.bundle(), env.body);
76
+ };
77
+ const [me, list] = await Promise.all([myInGameId(ctx), listMyGames(read)]);
78
+ return { me, ...list };
79
+ }
80
+ /** #317: the most games whose details one call reads for a pending surrender (the rest are `null`). */
81
+ export const MAX_SURRENDER_READS = 20;
82
+ /** Details read at once. */
83
+ const SURRENDER_READ_BATCH = 4;
84
+ /**
85
+ * #317: each game's pending surrenders, by game id: read for a game being played or picked where my seat
86
+ * still plays (at most {@link MAX_SURRENDER_READS}, war.app's order), `null` elsewhere or when unreadable.
87
+ * GetMyGames carries no GameFeed id, so `player` is `null`; the name is the list's, untrusted.
88
+ */
89
+ export async function myGamesSurrenders(ctx, games, me) {
90
+ const byGame = new Map();
91
+ const eligible = games.filter((g) => {
92
+ const mine = g.players.find((p) => p.id === me);
93
+ return surrenderMayBePending(gameStateName(g.stateCode), mine ? playerStateName(mine.stateCode) : undefined);
94
+ });
95
+ const read = eligible.slice(0, MAX_SURRENDER_READS);
96
+ for (let i = 0; i < read.length; i += SURRENDER_READ_BATCH) {
97
+ const batch = read.slice(i, i + SURRENDER_READ_BATCH);
98
+ const seats = await Promise.all(batch.map((g) => readDetailsSeats(ctx, g.id)));
99
+ batch.forEach((g, j) => {
100
+ const s = seats[j];
101
+ const names = new Map(g.players.map((p) => [p.id, p.name]));
102
+ byGame.set(g.id, s
103
+ ? pendingSurrenders(s, me).map((p) => ({ ...p, name: names.has(p.inGameId) ? untrustedText(names.get(p.inGameId)) : null }))
104
+ : null);
105
+ });
106
+ }
107
+ return { byGame, skipped: eligible.length - read.length };
108
+ }
109
+ /**
110
+ * The finished games of `me` (in-game id) in a GetMyGames list where its seat was held, newest first: the
111
+ * end-of-game sweep's candidates (#312).
112
+ */
113
+ export function finishedGamesOf(games, me) {
114
+ return games
115
+ .filter((g) => isFinished(g) && g.players.some((p) => p.id === me && holdsSeat(playerStateName(p.stateCode))))
116
+ .map((g) => g.id)
117
+ .sort((a, b) => b - a);
118
+ }
119
+ /**
120
+ * Also the end-of-game sweep (#312, src/tools/end-of-game.ts): the account's finished games not yet
121
+ * processed get their pass, at most `END_OF_GAME_PER_CALL` per call (`endOfGame` in the compact answer).
122
+ */
123
+ export function registerMyGamesTool(server, ctx, deps = {}) {
124
+ const env = deps.env ?? process.env;
125
+ server.registerTool('warapp_my_games', {
126
+ title: 'List my war.app games and which need me',
127
+ description: untrustedDescription('Your war.app (Warzone) games, games waiting on you first: each with its id, name, state ' +
128
+ '(WaitingForPlayers, DistributingTerritories, Playing, Finished), turn, players (name, state, whether ' +
129
+ 'they have committed this turn) and waitingOnYou — true when the game is being played or distributing ' +
130
+ 'territories, you are still playing, and you have not committed — and surrenderPending: the surrenders other ' +
131
+ 'players asked for that are still pending, each with owedByMe (true: waiting for you to accept it), read from ' +
132
+ 'the game details (unverified live; null when not read or unreadable, never "none"); the top-level ' +
133
+ 'surrenderPending counts the games where one waits on you, and those games come first too. ' +
134
+ 'Finished games are left out unless ' +
135
+ '`include_finished` (`finishedLeftOut` counts them). `listed` is how many games war.app returned and ' +
136
+ '`complete` false (with a `warning`) means the list may be partial. Use the id with the other warapp tools. ' +
137
+ 'Each call also gives up to two of your newest 250 finished games not yet processed their end-of-game pass (`endOfGame`: ' +
138
+ 'each game\'s history read once from GameFeed and kept name-free for later games; `pending` counts the rest). ' +
139
+ `${BRIDGE_NOTE} Read-only.`),
140
+ _meta: canonicalMeta('whats-new', ['my games', 'warzone', 'whose turn', 'games waiting on me', 'which games need me']),
141
+ annotations: readAnnotations('List my war.app games'),
142
+ inputSchema: z.object({
143
+ view: z
144
+ .enum(VIEWS)
145
+ .optional()
146
+ .describe('"compact" (default): the games as described. "brief": one line per game — name — "turn N" (or the ' +
147
+ 'state when not being played) — "waiting on you" or "waiting on others", inside the untrusted-data ' +
148
+ 'envelope as data: string[]; "-- none" when there are no games, and a last "-- the list may be ' +
149
+ 'partial…" line when it may be. Brief reads no game details, so it says nothing of pending surrenders.'),
150
+ include_finished: z
151
+ .boolean()
152
+ .optional()
153
+ .describe('List finished games too (default false: lobbies and games being picked or played).'),
154
+ }),
155
+ }, async ({ view, include_finished }) => {
156
+ const { me, games: raw, partial } = await fetchMyGames(ctx);
157
+ // #312: the end-of-game sweep, bounded per call; best effort, never throws.
158
+ const token = ctx.dataDir ? await ctx.myInviteToken().catch(() => undefined) : undefined;
159
+ const sweep = token !== undefined ? await sweepFinished({ client: ctx.client, dataDir: ctx.dataDir, env }, token, finishedGamesOf(raw, me)) : undefined;
160
+ const endOfGame = sweep && (sweep.processed.length || sweep.pending) ? { endOfGame: sweep } : {};
161
+ const kept = include_finished ? raw : raw.filter((g) => !isFinished(g));
162
+ const summary = summarizeMyGames(kept, me);
163
+ if (view === 'brief')
164
+ return briefResult(summary, partial ? raw.length : undefined);
165
+ const finishedLeftOut = raw.length - kept.length;
166
+ // #317: the surrenders pending in each game (the game details; null: not read or unreadable, never "none").
167
+ const { byGame, skipped } = await myGamesSurrenders(ctx, kept, me);
168
+ const withSurrenders = summary.map((g) => ({ ...g, surrenderPending: byGame.get(g.id) ?? null }));
169
+ // A game waiting on my acceptance waits on me too: it goes first with the turns waiting on me.
170
+ const first = (g) => g.waitingOnYou || surrenderOwed(g.surrenderPending);
171
+ const games = [...withSurrenders.filter(first), ...withSurrenders.filter((g) => !first(g))];
172
+ const unread = games.filter((g) => g.surrenderPending === null && byGame.has(g.id)).length;
173
+ return respond(undefined, ['compact'], () => ({
174
+ games,
175
+ count: games.length,
176
+ waitingOnYou: games.filter((g) => g.waitingOnYou).length,
177
+ surrenderPending: games.filter((g) => surrenderOwed(g.surrenderPending)).length,
178
+ surrenderNote: SURRENDER_PENDING_NOTE +
179
+ (unread ? ` The details of ${unread} game(s) could not be read.` : '') +
180
+ (skipped ? ` ${skipped} more game(s) were not read (at most ${MAX_SURRENDER_READS} per call).` : ''),
181
+ listed: raw.length,
182
+ ...(finishedLeftOut ? { finishedLeftOut } : {}),
183
+ complete: !partial,
184
+ ...endOfGame,
185
+ ...(partial
186
+ ? {
187
+ warning: `The list may be partial: war.app returned ${raw.length} games, the most this server asks for. ` +
188
+ 'A game missing here can still be read by id with warapp_get_game.',
189
+ }
190
+ : {}),
191
+ }));
192
+ });
193
+ }