@chrischall/warapp-mcp 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,181 @@
1
+ // warapp_leave_game: give up the signed-in account's seat in a game that has not started
2
+ // (`WaitingForPlayers`) with the web client's DeclineGame (method 64) — the lobby's Decline
3
+ // button, gated on the user's confirmation (#217). The encoding is read from the client bundle's
4
+ // writer, verified live 2026-11-14 for an open-seat lobby (docs/WEB-PROTOCOL.md "DeclineGame"). The game is read from GameFeed
5
+ // first (refused once started, for a seat the account does not hold, and for mod games), and the
6
+ // leave is reported only once GameFeed (else GetMyGames) shows the account no longer seated —
7
+ // never from the reply, whose one bool says whether war.app removed the account's chat.
8
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
9
+ import { z } from 'zod';
10
+ import { parseGameId } from '../client.js';
11
+ import { holdsSeat, playerStateName } from '../player-states.js';
12
+ import { Method, readDeclineGameReturn, writeDeclineGameParams } from '../protocol/methods.js';
13
+ import { WarappServerError } from '../protocol/rpc.js';
14
+ import { isTeamGame } from '../teams.js';
15
+ import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
16
+ import { mintMeta } from './hints.js';
17
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
18
+ import { BRIDGE_NOTE } from './live.js';
19
+ import { fetchMyGames } from './my-games.js';
20
+ import { defineGatedWrite, mySeat, refuse, requireMe, sendAndVerify } from './write-kit.js';
21
+ /** The only game state a seat can be left in: the lobby, still filling. */
22
+ const LOBBY = 'WaitingForPlayers';
23
+ /**
24
+ * The DeclineGame refusals the client words (read from the bundle). It also swallows 17
25
+ * (NotInGame), 4 and 7 (InvalidPlayerState) without a word; here all three are read back from
26
+ * game state like an accepted leave ({@link READ_BACK_ERRORS}), so game state, not a guessed
27
+ * wording, says whether the seat is gone.
28
+ */
29
+ const LEAVE_ERRORS = {
30
+ 191: 'You cannot leave an open game you created; delete it in war.app instead.',
31
+ 88: 'This game has been deleted.',
32
+ };
33
+ /**
34
+ * NotInGame and the codes the client swallows (4, 7): the seat may already be gone, so game
35
+ * state decides rather than a guessed wording.
36
+ */
37
+ const READ_BACK_ERRORS = new Set([17, 4, 7]);
38
+ /** The signed-in account's seat in lobby `game`, refused unless the account holds one there. */
39
+ function leavable(game, token) {
40
+ if (game.state !== LOBBY) {
41
+ refuse(`Game ${game.id} is not a lobby (game state: ${game.state}): only a game still ${LOBBY} can be left, so nothing was sent.`, 'A game that has started is surrendered with warapp_surrender, not left.');
42
+ }
43
+ const seat = mySeat(game, token);
44
+ if (!holdsSeat(seat.state)) {
45
+ refuse(`You hold no seat in game ${game.id} (your state: ${seat.state ?? 'unknown'}), so there is nothing to leave.`, 'An invitation is declined in war.app; check warapp_my_games.');
46
+ }
47
+ // Unread settings are treated as possibly modded: the mod-hook flag is sent false, which a
48
+ // mod game could refuse or mishandle.
49
+ const mods = game.settings?.mods;
50
+ if (mods === undefined || mods !== 0) {
51
+ refuse(mods === undefined
52
+ ? `Game ${game.id}'s settings could not be read, so whether it uses mods is unknown and nothing was sent.`
53
+ : `Game ${game.id} uses mods, which can hook leaving the game in ways this tool cannot reproduce, so nothing was sent.`, 'Leave it from war.app instead.');
54
+ }
55
+ return seat;
56
+ }
57
+ /** GameFeed's answer for a game the account is no longer in (seen live after a leave, #217). */
58
+ const NOT_IN_GAME = /can only be used for games you are in/i;
59
+ /**
60
+ * Whether game state shows account `me` (its GameFeed id) out of the game: GameFeed listing it
61
+ * with no seat (declined) or not at all, else GetMyGames listing the game with its seat given up.
62
+ * A game missing from GetMyGames proves nothing (the list may be partial, #260), and nothing read is `false`.
63
+ */
64
+ async function confirmLeft(ctx, gameId, me) {
65
+ try {
66
+ const game = await ctx.client.getGame(gameId, { map: false });
67
+ const seat = game.players.find((p) => p.id === me);
68
+ return !seat || !holdsSeat(seat.state);
69
+ }
70
+ catch (e) {
71
+ // Seen live (#217): once the seat is given up, GameFeed refuses the game outright ("This API
72
+ // can only be used for games you are in, tournament games…") instead of listing me as gone.
73
+ if (e instanceof Error && NOT_IN_GAME.test(e.message))
74
+ return true;
75
+ // No GameFeed credentials or another failed read: try the web client's list.
76
+ }
77
+ try {
78
+ const { me: inGame, games } = await fetchMyGames(ctx);
79
+ const seat = games.find((g) => g.id === gameId)?.players.find((p) => p.id === inGame);
80
+ return seat !== undefined && !holdsSeat(playerStateName(seat.stateCode));
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ export function registerLeaveGameTool(server, ctx) {
87
+ defineGatedWrite(server, {
88
+ title: 'Leave a war.app game that has not started',
89
+ _meta: mintMeta('change', ['leave game', 'leave a lobby', 'back out of a game', 'quit a lobby']),
90
+ }, {
91
+ name: 'warapp_leave_game',
92
+ description: 'Leave a war.app (Warzone) game that has not started — a lobby still WaitingForPlayers — giving up your ' +
93
+ "seat (war.app's DeclineGame, the lobby's Decline button; verified live for a lobby joined through an open " +
94
+ 'seat). Refuses a game that has started (surrender it with warapp_surrender), a lobby you ' +
95
+ 'hold no seat in, and mod games. Always as the signed-in war.app account; reported `left` only once ' +
96
+ 'GameFeed (or your games list) no longer shows you seated — `unconfirmed` otherwise, or `unknown` when ' +
97
+ `war.app did not answer (never resend blindly). ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
98
+ annotations: toolAnnotations({
99
+ title: 'Leave a war.app lobby',
100
+ readOnly: false,
101
+ destructive: true,
102
+ idempotent: false,
103
+ openWorld: true,
104
+ }),
105
+ inputSchema: z.object({ game_id: gameIdArg }),
106
+ async plan({ game_id }) {
107
+ const game = await ctx.client.getGame(parseGameId(game_id), { settings: true, map: false });
108
+ const token = await requireMe(ctx);
109
+ const seat = leavable(game, token);
110
+ const teamGame = isTeamGame(game.players);
111
+ return {
112
+ gate: {
113
+ action: 'warapp.leave_game',
114
+ // By id only: the game and player names (other people's words) go, delimited, in labelled fields.
115
+ summary: `Leave war.app game ${game.id}, which has not started, giving up your seat`,
116
+ account: writeAccount(seat.id),
117
+ target: game.id,
118
+ payload: { method: 'DeclineGame', gameId: game.id },
119
+ willSend: { game: game.id, player: untrustedText(seat.name) },
120
+ preview: {
121
+ warning: `This gives up your seat in game ${game.id}. You can only come back through an open seat that is ` +
122
+ 'still free, and war.app may remove the chat messages you sent to the game.' +
123
+ (teamGame ? ' It is a team game: leaving can leave your teammates a player short.' : ''),
124
+ account: shownAccount(seat.name, seat.id),
125
+ game: {
126
+ id: game.id,
127
+ name: game.name === undefined ? null : untrustedText(game.name),
128
+ state: game.state,
129
+ players: game.players.filter((p) => holdsSeat(p.state)).length,
130
+ },
131
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
132
+ },
133
+ },
134
+ state: { gameId: game.id, name: game.name ?? `game ${game.id}`, me: seat.id },
135
+ };
136
+ },
137
+ async execute({ gameId, name, me }) {
138
+ await requireApprovedAccount(ctx, writeAccount(me));
139
+ const game = { id: gameId, name };
140
+ let chatRemoved;
141
+ const extra = () => (chatRemoved ? { chatRemoved: true } : {});
142
+ const check = 'Check warapp_my_games (or warapp_get_game) before doing anything else.';
143
+ return sendAndVerify({
144
+ send: async () => {
145
+ const env = await ctx.rpc.call('DeclineGame', Method.DeclineGame, (w) => writeDeclineGameParams(w, gameId));
146
+ try {
147
+ chatRemoved = readDeclineGameReturn(env.body);
148
+ }
149
+ catch {
150
+ // An unreadable reply bool is only the chat note: the leave is read back below.
151
+ }
152
+ },
153
+ refused: (e) => {
154
+ if (READ_BACK_ERRORS.has(e.code))
155
+ return 'ignore';
156
+ const wording = LEAVE_ERRORS[e.code];
157
+ return wording ? new WarappServerError(e.code, `${wording} (war.app error ${e.code})`) : undefined;
158
+ },
159
+ unanswered: (failure) => ({
160
+ status: 'unknown',
161
+ outcome: 'unknown',
162
+ game,
163
+ warning: `war.app did not confirm the leave (${failure}), so you may already have left. ${check}`,
164
+ }),
165
+ // Never throws: nothing read is "not shown".
166
+ readBack: () => confirmLeft(ctx, gameId, me),
167
+ unreadable: () => ({ status: 'unconfirmed', outcome: 'unconfirmed', game, warning: check }),
168
+ classify: (left) => left
169
+ ? { status: 'left', outcome: 'confirmed', game, ...extra() }
170
+ : {
171
+ status: 'unconfirmed',
172
+ outcome: 'unconfirmed',
173
+ game,
174
+ ...extra(),
175
+ warning: 'war.app accepted the request, but GameFeed still shows you seated (or could not be read, and ' +
176
+ `your games list does not show the seat given up), so the leave could not be confirmed. ${check}`,
177
+ },
178
+ });
179
+ },
180
+ });
181
+ }
@@ -0,0 +1,339 @@
1
+ // What the live-game tools share: the GameFeed client (players, map, settings,
2
+ // chat), the web-client RPC channel through the bridge (board, picks, sends),
3
+ // and the client bundle whose readers decode the board.
4
+ import { McpToolError } from '@chrischall/mcp-utils';
5
+ import { dataDir } from '../config.js';
6
+ import { inGameId, readLatestGameInfo, standingFromInfo } from '../live.js';
7
+ import { BUNDLE_FETCH_TIMEOUT_MS, BUNDLE_MAX_BYTES, BundleProvider } from '../protocol/bundle.js';
8
+ import { Method, readTerritoryPicks, writeGetLatestGameInfoParams, writeGetTerritoryPicksParams, } from '../protocol/methods.js';
9
+ import { WarappRpc } from '../protocol/rpc.js';
10
+ import { BRIDGE_DOMAINS } from '../transport-bridge.js';
11
+ import { isHosted } from '../hosted.js';
12
+ /**
13
+ * The token from war.app's `/InviteToken` page ("Your invite token is N"), as text — the
14
+ * check digits are part of it, a leading 0 included (#130).
15
+ */
16
+ export function parseInviteTokenText(html) {
17
+ const m = /Your invite token is\s*(\d{5,20})/.exec(html);
18
+ if (!m)
19
+ return undefined;
20
+ return Number.isSafeInteger(Number(m[1])) ? m[1] : undefined;
21
+ }
22
+ /** The token as a number (= the GameFeed player id GameFeed reports). */
23
+ export function parseInviteToken(html) {
24
+ const t = parseInviteTokenText(html);
25
+ return t === undefined ? undefined : Number(t);
26
+ }
27
+ const INVITE_TOKEN_URL = 'https://war.app/InviteToken';
28
+ /**
29
+ * How long a read may reuse the signed-in account. Short: on the browser bridge
30
+ * the tab can be signed in as someone else without any state this process sees.
31
+ */
32
+ export const IDENTITY_TTL_MS = 60_000;
33
+ const onBridge = (url) => BRIDGE_DOMAINS.some((d) => url.hostname === d || url.hostname.endsWith(`.${d}`));
34
+ /**
35
+ * Read a response body as UTF-8, cancelling it as soon as it passes `maxBytes` or `signal` aborts
36
+ * (the download timed out): nothing keeps pulling the body in the background after that, even when
37
+ * the fetch itself ignored the signal.
38
+ */
39
+ async function readCapped(res, maxBytes, what, signal) {
40
+ const tooLarge = () => new Error(`${what} is larger than ${maxBytes} bytes`);
41
+ const aborted = () => (signal.reason instanceof Error ? signal.reason : new Error(`${what} was aborted`));
42
+ if (signal.aborted) {
43
+ await res.body?.cancel().catch(() => { });
44
+ throw aborted();
45
+ }
46
+ const declared = Number(res.headers.get('content-length'));
47
+ if (Number.isFinite(declared) && declared > maxBytes) {
48
+ await res.body?.cancel().catch(() => { });
49
+ throw tooLarge();
50
+ }
51
+ if (!res.body)
52
+ return '';
53
+ const reader = res.body.getReader();
54
+ const onAbort = () => {
55
+ reader.cancel().catch(() => { });
56
+ };
57
+ signal.addEventListener('abort', onAbort, { once: true });
58
+ try {
59
+ const chunks = [];
60
+ let total = 0;
61
+ for (;;) {
62
+ const { done, value } = await reader.read();
63
+ if (signal.aborted)
64
+ throw aborted();
65
+ if (done)
66
+ break;
67
+ total += value.byteLength;
68
+ if (total > maxBytes) {
69
+ await reader.cancel().catch(() => { });
70
+ throw tooLarge();
71
+ }
72
+ chunks.push(value);
73
+ }
74
+ // Decoded as `Response.text()` decodes (a leading byte-order mark dropped), so the cached
75
+ // bundle is the same text the unbounded read produced.
76
+ return new TextDecoder().decode(Buffer.concat(chunks));
77
+ }
78
+ finally {
79
+ signal.removeEventListener('abort', onAbort);
80
+ }
81
+ }
82
+ /**
83
+ * GET a URL as text: war.app pages through the signed-in tab (the bridge's
84
+ * only domain), the CDN-hosted bundle directly — with a timeout over the whole
85
+ * download and a byte cap enforced while the body streams, so an endless or
86
+ * enormous response is cut off rather than buffered.
87
+ */
88
+ export function bundleFetcher(bridge, fetchImpl = fetch, limits = {}) {
89
+ const timeoutMs = limits.timeoutMs ?? BUNDLE_FETCH_TIMEOUT_MS;
90
+ const maxBytes = limits.maxBytes ?? BUNDLE_MAX_BYTES;
91
+ return async (url) => {
92
+ const u = new URL(url);
93
+ if (onBridge(u)) {
94
+ const res = await (await bridge.ready()).fetch({ method: 'GET', path: u.href });
95
+ if (res.status !== 200)
96
+ throw new Error(`war.app answered HTTP ${res.status} for ${u.pathname}`);
97
+ return res.body;
98
+ }
99
+ const ac = new AbortController();
100
+ let timer;
101
+ // Raced as well as signalled, so a fetch that ignores the signal still cannot hang the load; the
102
+ // body reader is cancelled on the same signal, so nothing keeps pulling after the timeout.
103
+ const timedOut = new Promise((_, reject) => {
104
+ timer = setTimeout(() => {
105
+ const e = new Error(`${u.hostname} timed out after ${timeoutMs} ms fetching the client bundle`);
106
+ ac.abort(e);
107
+ reject(e);
108
+ }, timeoutMs);
109
+ });
110
+ const download = (async () => {
111
+ const res = await fetchImpl(u.href, { redirect: 'error', signal: ac.signal });
112
+ if (!res.ok)
113
+ throw new Error(`${u.hostname} answered HTTP ${res.status} for the client bundle`);
114
+ return readCapped(res, maxBytes, `the client bundle from ${u.hostname}`, ac.signal);
115
+ })();
116
+ try {
117
+ return await Promise.race([download, timedOut]);
118
+ }
119
+ finally {
120
+ clearTimeout(timer);
121
+ download.catch(() => { }); // a download still settling after a timeout is not unhandled
122
+ }
123
+ };
124
+ }
125
+ /** What to do about a frozen tab, said on every bridged `/Services` timeout (#130). */
126
+ const FROZEN_TAB_HINT = 'Chrome freezes background tabs, and war.app calls are relayed through a page tab: a frozen tab stalls them ' +
127
+ 'while page reads still work. Reload or focus a war.app tab, then check the game before retrying.';
128
+ /** A bridge timeout (fetchproxy's `FetchproxyTimeoutError`, matched by name across package copies). */
129
+ const isBridgeTimeout = (e) => e instanceof Error && e.name === 'FetchproxyTimeoutError';
130
+ /**
131
+ * The bridge with its `/Services` POST timeouts carrying {@link FROZEN_TAB_HINT}: the message is
132
+ * kept whole (it says whether the call may already have run), only the hint is added.
133
+ */
134
+ function withFrozenTabHint(bridge) {
135
+ return {
136
+ fetch: async (init) => {
137
+ try {
138
+ return await bridge.fetch(init);
139
+ }
140
+ catch (e) {
141
+ if (!isBridgeTimeout(e))
142
+ throw e;
143
+ throw new McpToolError(e.message, { kind: 'unknown', hint: FROZEN_TAB_HINT, cause: e });
144
+ }
145
+ },
146
+ };
147
+ }
148
+ /** A failed send's message for a result warning, with the frozen-tab hint when it was a bridge timeout. */
149
+ export function failureText(e) {
150
+ const message = e instanceof Error ? e.message : String(e);
151
+ return e instanceof McpToolError && e.hint === FROZEN_TAB_HINT ? `${message} ${FROZEN_TAB_HINT}` : message;
152
+ }
153
+ export function createLiveContext(opts) {
154
+ const rpc = new WarappRpc({
155
+ bridge: async () => withFrozenTabHint(await opts.bridge.ready()),
156
+ ...(opts.env ? { env: opts.env } : {}),
157
+ });
158
+ const dir = dataDir(opts.env);
159
+ const provider = new BundleProvider({
160
+ dataDir: dir,
161
+ fetchText: bundleFetcher(opts.bridge, opts.fetchImpl),
162
+ });
163
+ const load = opts.bundle ?? (() => provider.get());
164
+ let lastBundle;
165
+ const fetchText = bundleFetcher(opts.bridge, opts.fetchImpl);
166
+ const identity = opts.identity ?? (async () => '');
167
+ const now = opts.now ?? Date.now;
168
+ // The account behind the transport can change under a running process (a
169
+ // relink, or an expired direct session falling back to a tab signed in as
170
+ // someone else), so a success is kept only under the state key it was read
171
+ // in, and only for IDENTITY_TTL_MS. A failure (bridge down, signed out) is
172
+ // never kept: the next call retries. Every read takes a generation number
173
+ // when it starts, and only a read newer than the last one that settled may
174
+ // set or clear the cache, so a slow, older read finishing after a fresh one
175
+ // never overwrites it; forgetIdentity makes every read in flight older. The
176
+ // token is kept as TEXT: its check digits, a leading 0 included, are part of
177
+ // it (#130).
178
+ let cached;
179
+ let started = 0;
180
+ let settled = 0;
181
+ const tokenText = async (o = {}) => {
182
+ if (!o.fresh && cached && now() - cached.at < IDENTITY_TTL_MS && cached.key === (await identity())) {
183
+ return cached.token;
184
+ }
185
+ const gen = ++started;
186
+ const before = await identity();
187
+ const t = await fetchText(INVITE_TOKEN_URL)
188
+ .then(parseInviteTokenText)
189
+ .catch(() => undefined);
190
+ if (gen <= settled)
191
+ return t;
192
+ if (t === undefined) {
193
+ settled = gen;
194
+ cached = undefined;
195
+ return t;
196
+ }
197
+ // Kept only when the state did not move during the read. If it did (the
198
+ // read itself fell back, or a concurrent call moved the router), the answer
199
+ // may come from either leg, so it is returned but not cached: the next
200
+ // resolve re-reads under the settled state.
201
+ const after = await identity();
202
+ if (gen <= settled)
203
+ return t;
204
+ settled = gen;
205
+ cached = before === after ? { key: after, at: now(), token: t } : undefined;
206
+ return t;
207
+ };
208
+ const myIdentity = async (o = {}) => {
209
+ const t = await tokenText(o);
210
+ return t === undefined ? undefined : { token: Number(t), inGameId: inGameId({ id: Number(t), feedId: t }) };
211
+ };
212
+ return {
213
+ myInviteToken: async (o) => (await myIdentity(o))?.token,
214
+ myInGameId: async (o) => (await myIdentity(o))?.inGameId,
215
+ myIdentity,
216
+ forgetIdentity: () => {
217
+ cached = undefined;
218
+ settled = started;
219
+ },
220
+ fetchPage: fetchText,
221
+ dataDir: dir,
222
+ hosted: isHosted(opts.env ?? process.env),
223
+ client: opts.client,
224
+ rpc,
225
+ decoderReport: () => lastBundle?.report?.(),
226
+ bundle: async () => {
227
+ try {
228
+ const b = await load();
229
+ lastBundle = b;
230
+ return b;
231
+ }
232
+ catch (e) {
233
+ // A refused or failed load means boards are not being decoded: the earlier bundle is no longer
234
+ // what stands behind them, so it is not reported as the decoder (#148).
235
+ lastBundle = undefined;
236
+ if (e instanceof McpToolError)
237
+ throw e;
238
+ throw new McpToolError(`Could not load war.app's client bundle: ${e instanceof Error ? e.message : String(e)}`, {
239
+ kind: 'unknown',
240
+ hint: 'The live-game tools decode the board with the war.app web client. Make sure a signed-in war.app tab is open and paired, then retry.',
241
+ cause: e,
242
+ });
243
+ }
244
+ },
245
+ };
246
+ }
247
+ /**
248
+ * The account a write's gate binds (`gate.account`): the signed-in account's
249
+ * GameFeed id, read fresh in the plan step. Binding it makes the confirmToken
250
+ * and the elicitation approval commit to the account, so an approval given for
251
+ * one account never acts as another: the token minted for A's preview fails to
252
+ * validate once the plan resolves B. `undefined` (account unknown) binds as absent.
253
+ */
254
+ export function writeAccount(token) {
255
+ return token === undefined ? undefined : String(token);
256
+ }
257
+ /**
258
+ * Refuse a write's execute step unless the signed-in account is still the one
259
+ * its plan bound (`approved`, from {@link writeAccount}). Plan and execute are
260
+ * separated by the user's confirmation, and the account behind the transport
261
+ * can change in between (a relink, an expired direct session falling back to a
262
+ * tab signed in as someone else). The confirmToken rail is covered by the
263
+ * gate's binding; this covers elicitation, where plan and execute run in one
264
+ * call. Nothing is checked when the plan bound no account.
265
+ */
266
+ export async function requireApprovedAccount(ctx, approved) {
267
+ if (approved === undefined)
268
+ return;
269
+ const now = await ctx.myInviteToken({ fresh: true });
270
+ if (now === undefined) {
271
+ throw new McpToolError('Could not confirm which war.app account is signed in, so nothing was sent.', {
272
+ hint: 'Make sure a signed-in war.app tab is open and paired (or the linked session is current), then preview ' +
273
+ 'the action again.',
274
+ });
275
+ }
276
+ if (String(now) !== approved) {
277
+ throw new McpToolError('The signed-in war.app account changed since this action was previewed, so nothing was sent.', {
278
+ hint: 'Preview the action again: it will be checked for the account that is signed in now.',
279
+ });
280
+ }
281
+ }
282
+ /**
283
+ * The MoveOrder that makes the first turn a speed race ("No-luck cycle": the
284
+ * players who enter their first orders — or, in manual distribution, their
285
+ * picks — fastest move first). Read from the client bundle: in such a game
286
+ * war.app withholds the board until the player presses Begin (BeginFirstTurn,
287
+ * method 78), which starts their first-turn timer.
288
+ */
289
+ export const SPEED_FIRST_TURN_MOVE_ORDER = 'NoLuckCycle';
290
+ /**
291
+ * Whether a game with no board is waiting for this player to press Begin: it is
292
+ * on its first turn (or picking), and its move order is the speed first turn —
293
+ * or GameFeed did not say, since the web client shows Begin whenever a playing
294
+ * seat has no standing.
295
+ */
296
+ function awaitsBegin(game) {
297
+ if (game.state !== 'Playing' && game.state !== 'DistributingTerritories')
298
+ return false;
299
+ if ((game.numberOfTurns ?? 0) > 0)
300
+ return false;
301
+ const order = game.settings?.moveOrder;
302
+ return order === undefined || order === SPEED_FIRST_TURN_MOVE_ORDER;
303
+ }
304
+ /** What to say when the board is hidden until Begin. */
305
+ function beginFirstError(game) {
306
+ const picking = game.state === 'DistributingTerritories';
307
+ return new McpToolError(`war.app has no board for game ${game.id} yet: this game's first turn starts when you press Begin — call ` +
308
+ (picking
309
+ ? 'warapp_begin_turn, then choose and submit your picks at once: Begin starts the timer.'
310
+ : 'warapp_begin_turn, then plan and submit at once: Begin starts the turn timer.'), {
311
+ hint: 'The first turn is a speed race (move order "No-luck cycle"): the players who ' +
312
+ (picking ? 'pick fastest get their picks in a conflict.' : 'commit their first orders fastest move first.') +
313
+ ' Call warapp_begin_turn only when ready to act straight away.',
314
+ });
315
+ }
316
+ /** The game's live board through the bridge; throws when war.app has none for it. */
317
+ export async function loadLiveTerritories(ctx, game) {
318
+ return (await loadLiveGame(ctx, game)).territories;
319
+ }
320
+ /** The live board plus the decoded LatestGameInfo (cards live there); throws when war.app has no board. */
321
+ export async function loadLiveGame(ctx, game) {
322
+ const env = await ctx.rpc.call('GetLatestGameInfo', Method.GetLatestGameInfo, (w) => writeGetLatestGameInfoParams(w, game.id));
323
+ const bundle = await ctx.bundle();
324
+ const info = readLatestGameInfo(bundle, env.body);
325
+ const territories = standingFromInfo(info);
326
+ if (!territories) {
327
+ if (awaitsBegin(game))
328
+ throw beginFirstError(game);
329
+ throw new McpToolError(`war.app has no board for game ${game.id} yet (game state: ${game.state}).`, {
330
+ hint: 'A lobby has no board until territories are distributed. warapp_get_map works without one.',
331
+ });
332
+ }
333
+ return { territories, info };
334
+ }
335
+ /** A player's current territory picks, in priority order. */
336
+ export async function loadPicks(ctx, gameId, inGamePlayerId) {
337
+ const env = await ctx.rpc.call('GetTerritoryPicks', Method.GetTerritoryPicks, (w) => writeGetTerritoryPicksParams(w, gameId, inGamePlayerId));
338
+ return readTerritoryPicks(env.body);
339
+ }