@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,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
+ export 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
+ }