@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,84 @@
1
+ /** Every card play and discard in my teammates' entered orders (`teammates`: their player ids), in entry order. */
2
+ export function teamCardClaims(entries, teammates) {
3
+ const out = [];
4
+ for (const e of entries ?? []) {
5
+ if (!teammates.has(e.playerId) || !e.orders)
6
+ continue;
7
+ for (const c of e.orders.cards)
8
+ out.push({ player: e.playerId, kind: 'play', ...(c.cardId !== undefined ? { cardId: c.cardId } : {}), type: c.type, name: c.name });
9
+ for (const d of e.orders.discards)
10
+ out.push({ player: e.playerId, kind: 'discard', ...(d.cardId !== undefined ? { cardId: d.cardId } : {}), type: null });
11
+ }
12
+ return out;
13
+ }
14
+ /**
15
+ * The hand less what my teammates have claimed: a claim naming a card instance takes that card; a play
16
+ * naming only its type takes the first unclaimed card of that type (in hand order). Claims matching no card
17
+ * of the hand change nothing.
18
+ */
19
+ export function teamHandLeft(hand, claims) {
20
+ const taken = new Map();
21
+ for (const c of claims.filter((x) => x.cardId !== undefined)) {
22
+ const card = hand.find((h) => h.id === c.cardId);
23
+ if (card && !taken.has(card.id))
24
+ taken.set(card.id, { card, player: c.player, kind: c.kind });
25
+ }
26
+ for (const c of claims.filter((x) => x.cardId === undefined && x.type !== null)) {
27
+ const card = hand.find((h) => h.type === c.type && !taken.has(h.id));
28
+ if (card)
29
+ taken.set(card.id, { card, player: c.player, kind: c.kind });
30
+ }
31
+ return { left: hand.filter((h) => !taken.has(h.id)), claimed: hand.flatMap((h) => (taken.has(h.id) ? [taken.get(h.id)] : [])) };
32
+ }
33
+ /**
34
+ * Who plays each card of the team hand: a teammate for a card they entered, me for a card my orders play
35
+ * or discard, nobody for a card held (a Reinforcement held for the team says so).
36
+ */
37
+ export function teamCardRoles(hand, claimed, mine) {
38
+ const theirs = new Map(claimed.map((c) => [c.card.id, c]));
39
+ const plays = new Set(mine.plays.map((c) => c.id));
40
+ const discards = new Set(mine.discards.map((c) => c.id));
41
+ return hand.map((c) => {
42
+ const t = theirs.get(c.id);
43
+ if (t)
44
+ return {
45
+ card: c.id,
46
+ name: c.name,
47
+ by: t.player,
48
+ action: t.kind,
49
+ why: `player ${t.player} has already entered a ${t.kind} of it: leave it to them, so the team does not ${t.kind} one card twice`,
50
+ };
51
+ if (plays.has(c.id))
52
+ return { card: c.id, name: c.name, by: 'me', action: 'play', why: 'my plan plays it (it is in my orders)' };
53
+ if (discards.has(c.id))
54
+ return { card: c.id, name: c.name, by: 'me', action: 'discard', why: 'my plan discards it: the team hand is over the limit' };
55
+ return {
56
+ card: c.id,
57
+ name: c.name,
58
+ by: null,
59
+ action: 'hold',
60
+ why: 'nobody plays it this turn: whoever needs it plays it, said in team chat first',
61
+ };
62
+ });
63
+ }
64
+ /** Each card of `uses` (my orders' plays and discards) a teammate has claimed, in the order given. */
65
+ export function claimedCardUses(uses, claimed) {
66
+ const by = new Map(claimed.map((c) => [c.card.id, c]));
67
+ return uses.flatMap((u) => {
68
+ const c = by.get(u.card.id);
69
+ return c ? [{ card: u.card, mine: u.kind, player: c.player, theirs: c.kind }] : [];
70
+ });
71
+ }
72
+ /** The warning for {@link claimedCardUses} (card ids and player ids only), or undefined when there is none. */
73
+ export function claimedCardWarning(uses) {
74
+ if (!uses.length)
75
+ return undefined;
76
+ const each = uses.map((u) => `${u.mine === 'play' ? 'plays' : 'discards'} the ${u.card.name} card ${u.card.id}, which player ${u.player} has already entered a ${u.theirs} of`);
77
+ return (`These orders ${each.join('; ')}. A team shares one hand and must not use one card twice: leave it to them, or agree in ` +
78
+ 'team chat who uses it before committing. Their entered orders are read from the live board (UNVERIFIED live, V5).');
79
+ }
80
+ /** The hand with the cards my teammates have claimed moved last (order otherwise kept): a card named by type is then an unclaimed one when there is one. */
81
+ export function unclaimedFirst(hand, claimed) {
82
+ const ids = new Set(claimed.map((c) => c.card.id));
83
+ return [...hand.filter((c) => !ids.has(c.id)), ...hand.filter((c) => ids.has(c.id))];
84
+ }
@@ -0,0 +1,150 @@
1
+ // Teammates' entered orders and picks (C1, docs/PLAN-TEAMS.md), projected from a decoded LatestGameInfo.
2
+ //
3
+ // From the client bundle (read 2026-11-14, not live): LatestGameInfo carries, after the standings, a dict
4
+ // in-game player id → `warlight.shared.TeammateOrders` { a stamp (int), the orders entered (a list of
5
+ // GameOrder, during a turn), the picks entered (a list of territory ids, while distributing) }. The client
6
+ // shows a teammate's orders and picks from it, and counts the card plays and discards in it against the
7
+ // team's hand. UNVERIFIED live (V5): whether war.app fills it before the teammate commits, and what it holds
8
+ // once they have.
9
+ //
10
+ // Field names are minified, so the dict is found by the registered type name of its values, and an order's
11
+ // kind by its class name. Within an order, fields are read by kind and read order, as the bundle's readers
12
+ // fill them: Deploy (territory, free flag, armies, then the base: player …); AttackTransfer (attack-teammates
13
+ // flag, mode byte, by-percent flag, from, Armies, to, then the base); a card play (its own fields, the card
14
+ // GUID, the base); Discard (the GUID, the base). Tolerant throughout: absent means unknown, an entry it
15
+ // cannot read is listed as unread, nothing throws.
16
+ import { cardTypeByName, cardTypeName, normalizeGuid } from './cards.js';
17
+ import { playersByInGameId } from './live.js';
18
+ import { fields, isObj } from './protocol/decoded.js';
19
+ const TEAMMATE_ORDERS = 'warlight.shared.TeammateOrders';
20
+ const ORDER_PREFIX = 'warlight.shared.GameOrder';
21
+ const DEPLOY = 'warlight.shared.GameOrderDeploy';
22
+ const ATTACK_TRANSFER = 'warlight.shared.GameOrderAttackTransfer';
23
+ const DISCARD = 'warlight.shared.GameOrderDiscard';
24
+ const PLAY_CARD = 'warlight.shared.GameOrderPlayCard';
25
+ const ARMIES = 'warlight.shared.Armies';
26
+ const COMMANDER = 'warlight.shared.Commander';
27
+ /** AttackTransfer's mode byte (docs/WEB-PROTOCOL.md "Orders"). */
28
+ const MODES = { 1: 'attack', 2: 'transfer', 3: 'attack-transfer' };
29
+ /** Card-play classes whose name is not the card's (the Emergency Blockade card plays as "Abandon"). */
30
+ const CARD_CLASS_TYPES = { Abandon: 3 };
31
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
32
+ const shortName = (type) => (typeof type === 'string' ? type.replace(/^warlight\.shared\./, '') : 'unknown');
33
+ /** The teammate-orders dict of a decoded LatestGameInfo: the field whose values are TeammateOrders. */
34
+ function teammateDict(info) {
35
+ if (!isObj(info))
36
+ return undefined;
37
+ for (const v of fields(info)) {
38
+ if (!Array.isArray(v))
39
+ continue;
40
+ const pairs = v.filter((e) => Array.isArray(e) && e.length === 2);
41
+ if (pairs.some(([, x]) => isObj(x) && x.$type === TEAMMATE_ORDERS)) {
42
+ return pairs.filter((p) => isObj(p[1]) && p[1].$type === TEAMMATE_ORDERS);
43
+ }
44
+ }
45
+ return undefined;
46
+ }
47
+ function armiesOf(a) {
48
+ if (!isObj(a) || a.$type !== ARMIES)
49
+ return undefined;
50
+ const f = fields(a);
51
+ const numbers = f.filter(isInt);
52
+ if (numbers.length !== 1)
53
+ return undefined;
54
+ const units = f.find((x) => Array.isArray(x)) ?? [];
55
+ return { count: numbers[0], commander: units.some((u) => isObj(u) && u.$type === COMMANDER) };
56
+ }
57
+ /** Reads one order into `out`; false when its shape is not understood. */
58
+ function readOrder(o, out) {
59
+ const type = String(o.$type);
60
+ const f = fields(o);
61
+ const ints = f.filter(isInt);
62
+ if (type === DEPLOY) {
63
+ if (ints.length < 2)
64
+ return false;
65
+ out.deploys.push({ territoryId: ints[0], armies: ints[1] });
66
+ return true;
67
+ }
68
+ if (type === ATTACK_TRANSFER) {
69
+ // attackTeammates, mode, byPercent, from, Armies, to, then the base (player …).
70
+ const [attackTeammates, mode, percent, from, armies, to] = f;
71
+ const army = armiesOf(armies);
72
+ if (typeof attackTeammates !== 'boolean' || typeof percent !== 'boolean' || !isInt(mode) || !isInt(from) || !isInt(to) || !army)
73
+ return false;
74
+ const m = MODES[mode];
75
+ if (!m)
76
+ return false;
77
+ out.moves.push({
78
+ from,
79
+ to,
80
+ armies: army.count,
81
+ mode: m,
82
+ ...(percent ? { percent: true } : {}),
83
+ ...(attackTeammates ? { attackTeammates: true } : {}),
84
+ ...(army.commander ? { commander: true } : {}),
85
+ });
86
+ return true;
87
+ }
88
+ const cardId = f.map(normalizeGuid).find((g) => g !== undefined);
89
+ if (type === DISCARD) {
90
+ out.discards.push(cardId !== undefined ? { cardId } : {});
91
+ return true;
92
+ }
93
+ if (type.startsWith(PLAY_CARD)) {
94
+ const cls = type.slice(PLAY_CARD.length);
95
+ const t = CARD_CLASS_TYPES[cls] ?? cardTypeByName(cls) ?? null;
96
+ out.cards.push({ ...(cardId !== undefined ? { cardId } : {}), type: t, name: t !== null ? cardTypeName(t) : cls || 'card' });
97
+ return true;
98
+ }
99
+ return false;
100
+ }
101
+ function ordersOf(list) {
102
+ if (!Array.isArray(list))
103
+ return null;
104
+ const out = { deploys: [], moves: [], cards: [], discards: [], unread: [] };
105
+ for (const o of list) {
106
+ if (o === null)
107
+ continue;
108
+ if (!isObj(o) || typeof o.$type !== 'string' || !o.$type.startsWith(ORDER_PREFIX) || !readOrder(o, out)) {
109
+ out.unread.push(isObj(o) ? shortName(o.$type) : 'unknown');
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+ /**
115
+ * Every teammate entry of a decoded LatestGameInfo, by in-game id (ascending). `undefined` when the info
116
+ * carries no teammate orders at all (not a team game, or war.app sent none: unknown). Never throws.
117
+ */
118
+ export function readTeammateOrders(info) {
119
+ const dict = teammateDict(info);
120
+ if (!dict)
121
+ return undefined;
122
+ const out = new Map();
123
+ for (const [key, entry] of dict.filter(([k]) => isInt(k)).sort((a, b) => a[0] - b[0])) {
124
+ // The stamp, the orders, the picks, in read order.
125
+ const [, orders, picks] = fields(entry);
126
+ out.set(key, {
127
+ inGameId: key,
128
+ orders: ordersOf(orders),
129
+ picks: Array.isArray(picks) ? picks.filter(isInt) : null,
130
+ });
131
+ }
132
+ return out;
133
+ }
134
+ /** {@link readTeammateOrders} keyed by GameFeed id (the in-game id when the player is unknown). */
135
+ export function teammateOrdersOf(info, players) {
136
+ const raw = readTeammateOrders(info);
137
+ if (!raw)
138
+ return undefined;
139
+ const byInGame = playersByInGameId(players);
140
+ return [...raw.values()].map((r) => ({ playerId: byInGame.get(r.inGameId)?.id ?? r.inGameId, orders: r.orders, picks: r.picks }));
141
+ }
142
+ /**
143
+ * `board` with my teammates' entered orders (`BoardState.teammateOrders`, by GameFeed id, my own entry left
144
+ * out) when the decoded LatestGameInfo carries a teammate-orders dict; the board unchanged otherwise (a 1v1 or
145
+ * FFA board, or war.app sent none: unknown), so no key is added. Never throws.
146
+ */
147
+ export function withTeammateOrders(board, info, me, players) {
148
+ const entries = teammateOrdersOf(info, players)?.filter((e) => e.playerId !== me.id);
149
+ return entries ? { ...board, teammateOrders: entries } : board;
150
+ }
package/dist/teams.js ADDED
@@ -0,0 +1,19 @@
1
+ // Teams: the one test of "is this a team?" shared by the open-games list, joining and the
2
+ // game profile. war.app marks "no team" with -1 (verified from the client bundle, see
3
+ // docs/WEB-PROTOCOL.md "Open games"): any other team value makes it a team game.
4
+ /** The team value of a player or seat in a no-team game. */
5
+ export const NO_TEAM = -1;
6
+ /** Whether a player or seat carries a team (absent and {@link NO_TEAM} do not). */
7
+ export const carriesTeam = (team) => team !== undefined && team !== null && team !== NO_TEAM;
8
+ /** Whether any player of the game carries a team: the game is a team game. */
9
+ export const isTeamGame = (players) => players.some((p) => carriesTeam(p.team));
10
+ /**
11
+ * The players on `me`'s team, never `me` itself (matched by id), in the list's order; none when `me` carries
12
+ * no team. Players are whatever the caller holds (GameFeed players at the tool boundary, keyed by GameFeed id).
13
+ */
14
+ export function teammatesOf(players, me) {
15
+ const team = me.team;
16
+ if (!carriesTeam(team))
17
+ return [];
18
+ return players.filter((p) => p.id !== me.id && p.team === team);
19
+ }
@@ -0,0 +1,206 @@
1
+ // What the award of picks tells the turn tools (#166): read once from my stored pick list on the
2
+ // first board after distribution (src/analysis/award.ts, src/pick-list.ts), then reused all game.
3
+ import { firstMoverOnTurn, isCyclicMoveOrder, readAward } from '../analysis/award.js';
4
+ import { openingIncome, PICK_HORIZON } from '../analysis/picks.js';
5
+ import { FOG_LEVEL_NAMES, FOG_LEVEL_OWNER_ONLY, FOG_LEVEL_VISIBLE } from '../live.js';
6
+ import { readFirstMover, resolveFirstMover, verifiedFirstMover, writeFirstMover } from '../move-order.js';
7
+ import { readPickRecord, writeAward } from '../pick-list.js';
8
+ import { pickSettings } from './picks.js';
9
+ import { isTeamGame, teammatesOf } from '../teams.js';
10
+ const isMine = (t, me) => t.owner.kind === 'player' && t.owner.playerId === me;
11
+ /** The army count every territory of mine holds, when they all hold the same (the starting armies on turn 1). */
12
+ function uniformArmies(board, me) {
13
+ const counts = new Set();
14
+ for (const t of board.territories)
15
+ if (isMine(t, me))
16
+ counts.add(t.armies);
17
+ const only = counts.size === 1 ? [...counts][0] : null;
18
+ return only !== null && only > 0 ? only : null;
19
+ }
20
+ /**
21
+ * The award of `game` as `me` can read it, with the board to plan on; `undefined` when no pick
22
+ * list is kept for this player, the list did not explain the start, or the first board has
23
+ * passed unread. Reads the award (and keeps it) on turn 1; later turns reuse what was kept.
24
+ * `write: false` reads it the same way and keeps nothing (#275 pattern 3: a write's preview).
25
+ * Never throws.
26
+ */
27
+ export async function loadAward(dataDir, game, me, board, turn, o = {}) {
28
+ if (!dataDir || turn === null || game.players.length < 2)
29
+ return undefined;
30
+ const record = await readPickRecord(dataDir, game.id, me.id);
31
+ // A record that keeps only the pickable territories has no list to read the award from.
32
+ if (!record?.list)
33
+ return undefined;
34
+ let reading = record.award;
35
+ if (reading === undefined) {
36
+ // Only the first board shows what was granted: later I hold what I captured, too.
37
+ if (turn !== 1)
38
+ return undefined;
39
+ const mine = board.territories.filter((t) => isMine(t, me.id)).map((t) => t.territoryId);
40
+ // A team game (C2): a start the first board shows as a teammate's is theirs, not an opponent's.
41
+ const mates = isTeamGame(game.players) ? new Set(teammatesOf(game.players, me).map((p) => p.id)) : undefined;
42
+ const teammateHeld = mates
43
+ ? board.territories.filter((t) => t.owner.kind === 'player' && mates.has(t.owner.playerId)).map((t) => t.territoryId)
44
+ : undefined;
45
+ reading = readAward({ list: record.list, mine, players: game.players.length, ...(teammateHeld ? { teammateHeld } : {}) });
46
+ const state = new Map(board.territories.map((t) => [t.territoryId, t]));
47
+ // A start the board shows as nobody's, mine or a neutral cannot be another player's: the list is not the one awarded from.
48
+ if (reading?.opponentStarts.some((t) => contradicts(state.get(t), me.id)))
49
+ reading = null;
50
+ if (o.write !== false)
51
+ await writeAward(dataDir, game.id, me.id, reading);
52
+ }
53
+ if (!reading)
54
+ return undefined;
55
+ const pickable = record.pickable ? { pickable: record.pickable } : {};
56
+ const duel = game.players.length === 2;
57
+ const opponent = duel ? game.players.find((p) => p.id !== me.id) : undefined;
58
+ const firstMover = duel ? firstMoverOnTurn({ role: reading.role, turn, moveOrder: game.settings?.moveOrder }) : null;
59
+ if (!opponent)
60
+ return { reading, firstMover, board, assumed: [], assumedArmies: null, ...pickable };
61
+ // A fogged start of the opponent's is its territory until the board shows otherwise. On turn 1
62
+ // nobody has deployed, so it holds the starting armies; later only its owner is known.
63
+ const assumedArmies = turn === 1 ? (uniformArmies(board, me.id) ?? game.settings?.initialPlayerArmiesPerTerritory ?? null) : null;
64
+ const starts = new Set(reading.opponentStarts);
65
+ const assumed = [];
66
+ const territories = board.territories.map((t) => {
67
+ if (!starts.has(t.territoryId) || t.owner.kind !== 'unknown')
68
+ return t;
69
+ assumed.push(t.territoryId);
70
+ return {
71
+ territoryId: t.territoryId,
72
+ owner: { kind: 'player', playerId: opponent.id },
73
+ armies: assumedArmies,
74
+ fogLevel: FOG_LEVEL_NAMES[assumedArmies === null ? FOG_LEVEL_OWNER_ONLY : FOG_LEVEL_VISIBLE],
75
+ };
76
+ });
77
+ const order = new Map(reading.opponentStarts.map((t, i) => [t, i]));
78
+ assumed.sort((a, b) => order.get(a) - order.get(b));
79
+ return { reading, opponent, firstMover, board: assumed.length ? { ...board, territories } : board, assumed, assumedArmies, ...pickable };
80
+ }
81
+ /**
82
+ * The opening threat model (#166): in a two-player game whose award proved every start the
83
+ * opponent has, its income on `turn` as the pick advisor's opening simulation gives it from those
84
+ * starts (`openingIncome`; my starts are never its captures), keyed by its GameFeed id, for the
85
+ * planner's fog prior (`PlanGameContext.opening`). Only on turns 1..PICK_HORIZON + 1, the turns the
86
+ * simulation covers; `undefined` otherwise. Neutral sizes are the ones `seen` (the board as war.app
87
+ * showed it) gives, then the settings.
88
+ */
89
+ export function openingThreat(a, game, graph, seen, turn) {
90
+ if (!a?.opponent || game.players.length !== 2 || !a.reading.allStartsKnown || !a.reading.opponentStarts.length)
91
+ return undefined;
92
+ if (turn === null || turn < 1 || turn > PICK_HORIZON + 1)
93
+ return undefined;
94
+ const neutralArmies = new Map();
95
+ for (const t of seen.territories)
96
+ if (t.owner.kind === 'neutral' && t.armies !== null)
97
+ neutralArmies.set(t.territoryId, t.armies);
98
+ const income = openingIncome({
99
+ graph,
100
+ starts: a.reading.opponentStarts,
101
+ settings: pickSettings(game.settings),
102
+ taken: [...a.reading.granted, ...a.reading.unlisted],
103
+ neutralArmies,
104
+ ...(a.pickable ? { pickable: a.pickable } : {}),
105
+ });
106
+ return new Map([[a.opponent.id, income[turn - 1]]]);
107
+ }
108
+ /** On the first board: a territory the award calls another player's that the board shows as mine, a neutral or pickable. */
109
+ function contradicts(t, me) {
110
+ if (!t || t.owner.kind === 'unknown')
111
+ return false;
112
+ return t.owner.kind !== 'player' || t.owner.playerId === me;
113
+ }
114
+ /** The one line a plan's warnings carry when its board holds territories the award gave an owner. */
115
+ export function assumedWarning(a) {
116
+ if (!a.assumed.length)
117
+ return [];
118
+ const many = a.assumed.length > 1;
119
+ return [
120
+ `Fogged territor${many ? 'ies' : 'y'} ${a.assumed.join(', ')} ${many ? 'are' : 'is'} planned as the opponent's` +
121
+ (a.assumedArmies !== null ? ` (${a.assumedArmies} armies each, the starting armies)` : ' (armies unknown)') +
122
+ `: your own pick list proves ${many ? 'they were' : 'it was'} its start (see \`award\`).`,
123
+ ];
124
+ }
125
+ /** The award as a tool reports it: territories by `name`, and what it means in sentences (ids only). */
126
+ export function awardView(a, game, turn, name) {
127
+ const { reading } = a;
128
+ const duel = game.players.length === 2;
129
+ const whose = duel ? "the opponent's" : "another player's";
130
+ const ids = (xs) => xs.join(', ');
131
+ const notes = [];
132
+ const team = reading.teammateStarts;
133
+ if (team) {
134
+ // A team game (C2): each start the award proves is a teammate's (the board showed it) or an opponent's.
135
+ if (team.length)
136
+ notes.push(`Your pick list ranked territor${team.length === 1 ? 'y' : 'ies'} ${ids(team)} above a pick you were granted, and the first board showed ` +
137
+ `${team.length === 1 ? 'it' : 'them'} as your teammate's: your teammate's start${team.length === 1 ? '' : 's'}.`);
138
+ if (reading.opponentStarts.length)
139
+ notes.push(`Your pick list ranked territor${reading.opponentStarts.length === 1 ? 'y' : 'ies'} ${ids(reading.opponentStarts)} above a pick you were granted, ` +
140
+ `and the first board did not show ${reading.opponentStarts.length === 1 ? 'it' : 'them'} as your teammate's: an opponent's start ` +
141
+ "(unverified: that teammates see each other's territories; a fogged one could still be your teammate's).");
142
+ if (!team.length && !reading.opponentStarts.length)
143
+ notes.push('You were granted the top of your list, so the award shows no start of another player.');
144
+ }
145
+ else if (reading.opponentStarts.length)
146
+ notes.push(`Your pick list ranked territor${reading.opponentStarts.length === 1 ? 'y' : 'ies'} ${ids(reading.opponentStarts)} above a pick you were granted, ` +
147
+ `so ${reading.opponentStarts.length === 1 ? 'it was' : 'they were'} taken first: ${whose} start${reading.opponentStarts.length === 1 ? '' : 's'}` +
148
+ (reading.allStartsKnown ? ' (every start it has).' : '.'));
149
+ else
150
+ notes.push('You were granted the top of your list, so the award shows no start of another player.');
151
+ if (reading.unlisted.length)
152
+ notes.push(`Your list ran out: territor${reading.unlisted.length === 1 ? 'y' : 'ies'} ${ids(reading.unlisted)} ${reading.unlisted.length === 1 ? 'was' : 'were'} given to you at random.`);
153
+ if (a.assumed.length)
154
+ notes.push(`Still fogged, territor${a.assumed.length === 1 ? 'y' : 'ies'} ${ids(a.assumed)} ${a.assumed.length === 1 ? 'is' : 'are'} planned as the opponent's` +
155
+ (a.assumedArmies !== null ? ` with the ${a.assumedArmies} starting armies (nobody has deployed yet).` : ' (armies unknown).'));
156
+ if (duel && reading.role)
157
+ notes.push(`Only the ${reading.role} awarded can be granted this set` +
158
+ (a.firstMover
159
+ ? `; under this game's ${game.settings?.moveOrder} move order the first awarded moves second on turn 1 and the order alternates, so ` +
160
+ `${a.firstMover === 'me' ? 'you move' : 'the opponent moves'} first on turn ${turn} (an Order Priority or Order Delay card changes that). ` +
161
+ "This is the community wiki's rule and the game client's help text, not verified live."
162
+ : game.settings?.moveOrder === 'NoLuckCycle'
163
+ ? '; under a no-luck cycle play speed, not the award, set who moves first: the game shows it (Game → Move Order), so pass it as `first_mover`.'
164
+ : '.'));
165
+ const commanders = game.settings?.commanders === true;
166
+ if (commanders && duel && reading.opponentFirstAward !== null)
167
+ notes.push(`Territory ${reading.opponentFirstAward} was the opponent's first award, and a commander starts on its owner's first award: ` +
168
+ `its commander ${turn === 1 ? 'is' : 'started'} there.`);
169
+ return {
170
+ opponentStarts: reading.opponentStarts.map(name),
171
+ ...(team ? { teammateStarts: team.map(name) } : {}),
172
+ allStartsKnown: reading.allStartsKnown,
173
+ awarded: duel ? reading.role : null,
174
+ firstMover: a.firstMover === null ? null : a.firstMover === 'me' ? 'you' : 'opponent',
175
+ ...(commanders && duel ? { opponentCommanderStart: reading.opponentFirstAward === null ? null : name(reading.opponentFirstAward) } : {}),
176
+ assumedOnBoard: a.assumed.map(name),
177
+ notes,
178
+ };
179
+ }
180
+ /**
181
+ * Who moves first on `turn` (#127): `first_mover` when given, else what this server knows — a
182
+ * turn kept at `<dataDir>/move-order/` alternated, or the award of picks — in a two-player game
183
+ * under a cyclic move order. What is newly known is kept for later turns (not with `write: false`). Never throws.
184
+ */
185
+ export async function firstMoverFor(dataDir, game, me, turn, explicit, award, o = {}) {
186
+ const cyclicDuel = game.players.length === 2 && isCyclicMoveOrder(game.settings?.moveOrder);
187
+ const remembered = dataDir && cyclicDuel ? await readFirstMover(dataDir, game.id, me.id) : undefined;
188
+ const { resolved, record, warnings } = resolveFirstMover({
189
+ turn,
190
+ cyclicDuel,
191
+ ...(explicit ? { explicit } : {}),
192
+ award: award?.firstMover ?? null,
193
+ ...(remembered ? { remembered } : {}),
194
+ });
195
+ if (dataDir && record && o.write !== false)
196
+ await writeFirstMover(dataDir, game.id, me.id, record);
197
+ if (!resolved)
198
+ return { view: null, warnings };
199
+ return {
200
+ firstMover: resolved.firstMover,
201
+ // #215 review: only a first mover the user gave is verified; the award's is the wiki's rule.
202
+ verified: verifiedFirstMover(resolved),
203
+ view: { who: resolved.firstMover === 'me' ? 'you' : 'opponent', source: resolved.source, ...(resolved.from ? { from: resolved.from } : {}) },
204
+ warnings,
205
+ };
206
+ }
@@ -0,0 +1,162 @@
1
+ // warapp_begin_turn: press Begin in a game whose first turn is a speed race
2
+ // (MoveOrder "No-luck cycle"), with the web client's BeginFirstTurn (method 78),
3
+ // gated on the user's confirmation. war.app withholds the board until Begin is
4
+ // pressed, and pressing it starts the player's first-turn timer — so the agent
5
+ // should call this only when it is ready to plan and submit straight away.
6
+ // The game is read from GameFeed first and the live board checked (a board
7
+ // already visible means Begin was pressed); the outcome is read back from the
8
+ // live board, never from the reply.
9
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
10
+ import { z } from 'zod';
11
+ import { parseGameId } from '../client.js';
12
+ import { readLatestGameInfo, standingFromInfo } from '../live.js';
13
+ import { Method, writeBeginFirstTurnParams, writeGetLatestGameInfoParams } from '../protocol/methods.js';
14
+ import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
15
+ import { mintMeta } from './hints.js';
16
+ import { requireApprovedAccount, SPEED_FIRST_TURN_MOVE_ORDER, writeAccount } from './live-context.js';
17
+ import { defineGatedWrite, mySeat, refuse, requireMe, requirePlaying, sendAndVerify } from './write-kit.js';
18
+ const PLAYING = 'Playing';
19
+ const DISTRIBUTING = 'DistributingTerritories';
20
+ /**
21
+ * The BeginFirstTurn error the web client ignores (it refreshes as on success);
22
+ * read from the bundle, its meaning is not verified.
23
+ */
24
+ const IGNORED_ERROR = 4;
25
+ const gameLabel = (game) => game.name ?? `game ${game.id}`;
26
+ /** Refuse a game that is not waiting for this account's Begin (judged from GameFeed). */
27
+ function beginnable(game, me) {
28
+ if (game.state === 'Finished') {
29
+ refuse(`Game ${game.id} is already over, so there is no first turn to begin.`, 'Check warapp_get_game.');
30
+ }
31
+ if (game.state !== PLAYING && game.state !== DISTRIBUTING) {
32
+ refuse(`Game ${game.id} has not started yet (game state: ${game.state}), so there is no first turn to begin.`, 'A lobby starts when its seats fill; check warapp_get_game.');
33
+ }
34
+ if ((game.numberOfTurns ?? 0) > 0) {
35
+ refuse(`Game ${game.id} is past its first turn (turn ${(game.numberOfTurns ?? 0) + 1}), so there is nothing to begin.`, 'Plan the turn with warapp_plan_turn.');
36
+ }
37
+ const order = game.settings?.moveOrder;
38
+ if (order !== undefined && order !== SPEED_FIRST_TURN_MOVE_ORDER) {
39
+ refuse(`Game ${game.id} does not race its first turn (move order: ${order}), so it has no Begin button.`, 'Only games with the "No-luck cycle" move order need Begin. Read the board with warapp_get_live_board.');
40
+ }
41
+ requirePlaying(game, mySeat(game, me));
42
+ }
43
+ /** The live board, or undefined while war.app withholds it. */
44
+ async function liveBoard(ctx, gameId) {
45
+ const env = await ctx.rpc.call('GetLatestGameInfo', Method.GetLatestGameInfo, (w) => writeGetLatestGameInfoParams(w, gameId));
46
+ return standingFromInfo(readLatestGameInfo(await ctx.bundle(), env.body)) ?? undefined;
47
+ }
48
+ export function registerBeginTurnTool(server, ctx) {
49
+ defineGatedWrite(server, {
50
+ title: 'Begin the first turn of a war.app speed game',
51
+ _meta: mintMeta('change', ['begin first turn', 'press begin', 'start my first turn']),
52
+ }, {
53
+ name: 'warapp_begin_turn',
54
+ description: 'Press Begin in a war.app (Warzone) game whose first turn is a speed race (move order "No-luck ' +
55
+ 'cycle": whoever commits their first orders fastest moves first). war.app hides the board until ' +
56
+ 'Begin is pressed, and pressing it STARTS YOUR TURN TIMER — call this only when ready to plan and ' +
57
+ 'submit at once (warapp_plan_turn, then warapp_submit_turn; in manual distribution, the picks). ' +
58
+ 'Refuses games past their first turn, games without the speed first turn, games you are not ' +
59
+ 'playing, and games whose board is already visible; reads the board back to report `begun`. ' +
60
+ `The BeginFirstTurn encoding is read from the war.app client, not yet verified live. ${CONFIRM_INJECTION_RULE}`,
61
+ annotations: toolAnnotations({
62
+ title: 'Begin the first turn of a war.app speed game',
63
+ readOnly: false,
64
+ destructive: true,
65
+ idempotent: false,
66
+ openWorld: true,
67
+ }),
68
+ inputSchema: z.object({ game_id: gameIdArg }),
69
+ async plan({ game_id }) {
70
+ const gameId = parseGameId(game_id);
71
+ const me = await requireMe(ctx);
72
+ const game = await ctx.client.getGame(gameId, { settings: true, map: false });
73
+ beginnable(game, me);
74
+ if (await liveBoard(ctx, gameId)) {
75
+ refuse(`Your first turn in game ${gameId} has already begun: the board is visible.`, 'Plan and submit now with warapp_plan_turn and warapp_submit_turn — the turn timer is running.');
76
+ }
77
+ const name = gameLabel(game);
78
+ const picking = game.state === DISTRIBUTING;
79
+ const warning = picking
80
+ ? `Begin STARTS YOUR PICK TIMER in game ${gameId}: the players who pick fastest get their picks in a conflict. ` +
81
+ 'Choose and submit your picks straight after.'
82
+ : `Begin STARTS YOUR FIRST-TURN TIMER in game ${gameId}: the players who commit fastest move first. ` +
83
+ 'Plan and submit straight after (warapp_plan_turn, then warapp_submit_turn).';
84
+ // The sentences name the game by id only; its name (its creator's words) goes,
85
+ // delimited, in `game.name`.
86
+ return {
87
+ gate: {
88
+ action: 'warapp.begin_first_turn',
89
+ summary: `Press Begin in war.app game ${gameId} — this starts your turn timer`,
90
+ account: writeAccount(me),
91
+ target: gameId,
92
+ payload: { method: 'BeginFirstTurn', gameId },
93
+ willSend: { game: gameId },
94
+ preview: {
95
+ warning,
96
+ account: shownAccount(game.players.find((p) => p.id === me)?.name, me),
97
+ game: { id: gameId, name: game.name === undefined ? null : untrustedText(game.name), state: game.state, turn: 1 },
98
+ untrusted: UNTRUSTED_PREVIEW_NOTE,
99
+ },
100
+ },
101
+ state: { gameId, name, picking, me },
102
+ };
103
+ },
104
+ async execute({ gameId, name, picking, me }) {
105
+ await requireApprovedAccount(ctx, writeAccount(me));
106
+ const game = { id: gameId, name };
107
+ const notReadBack = (ignored, readFailure) => ({
108
+ status: 'unconfirmed',
109
+ outcome: 'unconfirmed',
110
+ game,
111
+ warning: (ignored
112
+ ? `war.app answered Begin with error ${IGNORED_ERROR} (the web client ignores it)`
113
+ : 'war.app accepted Begin') +
114
+ `, but the board could not be read back${readFailure ? ` (${readFailure})` : ' yet'}. ` +
115
+ 'Check warapp_get_live_board shortly — your timer is probably running; do not press Begin ' +
116
+ 'again blindly.',
117
+ });
118
+ return sendAndVerify({
119
+ send: async () => {
120
+ await ctx.rpc.call('BeginFirstTurn', Method.BeginFirstTurn, (w) => writeBeginFirstTurnParams(w, gameId));
121
+ },
122
+ // The web client ignores this error and refreshes as on success: read the board back,
123
+ // and judge from it alone (#130).
124
+ refused: (e) => (e.code === IGNORED_ERROR ? 'ignore' : undefined),
125
+ unanswered: (failure) => ({
126
+ status: 'unknown',
127
+ outcome: 'unknown',
128
+ game,
129
+ warning: `war.app did not confirm Begin (${failure}), so it may ` +
130
+ 'already have gone through and your timer may be running. Check warapp_get_live_board; do not ' +
131
+ 'press Begin again blindly.',
132
+ }),
133
+ readBack: () => liveBoard(ctx, gameId),
134
+ // Nothing was read: never conclude the board is hidden from a failed read (#130).
135
+ unreadable: (failure, ignored) => notReadBack(ignored !== undefined, failure),
136
+ classify: (territories, ignored) => {
137
+ if (!territories && ignored) {
138
+ return {
139
+ status: 'not_begun',
140
+ outcome: 'not_applied',
141
+ game,
142
+ warning: `war.app answered Begin with error ${IGNORED_ERROR} (the web client ignores it; its meaning is not ` +
143
+ 'verified) and the board is still hidden, so Begin did not take effect as far as can be read. ' +
144
+ 'Check warapp_get_live_board before pressing Begin again.',
145
+ };
146
+ }
147
+ if (!territories)
148
+ return notReadBack(false, undefined);
149
+ return {
150
+ status: 'begun',
151
+ outcome: 'confirmed',
152
+ game,
153
+ territoriesVisible: territories.length,
154
+ next: picking
155
+ ? 'Your pick timer is running: choose and submit your picks now (warapp_submit_picks).'
156
+ : 'Your turn timer is running: plan and submit now (warapp_plan_turn, then warapp_submit_turn).',
157
+ };
158
+ },
159
+ });
160
+ },
161
+ });
162
+ }