@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,99 @@
1
+ import { COUNTER_PLAY, emptyHabits, estimateHabits, HABIT_NAMES, habitsOf, labelsOf, lastAttackTurn, PROFILE_MIN_CONFIDENCE, profileFormatOf, } from '../analysis/opponent-profile.js';
2
+ import { observeBoards, profileEnabled, readProfileHistory, readProfileTurns } from '../profile-store.js';
3
+ import { graphOf } from './common.js';
4
+ import { mapOf } from './map.js';
5
+ import { cardsInPlay, observeSettings, profiledOpponents } from './profile-hook.js';
6
+ /**
7
+ * The reads of my opponents in `game`: the turns stored for it (when kept) and those `boards` show now,
8
+ * with the cross-game record when the teams are known (never a possible teammate's past). Never writes.
9
+ */
10
+ export async function readOpponents(o) {
11
+ const { dataDir, env, game, me, teamsKnown, boards } = o;
12
+ const on = profileEnabled(env);
13
+ const opponents = profiledOpponents(game, me);
14
+ const stored = on && dataDir ? await readProfileTurns(dataDir, game.id, me.id, env) : new Map();
15
+ const fresh = observeBoards({ gameId: game.id, me: me.id, graph: graphOf(mapOf(game)), settings: observeSettings(game), ...cardsInPlay(game), opponents, boards });
16
+ const turnsOf = (id) => {
17
+ const byTurn = new Map();
18
+ for (const t of stored.get(id) ?? [])
19
+ byTurn.set(t.turn, t);
20
+ for (const [t, m] of fresh) {
21
+ const p = m.get(id);
22
+ if (p)
23
+ byTurn.set(t, { turn: t, primitives: p });
24
+ }
25
+ return [...byTurn.values()].sort((a, b) => a.turn - b.turn);
26
+ };
27
+ const record = on && dataDir ? await readProfileHistory(dataDir, teamsKnown ? opponents : [], { me: me.id, gameId: game.id }, env) : undefined;
28
+ const known = typeof record === 'object' ? record : undefined;
29
+ const format = profileFormatOf(game.players);
30
+ const players = new Map(game.players.map((p) => [p.id, p]));
31
+ // The turn being played: the newest board handed in (the live one), else none (#264).
32
+ const turn = boards.length ? Math.max(...boards.map((b) => b.turn)) : null;
33
+ const reads = opponents.map((id) => {
34
+ const p = players.get(id);
35
+ const turns = turnsOf(id);
36
+ const habits = habitsOf(turns);
37
+ const estimates = estimateHabits(habits, priorsOf(known, format, id, Boolean(p?.isAI)));
38
+ const last = lastAttackTurn(turns);
39
+ return {
40
+ id,
41
+ ai: Boolean(p?.isAI || p?.humanTurnedIntoAI),
42
+ turns,
43
+ habits,
44
+ estimates,
45
+ labels: labelsOf(estimates, { lastAttackTurn: last, turn }),
46
+ lastAttackTurn: last,
47
+ ...(p?.isAI ? {} : { gamesMet: known?.players.get(id)?.games ?? 0 }),
48
+ };
49
+ });
50
+ return { on, record, reads };
51
+ }
52
+ /** What the estimate pools with a game's counts: the player's past and the population (the AI pool for an AI seat). */
53
+ function priorsOf(known, format, id, ai) {
54
+ if (!known)
55
+ return {};
56
+ if (ai)
57
+ return { pools: [known.pools.ai] };
58
+ const pools = [known.pools.byFormat[format], known.pools.all].filter((x) => x !== undefined);
59
+ const rec = known.players.get(id);
60
+ return { pools, ...(rec ? { past: rec.past, pastHistory: rec.fromHistory } : {}) };
61
+ }
62
+ /** The habits at the confidence bar, each with its value, `n` and `basis`. */
63
+ export function confidentHabits(e) {
64
+ return Object.fromEntries(HABIT_NAMES.filter((n) => e[n].confidence >= PROFILE_MIN_CONFIDENCE).map((n) => [n, { value: e[n].value, n: e[n].n, basis: e[n].basis }]));
65
+ }
66
+ /** The counter-play lines of `labels`. */
67
+ export const counterOf = (labels) => labels.flatMap((l) => (COUNTER_PLAY[l] ? [COUNTER_PLAY[l]] : []));
68
+ /** The players next to me on `board`, ascending. */
69
+ export function neighboursOf(graph, board, me) {
70
+ const at = new Map(board.territories.map((t) => [t.territoryId, t]));
71
+ const out = new Set();
72
+ for (const t of board.territories) {
73
+ if (t.owner.kind !== 'player' || t.owner.playerId !== me)
74
+ continue;
75
+ for (const n of graph.territoryById.get(t.territoryId)?.connectedTo ?? []) {
76
+ const o = at.get(n)?.owner;
77
+ if (o?.kind === 'player' && o.playerId !== me)
78
+ out.add(o.playerId);
79
+ }
80
+ }
81
+ return [...out].sort((a, b) => a - b);
82
+ }
83
+ /**
84
+ * The read of a player from the cross-game record alone (warapp_scout_player's `met`: no game in
85
+ * hand, so every format's pool): games met, every habit and the labels; `undefined` when the record
86
+ * does not hold the player, is unreadable, or profiling is off. Never throws, never writes.
87
+ */
88
+ export async function metRead(dataDir, env, id) {
89
+ if (!dataDir || !profileEnabled(env))
90
+ return undefined;
91
+ const record = await readProfileHistory(dataDir, [id], {}, env);
92
+ if (typeof record !== 'object')
93
+ return undefined;
94
+ const p = record.players.get(id);
95
+ if (!p)
96
+ return undefined;
97
+ const habits = estimateHabits(emptyHabits(), { past: p.past, pastHistory: p.fromHistory, pools: [record.pools.all] });
98
+ return { games: p.games, habits, labels: labelsOf(habits) };
99
+ }
@@ -0,0 +1,445 @@
1
+ // Turn notifications: wait until one of my games is waiting on me, woken by
2
+ // war.app's push socket (src/push/), and list the pushes this process has
3
+ // seen. Both are read-only.
4
+ import { callerWantsProgress, currentCallSignal, McpToolError, reportProgress } from '@chrischall/mcp-utils';
5
+ import { z } from 'zod';
6
+ import { parseGameId } from '../client.js';
7
+ import { activeGameIds } from '../my-games.js';
8
+ import { foldFinishedGame } from '../profile-store.js';
9
+ import { endOfGame } from './end-of-game.js';
10
+ import { currentTurn, gameIdArg, readAnnotations, respond, untrustedDescription } from './common.js';
11
+ import { lookupMeta, mintMeta } from './hints.js';
12
+ import { failureText, FROZEN_TAB_HINT } from './live-context.js';
13
+ import { fetchMyGames } from './my-games.js';
14
+ import { requireMe } from './write-kit.js';
15
+ import { surrenderOwed } from '../surrender-pending.js';
16
+ import { fetchDetailsSeats, readPendingSurrenders, SURRENDER_PENDING_NOTE, surrenderOwedLine } from './surrender-pending.js';
17
+ /** Game states in which a player has something to submit (picks or orders). */
18
+ const ACTION_STATES = new Set(['Playing', 'DistributingTerritories']);
19
+ /** Game states that never change again: the push listener forgets such a game. */
20
+ const TERMINAL_STATES = new Set(['Finished']);
21
+ const MAX_WAIT_GAMES = 20;
22
+ const DEFAULT_TIMEOUT_SECONDS = 300;
23
+ const MAX_TIMEOUT_SECONDS = 1800;
24
+ /** How often a waiting call reports progress, when the caller asked for it. */
25
+ const PROGRESS_EVERY_MS = 15_000;
26
+ const VIEWS = ['compact'];
27
+ /** Whether the game is waiting on this player: game in a turn/pick phase, my player Playing and not committed. */
28
+ export function isWaitingOn(game, playerId) {
29
+ if (!ACTION_STATES.has(game.state))
30
+ return false;
31
+ const me = game.players.find((p) => p.id === playerId);
32
+ return me !== undefined && me.state === 'Playing' && !me.hasCommittedOrders;
33
+ }
34
+ /** Why no turn of mine can come in `game` any more, or undefined while one still can (#130). */
35
+ function endedReason(game, playerId) {
36
+ if (game.state === 'Finished')
37
+ return 'The game is finished.';
38
+ if (!ACTION_STATES.has(game.state))
39
+ return undefined;
40
+ const me = game.players.find((p) => p.id === playerId);
41
+ if (me?.state !== undefined && me.state !== 'Playing')
42
+ return `You are out of this game (your state: ${me.state}).`;
43
+ return undefined;
44
+ }
45
+ export function checkOf(game, playerId, surrenders) {
46
+ const ended = endedReason(game, playerId);
47
+ return {
48
+ id: game.id,
49
+ name: game.name ?? null,
50
+ state: game.state,
51
+ turn: currentTurn(game),
52
+ waitingOnYou: isWaitingOn(game, playerId),
53
+ ...(ended ? { ended } : {}),
54
+ ...(surrenders !== undefined ? { surrenderPending: surrenders } : {}),
55
+ ...(surrenderOwed(surrenders) ? { surrenderOwed: true } : {}),
56
+ };
57
+ }
58
+ /**
59
+ * Resolve as soon as one of `gameIds` is waiting on me — checked once at
60
+ * start, again for a game on every GameUpdated push for it, and again for
61
+ * every game after the push socket reconnects (pushes sent during the gap are
62
+ * lost) — or when `timeoutMs` passes. A cancelled `signal` rejects with its
63
+ * reason. The games are checked before they are watched, so a game the check
64
+ * refuses (not mine) is never subscribed; a finished game, or one where my seat is out, is not watched. Re-reads
65
+ * are debounced per game: at most one in flight and one queued (#131).
66
+ */
67
+ export async function waitForTurn(opts) {
68
+ const now = opts.now ?? Date.now;
69
+ const start = now();
70
+ const ids = new Set(opts.gameIds);
71
+ const queue = [];
72
+ let wake;
73
+ let updates = 0;
74
+ let reconnects = 0;
75
+ /** Set by a reconnect: report it once the loop resumes. */
76
+ let reconnectNote = false;
77
+ const errors = [];
78
+ const chatActivity = new Set();
79
+ const off = opts.push.onUpdate((u) => {
80
+ if (!ids.has(u.gameId))
81
+ return;
82
+ updates++;
83
+ if (u.chat)
84
+ chatActivity.add(u.gameId);
85
+ // Debounced (#131): a burst of pushes while the game is queued is one re-read; one arriving
86
+ // while its re-read is in flight queues one more (the read in flight may predate the change).
87
+ if (!queue.includes(u.gameId))
88
+ queue.push(u.gameId);
89
+ wake?.();
90
+ });
91
+ const requeue = (reconnect) => {
92
+ if (reconnect) {
93
+ reconnects++;
94
+ reconnectNote = true;
95
+ }
96
+ for (const id of ids)
97
+ if (!queue.includes(id))
98
+ queue.push(id);
99
+ wake?.();
100
+ };
101
+ // Every connect, the first included: watch() returns before the socket connects, so a turn
102
+ // that resolves between the initial check and the first Subscribe is only seen by a re-read.
103
+ // Cost, accepted (#148): a wait that starts the socket reads each game twice up front (its check,
104
+ // then the re-read on that first connect), 2N GameFeed reads for N games where N would do when the
105
+ // two are milliseconds apart. Skipping the re-read would trade a few reads for a missed turn
106
+ // whenever they are not; a re-read asked for while one is in flight is coalesced (`coalesced`).
107
+ const offReconnect = opts.push.onConnect
108
+ ? opts.push.onConnect((e) => requeue(e.reconnect))
109
+ : opts.push.onReconnect?.(() => requeue(true));
110
+ const timers = [];
111
+ /** The games this wait watches (released when it ends). */
112
+ let watched = [];
113
+ /** A finished game cannot need me again: the listener stops watching it. */
114
+ const settle = (c) => {
115
+ if (TERMINAL_STATES.has(c.state))
116
+ opts.push.forget?.([c.id]);
117
+ };
118
+ let onAbort;
119
+ try {
120
+ opts.signal?.throwIfAborted();
121
+ // Check first, watch second (#131): the check refuses a game the account does not play in, and
122
+ // such a game must never be subscribed. The gap this opens (a turn resolving between the check
123
+ // and the Subscribe sends no push) is closed by a re-read: on the connect when the socket is not
124
+ // up yet, or right after `watch` when it subscribed on a live session.
125
+ const latest = new Map();
126
+ // Taken before the first checks: a Subscribe for these games that another wait gets through after
127
+ // it (or has in flight when this one watches) makes `watch` say so, and the games are re-read (#148).
128
+ const mark = opts.push.mark?.();
129
+ const first = await Promise.all([...ids].map(async (id) => [id, await opts.check(id)]));
130
+ for (const [id, c] of first) {
131
+ latest.set(id, c);
132
+ settle(c);
133
+ }
134
+ const outcome = (status) => ({
135
+ status,
136
+ games: [...ids].map((id) => latest.get(id)),
137
+ updates,
138
+ reconnects,
139
+ waitedMs: now() - start,
140
+ errors,
141
+ chatActivity: [...ids].filter((id) => chatActivity.has(id)),
142
+ });
143
+ const allEnded = () => [...latest.values()].every((c) => c.ended !== undefined);
144
+ const owed = () => opts.wakeOnSurrender === true && [...latest.values()].some((c) => c.surrenderOwed === true);
145
+ if ([...latest.values()].some((c) => c.waitingOnYou))
146
+ return outcome('your_turn');
147
+ if (owed())
148
+ return outcome('surrender_pending');
149
+ // Every game ended (finished, or my seat out): no turn can come, so return before watching (#130).
150
+ if (allEnded())
151
+ return outcome('game_over');
152
+ opts.signal?.throwIfAborted();
153
+ // Watch only a game that can still need me: not a finished one (#131), nor one where my seat is out (#130).
154
+ const live = [...ids].filter((id) => !TERMINAL_STATES.has(latest.get(id).state) && latest.get(id).ended === undefined);
155
+ if (live.length) {
156
+ const subscribedNow = await opts.push.watch(live, mark === undefined ? {} : { since: mark });
157
+ watched = live;
158
+ if (subscribedNow === true)
159
+ for (const id of live)
160
+ if (!queue.includes(id))
161
+ queue.push(id);
162
+ }
163
+ opts.progress?.(0, `Waiting for your turn in ${ids.size} game(s).`);
164
+ let timedOut = false;
165
+ let aborted = false;
166
+ const ping = () => wake?.();
167
+ timers.push(setTimeout(() => {
168
+ timedOut = true;
169
+ ping();
170
+ }, opts.timeoutMs));
171
+ if (opts.progress) {
172
+ const every = opts.progressEveryMs ?? PROGRESS_EVERY_MS;
173
+ const tick = () => {
174
+ opts.progress?.(now() - start, 'Still waiting for your turn.');
175
+ timers.push(setTimeout(tick, every));
176
+ };
177
+ timers.push(setTimeout(tick, every));
178
+ }
179
+ if (opts.signal) {
180
+ onAbort = () => {
181
+ aborted = true;
182
+ ping();
183
+ };
184
+ opts.signal.addEventListener('abort', onAbort, { once: true });
185
+ }
186
+ for (;;) {
187
+ if (aborted)
188
+ opts.signal.throwIfAborted();
189
+ if (reconnectNote) {
190
+ reconnectNote = false;
191
+ opts.progress?.(now() - start, 'Push socket reconnected; re-checking every game (pushes in the gap are lost).');
192
+ }
193
+ const id = queue.shift();
194
+ if (id !== undefined) {
195
+ try {
196
+ const c = await opts.check(id);
197
+ latest.set(id, c);
198
+ settle(c);
199
+ if (c.waitingOnYou)
200
+ return outcome('your_turn');
201
+ if (opts.wakeOnSurrender === true && c.surrenderOwed === true)
202
+ return outcome('surrender_pending');
203
+ if (allEnded())
204
+ return outcome('game_over');
205
+ opts.progress?.(now() - start, `Game ${id} updated; not your turn there yet.`);
206
+ }
207
+ catch (e) {
208
+ errors.push(`Game ${id}: ${e instanceof Error ? e.message : String(e)}`);
209
+ }
210
+ continue;
211
+ }
212
+ if (timedOut)
213
+ return outcome('timed_out');
214
+ await new Promise((resolve) => {
215
+ wake = resolve;
216
+ });
217
+ wake = undefined;
218
+ }
219
+ }
220
+ finally {
221
+ off();
222
+ offReconnect?.();
223
+ if (watched.length)
224
+ opts.push.release?.(watched);
225
+ timers.forEach((t) => clearTimeout(t));
226
+ if (onAbort)
227
+ opts.signal?.removeEventListener('abort', onAbort);
228
+ }
229
+ }
230
+ /**
231
+ * Coalesce reads per key (#131): at most one read in flight and one queued. A call while a read is
232
+ * in flight gets the queued read, which starts once the one in flight settles, so it sees data read
233
+ * after it asked; every call while that read is queued shares it.
234
+ */
235
+ export function coalesced(read) {
236
+ const inFlight = new Map();
237
+ const queued = new Map();
238
+ const start = (key) => {
239
+ const p = read(key).finally(() => {
240
+ if (inFlight.get(key) === p)
241
+ inFlight.delete(key);
242
+ });
243
+ inFlight.set(key, p);
244
+ return p;
245
+ };
246
+ return (key) => {
247
+ const waiting = queued.get(key);
248
+ if (waiting)
249
+ return waiting;
250
+ const current = inFlight.get(key);
251
+ if (!current)
252
+ return start(key);
253
+ const next = current.then(() => undefined, () => undefined).then(() => {
254
+ queued.delete(key);
255
+ return start(key);
256
+ });
257
+ queued.set(key, next);
258
+ return next;
259
+ };
260
+ }
261
+ export function registerPushTools(server, ctx, push, deps = {}) {
262
+ const env = deps.env ?? process.env;
263
+ // One GameFeed read per game at a time across every wait in the process, one queued (#131).
264
+ const readGame = coalesced((id) => ctx.client.getGame(id, { map: false }));
265
+ // #317: and one game-details read per game at a time, for a pending surrender.
266
+ const readDetails = coalesced((id) => fetchDetailsSeats(ctx, id));
267
+ server.registerTool('warapp_wait_for_turn', {
268
+ title: 'Wait for my turn in war.app games',
269
+ description: untrustedDescription('Wait until one of the given war.app (Warzone) games is waiting on you — the game is being played or its ' +
270
+ 'territories picked, you are still playing, and you have not committed — and return as soon as it is, ' +
271
+ 'or at the timeout (default 300 s, max 1800 s) — or at once with `game_over` when every game has finished or ' +
272
+ 'your seat is out (each says why in `ended`). It checks each game once at the start, then listens to ' +
273
+ "war.app's push notifications — over a direct WebSocket while a linked war.app session serves calls, else " +
274
+ 'through your signed-in war.app tab (ContextMint Bridge) — and re-checks a game whenever war.app says it ' +
275
+ 'changed, and every game after the push socket reconnects. It also returns (status `surrender_pending`) when ' +
276
+ 'another player\'s surrender waits for you to accept it (each game\'s `surrenderPending`, read from the game ' +
277
+ 'details, unverified live: null when unreadable, never "none"; after one failed read it stops asking for the ' +
278
+ 'rest of the wait and says why in `surrenderUnread`), unless `ignore_surrenders`. ' +
279
+ 'Pass the game ids to watch (1–20), or omit them to watch every game ' +
280
+ 'of yours being played or picked (the first 20, as warapp_my_games lists them). Reports progress while it ' +
281
+ 'waits and stops when the call is cancelled. Then plan with warapp_plan_turn (or pick with ' +
282
+ 'warapp_submit_picks). Read-only.'),
283
+ _meta: mintMeta('whats-new', ['is it my turn', 'wait for my turn', 'tell me when it is my turn', 'warzone turn ready']),
284
+ annotations: readAnnotations('Wait for my war.app turn'),
285
+ inputSchema: z.object({
286
+ game_ids: z
287
+ .array(gameIdArg)
288
+ .min(1)
289
+ .max(MAX_WAIT_GAMES)
290
+ .optional()
291
+ .describe('The war.app game ids to watch (the number after GameID= in each game URL). Omit to watch every game ' +
292
+ 'of yours being played or picked.'),
293
+ timeout_seconds: z.coerce
294
+ .number()
295
+ .int()
296
+ .min(1)
297
+ .max(MAX_TIMEOUT_SECONDS)
298
+ .optional()
299
+ .describe(`Give up after this many seconds (default ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}).`),
300
+ ignore_surrenders: z
301
+ .boolean()
302
+ .optional()
303
+ .describe('Do not return for a surrender waiting on your acceptance (default false). Use it once the owner has ' +
304
+ 'decided not to accept yet, or the wait returns at once every time; games still report surrenderPending.'),
305
+ }),
306
+ }, async ({ game_ids, timeout_seconds, ignore_surrenders }) => {
307
+ let ids;
308
+ if (game_ids) {
309
+ ids = [...new Set(game_ids.map((g) => parseGameId(g)))];
310
+ }
311
+ else {
312
+ const { me, games } = await fetchMyGames(ctx);
313
+ ids = activeGameIds(games, me).slice(0, MAX_WAIT_GAMES);
314
+ if (!ids.length) {
315
+ throw new McpToolError('None of your war.app games is being played or picked right now, so there is no turn to wait for.', {
316
+ hint: 'warapp_my_games lists your games and their states; a lobby starts once enough players join.',
317
+ });
318
+ }
319
+ }
320
+ // Turns are watched for the account signed in to the war.app tab.
321
+ const token = await requireMe(ctx, { fresh: false, consequence: 'there is no turn to wait for' });
322
+ // #317: once a details read fails in this wait (a frozen tab stalls each call until it times out),
323
+ // it is not asked again until the wait ends; every later check reports the surrenders as unknown.
324
+ // (The rpc layer has no per-call timeout, so the first failure costs one bridge timeout.)
325
+ let detailsFailed;
326
+ const readSurrenderSeats = async (gameId) => {
327
+ if (detailsFailed !== undefined)
328
+ return undefined;
329
+ try {
330
+ return await readDetails(gameId);
331
+ }
332
+ catch (e) {
333
+ detailsFailed ??= failureText(e);
334
+ return undefined;
335
+ }
336
+ };
337
+ const check = async (id) => {
338
+ // A turn check reads only the game's state: no map (a cold map is ~190 KB per game, #131).
339
+ const game = await readGame(id);
340
+ if (!game.players.some((p) => p.id === token)) {
341
+ throw new McpToolError(`The signed-in war.app account is not a player in game ${id}.`, {
342
+ hint: 'Watch only games you play in.',
343
+ });
344
+ }
345
+ // The first read that shows a game of mine finished folds its opponent profile (B2; best effort, no request).
346
+ if (game.state === 'Finished' && ctx.dataDir)
347
+ await foldFinishedGame(ctx.dataDir, game, env);
348
+ // #312: its end-of-game pass, once (one history read; best effort, never throws).
349
+ if (game.state === 'Finished')
350
+ await endOfGame({ client: ctx.client, dataDir: ctx.dataDir, env }, id, token, game);
351
+ // #317: a surrender waiting on my acceptance (only while the game is in play and my seat plays).
352
+ const surrenders = await readPendingSurrenders(ctx, game, game.players.find((p) => p.id === token), readSurrenderSeats);
353
+ return checkOf(game, token, surrenders);
354
+ };
355
+ const timeoutSec = timeout_seconds ?? DEFAULT_TIMEOUT_SECONDS;
356
+ const progress = callerWantsProgress()
357
+ ? (elapsedMs, message) => {
358
+ void reportProgress(Math.min(timeoutSec, Math.round(elapsedMs / 1000)), timeoutSec, message).catch(() => undefined);
359
+ }
360
+ : undefined;
361
+ const signal = currentCallSignal();
362
+ const out = await waitForTurn({
363
+ gameIds: ids,
364
+ timeoutMs: timeoutSec * 1000,
365
+ push,
366
+ check,
367
+ wakeOnSurrender: ignore_surrenders !== true,
368
+ ...(signal ? { signal } : {}),
369
+ ...(progress ? { progress } : {}),
370
+ });
371
+ const st = push.status();
372
+ return respond(undefined, VIEWS, () => ({
373
+ status: out.status,
374
+ watching: ids,
375
+ ...(out.status === 'your_turn' ? { ready: out.games.filter((g) => g.waitingOnYou).map((g) => g.id) } : {}),
376
+ // #317: the games where a surrender waits on my acceptance, whatever the status.
377
+ ...(out.games.some((g) => g.surrenderOwed) ? { surrenders: out.games.filter((g) => g.surrenderOwed).map((g) => g.id) } : {}),
378
+ games: out.games.map((g) => (out.chatActivity.includes(g.id) ? { ...g, chatActivity: true } : g)),
379
+ waited_seconds: Math.round(out.waitedMs / 1000),
380
+ updates: out.updates,
381
+ ...(out.reconnects ? { reconnects: out.reconnects } : {}),
382
+ push: {
383
+ connected: st.connected,
384
+ ...(st.transport ? { transport: st.transport } : {}),
385
+ ...(st.lastError ? { last_error: st.lastError } : {}),
386
+ },
387
+ ...(out.errors.length ? { errors: out.errors } : {}),
388
+ surrenderNote: SURRENDER_PENDING_NOTE,
389
+ ...(detailsFailed !== undefined
390
+ ? {
391
+ surrenderUnread: `The game details could not be read (${detailsFailed}), so pending surrenders were skipped for the ` +
392
+ 'rest of this wait (surrenderPending null: unknown, not none).' +
393
+ (detailsFailed.includes(FROZEN_TAB_HINT) ? '' : ` ${FROZEN_TAB_HINT}`),
394
+ }
395
+ : {}),
396
+ next: out.status === 'surrender_pending'
397
+ ? out.games
398
+ .filter((g) => g.surrenderOwed)
399
+ .map((g) => `Game ${g.id}: ${surrenderOwedLine(g.surrenderPending ?? null)}`)
400
+ .join(' ') +
401
+ ' ' +
402
+ 'Once decided, wait again (with ignore_surrenders: true while it stays unaccepted).'
403
+ : out.status === 'your_turn'
404
+ ? 'Plan the turn with warapp_plan_turn (or, while territories are being picked, warapp_get_live_board and warapp_submit_picks).'
405
+ : out.status === 'game_over'
406
+ ? 'No turn is coming in these games (each finished or your seat is out — see `ended`), so stop watching them.'
407
+ : st.connected
408
+ ? 'No game needed you before the timeout. Call warapp_wait_for_turn again to keep waiting.'
409
+ : 'No game needed you before the timeout, and the push socket was not connected (no war.app tab paired?), ' +
410
+ 'so only the start was checked. Open and focus a signed-in war.app tab, then retry.',
411
+ }));
412
+ });
413
+ server.registerTool('warapp_recent_events', {
414
+ title: 'Recent war.app push events',
415
+ description: 'List the war.app game-update pushes this server process has received (newest first): which game ' +
416
+ 'changed and when. Only games watched by warapp_wait_for_turn are listened to; a push says only that a ' +
417
+ 'game changed, so re-read it with warapp_get_game. Also reports whether the push socket is connected and its ' +
418
+ 'transport (websocket or xhr-polling). Read-only.',
419
+ _meta: lookupMeta(['recent game updates', 'warzone notifications']),
420
+ annotations: readAnnotations('Recent war.app push events'),
421
+ inputSchema: z.object({
422
+ limit: z.coerce.number().int().min(1).max(100).optional().describe('How many events (default 20, max 100).'),
423
+ game_id: gameIdArg.optional().describe('Only events for this game.'),
424
+ }),
425
+ }, async ({ limit, game_id }) => {
426
+ const only = game_id === undefined ? undefined : parseGameId(game_id);
427
+ const events = push
428
+ .recent()
429
+ .filter((e) => only === undefined || e.gameId === only)
430
+ .slice(0, limit ?? 20)
431
+ .map((e) => ({ game_id: e.gameId, at: e.at, ...(e.chat ? { chat: true } : {}) }));
432
+ const st = push.status();
433
+ return respond(undefined, VIEWS, () => ({
434
+ events,
435
+ listening: {
436
+ started: st.started,
437
+ connected: st.connected,
438
+ watching: st.watching,
439
+ ...(st.transport ? { transport: st.transport } : {}),
440
+ ...(Object.keys(st.refused).length ? { refused: st.refused } : {}),
441
+ ...(st.lastError ? { last_error: st.lastError } : {}),
442
+ },
443
+ }));
444
+ });
445
+ }