@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,311 @@
1
+ // warapp_accept_surrender (#317): accept another player's pending surrender with the web client's
2
+ // AcceptSurrender (method 68), gated on the user's confirmation. The encoder is read from the client
3
+ // bundle and golden-pinned, UNVERIFIED live (docs/WEB-PROTOCOL.md "Accepting a surrender").
4
+ //
5
+ // A pending surrender lives only in the game details (src/surrender-pending.ts), so the plan reads
6
+ // them and refuses when no surrender is pending from that player or my acceptance is not owed; a
7
+ // finished game and a game I am not playing are refused first. The preview says what accepting does
8
+ // here: whose seat, whether its land turns neutral or goes to an AI, who borders that land (from the
9
+ // live board when it reads), whether it goes through now or others still owe theirs, whether it
10
+ // leaves only my side playing (a win), and in a free-for-all one advice line naming the neighbour
11
+ // that gains most (strategy note ffa-surrender-veto).
12
+ //
13
+ // The outcome is read back from game state — GameFeed (the seat SurrenderAccepted, handed to an AI,
14
+ // or the game over) and the game details (my id among those that accepted) — never from the reply,
15
+ // which carries no result, and nothing is ever resent.
16
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
17
+ import { z } from 'zod';
18
+ import { surrenderLand, winsOnAcceptance } from '../analysis/accept-surrender.js';
19
+ import { parseGameId } from '../client.js';
20
+ import { inGameOf, playersByInGameId } from '../live.js';
21
+ import { Method, writeAcceptSurrenderParams } from '../protocol/methods.js';
22
+ import { pendingSurrenders, seatPlaying } from '../surrender-pending.js';
23
+ import { isTeamGame, teammatesOf } from '../teams.js';
24
+ import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
25
+ import { mintMeta } from './hints.js';
26
+ import { loadLiveTerritories, requireApprovedAccount, writeAccount } from './live-context.js';
27
+ import { mapOf } from './map.js';
28
+ import { resolvePlayer } from './resolve.js';
29
+ import { noBrowserNote } from './session.js';
30
+ import { readDetailsSeats } from './surrender-pending.js';
31
+ import { resolveTeamsFor } from './team-source.js';
32
+ import { defineGatedWrite, mySeat, refuse, requireMe, requirePlaying, sendAndVerify, worded } from './write-kit.js';
33
+ const PLAYING = 'Playing';
34
+ const FINISHED = 'Finished';
35
+ const DISTRIBUTING = 'DistributingTerritories';
36
+ /** The strategy note the free-for-all advice cites. */
37
+ export const FFA_SURRENDER_NOTE = 'ffa-surrender-veto';
38
+ /** The AcceptSurrender refusals, worded here from the codes' meaning (read from the bundle, UNVERIFIED live). */
39
+ const ACCEPT_ERRORS = {
40
+ 4: 'war.app says the game has ended: there is no surrender left to accept.',
41
+ 7: 'One of the two seats (yours or the surrendering player\'s) has left the game, so the acceptance was refused.',
42
+ 186: 'That player has taken its surrender back, so there is nothing to accept.',
43
+ 230: 'Your seat no longer takes part in the game, so war.app refused your acceptance.',
44
+ };
45
+ const gameLabel = (game) => game.name ?? `game ${game.id}`;
46
+ /** The surrendering player the call names (or the one pending when none is named), refused when it has no pending surrender. */
47
+ function targetOf(game, seats, meInGame, input) {
48
+ const byInGame = playersByInGameId(game.players);
49
+ const pending = pendingSurrenders(seats, meInGame, (id) => byInGame.get(id)?.id ?? null);
50
+ const label = (p) => {
51
+ const pl = byInGame.get(p.inGameId);
52
+ return pl ? `${untrustedText(pl.name)} (${pl.id})` : `in-game ${p.inGameId}`;
53
+ };
54
+ if (input === undefined || String(input).trim() === '') {
55
+ if (!pending.length) {
56
+ refuse(`No surrender is pending in game ${game.id}, so there is nothing to accept and nothing was sent.`, 'warapp_my_games and warapp_wait_for_turn report a pending surrender.');
57
+ }
58
+ if (pending.length > 1) {
59
+ refuse(`More than one surrender is pending in game ${game.id}: ${pending.map(label).join(', ')}. Say which with \`player\`; nothing was sent.`, 'Pass `player` as the surrendering player\'s name or id.');
60
+ }
61
+ return pending[0];
62
+ }
63
+ const named = resolvePlayer(game.players, input);
64
+ const id = inGameOf(named);
65
+ const hit = pending.find((p) => p.inGameId === id);
66
+ if (!hit) {
67
+ refuse(`${untrustedText(named.name)} (${named.id}) has no surrender pending in game ${game.id}, so nothing was sent.`, pending.length ? `Pending: ${pending.map(label).join(', ')}.` : 'No surrender is pending in this game.');
68
+ }
69
+ return hit;
70
+ }
71
+ /** The free-for-all advice line, or the win line; `undefined` in a team game that does not end. */
72
+ function adviceOf(opts) {
73
+ if (opts.wins === true) {
74
+ return opts.goesThroughNow
75
+ ? 'Accepting wins the game: once it goes through, no one off your side is left playing.'
76
+ : 'Accepting wins the game once the others still owing their acceptance give it: no one off your side is left playing then.';
77
+ }
78
+ if (!opts.ffa)
79
+ return undefined;
80
+ const cite = `Strategy note ${FFA_SURRENDER_NOTE}: accept when the land helps you more than your rivals; refusing keeps the player in (it must move or be booted).` +
81
+ (opts.teamsKnown ? '' : ' The teams could not be read, so a neighbour named here may be a teammate.');
82
+ if (!opts.land)
83
+ return `${cite} Who borders its land is unknown: the live board could not be read.`;
84
+ const top = opts.land.neighbours[0];
85
+ const ai = opts.toAI === true ? ' Its land goes to an AI, which keeps playing it, so it is not up for taking at once.' : '';
86
+ if (!top)
87
+ return `${cite} No player borders its land in view, so no neighbour gains it at once.${ai}`;
88
+ const mine = opts.land.neighbours.find((n) => n.inGameId === opts.meInGame)?.bordering ?? 0;
89
+ const fog = opts.land.hiddenNeighbours ? ` (${opts.land.hiddenNeighbours} territories beside it are hidden by fog)` : '';
90
+ if (top.inGameId === opts.meInGame) {
91
+ return `${cite} You border its land with the most territories (${top.bordering})${fog}, so of its neighbours you gain most from it.${ai}`;
92
+ }
93
+ return (`${cite} ${opts.idOf(top.inGameId)} borders its land with the most territories (${top.bordering}; you: ${mine})${fog}, ` +
94
+ `so it gains most from it.${ai}`);
95
+ }
96
+ export function registerAcceptSurrenderTool(server, ctx) {
97
+ defineGatedWrite(server, {
98
+ title: "Accept a player's surrender in a war.app game",
99
+ _meta: mintMeta('change', ['accept surrender', 'accept resignation warzone', 'let player surrender']),
100
+ }, {
101
+ name: 'warapp_accept_surrender',
102
+ description: "Accept another player's pending surrender in a war.app (Warzone) game as the signed-in account (where the " +
103
+ "game's InstantSurrender setting asks the others to accept). Refused when no surrender is pending from that " +
104
+ 'player, when your acceptance is not owed (already given, or your seat cannot accept), in a finished game, ' +
105
+ 'and in a game you are not playing. `player` names the surrendering player (name or id); it may be omitted ' +
106
+ 'when one surrender is pending. The preview says what accepting does: whose seat, whether its land turns ' +
107
+ 'neutral or goes to an AI, which players border that land (live board), whether it goes through now or ' +
108
+ 'others still owe their acceptance, whether it leaves only your side playing (a win), and in a free-for-all ' +
109
+ `one advice line naming the neighbour that gains most (strategy note ${FFA_SURRENDER_NOTE}). Accepting is the ` +
110
+ "owner's decision. The outcome is read back from GameFeed and the game details (`accepted`, `pending` — others " +
111
+ 'still owe theirs —, `unconfirmed`, `unknown`). The encoding is read from the client bundle, UNVERIFIED live.' +
112
+ `${noBrowserNote(ctx.hosted)} ${CONFIRM_INJECTION_RULE}`,
113
+ annotations: toolAnnotations({
114
+ title: "Accept a player's surrender in a war.app game",
115
+ readOnly: false,
116
+ destructive: true,
117
+ idempotent: false,
118
+ openWorld: true,
119
+ }),
120
+ inputSchema: z.object({
121
+ game_id: gameIdArg,
122
+ player: z
123
+ .union([z.number(), z.string()])
124
+ .optional()
125
+ .describe('The surrendering player, by name or GameFeed id (optional when exactly one surrender is pending).'),
126
+ }),
127
+ async plan({ game_id, player }) {
128
+ const gameId = parseGameId(game_id);
129
+ const me = await requireMe(ctx);
130
+ const feed = await ctx.client.getGame(gameId, { settings: true });
131
+ if (feed.state === FINISHED)
132
+ refuse(`Game ${gameId} is already over, so there is no surrender to accept.`, 'Check warapp_get_game.');
133
+ if (feed.state !== PLAYING && feed.state !== DISTRIBUTING) {
134
+ refuse(`Game ${gameId} has not started (game state: ${feed.state}), so there is no surrender to accept.`, 'Check warapp_get_game.');
135
+ }
136
+ const seat = mySeat(feed, me);
137
+ requirePlaying(feed, seat);
138
+ if (feed.endRules?.instantSurrender === true) {
139
+ refuse(`Surrender is instant in game ${gameId}: it never waits for acceptance, so there is nothing to accept.`, 'Check warapp_get_game.');
140
+ }
141
+ const seats = await readDetailsSeats(ctx, gameId);
142
+ if (!seats) {
143
+ refuse(`Could not read game ${gameId}'s details, so whether a surrender is pending cannot be told and nothing was sent.`, 'Make sure a war.app tab signed in to your account is open and paired (reload or focus it if it is frozen), then retry.');
144
+ }
145
+ const meInGame = inGameOf(seat);
146
+ const target = targetOf(feed, seats, meInGame, player);
147
+ if (target.owedByMe !== true) {
148
+ refuse(target.owedByMe === false
149
+ ? `Your acceptance of that surrender is not owed in game ${gameId} (you already accepted it, or your seat cannot accept), so nothing was sent.`
150
+ : `Your seat is not in game ${gameId}'s details, so whether your acceptance is owed cannot be told and nothing was sent.`, 'Check warapp_my_games: it reports each pending surrender and whether it waits on you.');
151
+ }
152
+ const { game, me: mine, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
153
+ const byInGame = playersByInGameId(game.players);
154
+ const surrendering = byInGame.get(target.inGameId);
155
+ const idOf = (inGame) => {
156
+ const p = byInGame.get(inGame);
157
+ return p ? `player ${p.id}` : `in-game ${inGame}`;
158
+ };
159
+ const teammates = new Set(teammatesOf(game.players, mine).map((p) => p.id));
160
+ const sideOf = (p) => p.id === me || teammates.has(p.id);
161
+ // Who must still accept, besides me: every other seat playing, neither an AI nor turned into one.
162
+ const theirs = seats.find((s) => s.id === target.inGameId);
163
+ const othersStillToAccept = seats
164
+ .filter((s) => s.id !== target.inGameId && s.id !== meInGame && seatPlaying(s) && !s.ai && !s.turnedAI)
165
+ .filter((s) => !(theirs?.acceptedBy ?? []).includes(s.id))
166
+ .map((s) => ({ player: byInGame.get(s.id)?.id ?? null, inGameId: s.id }));
167
+ const goesThroughNow = othersStillToAccept.length === 0;
168
+ // What the land becomes: an AI seat when the setting says so and the player is not already one.
169
+ const toAISetting = game.endRules?.surrenderedTurnIntoAI;
170
+ const alreadyAI = surrendering ? surrendering.isAI || surrendering.humanTurnedIntoAI : false;
171
+ const toAI = toAISetting === undefined ? undefined : toAISetting && !alreadyAI;
172
+ const remaining = game.players
173
+ .filter((p) => p.state === PLAYING && p.id !== surrendering?.id)
174
+ .map((p) => ({ id: p.id, ai: p.isAI || p.humanTurnedIntoAI, mine: sideOf(p) }));
175
+ const raw = winsOnAcceptance(remaining, toAI, game.endRules?.aisSurrenderWhenOneHumanRemains);
176
+ // A seat that may be my teammate makes "no rival left" unknowable, unless no one else is left at all.
177
+ const wins = raw === true && !teamsKnown && remaining.some((s) => s.id !== me) ? null : raw;
178
+ const ffa = !isTeamGame(game.players);
179
+ // Who borders the land, from the live board when it reads.
180
+ let land = null;
181
+ try {
182
+ const territories = await loadLiveTerritories(ctx, game);
183
+ const map = mapOf(game);
184
+ land = surrenderLand(territories, new Map(map.territories.map((t) => [t.id, t.connectedTo])), target.inGameId);
185
+ }
186
+ catch {
187
+ land = null;
188
+ }
189
+ const advice = adviceOf({ wins, ffa, land, meInGame, idOf, toAI, goesThroughNow, teamsKnown });
190
+ const who = `player ${target.player ?? `in-game ${target.inGameId}`}`;
191
+ const summary = `Accept ${who}'s surrender in war.app game ${gameId}`;
192
+ return {
193
+ gate: {
194
+ action: 'warapp.accept_surrender',
195
+ summary,
196
+ account: writeAccount(me),
197
+ target: gameId,
198
+ payload: { method: 'AcceptSurrender', gameId, playerId: target.inGameId, accept: true },
199
+ willSend: { game: gameId, player: target.player, inGameId: target.inGameId, accept: true },
200
+ preview: {
201
+ warning: `This accepts ${who}'s surrender in game ${gameId}` +
202
+ (goesThroughNow ? ': yours is the last acceptance owed, so it goes through.' : ': others still owe theirs, so it stays pending until they accept.'),
203
+ account: shownAccount(seat.name, me),
204
+ game: { id: gameId, name: game.name === undefined ? null : untrustedText(game.name), state: game.state },
205
+ seat: {
206
+ player: target.player,
207
+ inGameId: target.inGameId,
208
+ name: surrendering ? untrustedText(surrendering.name) : null,
209
+ },
210
+ landBecomes: toAI === undefined ? null : toAI ? 'AI' : 'neutral',
211
+ land: land
212
+ ? {
213
+ territoriesInView: land.territories.length,
214
+ borderedBy: land.neighbours.map((n) => {
215
+ const p = byInGame.get(n.inGameId);
216
+ return {
217
+ player: p?.id ?? null,
218
+ inGameId: n.inGameId,
219
+ name: p ? untrustedText(p.name) : null,
220
+ territoriesBordering: n.bordering,
221
+ ...(n.inGameId === meInGame ? { you: true } : p && teammates.has(p.id) ? { teammate: true } : {}),
222
+ };
223
+ }),
224
+ hiddenNeighbours: land.hiddenNeighbours,
225
+ }
226
+ : null,
227
+ othersStillToAccept,
228
+ goesThroughNow,
229
+ winsGame: wins,
230
+ ...(advice ? { advice } : {}),
231
+ unverified: 'AcceptSurrender is read from the client bundle and not yet verified live; the outcome is read back from game state.',
232
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
233
+ },
234
+ },
235
+ state: { gameId, name: gameLabel(game), me, player: target.player, inGameId: target.inGameId, alreadyAI },
236
+ };
237
+ },
238
+ async execute({ gameId, name, me, player, inGameId, alreadyAI }) {
239
+ await requireApprovedAccount(ctx, writeAccount(me));
240
+ const game = { id: gameId, name };
241
+ const who = { player, inGameId };
242
+ return sendAndVerify({
243
+ send: async () => {
244
+ await ctx.rpc.call('AcceptSurrender', Method.AcceptSurrender, (w) => writeAcceptSurrenderParams(w, { gameId, playerId: inGameId, accept: true }));
245
+ },
246
+ refused: worded(ACCEPT_ERRORS),
247
+ unanswered: (failure) => ({
248
+ status: 'unknown',
249
+ outcome: 'unknown',
250
+ game,
251
+ ...who,
252
+ warning: `war.app did not confirm the acceptance (${failure}), so it may already have gone through. ` +
253
+ 'Check warapp_my_games or warapp_get_game before doing anything else.',
254
+ }),
255
+ readBack: async () => {
256
+ const after = await ctx.client.getGame(gameId, { map: false });
257
+ const seats = await readDetailsSeats(ctx, gameId);
258
+ return { after, seats };
259
+ },
260
+ unreadable: (failure) => ({
261
+ status: 'unconfirmed',
262
+ outcome: 'unconfirmed',
263
+ game,
264
+ ...who,
265
+ warning: `war.app took the request, but GameFeed could not be read back (${failure}). Check warapp_my_games.`,
266
+ }),
267
+ classify: ({ after, seats }) => {
268
+ // By GameFeed id when known, else by the in-game id its GameFeed id wraps: never one against the other.
269
+ const theirs = after.players.find((p) => (player !== null ? p.id === player : inGameOf(p) === inGameId));
270
+ const state = { theirState: theirs?.state ?? null, gameState: after.state };
271
+ // Turned into an AI counts only when it was not one already at plan time.
272
+ const turnedAINow = !alreadyAI && theirs?.humanTurnedIntoAI === true;
273
+ if (after.state === FINISHED || theirs?.state === 'SurrenderAccepted' || turnedAINow) {
274
+ return { status: 'accepted', outcome: 'confirmed', game, ...who, ...state };
275
+ }
276
+ const detail = seats?.find((s) => s.id === inGameId);
277
+ const meInGame = (() => {
278
+ const p = after.players.find((x) => x.id === me);
279
+ return p ? inGameOf(p) : undefined;
280
+ })();
281
+ if (detail && !seatPlaying(detail)) {
282
+ return { status: 'accepted', outcome: 'confirmed', game, ...who, ...state };
283
+ }
284
+ if (detail?.surrendered && meInGame !== undefined && detail.acceptedBy.includes(meInGame)) {
285
+ return {
286
+ status: 'pending',
287
+ outcome: 'confirmed',
288
+ game,
289
+ ...who,
290
+ ...state,
291
+ message: 'Your acceptance is recorded; the surrender stays pending until the others still owing theirs accept it.',
292
+ };
293
+ }
294
+ return {
295
+ status: 'unconfirmed',
296
+ outcome: 'unconfirmed',
297
+ game,
298
+ ...who,
299
+ ...state,
300
+ warning: (detail && !detail.surrendered
301
+ ? 'The game details show the surrender no longer pending and the player still playing: it may have been taken back. '
302
+ : seats
303
+ ? 'war.app took the request, but the game details do not show your acceptance yet. '
304
+ : 'war.app took the request, but the game details could not be read back. ') +
305
+ 'Check warapp_my_games shortly; do not send it again blindly.',
306
+ };
307
+ },
308
+ });
309
+ },
310
+ });
311
+ }
@@ -0,0 +1,206 @@
1
+ // What the award of picks tells the turn tools (#166): read once from my stored pick list on the
2
+ // first board after distribution (src/analysis/award.ts, src/pick-list.ts), then reused all game.
3
+ import { firstMoverOnTurn, isCyclicMoveOrder, readAward } from '../analysis/award.js';
4
+ import { openingIncome, PICK_HORIZON } from '../analysis/picks.js';
5
+ import { FOG_LEVEL_NAMES, FOG_LEVEL_OWNER_ONLY, FOG_LEVEL_VISIBLE } from '../live.js';
6
+ import { readFirstMover, resolveFirstMover, verifiedFirstMover, writeFirstMover } from '../move-order.js';
7
+ import { readPickRecord, writeAward } from '../pick-list.js';
8
+ import { pickSettings } from './picks.js';
9
+ import { isTeamGame, teammatesOf } from '../teams.js';
10
+ const isMine = (t, me) => t.owner.kind === 'player' && t.owner.playerId === me;
11
+ /** The army count every territory of mine holds, when they all hold the same (the starting armies on turn 1). */
12
+ function uniformArmies(board, me) {
13
+ const counts = new Set();
14
+ for (const t of board.territories)
15
+ if (isMine(t, me))
16
+ counts.add(t.armies);
17
+ const only = counts.size === 1 ? [...counts][0] : null;
18
+ return only !== null && only > 0 ? only : null;
19
+ }
20
+ /**
21
+ * The award of `game` as `me` can read it, with the board to plan on; `undefined` when no pick
22
+ * list is kept for this player, the list did not explain the start, or the first board has
23
+ * passed unread. Reads the award (and keeps it) on turn 1; later turns reuse what was kept.
24
+ * `write: false` reads it the same way and keeps nothing (#275 pattern 3: a write's preview).
25
+ * Never throws.
26
+ */
27
+ export async function loadAward(dataDir, game, me, board, turn, o = {}) {
28
+ if (!dataDir || turn === null || game.players.length < 2)
29
+ return undefined;
30
+ const record = await readPickRecord(dataDir, game.id, me.id);
31
+ // A record that keeps only the pickable territories has no list to read the award from.
32
+ if (!record?.list)
33
+ return undefined;
34
+ let reading = record.award;
35
+ if (reading === undefined) {
36
+ // Only the first board shows what was granted: later I hold what I captured, too.
37
+ if (turn !== 1)
38
+ return undefined;
39
+ const mine = board.territories.filter((t) => isMine(t, me.id)).map((t) => t.territoryId);
40
+ // A team game (C2): a start the first board shows as a teammate's is theirs, not an opponent's.
41
+ const mates = isTeamGame(game.players) ? new Set(teammatesOf(game.players, me).map((p) => p.id)) : undefined;
42
+ const teammateHeld = mates
43
+ ? board.territories.filter((t) => t.owner.kind === 'player' && mates.has(t.owner.playerId)).map((t) => t.territoryId)
44
+ : undefined;
45
+ reading = readAward({ list: record.list, mine, players: game.players.length, ...(teammateHeld ? { teammateHeld } : {}) });
46
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
47
+ // A start the board shows as nobody's, mine or a neutral cannot be another player's: the list is not the one awarded from.
48
+ if (reading?.opponentStarts.some((t) => contradicts(state.get(t), me.id)))
49
+ reading = null;
50
+ if (o.write !== false)
51
+ await writeAward(dataDir, game.id, me.id, reading);
52
+ }
53
+ if (!reading)
54
+ return undefined;
55
+ const pickable = record.pickable ? { pickable: record.pickable } : {};
56
+ const duel = game.players.length === 2;
57
+ const opponent = duel ? game.players.find((p) => p.id !== me.id) : undefined;
58
+ const firstMover = duel ? firstMoverOnTurn({ role: reading.role, turn, moveOrder: game.settings?.moveOrder }) : null;
59
+ if (!opponent)
60
+ return { reading, firstMover, board, assumed: [], assumedArmies: null, ...pickable };
61
+ // A fogged start of the opponent's is its territory until the board shows otherwise. On turn 1
62
+ // nobody has deployed, so it holds the starting armies; later only its owner is known.
63
+ const assumedArmies = turn === 1 ? (uniformArmies(board, me.id) ?? game.settings?.initialPlayerArmiesPerTerritory ?? null) : null;
64
+ const starts = new Set(reading.opponentStarts);
65
+ const assumed = [];
66
+ const territories = board.territories.map((t) => {
67
+ if (!starts.has(t.territoryId) || t.owner.kind !== 'unknown')
68
+ return t;
69
+ assumed.push(t.territoryId);
70
+ return {
71
+ territoryId: t.territoryId,
72
+ owner: { kind: 'player', playerId: opponent.id },
73
+ armies: assumedArmies,
74
+ fogLevel: FOG_LEVEL_NAMES[assumedArmies === null ? FOG_LEVEL_OWNER_ONLY : FOG_LEVEL_VISIBLE],
75
+ };
76
+ });
77
+ const order = new Map(reading.opponentStarts.map((t, i) => [t, i]));
78
+ assumed.sort((a, b) => order.get(a) - order.get(b));
79
+ return { reading, opponent, firstMover, board: assumed.length ? { ...board, territories } : board, assumed, assumedArmies, ...pickable };
80
+ }
81
+ /**
82
+ * The opening threat model (#166): in a two-player game whose award proved every start the
83
+ * opponent has, its income on `turn` as the pick advisor's opening simulation gives it from those
84
+ * starts (`openingIncome`; my starts are never its captures), keyed by its GameFeed id, for the
85
+ * planner's fog prior (`PlanGameContext.opening`). Only on turns 1..PICK_HORIZON + 1, the turns the
86
+ * simulation covers; `undefined` otherwise. Neutral sizes are the ones `seen` (the board as war.app
87
+ * showed it) gives, then the settings.
88
+ */
89
+ export function openingThreat(a, game, graph, seen, turn) {
90
+ if (!a?.opponent || game.players.length !== 2 || !a.reading.allStartsKnown || !a.reading.opponentStarts.length)
91
+ return undefined;
92
+ if (turn === null || turn < 1 || turn > PICK_HORIZON + 1)
93
+ return undefined;
94
+ const neutralArmies = new Map();
95
+ for (const t of seen.territories)
96
+ if (t.owner.kind === 'neutral' && t.armies !== null)
97
+ neutralArmies.set(t.territoryId, t.armies);
98
+ const income = openingIncome({
99
+ graph,
100
+ starts: a.reading.opponentStarts,
101
+ settings: pickSettings(game.settings),
102
+ taken: [...a.reading.granted, ...a.reading.unlisted],
103
+ neutralArmies,
104
+ ...(a.pickable ? { pickable: a.pickable } : {}),
105
+ });
106
+ return new Map([[a.opponent.id, income[turn - 1]]]);
107
+ }
108
+ /** On the first board: a territory the award calls another player's that the board shows as mine, a neutral or pickable. */
109
+ function contradicts(t, me) {
110
+ if (!t || t.owner.kind === 'unknown')
111
+ return false;
112
+ return t.owner.kind !== 'player' || t.owner.playerId === me;
113
+ }
114
+ /** The one line a plan's warnings carry when its board holds territories the award gave an owner. */
115
+ export function assumedWarning(a) {
116
+ if (!a.assumed.length)
117
+ return [];
118
+ const many = a.assumed.length > 1;
119
+ return [
120
+ `Fogged territor${many ? 'ies' : 'y'} ${a.assumed.join(', ')} ${many ? 'are' : 'is'} planned as the opponent's` +
121
+ (a.assumedArmies !== null ? ` (${a.assumedArmies} armies each, the starting armies)` : ' (armies unknown)') +
122
+ `: your own pick list proves ${many ? 'they were' : 'it was'} its start (see \`award\`).`,
123
+ ];
124
+ }
125
+ /** The award as a tool reports it: territories by `name`, and what it means in sentences (ids only). */
126
+ export function awardView(a, game, turn, name) {
127
+ const { reading } = a;
128
+ const duel = game.players.length === 2;
129
+ const whose = duel ? "the opponent's" : "another player's";
130
+ const ids = (xs) => xs.join(', ');
131
+ const notes = [];
132
+ const team = reading.teammateStarts;
133
+ if (team) {
134
+ // A team game (C2): each start the award proves is a teammate's (the board showed it) or an opponent's.
135
+ if (team.length)
136
+ notes.push(`Your pick list ranked territor${team.length === 1 ? 'y' : 'ies'} ${ids(team)} above a pick you were granted, and the first board showed ` +
137
+ `${team.length === 1 ? 'it' : 'them'} as your teammate's: your teammate's start${team.length === 1 ? '' : 's'}.`);
138
+ if (reading.opponentStarts.length)
139
+ notes.push(`Your pick list ranked territor${reading.opponentStarts.length === 1 ? 'y' : 'ies'} ${ids(reading.opponentStarts)} above a pick you were granted, ` +
140
+ `and the first board did not show ${reading.opponentStarts.length === 1 ? 'it' : 'them'} as your teammate's: an opponent's start ` +
141
+ "(unverified: that teammates see each other's territories; a fogged one could still be your teammate's).");
142
+ if (!team.length && !reading.opponentStarts.length)
143
+ notes.push('You were granted the top of your list, so the award shows no start of another player.');
144
+ }
145
+ else if (reading.opponentStarts.length)
146
+ notes.push(`Your pick list ranked territor${reading.opponentStarts.length === 1 ? 'y' : 'ies'} ${ids(reading.opponentStarts)} above a pick you were granted, ` +
147
+ `so ${reading.opponentStarts.length === 1 ? 'it was' : 'they were'} taken first: ${whose} start${reading.opponentStarts.length === 1 ? '' : 's'}` +
148
+ (reading.allStartsKnown ? ' (every start it has).' : '.'));
149
+ else
150
+ notes.push('You were granted the top of your list, so the award shows no start of another player.');
151
+ if (reading.unlisted.length)
152
+ notes.push(`Your list ran out: territor${reading.unlisted.length === 1 ? 'y' : 'ies'} ${ids(reading.unlisted)} ${reading.unlisted.length === 1 ? 'was' : 'were'} given to you at random.`);
153
+ if (a.assumed.length)
154
+ notes.push(`Still fogged, territor${a.assumed.length === 1 ? 'y' : 'ies'} ${ids(a.assumed)} ${a.assumed.length === 1 ? 'is' : 'are'} planned as the opponent's` +
155
+ (a.assumedArmies !== null ? ` with the ${a.assumedArmies} starting armies (nobody has deployed yet).` : ' (armies unknown).'));
156
+ if (duel && reading.role)
157
+ notes.push(`Only the ${reading.role} awarded can be granted this set` +
158
+ (a.firstMover
159
+ ? `; under this game's ${game.settings?.moveOrder} move order the first awarded moves second on turn 1 and the order alternates, so ` +
160
+ `${a.firstMover === 'me' ? 'you move' : 'the opponent moves'} first on turn ${turn} (an Order Priority or Order Delay card changes that). ` +
161
+ "This is the community wiki's rule and the game client's help text, not verified live."
162
+ : game.settings?.moveOrder === 'NoLuckCycle'
163
+ ? '; under a no-luck cycle play speed, not the award, set who moves first: the game shows it (Game → Move Order), so pass it as `first_mover`.'
164
+ : '.'));
165
+ const commanders = game.settings?.commanders === true;
166
+ if (commanders && duel && reading.opponentFirstAward !== null)
167
+ notes.push(`Territory ${reading.opponentFirstAward} was the opponent's first award, and a commander starts on its owner's first award: ` +
168
+ `its commander ${turn === 1 ? 'is' : 'started'} there.`);
169
+ return {
170
+ opponentStarts: reading.opponentStarts.map(name),
171
+ ...(team ? { teammateStarts: team.map(name) } : {}),
172
+ allStartsKnown: reading.allStartsKnown,
173
+ awarded: duel ? reading.role : null,
174
+ firstMover: a.firstMover === null ? null : a.firstMover === 'me' ? 'you' : 'opponent',
175
+ ...(commanders && duel ? { opponentCommanderStart: reading.opponentFirstAward === null ? null : name(reading.opponentFirstAward) } : {}),
176
+ assumedOnBoard: a.assumed.map(name),
177
+ notes,
178
+ };
179
+ }
180
+ /**
181
+ * Who moves first on `turn` (#127): `first_mover` when given, else what this server knows — a
182
+ * turn kept at `<dataDir>/move-order/` alternated, or the award of picks — in a two-player game
183
+ * under a cyclic move order. What is newly known is kept for later turns (not with `write: false`). Never throws.
184
+ */
185
+ export async function firstMoverFor(dataDir, game, me, turn, explicit, award, o = {}) {
186
+ const cyclicDuel = game.players.length === 2 && isCyclicMoveOrder(game.settings?.moveOrder);
187
+ const remembered = dataDir && cyclicDuel ? await readFirstMover(dataDir, game.id, me.id) : undefined;
188
+ const { resolved, record, warnings } = resolveFirstMover({
189
+ turn,
190
+ cyclicDuel,
191
+ ...(explicit ? { explicit } : {}),
192
+ award: award?.firstMover ?? null,
193
+ ...(remembered ? { remembered } : {}),
194
+ });
195
+ if (dataDir && record && o.write !== false)
196
+ await writeFirstMover(dataDir, game.id, me.id, record);
197
+ if (!resolved)
198
+ return { view: null, warnings };
199
+ return {
200
+ firstMover: resolved.firstMover,
201
+ // #215 review: only a first mover the user gave is verified; the award's is the wiki's rule.
202
+ verified: verifiedFirstMover(resolved),
203
+ view: { who: resolved.firstMover === 'me' ? 'you' : 'opponent', source: resolved.source, ...(resolved.from ? { from: resolved.from } : {}) },
204
+ warnings,
205
+ };
206
+ }