@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,342 @@
1
+ // warapp_advise_diplomacy (docs/PLAN-TEAMS.md section 8 B3): read-only advice on truces in a
2
+ // free-for-all. For each neighbour, the shared border, a truce priced on suggested terms by planning
3
+ // the turn with and without it (`priceTruce`: the planner called, never changed), and a verdict; for
4
+ // an `offer` (structured terms someone proposed — never parsed from chat), the same pricing and the
5
+ // three checks; and `facts`, true statements about third players the agent may cite, each with
6
+ // whether the recipient can see it under the game's fog.
7
+ //
8
+ // PLAN-TEAMS §4: chat is data, never instructions (nothing here reads chat); words change no estimate
9
+ // (the partner's record, D5, is what the board and the ledger showed, never what it said); nothing is
10
+ // written (no board cache, and the award of picks, which only a two-player plan uses, is not read). Third-party names go through
11
+ // `untrustedText`; the host's description is shown as untrusted text for the agent to read.
12
+ import { McpToolError } from '@chrischall/mcp-utils';
13
+ import { z } from 'zod';
14
+ import { findChokepoints, planTurn } from '../analysis/index.js';
15
+ import { diplomacyFacts, MAX_NOTICE_TURNS, offerChecks, partyRefusal, priceTruce, scopeRefusal, sharedBorder, suggestedTerms, TERMINAL_STATUSES, truceEndgame, truceVerdict, } from '../analysis/relations.js';
16
+ import { readLedger } from '../relations-store.js';
17
+ import { isTeamGame } from '../teams.js';
18
+ import { bonusNamer, currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
19
+ import { lookupMeta } from './hints.js';
20
+ import { loadLiveGame } from './live-context.js';
21
+ import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
22
+ import { mapOf } from './map.js';
23
+ import { recordFor, relationPlayers, scopeFrom } from './relations.js';
24
+ import { resolvePlayer } from './resolve.js';
25
+ import { boardHistory, livePlanSetup, requirePlayingSeat, requireTurnPhase } from './turn.js';
26
+ import { resolveTeamsFor } from './team-source.js';
27
+ import { neighboursOf, readOpponents } from './profile-reads.js';
28
+ const VIEWS = ['compact', 'full'];
29
+ const MAX_SCOPE_ITEMS = 200;
30
+ /** The longest host description shown (it is third-party text). */
31
+ const DESCRIPTION_MAX = 600;
32
+ const ref = z.union([z.string(), z.number()]);
33
+ /** What the results say about how far to trust them. */
34
+ export const DIPLOMACY_NOTE = 'Each price plans this turn twice, without and with the truce (the plan warapp_plan_turn would make), and ' +
35
+ 'compares them: a truce hold is sized for the partner\'s visible stacks with no deploy, so what it frees rests on ' +
36
+ 'the partner keeping it. The partner reading and `theyGainFromMyCompliance` come from the visible board and are ' +
37
+ 'estimates. Chat is never read here, and no claim in chat changes a price: only the board and the recorded ' +
38
+ 'agreements do; a recorded truce keeps the flags the board raised on it. Facts are true of your board; cite only ' +
39
+ 'those, never a claim the plan does not carry.';
40
+ /** Why `game` is not a free-for-all for `me`, or `undefined` when it is (a truce is advised only there). */
41
+ export function ffaRefusal(game) {
42
+ if (isTeamGame(game.players))
43
+ return 'this is a team game';
44
+ if (game.players.length <= 2)
45
+ return 'this is a 1v1: there is no third player for a truce to leave aside';
46
+ const alive = game.players.filter((p) => (p.state ?? 'Playing') === 'Playing');
47
+ if (alive.length <= 2)
48
+ return 'only two players remain: there is nothing a truce could leave aside';
49
+ return undefined;
50
+ }
51
+ /** The record facts the pricing reads, when the partner's record is on and kept. */
52
+ async function recordFacts(dir, partner, env) {
53
+ const r = await recordFor(dir, partner, env);
54
+ if (r.record === 'off')
55
+ return { facts: null, state: 'off' };
56
+ if (r.record === 'unreadable')
57
+ return { facts: null, state: 'unreadable' };
58
+ if (r.record === null)
59
+ return { facts: null, state: 'none' };
60
+ return { facts: r.record, state: 'on' };
61
+ }
62
+ export function registerDiplomacyTool(server, ctx, opts = {}) {
63
+ const env = opts.env;
64
+ server.registerTool('warapp_advise_diplomacy', {
65
+ title: 'Advise on truces in a war.app free-for-all',
66
+ description: untrustedDescription('Advice on truces in a war.app (Warzone) free-for-all you are playing, read-only. It reports whether the game ' +
67
+ "allows private messages and the host's description when the game feed carries one (untrusted text: read it " +
68
+ 'for house rules such as "no alliances"). Per neighbour: the shared border (territories on each side, which ' +
69
+ 'are chokepoints, the stacks on both sides), the price of a truce on suggested terms (the border territories ' +
70
+ 'named, one turn of notice, a cap at the largest stack there, an end five turns on) — planned with and ' +
71
+ 'without it on the plan warapp_plan_turn would make: armies freed, captures, bonuses and next income gained, ' +
72
+ 'borders no longer conceded, planned attacks given up, and `lossIfBroken` (a break this turn) — a rough, ' +
73
+ "estimated reading of the partner's side (another front, room to grow), the partner's cross-game record when " +
74
+ 'on (WARAPP_PLAYER_RECORD) and beside it the partner\'s `retaliate` and `attack` habits when profiles are on ' +
75
+ '(WARAPP_PLAYER_PROFILE; as warapp_profile_opponents reads them, shown only: no price or verdict reads them), and a verdict: `propose`, `accept-if-offered` or `no`, with reasons. A neighbour ' +
76
+ 'with a recorded open agreement is priced on its recorded terms and on the board\'s reading of it, shown as ' +
77
+ '`relation`: a break by them, or a watch flag (massing, a cap exceeded, outgrowing, their notice), is a `no`. With `offer` (the structured terms someone ' +
78
+ 'proposed — never parsed from chat), the same price and three checks: do I gain only if they keep it, do I ' +
79
+ 'lose if I comply and they do not, do they gain from my compliance; all three true means run warapp_check_plan ' +
80
+ 'first. `facts`: true statements about third players you may cite to each neighbour, each with whether it can ' +
81
+ `see them under the game's fog. Refused outside a free-for-all. ${BRIDGE_NOTE} Sends nothing and records ` +
82
+ 'nothing: record an agreement with warapp_record_agreement, and send a message with warapp_send_chat.'),
83
+ _meta: lookupMeta(['truce advice', 'should i make a truce', 'diplomacy', 'price a deal', 'they offered a truce', 'alliance']),
84
+ annotations: readAnnotations('Advise on war.app truces'),
85
+ inputSchema: z.object({
86
+ game_id: gameIdArg,
87
+ player: playerArg,
88
+ offer: z
89
+ .object({
90
+ with: ref.describe('Who proposed it (name or GameFeed id).'),
91
+ territories: z.array(ref).max(MAX_SCOPE_ITEMS).optional().describe('Only these territories (names or ids) are covered.'),
92
+ bonuses: z.array(ref).max(MAX_SCOPE_ITEMS).optional().describe("Only these bonuses' territories (names or ids) are covered."),
93
+ notice_turns: z.coerce.number().int().min(0).max(MAX_NOTICE_TURNS).optional().describe('Turns of notice before it ends (default 1).'),
94
+ border_cap: z.coerce.number().int().min(0).optional().describe('The most armies either side keeps on a territory of the covered border.'),
95
+ until_turn: z.coerce.number().int().min(1).optional().describe('The last turn it binds.'),
96
+ })
97
+ .optional()
98
+ .describe('Terms someone proposed, as structured terms (omit both territories and bonuses to cover everything).'),
99
+ view: viewArg(VIEWS, 'compact (default) gives each neighbour\'s border, price, verdict and facts; "full" adds the partner reading, the loss if broken in detail, the plan\'s warnings and the record\'s facts.'),
100
+ }),
101
+ }, async ({ game_id, player, offer, view }) => {
102
+ const feed = await ctx.client.getGame(game_id, { settings: true });
103
+ requireTurnPhase(feed);
104
+ const seat = await resolveMe(ctx, feed.players, player);
105
+ requirePlayingSeat(feed, seat);
106
+ // The teams, after the seat refusals: GameFeed's, else the game list's (asked once per game, kept).
107
+ const { game, me, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
108
+ const ffa = ffaRefusal(game);
109
+ if (ffa)
110
+ throw new McpToolError(`No truce advice for game ${game.id}: ${ffa}. Truces are advised only in a free-for-all.`, {
111
+ hint: 'In a 1v1 every player is an opponent; in a team game, coordinate with your teammates instead.',
112
+ });
113
+ const map = mapOf(game);
114
+ const graph = graphOf(map);
115
+ const turn = currentTurn(game);
116
+ const players = relationPlayers(game.players);
117
+ // An offer is checked before any board read: a refused partner or scope reads nothing.
118
+ const offered = offer ? offerTerms(game, map, graph, me, offer) : undefined;
119
+ const [{ territories, info }, history] = await Promise.all([loadLiveGame(ctx, game), boardHistory(ctx, game, me, turn)]);
120
+ // award: false — the award of picks shapes only a two-player plan, and reading it on turn 1 writes it.
121
+ const setup = await livePlanSetup(ctx, { game, map, me, turn, territories, info, history, award: false, teamsKnown });
122
+ const input = setup.input;
123
+ // The no-deal plan, shared by every partner with no recorded relation; for one with a relation
124
+ // the input already holds its truce, so priceTruce plans the no-deal side itself.
125
+ const without = planTurn(input);
126
+ const related = new Set((input.relations ?? []).map((r) => r.player));
127
+ const board = setup.board;
128
+ const chokepoints = new Set(findChokepoints(graph).map((c) => c.territoryId));
129
+ const ledger = ctx.dataDir ? await readLedger(ctx.dataDir, game.id, me.id) : undefined;
130
+ // Part D (docs/PLAN-PROFILES.md section 11): each neighbour's `retaliate` and `attack`, beside the
131
+ // deal record. Shown only: no verdict or price reads them. Read-only (nothing kept here); none with
132
+ // profiling off or while the teams cannot be read (any player may be my teammate).
133
+ const habitReads = teamsKnown && turn !== null
134
+ ? await readOpponents({
135
+ dataDir: ctx.dataDir,
136
+ env: env ?? process.env,
137
+ game,
138
+ me,
139
+ teamsKnown,
140
+ boards: [...history.boards, { turn, board: setup.seen }],
141
+ }).catch(() => undefined)
142
+ : undefined;
143
+ const habitsOf = (partner) => {
144
+ if (!habitReads?.on)
145
+ return undefined;
146
+ const r = habitReads.reads.find((x) => x.id === partner);
147
+ return r ? { retaliate: r.estimates.retaliate, attack: r.estimates.attack } : undefined;
148
+ };
149
+ // The endgame (T3): no other opponent's income still a match for either of us — a truce then relaxes nothing.
150
+ const incomes = new Map(game.players
151
+ .filter((p) => p.id !== me.id && (p.state ?? 'Playing') === 'Playing')
152
+ .map((p) => {
153
+ const t = setup.tracks?.find((x) => x.playerId === p.id);
154
+ return [p.id, t && t.firstSeen !== null ? (t.income ?? t.visibleIncome) : null];
155
+ }));
156
+ const endgameWith = (partner) => {
157
+ const mine = setup.boardIncome;
158
+ const theirs = incomes.get(partner);
159
+ const others = [...incomes].filter(([id]) => id !== partner).map(([, v]) => v);
160
+ if (theirs == null || others.some((v) => v === null))
161
+ return false;
162
+ return truceEndgame({ mine, partner: theirs, others: others });
163
+ };
164
+ const price = async (partner, terms, agreement) => {
165
+ const record = await recordFacts(ctx.dataDir, partner, env);
166
+ const endgame = endgameWith(partner);
167
+ const priced = priceTruce(input, partner, terms, {
168
+ ...(related.has(partner) ? {} : { without }),
169
+ record: record.facts,
170
+ ...(endgame ? { trust: 'watch', watch: ['endgame'] } : {}),
171
+ ...(agreement !== undefined ? { agreement } : {}),
172
+ });
173
+ // A recorded truce keeps the board's reading (priceTruce): a breach or a watch flag is a `no`, with it as the reason.
174
+ const verdict = truceVerdict(priced, setup.income);
175
+ return { priced, verdict, recordState: record.state, related: related.has(partner) };
176
+ };
177
+ const name = namer(map);
178
+ const bonusName = bonusNamer(map);
179
+ const playerRef = (id) => {
180
+ const p = game.players.find((x) => x.id === id);
181
+ return { id, name: p ? untrustedText(p.name) : null };
182
+ };
183
+ const termsView = (t) => ({
184
+ scope: t.scope === 'all'
185
+ ? 'all'
186
+ : 'territories' in t.scope
187
+ ? { territories: t.scope.territories.map(name) }
188
+ : { bonuses: t.scope.bonuses.map(bonusName) },
189
+ noticeTurns: t.noticeTurns,
190
+ ...(t.borderCap !== undefined ? { borderCap: t.borderCap } : {}),
191
+ ...(t.untilTurn !== undefined ? { untilTurn: t.untilTurn } : {}),
192
+ });
193
+ const priceView = (p, rung) => ({
194
+ coveredMine: p.coveredMine.map(name),
195
+ coveredTheirs: p.coveredTheirs.map(name),
196
+ honoured: p.honoured,
197
+ armiesFreed: p.armiesFreed,
198
+ capturesGained: p.capturesGained.map(name),
199
+ ...(p.capturesLost.length ? { capturesLost: p.capturesLost.map(name) } : {}),
200
+ bonusesGained: p.bonusesGained,
201
+ ...(p.bonusesLost.length ? { bonusesLost: p.bonusesLost } : {}),
202
+ incomeGained: p.incomeGained,
203
+ ...(p.concededAvoided.length ? { concededAvoided: p.concededAvoided.map(name) } : {}),
204
+ ...(p.concededAdded.length ? { concededAdded: p.concededAdded.map(name) } : {}),
205
+ ...(p.attacksForgone.length ? { attacksForgone: p.attacksForgone.map(name) } : {}),
206
+ lossIfBroken: p.lossIfBroken === null
207
+ ? null
208
+ : rung === 'full'
209
+ ? { ...p.lossIfBroken, from: name(p.lossIfBroken.from), to: name(p.lossIfBroken.to), territories: p.lossIfBroken.territories.map(name) }
210
+ : {
211
+ from: name(p.lossIfBroken.from),
212
+ to: name(p.lossIfBroken.to),
213
+ territories: p.lossIfBroken.territories.length,
214
+ armies: p.lossIfBroken.armies,
215
+ income: p.lossIfBroken.bonusValue,
216
+ commanderLost: p.lossIfBroken.commanderLost,
217
+ },
218
+ reliability: p.reliability,
219
+ ...(rung === 'full'
220
+ ? {
221
+ relaxed: p.relaxed.map(name),
222
+ fullHold: p.fullHold.map((f) => ({ territory: name(f.territory), why: f.why })),
223
+ partner: { ...p.partner, otherFronts: p.partner.otherFronts.map(playerRef) },
224
+ record: p.record,
225
+ warnings: p.warnings,
226
+ }
227
+ : { partner: { estimate: true, otherFronts: p.partner.otherFronts.length, roomToGrow: p.partner.roomToGrow } }),
228
+ });
229
+ // The board's reading of a recorded truce with this partner (warapp_plan_turn's): state, trust and flags.
230
+ const relationView = (p) => ({
231
+ state: p.state,
232
+ trust: p.trust,
233
+ watch: p.watch,
234
+ ...(p.breach
235
+ ? { breach: { term: p.breach.term, turn: p.breach.turn, evidence: p.breach.evidence, territories: p.breach.territories.map(name) } }
236
+ : {}),
237
+ });
238
+ const factView = (f) => ({
239
+ about: playerRef(f.about),
240
+ text: f.text,
241
+ recipientSees: f.recipientSees,
242
+ ...(f.territory !== undefined ? { territory: name(f.territory) } : {}),
243
+ ...(f.beside !== undefined ? { beside: name(f.beside) } : {}),
244
+ });
245
+ const fog = game.settings?.fog;
246
+ const built = [];
247
+ for (const partner of neighboursOf(graph, board, me.id)) {
248
+ const facts = diplomacyFacts({ graph, board, me: me.id, recipient: partner, ...(fog !== undefined ? { fog } : {}) });
249
+ const refused = partyRefusal(players, me.id, partner);
250
+ if (refused) {
251
+ built.push({ partner, refused, facts });
252
+ continue;
253
+ }
254
+ const border = sharedBorder(graph, board, me.id, partner, chokepoints);
255
+ const open = ledger?.agreements.find((a) => a.with === partner && !TERMINAL_STATUSES.has(a.status));
256
+ const terms = open ? open.terms : suggestedTerms(border, turn);
257
+ const { priced, verdict, recordState, related: rel } = await price(partner, terms, open?.id);
258
+ built.push({ partner, ...(open ? { agreement: open.id } : {}), border, terms, priced, verdict, recordState, related: rel, facts });
259
+ }
260
+ const offerResult = offered
261
+ ? await (async () => {
262
+ const { priced, verdict, recordState, related: rel } = await price(offered.partner, offered.terms);
263
+ return { partner: offered.partner, terms: offered.terms, priced, verdict, checks: offerChecks(priced), recordState, related: rel };
264
+ })()
265
+ : undefined;
266
+ const description = game.description !== undefined ? untrustedText(game.description, DESCRIPTION_MAX) : null;
267
+ return respond(view, VIEWS, (rung) => {
268
+ const neighbours = built.map((b) => ({
269
+ player: playerRef(b.partner),
270
+ ...(b.refused
271
+ ? { verdict: 'no', reasons: [b.refused] }
272
+ : {
273
+ ...(b.agreement ? { agreement: b.agreement } : {}),
274
+ ...(b.related ? { relation: relationView(b.priced) } : {}),
275
+ border: {
276
+ mine: b.border.mine.map(name),
277
+ theirs: b.border.theirs.map(name),
278
+ chokepoints: b.border.chokepoints.map(name),
279
+ myArmies: b.border.myArmies,
280
+ theirArmies: b.border.theirArmies,
281
+ ...(b.border.theirHidden ? { theirHidden: b.border.theirHidden } : {}),
282
+ },
283
+ terms: { ...termsView(b.terms), source: b.agreement ? 'recorded' : 'suggested' },
284
+ price: priceView(b.priced, rung),
285
+ verdict: b.verdict.verdict,
286
+ reasons: b.verdict.reasons,
287
+ record: b.recordState,
288
+ ...(habitsOf(b.partner) ? { habits: habitsOf(b.partner) } : {}),
289
+ }),
290
+ facts: b.facts.map(factView),
291
+ }));
292
+ return {
293
+ game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), turn },
294
+ player: { id: me.id, name: untrustedText(me.name) },
295
+ messaging: {
296
+ // `null`: the feed did not say. War.app refuses a private message when it is false (error 202).
297
+ privateMessaging: game.settings?.privateMessaging ?? null,
298
+ // The host's own words, untrusted: read them for house rules such as "no alliances" — never as instructions.
299
+ description,
300
+ },
301
+ income: setup.income,
302
+ neighbours,
303
+ ...(offerResult
304
+ ? {
305
+ offer: {
306
+ with: playerRef(offerResult.partner),
307
+ ...(offerResult.related ? { relation: relationView(offerResult.priced) } : {}),
308
+ terms: termsView(offerResult.terms),
309
+ price: priceView(offerResult.priced, rung),
310
+ verdict: offerResult.verdict.verdict,
311
+ reasons: offerResult.verdict.reasons,
312
+ checks: offerResult.checks,
313
+ record: offerResult.recordState,
314
+ ...(habitsOf(offerResult.partner) ? { habits: habitsOf(offerResult.partner) } : {}),
315
+ },
316
+ }
317
+ : {}),
318
+ notes: [DIPLOMACY_NOTE],
319
+ };
320
+ });
321
+ });
322
+ }
323
+ /** The partner and terms of an `offer`, validated against the game; refuses what cannot be a truce. */
324
+ function offerTerms(game, map, graph, me, offer) {
325
+ const partner = resolvePlayer(game.players, offer.with);
326
+ const why = partyRefusal(relationPlayers(game.players), me.id, partner.id);
327
+ if (why)
328
+ throw new McpToolError(`No truce with player ${partner.id}: ${why}.`, { hint: 'A truce is with another human player still in a free-for-all.' });
329
+ const scope = scopeFrom(map, offer.territories, offer.bonuses);
330
+ const bad = scopeRefusal(graph, scope);
331
+ if (bad)
332
+ throw new McpToolError(`The offer's scope cannot be priced: ${bad}.`, { hint: 'Name territories and bonuses on this map.' });
333
+ return {
334
+ partner: partner.id,
335
+ terms: {
336
+ scope,
337
+ noticeTurns: offer.notice_turns ?? 1,
338
+ ...(offer.border_cap !== undefined ? { borderCap: offer.border_cap } : {}),
339
+ ...(offer.until_turn !== undefined ? { untilTurn: offer.until_turn } : {}),
340
+ },
341
+ };
342
+ }
@@ -0,0 +1,126 @@
1
+ import { z } from 'zod';
2
+ import { leavers } from '../normalize.js';
3
+ import { recordFinalResult } from '../outlook-log.js';
4
+ import { currentTurn, gameIdArg, mapSummary, readAnnotations, respond, turnsCompleted, untrustedDescription, viewArg } from './common.js';
5
+ import { lookupMeta } from './hints.js';
6
+ import { lossReport } from './how-lost.js';
7
+ import { foldFinished } from './profile-hook.js';
8
+ const VIEWS = ['compact', 'full', 'raw'];
9
+ function settingsDigest(s) {
10
+ if (!s)
11
+ return null;
12
+ const { raw: _raw, ...digest } = s;
13
+ return digest;
14
+ }
15
+ function compact(game) {
16
+ const out = {
17
+ game: {
18
+ id: game.id,
19
+ name: game.name ?? null,
20
+ state: game.state,
21
+ // #130: the turn being played, as every turn tool reports it; the completed count apart.
22
+ turn: currentTurn(game),
23
+ turnsCompleted: turnsCompleted(game),
24
+ created: game.created ?? null,
25
+ lastTurnTime: game.lastTurnTime ?? null,
26
+ },
27
+ players: game.players.map((p) => {
28
+ const row = { id: p.id, name: p.name, state: p.state ?? null, committed: p.hasCommittedOrders };
29
+ if (p.isAI)
30
+ row.ai = true;
31
+ if (p.humanTurnedIntoAI)
32
+ row.turnedIntoAI = true;
33
+ return row;
34
+ }),
35
+ // Humans still to commit orders this turn (only meaningful while playing).
36
+ waitingOn: game.state === 'Playing'
37
+ ? game.players.filter((p) => p.state === 'Playing' && !p.isAI && !p.hasCommittedOrders).map((p) => p.name)
38
+ : [],
39
+ settings: settingsDigest(game.settings),
40
+ // #178: how the game ends and what a leaver's seat becomes.
41
+ endRules: game.endRules ?? null,
42
+ map: game.map ? mapSummary(game.map) : null,
43
+ boardAvailable: game.standing !== undefined,
44
+ };
45
+ // #178: humans who have not committed, with the time left to each boot (lastTurnTime UNVERIFIED).
46
+ // Only where a boot setting exists: without AutoBoot or DirectBoot nobody is close to a boot, and
47
+ // the list would repeat `waitingOn`.
48
+ const l = leavers(game, Date.now());
49
+ const booted = l.players.filter((p) => p.autoBootInMinutes !== undefined || p.directBootInMinutes !== undefined);
50
+ if (booted.length)
51
+ out.leavers = {
52
+ players: booted.map(({ playerId, ...rest }) => ({ id: playerId, name: game.players.find((p) => p.id === playerId)?.name ?? null, ...rest })),
53
+ unverified: l.unverified,
54
+ };
55
+ if (game.history !== undefined)
56
+ out.history = game.history;
57
+ if (game.chat !== undefined)
58
+ out.chat = game.chat;
59
+ return out;
60
+ }
61
+ /**
62
+ * `dir` is the data directory: a finished game this server planned gets its final result in the
63
+ * outlook log (#178), and its opponent profile is folded into the cross-game stores (B2,
64
+ * docs/PLAN-PROFILES.md; off with `WARAPP_PLAYER_PROFILE=off` in `env`): the per-game file kept while it
65
+ * was played, else, once, its cached boards (#264's backfill), reported as `profileFold`. A finished game
66
+ * the cached account did not win says how (`howLost`, #274, src/tools/how-lost.ts), as does (#283) a game
67
+ * still playing once that account's seat is out.
68
+ */
69
+ export function registerGameTool(server, client, dir, env) {
70
+ server.registerTool('warapp_get_game', {
71
+ title: 'Get a war.app (Warzone) game',
72
+ description: untrustedDescription('Look up one war.app (Warzone) multiplayer game by id: its state (lobby, distributing, playing, finished), ' +
73
+ 'the turn being played (`turn`; `turnsCompleted` counts the finished ones), the players and who has committed orders (who the game is waiting on), and a digest of ' +
74
+ 'its settings — fog, kill rates, luck, rounding, base income, army cap, enabled cards — plus which map it ' +
75
+ 'is on and whether the board is available for warapp_analyze_board; the end-of-game, boot and AI settings ' +
76
+ '(`endRules`) and the humans who have not committed with the time left to each boot (`leavers`, when the game boots; from ' +
77
+ 'lastTurnTime, whose meaning is unverified). Optional game history and chat. ' +
78
+ 'A game I lost says how (`howLost`), once finished or, while the others play on, once my seat is out (eliminated, ' +
79
+ 'booted or surrendered): a surrender or boot by my state, with the last turn played here and the last logged outlook ' +
80
+ '(its state, my income and armies against the strongest opponent\'s in view); an elimination from the boards ' +
81
+ 'this server cached while it played — the turn (certain only when it is the newest completed turn), my commander\'s territory ' +
82
+ 'that fell with what it held, the attackers that needed and who bordered it (at a commander walk\'s destination, ' +
83
+ 'which may instead have fallen before the walk ran), or else my last territories (inferred, never seen). ' +
84
+ 'A finished game is folded once into the opponent profiles (`profileFold`; from the turns kept while it was played, ' +
85
+ 'else from the boards cached then — a backfill; no other request), as warapp_profile_opponents reads them. ' +
86
+ 'For the map\'s bonuses and chokepoints use warapp_get_map. Read-only.'),
87
+ _meta: lookupMeta(['warzone game', 'war.app game', 'whose turn is it', 'game status']),
88
+ annotations: readAnnotations('Get a war.app game'),
89
+ inputSchema: z.object({
90
+ game_id: gameIdArg,
91
+ include_history: z
92
+ .boolean()
93
+ .optional()
94
+ .describe('Also fetch past turns (GetHistory; war.app documents it for finished games). Default false.'),
95
+ include_chat: z.boolean().optional().describe('Also fetch the game chat (GetChat). Default false.'),
96
+ view: viewArg(VIEWS, 'compact (default) keeps the game state and turn, players with committed flags, a settings digest and a map ' +
97
+ 'summary; "full" is every normalized field (all settings as sent, the board standing) with the map ' +
98
+ 'summarized; "raw" is the whole normalized game including the full map.'),
99
+ }),
100
+ }, async ({ game_id, include_history, include_chat, view }) => {
101
+ const game = await client.getGame(game_id, {
102
+ settings: true,
103
+ ...(include_history ? { history: true } : {}),
104
+ ...(include_chat ? { chat: true } : {}),
105
+ });
106
+ let fold;
107
+ let lost;
108
+ if (dir) {
109
+ await recordFinalResult(dir(), game);
110
+ // #274: a game I lost says how, from the boards cached while it was played.
111
+ lost = await lossReport(dir(), game);
112
+ // The first read that shows the game finished folds its opponent profile, or backfills it from
113
+ // the cached boards once (#264; best effort, no request).
114
+ if (game.state === 'Finished')
115
+ fold = await foldFinished(dir(), env ?? process.env, game);
116
+ }
117
+ const folded = { ...(fold && fold.status !== 'off' ? { profileFold: fold } : {}), ...(lost ? { howLost: lost } : {}) };
118
+ return respond(view, VIEWS, (rung) => {
119
+ if (rung === 'compact')
120
+ return { ...compact(game), ...folded };
121
+ if (rung === 'full')
122
+ return { game: { ...game, map: game.map ? mapSummary(game.map) : undefined }, ...folded };
123
+ return { game };
124
+ });
125
+ });
126
+ }
@@ -0,0 +1,56 @@
1
+ // warapp_plan_turn's `guess` (src/analysis/guess.ts): how it is shown, and the orders that carry it.
2
+ const pct = (p) => `${Math.round(p * 100)}%`;
3
+ const r2 = (x) => Math.round(x * 100) / 100;
4
+ /** The guess for the tool: compact (borders by name with hold probability, losses, deploys, a sentence) or full. */
5
+ export function guessView(guess, rung, name, opponentName) {
6
+ const label = (id) => `${name(id).name} (#${id})`;
7
+ const deployed = guess.borders.map((b) => `${b.guessDeploy} on ${label(b.id)}`).join(', ');
8
+ const odds = guess.borders
9
+ .map((b) => b.holdAloneProbability > b.holdProbability
10
+ ? `${label(b.id)} holds everything ${pct(b.holdProbability)}, its stacks alone ${pct(b.holdAloneProbability)}`
11
+ : `${label(b.id)} holds everything ${pct(b.holdProbability)}`)
12
+ .join('; ');
13
+ const summary = `The opponent touches ${guess.borders.length} of your borders and the ${guess.budget} armies the plan deploys there ` +
14
+ `cannot hold them all against its stacks plus its deploy of ${guess.enemyDeploy}: whichever split you fix, it can hit the ` +
15
+ `border left short (worst case ${guess.fixedLoss} of ${guess.worthAtStake} worth at stake; the plan's split ${guess.planLoss}). ` +
16
+ `Drawing the split at random, weighted by worth (${odds}), expects to lose ${r2(guess.mixedLoss)}. ` +
17
+ `This turn's draw: ${deployed}. Optional — guessOrders carries it, orders keep the plan's split.`;
18
+ const opponent = { id: guess.opponent, name: opponentName };
19
+ const deploys = guess.deploys.map((d) => ({ territory: name(d.territoryId), armies: d.armies }));
20
+ if (rung === 'compact')
21
+ return {
22
+ opponent,
23
+ borders: guess.borders.map((b) => ({ ...name(b.id), holdProbability: b.holdProbability, holdAloneProbability: b.holdAloneProbability })),
24
+ fixedLoss: guess.fixedLoss,
25
+ mixedLoss: r2(guess.mixedLoss),
26
+ planLoss: guess.planLoss,
27
+ deploys,
28
+ summary,
29
+ };
30
+ return {
31
+ opponent,
32
+ enemyDeploy: guess.enemyDeploy,
33
+ budget: guess.budget,
34
+ worthAtStake: guess.worthAtStake,
35
+ borders: guess.borders.map((b) => ({ ...b, name: name(b.id).name })),
36
+ fixedLoss: guess.fixedLoss,
37
+ mixedLoss: guess.mixedLoss,
38
+ planLoss: guess.planLoss,
39
+ targets: guess.targets.map((t) => ({ ...name(t.id), probability: t.probability })),
40
+ mix: guess.mix,
41
+ allocation: guess.allocation,
42
+ deploys,
43
+ summary,
44
+ };
45
+ }
46
+ /**
47
+ * The plan's orders with the guess's deploys in place of the plan's: every deploy order replaced by
48
+ * the guess's deploy list (same total), at the place the first deploy stood; every other order kept.
49
+ */
50
+ export function guessOrdersOf(orders, guess) {
51
+ const at = orders.findIndex((o) => o.kind === 'deploy');
52
+ const rest = orders.filter((o) => o.kind !== 'deploy');
53
+ const deploys = guess.deploys.map((d) => ({ kind: 'deploy', territory: d.territoryId, armies: d.armies }));
54
+ const index = at < 0 ? rest.length : orders.slice(0, at).filter((o) => o.kind !== 'deploy').length;
55
+ return [...rest.slice(0, index), ...deploys, ...rest.slice(index)];
56
+ }
@@ -0,0 +1,90 @@
1
+ import { McpToolError } from '@chrischall/mcp-utils';
2
+ import { registerAdaptiveHealthcheckTool, } from '@chrischall/mcp-utils/fetchproxy';
3
+ import { AUTH_FAILED_HINT, PROBE_GAME_ID, WarappClient } from '../client.js';
4
+ import { readCredentials, TOKEN_URL, WarappConfigError } from '../config.js';
5
+ import { readSessionSync } from '../direct/session.js';
6
+ /**
7
+ * `warapp_healthcheck` — does war.app accept the configured email + token?
8
+ *
9
+ * The probe ({@link WarappClient.probeAuth}) asks GameFeed for a game id that
10
+ * does not exist. war.app checks the credentials first, so the two answers
11
+ * separate cleanly: `Auth failed` is a rejected credential,
12
+ * `ServerGameKeyNotFound` proves the credential works without loading (or
13
+ * caching) any real game.
14
+ *
15
+ * The live-game tools reach war.app a second way — the web-client protocol —
16
+ * now over a direct-first transport: a chrome-less HTTPS leg carrying the
17
+ * linked `AuthToken` session, falling back to the browser bridge. So this is
18
+ * ONE adaptive tool: it answers from the bridge arm once the browser bridge has
19
+ * carried a request in this process (i.e. after the router fell back to it —
20
+ * "on fetchproxy, the bridge probe"), and from the credential arm before that,
21
+ * which is the whole time the direct leg is serving calls ("on direct, the
22
+ * credential probe"). Either way the result carries which leg is active and
23
+ * whether a direct session is linked and how old it is — never the token.
24
+ */
25
+ export { PROBE_GAME_ID };
26
+ const PROBE_PATH = `/API/GameFeed?GameID=${PROBE_GAME_ID}&GetMap=false`;
27
+ /** The page the bridge arm round-trips through the user's war.app tab. */
28
+ export const BRIDGE_PROBE_PATH = '/';
29
+ /** The non-secret facts about the linked direct session — never the token. */
30
+ function sessionSummary(env, now) {
31
+ const s = readSessionSync(env);
32
+ if (!s)
33
+ return { linked: false };
34
+ const ageSeconds = Math.max(0, Math.round((now() - Date.parse(s.capturedAt)) / 1000));
35
+ return { linked: true, capturedAt: s.capturedAt, ageSeconds };
36
+ }
37
+ /** Which leg is active (+ its configured mode) and the linked-session summary. */
38
+ function transportHealth(status, env, now) {
39
+ return { ...status, session: sessionSummary(env, now) };
40
+ }
41
+ export function registerHealthcheckTool(server, bridge, direct, deps = {}) {
42
+ const now = deps.now ?? Date.now;
43
+ registerAdaptiveHealthcheckTool({
44
+ server,
45
+ prefix: 'warapp',
46
+ hostLabel: 'war.app',
47
+ // The browser bridge is on the path only when THIS connection's
48
+ // direct-first router is on its fetchproxy leg (it fell back, or is pinned
49
+ // to fetchproxy) AND the bridge has carried a request. The fetchproxy
50
+ // bridge is shared process-wide, so its role alone is not enough: another
51
+ // connection may have used it while this one rides the direct leg (always,
52
+ // under WARAPP_TRANSPORT=direct). Otherwise the credential arm answers.
53
+ usingBridge: () => direct.status().transport === 'fetchproxy' && bridge.transport().role !== null,
54
+ bridge: {
55
+ probePath: BRIDGE_PROBE_PATH,
56
+ transport: () => bridge.transport(),
57
+ path: () => transportHealth(direct.status(), deps.env, now),
58
+ probeFn: async (path) => {
59
+ const res = await (await bridge.ready()).fetch({ method: 'GET', path });
60
+ if (res.status !== 200) {
61
+ throw new McpToolError(`war.app answered HTTP ${res.status} through the bridge.`, {
62
+ status: res.status,
63
+ kind: 'http',
64
+ });
65
+ }
66
+ return res.body;
67
+ },
68
+ },
69
+ credential: {
70
+ probePath: PROBE_PATH,
71
+ resolveCredential: async () => {
72
+ const health = transportHealth(direct.status(), deps.env, now);
73
+ try {
74
+ readCredentials(deps.env);
75
+ return { source: 'env', detail: health };
76
+ }
77
+ catch (e) {
78
+ if (e instanceof WarappConfigError)
79
+ return { source: null, detail: { ...health, reason: e.message } };
80
+ throw e;
81
+ }
82
+ },
83
+ probeFn: () => new WarappClient(deps).probeAuth(),
84
+ classifyThrown: (err) => err instanceof McpToolError && err.kind === 'credential_rejected'
85
+ ? { kind: 'credential_rejected', hint: AUTH_FAILED_HINT }
86
+ : undefined,
87
+ hints: { no_credential: `Set WARAPP_EMAIL and WARAPP_API_TOKEN (token from ${TOKEN_URL}).` },
88
+ },
89
+ });
90
+ }
@@ -0,0 +1,34 @@
1
+ /** `_meta` for a war.app tool, with optional spoken aliases. */
2
+ export function mintMeta(intent, aliases) {
3
+ return { mint: aliases ? { domain: 'work', intent, aliases } : { domain: 'work', intent } };
4
+ }
5
+ /** `_meta` for the group's canonical tool for `intent` (it must accept `view: 'brief'`). */
6
+ export function canonicalMeta(intent, aliases) {
7
+ return { mint: { domain: 'work', intent, canonical: true, aliases } };
8
+ }
9
+ /** `_meta` for a war.app lookup, with optional spoken aliases. */
10
+ export function lookupMeta(aliases) {
11
+ return mintMeta('lookup', aliases);
12
+ }
13
+ /**
14
+ * Run `register` with `extra` (a `title`, `_meta`) merged into the config of
15
+ * every tool it registers — for mcp-utils' `registerWrite`, which builds the
16
+ * `registerTool` config itself and takes neither. The SAME server object is
17
+ * patched (not a proxy), so registerWrite's per-server registry still keys on
18
+ * the real server; the original is restored afterwards, even on a throw.
19
+ */
20
+ export function withToolConfig(server, extra, register) {
21
+ const target = server;
22
+ const hadOwn = Object.hasOwn(target, 'registerTool');
23
+ const original = target.registerTool;
24
+ target.registerTool = (name, config, ...rest) => original.call(server, name, { ...config, ...extra }, ...rest);
25
+ try {
26
+ register();
27
+ }
28
+ finally {
29
+ if (hadOwn)
30
+ target.registerTool = original;
31
+ else
32
+ delete target.registerTool;
33
+ }
34
+ }