@chrischall/warapp-mcp 0.10.0 → 0.12.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 (65) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +10 -8
  4. package/dist/analysis/cards-in-effect.js +10 -1
  5. package/dist/analysis/chat-mentions.js +17 -0
  6. package/dist/analysis/commander-fog.js +126 -0
  7. package/dist/analysis/end-game-stats.js +149 -0
  8. package/dist/analysis/local-deploy.js +3 -2
  9. package/dist/analysis/outlook.js +133 -55
  10. package/dist/analysis/picks.js +125 -0
  11. package/dist/analysis/plan/commander.js +3 -2
  12. package/dist/analysis/plan/deploy-estimates.js +11 -7
  13. package/dist/analysis/plan/estimates.js +63 -9
  14. package/dist/analysis/plan/relations.js +29 -14
  15. package/dist/analysis/plan/shared.js +21 -0
  16. package/dist/analysis/plan/threats.js +74 -5
  17. package/dist/analysis/player-record.js +31 -1
  18. package/dist/analysis/player.js +23 -10
  19. package/dist/analysis/relations.js +83 -9
  20. package/dist/analysis/scale.js +71 -0
  21. package/dist/analysis/single-pick.js +356 -0
  22. package/dist/bundle.js +3099 -809
  23. package/dist/chat-links.js +141 -0
  24. package/dist/finished-store.js +30 -0
  25. package/dist/index.js +1 -1
  26. package/dist/known-mods.js +33 -0
  27. package/dist/map-stats.js +24 -2
  28. package/dist/mod-alliances.js +217 -0
  29. package/dist/mod-data.js +160 -0
  30. package/dist/my-games.js +53 -2
  31. package/dist/normalize.js +7 -0
  32. package/dist/outlook-log.js +13 -0
  33. package/dist/player-record-store.js +5 -3
  34. package/dist/protocol/methods.js +14 -2
  35. package/dist/relations-store.js +29 -1
  36. package/dist/tools/card-advice.js +29 -9
  37. package/dist/tools/card-effects.js +3 -1
  38. package/dist/tools/card-support-advice.js +1 -1
  39. package/dist/tools/chat-advice.js +1 -1
  40. package/dist/tools/chat-inbox.js +67 -10
  41. package/dist/tools/chat.js +46 -8
  42. package/dist/tools/check-plan.js +115 -11
  43. package/dist/tools/close-finished-game.js +110 -0
  44. package/dist/tools/commander-check.js +80 -1
  45. package/dist/tools/diplomacy.js +11 -2
  46. package/dist/tools/end-of-game.js +57 -3
  47. package/dist/tools/game.js +7 -3
  48. package/dist/tools/how-lost.js +68 -5
  49. package/dist/tools/index.js +21 -1
  50. package/dist/tools/map.js +50 -1
  51. package/dist/tools/mod-alliances.js +191 -0
  52. package/dist/tools/my-games.js +12 -1
  53. package/dist/tools/pace.js +44 -0
  54. package/dist/tools/picks.js +41 -1
  55. package/dist/tools/relations.js +120 -7
  56. package/dist/tools/session.js +20 -6
  57. package/dist/tools/stress-opponents.js +25 -2
  58. package/dist/tools/turn.js +338 -42
  59. package/dist/tools/write-kit.js +1 -0
  60. package/dist/version.js +1 -1
  61. package/manifest.json +10 -2
  62. package/mint.yaml +3 -4
  63. package/package.json +1 -1
  64. package/server.json +2 -2
  65. package/skills/warapp-mcp/SKILL.md +73 -11
@@ -8,6 +8,7 @@ import { CHAT_CHANNELS, feedChatLines, fillFromFeed, mergeChatLines, oldestId, r
8
8
  import { advanceCursor, markedChannels, markNew, readChatCursor, unreadCounts, writeChatCursor, } from '../chat-cursor.js';
9
9
  import { parseGameId } from '../client.js';
10
10
  import { inGameId, inGameOf, playersByInGameId } from '../live.js';
11
+ import { decodeChatLinks, encodeChatLinks, hasChatLinkMarkers } from '../chat-links.js';
11
12
  import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
12
13
  import { carriesTeam } from '../teams.js';
13
14
  import { gameIdArg, readAnnotations, respond, UNTRUSTED_PREVIEW_NOTE, untrustedBody, untrustedDescription, untrustedText, } from './common.js';
@@ -23,6 +24,9 @@ import { AUTOMATED_CHAT_OFF, chatAutomationMode } from '../chat-automation.js';
23
24
  import { resolveTeams } from './team-source.js';
24
25
  const DEFAULT_LIMIT = 50;
25
26
  const MAX_CHAT_LENGTH = 2000;
27
+ /** The send preview's note on links: what goes out, and what is verified. */
28
+ const LINKS_NOTE = 'Each link goes out as the client\'s token (`<a t=ID>` territory, `<a b=ID>` bonus) and players see the name from ' +
29
+ 'the map. Territory and bonus links are verified live (2026-11-23).';
26
30
  /** The UNVERIFIED notes a chat result carries, by source. */
27
31
  export const CHAT_SOURCE_NOTES = {
28
32
  web: "Read from the web client's GameRefresh reply; its channel, recipient and turn fields come from the client " +
@@ -270,7 +274,7 @@ export async function markChatSeen(ctx, gameId, me, read, cursor, channels) {
270
274
  }
271
275
  const playerOf = (players, byInGame, id) => byInGame.get(id) ?? players.find((p) => p.id === id);
272
276
  /** A line as the tool shows it: players by GameFeed id, names and the text delimited. */
273
- export function shown(line, isNew, players, byInGame, me) {
277
+ export function shown(line, isNew, players, byInGame, me, map) {
274
278
  let from = null;
275
279
  let fromId = null;
276
280
  if (line.sender !== null) {
@@ -286,10 +290,13 @@ export function shown(line, isNew, players, byInGame, me) {
286
290
  const p = playerOf(players, byInGame, line.to);
287
291
  to = { id: p?.id ?? null, name: p ? untrustedText(p.name) : null };
288
292
  }
293
+ // Territory and bonus links (`<a t=ID>` / `<a b=ID>`): rendered as their names, listed in `links`.
294
+ const decoded = decodeChatLinks(line.text, map);
289
295
  return {
290
296
  from,
291
297
  fromId,
292
- text: untrustedBody(line.text),
298
+ text: untrustedBody(decoded.text),
299
+ ...(decoded.links.length ? { links: decoded.links.map((l) => ({ ...l, name: l.name === null ? null : untrustedText(l.name) })) } : {}),
293
300
  ...(line.time !== undefined ? { time: line.time } : {}),
294
301
  turn: line.turn,
295
302
  channel: line.channel,
@@ -360,7 +367,7 @@ export function registerChatTools(server, ctx, opts = {}) {
360
367
  const picked = read.lines.map((l, i) => [l, fresh[i], i]).filter(([l]) => wanted(l));
361
368
  // #415: each message another player sent is labelled, and an unread one advised on (this machine's logs only).
362
369
  const reading = chatReader(read.lines, game, me, await chatAdviceContext(ctx, game, me));
363
- const messages = picked.slice(-n).map(([l, isNew, i]) => ({ ...shown(l, isNew, game.players, byInGame, me), ...readingFields(reading(i, isNew)) }));
370
+ const messages = picked.slice(-n).map(([l, isNew, i]) => ({ ...shown(l, isNew, game.players, byInGame, me, game.map), ...readingFields(reading(i, isNew)) }));
364
371
  const marked = mark_seen
365
372
  ? await markChatSeen(ctx, game.id, me, read, cursor, channel === undefined || channel === 'all' ? [...CHAT_CHANNELS] : [channel])
366
373
  : undefined;
@@ -422,6 +429,10 @@ export function registerChatTools(server, ctx, opts = {}) {
422
429
  'advances the agreement, a notice moves it to notice-by-me); warapp_submit_turn warns when later orders break one. ' +
423
430
  'Pass `automated: true` for a reply the owner did not tell you to send (e.g. an advice\'s `send`): it is refused ' +
424
431
  'unless WARAPP_CHAT_AUTOMATION is on (off by default: the owner sends replies), and even then it is confirm-gated. ' +
432
+ 'Link a territory or bonus as players see it in the official client with `[[t:<id or name>]]` / `[[b:<id or name>]]` ' +
433
+ 'in the message, or set `link_territories` to link every territory name it mentions: names resolve against the ' +
434
+ "game's map (exact, case-insensitive; an unknown or shared name is refused, listing the ids), and the preview shows " +
435
+ 'the message as rendered with its `links`. ' +
425
436
  `${CONFIRM_INJECTION_RULE}`,
426
437
  annotations: toolAnnotations({
427
438
  title: 'Send a war.app chat message',
@@ -432,7 +443,17 @@ export function registerChatTools(server, ctx, opts = {}) {
432
443
  }),
433
444
  inputSchema: z.object({
434
445
  game_id: gameIdArg,
435
- message: z.string().trim().min(1).max(MAX_CHAT_LENGTH).describe('The message text.'),
446
+ message: z
447
+ .string()
448
+ .trim()
449
+ .min(1)
450
+ .max(MAX_CHAT_LENGTH)
451
+ .describe('The message text. `[[t:<id or name>]]` links a territory, `[[b:<id or name>]]` a bonus (shown as its name).'),
452
+ link_territories: z
453
+ .boolean()
454
+ .optional()
455
+ .describe('true: also link every whole-word mention of a territory name in the message, repeats included (the longest ' +
456
+ 'name where names overlap; never inside a [[…]] link). Default false.'),
436
457
  channel: z
437
458
  .enum(['public', 'team'])
438
459
  .optional()
@@ -448,7 +469,7 @@ export function registerChatTools(server, ctx, opts = {}) {
448
469
  .describe('true when you send a reply the owner did not tell you to send (an automated reply). Refused unless ' +
449
470
  'WARAPP_CHAT_AUTOMATION is on; default false (a send the owner asked for).'),
450
471
  }),
451
- async plan({ game_id, message, channel, to, commitments, automated }) {
472
+ async plan({ game_id, message, channel, to, commitments, automated, link_territories }) {
452
473
  // #415: an automated reply is refused with the gate off, before any request.
453
474
  const auto = automated === true;
454
475
  if (auto && (ctx.chatAutomation ?? chatAutomationMode(opts.env ?? process.env)) !== 'on') {
@@ -466,7 +487,17 @@ export function registerChatTools(server, ctx, opts = {}) {
466
487
  // Read the game for every message (#130): one GameFeed does not know is refused here. Its
467
488
  // settings say whether private messages are allowed. Commitments are checked on a plan: the map too.
468
489
  const promises = commitments?.length ? commitments : undefined;
469
- const feed = await ctx.client.getGame(gameId, { map: promises !== undefined, settings: true });
490
+ // Territory and bonus links resolve against the map (src/chat-links.ts); a message with none goes as written.
491
+ const linking = link_territories === true || hasChatLinkMarkers(message);
492
+ const feed = await ctx.client.getGame(gameId, { map: promises !== undefined || linking, settings: true });
493
+ const linked = linking ? encodeChatLinks(message, mapOf(feed), { linkTerritories: link_territories === true }) : undefined;
494
+ const links = linked?.links.length ? linked : undefined;
495
+ const text = links ? links.wire : message;
496
+ if (text.length > MAX_CHAT_LENGTH) {
497
+ throw new McpToolError(`With its links the message is ${text.length} characters, over ${MAX_CHAT_LENGTH}: nothing was sent.`, {
498
+ hint: 'Shorten the message or link fewer places.',
499
+ });
500
+ }
470
501
  // The message goes out as whoever is signed in: bind that account, so an
471
502
  // approval given while one account was signed in never posts as another (#133:
472
503
  // refused when it cannot be read, as every write is).
@@ -543,7 +574,7 @@ export function registerChatTools(server, ctx, opts = {}) {
543
574
  payload: {
544
575
  method: 'SendChat',
545
576
  gameId,
546
- text: message,
577
+ text,
547
578
  channel: chatChannel,
548
579
  recipient: recipient?.id ?? null,
549
580
  ...(promised ? { commitments: promised.commitments } : {}),
@@ -562,6 +593,13 @@ export function registerChatTools(server, ctx, opts = {}) {
562
593
  : 'Other players will see this message; it cannot be unsent.',
563
594
  game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state },
564
595
  ...(shownRecipient ? { recipient: shownRecipient } : {}),
596
+ ...(links
597
+ ? {
598
+ rendered: untrustedBody(links.rendered),
599
+ links: links.links.map((l) => ({ ...l, name: l.name === null ? null : untrustedText(l.name) })),
600
+ linksNote: LINKS_NOTE,
601
+ }
602
+ : {}),
565
603
  ...(auto ? { automated: true, automatedNote: 'An automated reply (WARAPP_CHAT_AUTOMATION is on): the owner did not ask for this message.' } : {}),
566
604
  ...(promised
567
605
  ? {
@@ -578,7 +616,7 @@ export function registerChatTools(server, ctx, opts = {}) {
578
616
  },
579
617
  state: {
580
618
  gameId,
581
- text: message,
619
+ text,
582
620
  kind,
583
621
  channel: chatChannel,
584
622
  ...(recipient ? { recipient } : {}),
@@ -20,6 +20,7 @@ import { withTeammateOrders } from '../team-orders.js';
20
20
  import { assumedWarning, awardView, loadAward, openingThreat } from './award.js';
21
21
  import { readLedger } from '../relations-store.js';
22
22
  import { resolveIntel } from '../analysis/intel.js';
23
+ import { allyAttackLine, attacksOnAllies, modAllianceWarnings } from './mod-alliances.js';
23
24
  import { avoidPlayersArg, avoidTerritoriesArg, gameIdArg, graphOf, knownIncomeArg, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
24
25
  import { lookupMeta } from './hints.js';
25
26
  import { HEADROOM_COMPACT, headroomView, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
@@ -30,8 +31,11 @@ import { resolveTerritory } from './resolve.js';
30
31
  import { BELOW_PLAN_BASIS, boardHistory, bordersBelowPlan, currentTurn, truceRelations, friendsOf, guardOffWarnings, modsWarning, plannerSettings, requirePlayingSeat, requireTurnPhase, turnOrdersArg, } from './turn.js';
31
32
  import { resolveTeamsFor } from './team-source.js';
32
33
  import { stressOpponents } from './stress-opponents.js';
33
- import { COMMANDER_SIZING, commanderCheckOn } from './commander-check.js';
34
+ import { sanctionPercentage } from '../analysis/cards-in-effect.js';
35
+ import { COMMANDER_SIZING, commanderCheckOn, defaultFoggedCount, foggedAttackersArg, foggedCommanderOn, foggedCommanderText, myLargestStack } from './commander-check.js';
36
+ import { DEFAULT_FOGGED_ATTACKERS, foggedStack } from '../analysis/commander-fog.js';
34
37
  import { captureCheck, checkPlanLog } from './decision-capture.js';
38
+ import { farSummary, opponentScope } from '../analysis/scale.js';
35
39
  const VIEWS = ['compact', 'full'];
36
40
  const MAX_ENEMY_DEPLOY = 10_000;
37
41
  /** Replies listed beside the worst one on the compact view; the full view lists the stress test's own maximum. */
@@ -63,7 +67,9 @@ export const CHECK_PLAN_NOT_COVERED = [
63
67
  export function registerCheckPlanTool(server, ctx) {
64
68
  server.registerTool('warapp_check_plan', {
65
69
  title: 'Stress-test a planned turn in a war.app game',
66
- description: untrustedDescription('Stress-test a list of orders for your turn in an in-progress war.app (Warzone) game before you submit it: ' +
70
+ description: untrustedDescription('Stress-test a list of orders for your turn in an in-progress war.app (Warzone) game before you submit it ' +
71
+ '(in a game of more than 16 opponents, `unseenOpponents` lists only those near your land — `unseenOpponentsMore` ' +
72
+ 'counts the rest — and `scale` sums the opponents not in view or within 2 steps of your land): ' +
67
73
  'the orders (the `orders` array warapp_plan_turn returns, or your own edit of it) are carried out on the ' +
68
74
  'live board, turn rules included (deploys first, then attacks and transfers interleaved in the zigzag move ' +
69
75
  'order; each order an attack or a transfer by who holds its target when it runs; kill rates, the guard ' +
@@ -89,7 +95,10 @@ export function registerCheckPlanTool(server, ctx) {
89
95
  'board, `commander` says where it stands after the orders, the armies there and `needs`: the armies its ' +
90
96
  'territory needs to survive every reply tried, by the check warapp_submit_turn refuses on (each reply at the larger ' +
91
97
  'of the estimate and your income, enemy_deploy only raising it, both move orders, your Airlifts counted); when a ' +
92
- 'reply kills it, the summary starts with it. Exact with no luck and ' +
98
+ 'reply kills it, the summary starts with it. `commander.fogged` tests it against `fogged_attackers` (default as warapp_plan_turn: 2 in a Commanders free-for-all of eight or more players under fog, else off) ' +
99
+ 'unknown opponents the fog may hide within two moves of where it ends, striking together (each a start of the ' +
100
+ "game's starting armies, else your largest stack, plus a deploy of your income; luck-free): `safe`, `needs`, where " +
101
+ 'they may come from; the summary names it when it can fall, and it never changes `safe`. Exact with no luck and ' +
93
102
  'straight rounding; otherwise battles are resolved at their expectation and `exact` is false. It does not ' +
94
103
  `try: ${CHECK_PLAN_NOT_COVERED.join('; ')}. When this server kept your pick list, \`award\` says what the ` +
95
104
  "award of picks showed (as in warapp_plan_turn): the opponent's proven starts stand on the board the " +
@@ -98,7 +107,9 @@ export function registerCheckPlanTool(server, ctx) {
98
107
  '`headroom` lists, weakest first, each border of yours with the smallest single deploy by a neighbouring opponent that ' +
99
108
  'takes it after these orders, and what falls with it (the bonuses it breaks, the territories behind it and their bonus ' +
100
109
  'income). An opponent whose estimate one observation broke (see warapp_plan_turn) is tried at the larger of what it ' +
101
- 'implied and your own income (`enemyDeploy` source `untrusted`), said in the first warning. ' +
110
+ 'implied and your own income (`enemyDeploy` source `untrusted`), said in the first warning. Each `enemyDeploy` entry ' +
111
+ "shows the Reinforcement card the clock says it may hold apart as `cardBonus` (in `deploy` unless `assume_enemy_cards` is " +
112
+ '"none"; a progressive card\'s source in `cardBonusBasis`, as warapp_plan_turn has it) and, under Sanctions, `sanctionApplied` (its income before and after the cut). ' +
102
113
  '`belowPlan` compares these orders with the default plan made now on the same board (warapp_plan_turn with no ' +
103
114
  'options, the award of picks read as it reads it), or with its border guess when the deploys given are the ' +
104
115
  "guess's (`belowPlanAgainst`: plan or guess): each border they leave below what that plan leaves standing there, " +
@@ -107,7 +118,10 @@ export function registerCheckPlanTool(server, ctx) {
107
118
  'differ from the default plan by design. ' +
108
119
  'In a free-for-all with a truce in force (the agreement ledger), its partner is still tried — `safe` is safe ' +
109
120
  'against a break too — each reply that attacks a territory a truce covers is marked `breaksTruce`, and ' +
110
- '`safeIfTruceHolds` is the verdict over the other replies (null when every reply is a break). ' +
121
+ '`safeIfTruceHolds` is the verdict over the other replies (null when every reply is a break); a partner-approved ' +
122
+ 'truce exception on this turn opens its territories (no break) and is listed under `relations`. ' +
123
+ 'In a game running the Diplomacy 2 mod, an ally is such a truce too, and a warning names any order that attacks ' +
124
+ 'a territory an ally holds (the game skips it; its armies sit idle). ' +
111
125
  `Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on ` +
112
126
  'war.app; it never submits orders.'),
113
127
  _meta: lookupMeta(['check my plan', 'stress test my orders', 'what can my opponent do to this turn', 'is this plan safe']),
@@ -133,6 +147,10 @@ export function registerCheckPlanTool(server, ctx) {
133
147
  'observation has made its estimate untrusted, the larger of what it implied and your own income). ' +
134
148
  'Income in the fog is unseen, so raise it to test a stronger opponent.'),
135
149
  known_income: knownIncomeArg,
150
+ fogged_attackers: foggedAttackersArg.describe(`With your commander on the board: how many unknown opponents the fog may hide within two moves of where it ends ` +
151
+ `strike it together (default ${DEFAULT_FOGGED_ATTACKERS} in a free-for-all of eight or more players under fog, as warapp_plan_turn; else 0, which skips the test). Each is taken as a player's start ` +
152
+ "(the game's starting armies, else your largest stack) plus a deploy of your income. Reported as `commander.fogged`; " +
153
+ 'never changes `safe`.'),
136
154
  avoid_territories: avoidTerritoriesArg,
137
155
  avoid_players: avoidPlayersArg,
138
156
  first_mover: z
@@ -140,10 +158,16 @@ export function registerCheckPlanTool(server, ctx) {
140
158
  .optional()
141
159
  .describe('Who moves first this turn, when you know (under cyclic move order it alternates every turn). Omit to ' +
142
160
  'try both.'),
161
+ assume_enemy_cards: z
162
+ .enum(['none', 'clock'])
163
+ .optional()
164
+ .describe('"clock" (default): each opponent the Reinforcement card clock says may hold a card (one due, none of its plays ' +
165
+ 'seen since) deploys that card on top of its estimate; "none": the replies are sized without it. Each ' +
166
+ "`enemyDeploy` entry shows the card apart as `cardBonus`, so run both to see which risks rest on a guessed card."),
143
167
  view: viewArg(VIEWS, `compact (default) gives the verdict, the worst reply and up to ${COMPACT_OTHERS} more; "full" adds every ` +
144
168
  'reply listed, each order\'s result unanswered and the rules assumed.'),
145
169
  }),
146
- }, async ({ game_id, player, orders, enemy_deploy, known_income, avoid_territories, avoid_players, first_mover, view }) => {
170
+ }, async ({ game_id, player, orders, enemy_deploy, known_income, fogged_attackers, avoid_territories, avoid_players, first_mover, assume_enemy_cards, view }) => {
147
171
  const feed = await ctx.client.getGame(game_id, { settings: true });
148
172
  requireTurnPhase(feed);
149
173
  const map = mapOf(feed);
@@ -274,7 +298,9 @@ export function registerCheckPlanTool(server, ctx) {
274
298
  ignored.push('a card play other than Order Priority or Reinforcement');
275
299
  }
276
300
  }
277
- // The same per-opponent estimates warapp_plan_turn works from (stress-opponents.ts).
301
+ // The same per-opponent estimates warapp_plan_turn works from (stress-opponents.ts); an opponent's
302
+ // Reinforcement card the clock adds is on top unless `assume_enemy_cards` is "none".
303
+ const assumeCards = assume_enemy_cards ?? 'clock';
278
304
  const so = stressOpponents({
279
305
  graph,
280
306
  map,
@@ -291,6 +317,7 @@ export function registerCheckPlanTool(server, ctx) {
291
317
  ...(opening ? { opening } : {}),
292
318
  ...(mapPace ? { mapPace } : {}),
293
319
  ...(enemy_deploy !== undefined ? { enemyDeploy: enemy_deploy } : {}),
320
+ assumeCards,
294
321
  // #444: the stated incomes scale the other opponents' prior, as warapp_plan_turn has them.
295
322
  ...(intel.knownIncome?.length ? { known: intel.knownIncome } : {}),
296
323
  });
@@ -322,7 +349,7 @@ export function registerCheckPlanTool(server, ctx) {
322
349
  const opponents = so.opponents.map((o) => {
323
350
  const known = knownOf.get(o.id);
324
351
  if (known !== undefined)
325
- return { ...o, deploy: known + (o.card ?? 0) };
352
+ return { ...o, deploy: known + (assumeCards === 'none' ? 0 : (o.card ?? 0)) };
326
353
  const untrusted = untrustedOf.get(o.id);
327
354
  return enemy_deploy !== undefined || untrusted === undefined ? o : { ...o, deploy: Math.max(untrusted, o.deploy) };
328
355
  });
@@ -334,8 +361,10 @@ export function registerCheckPlanTool(server, ctx) {
334
361
  // `income` is the board's, card armies out — the same figure warapp_plan_turn passes.
335
362
  // PLAN-TEAMS D3: a Diplomacy card in effect that the decoder is sure of is a truce here in any format
336
363
  // (T9: the game enforces it). Its player stays among the opponents too: the decoder is unverified.
337
- const truces = (await truceRelations(ctx, { game, me, turn, graph, board: seen, boards: history.boards, myIncome: income, tracks, diplomacy: effect.diplomacy }))
338
- ?.relations ?? [];
364
+ // T9 too: a Diplomacy 2 mod alliance (read only in a game that runs the mod) is a truce the game enforces.
365
+ const resolvedTruces = await truceRelations(ctx, { game, me, turn, graph, board: seen, boards: history.boards, myIncome: income, tracks, diplomacy: effect.diplomacy });
366
+ const truces = resolvedTruces?.relations ?? [];
367
+ const modRead = resolvedTruces?.mod;
339
368
  const binding = truces.filter((r) => !friend(r.player) &&
340
369
  (r.enforced
341
370
  ? r.enforcedUntil === undefined || turn === null || turn < r.enforcedUntil
@@ -560,7 +589,22 @@ export function registerCheckPlanTool(server, ctx) {
560
589
  // The count and `needs` come from one run (the commander check's), so the line never pairs a count
561
590
  // the full run found with armies the targeted run says hold.
562
591
  const commanderLine = guard ? commanderText(guard, guard.killers) : undefined;
592
+ // Part 5 (mega game): my commander against unknown opponents in the fog striking it together (report only).
593
+ const fogged = guard
594
+ ? foggedCommanderOn({
595
+ graph,
596
+ board,
597
+ me: me.id,
598
+ settings,
599
+ deploys,
600
+ moves,
601
+ count: fogged_attackers ?? defaultFoggedCount(game),
602
+ stack: foggedStack(game.settings?.initialPlayerArmiesPerTerritory, myLargestStack(board, me.id)),
603
+ deploy: income,
604
+ })
605
+ : undefined;
563
606
  const summary = (guard && (guard.killers > 0 || guard.lostUnanswered) && commanderLine ? `${commanderLine} ` : '') +
607
+ (fogged && !fogged.safe ? `${foggedCommanderText(fogged)} ` : '') +
564
608
  (report.safe === null
565
609
  ? `Nothing could be tested this turn: no opposing stack in view touches you.${blind}${ahead}`
566
610
  : report.safe
@@ -588,6 +632,8 @@ export function registerCheckPlanTool(server, ctx) {
588
632
  const o = board.territories.find((t) => t.territoryId === id)?.owner;
589
633
  return o?.kind === 'player' ? o.playerId : undefined;
590
634
  };
635
+ // A Diplomacy 2 ally's territory (owner at the start of the turn): the game skips the attack, its armies sit idle.
636
+ const allyHits = modRead ? attacksOnAllies(modRead, moves, ownerOf) : [];
591
637
  const avoidedHits = [...new Set(moves.map((m) => m.to))].filter((to) => !mine.has(to) && (avoidT.has(to) || avoidP.has(ownerOf(to) ?? Number.NaN)));
592
638
  const warnings = [
593
639
  // The owner, 2026-11-17: while an older build stands in for a client this server cannot read, say so first.
@@ -596,6 +642,13 @@ export function registerCheckPlanTool(server, ctx) {
596
642
  ...(avoidedHits.length
597
643
  ? [`These orders attack ${avoidedHits.map((t) => name(t)).join(', ')}, which you asked to avoid (avoid_territories / avoid_players).`]
598
644
  : []),
645
+ ...(allyHits.length
646
+ ? [
647
+ `These orders attack a Diplomacy 2 ally — ${allyHits.map((a) => allyAttackLine(a, (t) => name(t).name)).join('; ')}: ` +
648
+ 'the game skips each such attack and its armies sit idle this turn (warapp_submit_turn refuses it unless attack_ally is true).',
649
+ ]
650
+ : []),
651
+ ...(modRead ? modAllianceWarnings(modRead) : []),
599
652
  // #275 (b): an untrusted estimate is the first thing said (not under an explicit enemy_deploy).
600
653
  ...(enemy_deploy === undefined ? tripwireWarnings(trip.tripwires, (w) => untrustedOf.get(w.player) ?? untrustedDeploy(w, income), (p) => estimates.find((x) => x.playerId === p)?.estimate) : []),
601
654
  ...(award ? assumedWarning(award) : []),
@@ -627,7 +680,20 @@ export function registerCheckPlanTool(server, ctx) {
627
680
  : []),
628
681
  ];
629
682
  const atRiskList = (rows) => rows.slice(0, LIST_MAX);
683
+ // Scale: a large game (more than LARGE_GAME_OPPONENTS opponents) lists only the opponents near my land and
684
+ // sums the rest in `scale`; every other game is unchanged.
685
+ const scope = opponentScope(graph, seen, me.id, opponents.map((o) => o.id));
686
+ const inScope = (p) => !scope.large || scope.near.includes(p);
630
687
  return respond(view, VIEWS, (rung) => ({
688
+ ...(scope.large
689
+ ? {
690
+ scale: {
691
+ opponents: scope.near.length + scope.far.length,
692
+ near: scope.near.length,
693
+ far: farSummary(scope.far, (p) => opponents.find((o) => o.id === p)?.deploy),
694
+ },
695
+ }
696
+ : {}),
631
697
  game: { id: game.id, name: game.name ?? null, turn },
632
698
  player: { id: me.id, name: me.name },
633
699
  safe: report.safe,
@@ -646,6 +712,18 @@ export function registerCheckPlanTool(server, ctx) {
646
712
  }
647
713
  : {}),
648
714
  summary,
715
+ // Partner-approved truce exceptions on this turn: normal targets (mine), or open to the partner (theirs).
716
+ ...(binding.some((r) => r.exceptions?.length)
717
+ ? {
718
+ relations: binding
719
+ .filter((r) => r.exceptions?.length)
720
+ .map((r) => ({
721
+ player: who(r.player),
722
+ ...(r.agreement ? { agreement: r.agreement } : {}),
723
+ exceptions: r.exceptions.map((e) => ({ direction: e.direction, territories: e.territories.map(name) })),
724
+ })),
725
+ }
726
+ : {}),
649
727
  exact: report.exact,
650
728
  // Where the teams came from (GameFeed, else the game list), in a team game only.
651
729
  ...(teamSource !== 'none' ? { teamSource } : {}),
@@ -666,10 +744,21 @@ export function registerCheckPlanTool(server, ctx) {
666
744
  player: { id: o.id, name: playerName.get(o.id) ?? String(o.id) },
667
745
  deploy: o.deploy,
668
746
  source: enemy_deploy !== undefined ? 'enemy_deploy' : knownOf.has(o.id) ? 'known_income' : untrustedOf.has(o.id) ? 'untrusted' : 'estimate',
747
+ // The Reinforcement card the clock says it may hold, apart: in `deploy` under assume_enemy_cards "clock" only.
748
+ ...(o.cardBonus !== undefined && enemy_deploy === undefined
749
+ ? { cardBonus: o.cardBonus, ...(o.cardBonusBasis !== undefined ? { cardBonusBasis: o.cardBonusBasis } : {}) }
750
+ : {}),
751
+ // Sanctions on it: its estimate's income before and after the cut (the card left out).
752
+ ...(o.sanctioned?.applied && o.sanctioned.after !== undefined
753
+ ? { sanctionApplied: { player: o.id, percentage: sanctionPercentage(o.sanctioned.percentages), before: o.sanctioned.before, after: o.sanctioned.after } }
754
+ : {}),
669
755
  })),
756
+ // Whether the replies carry the card the clock adds (default "clock").
757
+ assumeEnemyCards: assumeCards,
670
758
  // #180: in a free-for-all, whether you lead (any two opponents are then tried together).
671
759
  leader,
672
- unseenOpponents: opponents.filter((o) => !inView.has(o.id)).map((o) => ({ id: o.id, name: playerName.get(o.id) ?? String(o.id) })),
760
+ unseenOpponents: opponents.filter((o) => !inView.has(o.id) && inScope(o.id)).map((o) => ({ id: o.id, name: playerName.get(o.id) ?? String(o.id) })),
761
+ ...(scope.large ? { unseenOpponentsMore: opponents.filter((o) => !inView.has(o.id) && !inScope(o.id)).length } : {}),
673
762
  plan: {
674
763
  captures: report.baseline.captured.map(name),
675
764
  failedAttacks: report.baseline.failed.map(name),
@@ -709,6 +798,21 @@ export function registerCheckPlanTool(server, ctx) {
709
798
  sizing: COMMANDER_SIZING,
710
799
  // A Blockade or Gift of its territory, which the check does not simulate (the submit refuses it).
711
800
  ...(checked.cards ? { cards: checked.cards } : {}),
801
+ // Part 5: against unknown opponents the fog may hide within two moves, striking together.
802
+ ...(fogged
803
+ ? {
804
+ fogged: {
805
+ text: foggedCommanderText(fogged),
806
+ safe: fogged.safe,
807
+ needs: fogged.needs,
808
+ armies: fogged.armies,
809
+ attackers: fogged.attackers,
810
+ from: fogged.from.map((f) => ({ territory: name(f.territory), ...(f.via !== undefined ? { via: name(f.via) } : {}), armies: f.armies })),
811
+ stack: fogged.stack,
812
+ deploy: fogged.deploy,
813
+ },
814
+ }
815
+ : {}),
712
816
  },
713
817
  }
714
818
  : {}),
@@ -0,0 +1,110 @@
1
+ // warapp_close_finished_game (#523): close out a finished game so the app's My Games stops listing it, gated on the
2
+ // user's confirmation. The client has no hide or remove call: when it shows a finished game's end-of-game window
3
+ // (Victory / Defeat, `EndGameWindowVM`) it sets my seat's SeenEndGameWindow and asks GetEndGameWindowData (85) — the
4
+ // only server call there, so the one that records the flag. The app's My Games is GetMyGames' Default list, which
5
+ // (read live 2026-11-23, read-only) holds finished games only while that flag is clear: of 37 finished games in the
6
+ // All list, the 18 unseen were all in Default and the 19 seen none. Parameters as UnCommit's (auth, int32 game id),
7
+ // from the bundle's writer; VERIFIED live 2026-11-23 (a finished game closed: confirmed by the games-list read-back; a second call refused it as already closed, nothing sent).
8
+ //
9
+ // It reaches no other player. Read back from GetMyGames (All): GameInfo field 20, `seenEndGame` (`closed`, confirmed);
10
+ // still clear or not listed is `unconfirmed`; no answer `unknown`, never resent.
11
+ import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
12
+ import { z } from 'zod';
13
+ import { parseGameId } from '../client.js';
14
+ import { holdsSeat } from '../player-states.js';
15
+ import { Method, writeGetEndGameWindowDataParams } from '../protocol/methods.js';
16
+ import { gameIdArg, shownAccount } from './common.js';
17
+ import { mintMeta } from './hints.js';
18
+ import { requireApprovedAccount, writeAccount } from './live-context.js';
19
+ import { BRIDGE_NOTE } from './live.js';
20
+ import { fetchMyGames } from './my-games.js';
21
+ import { defineGatedWrite, refuse, requireMe, sendAndVerify } from './write-kit.js';
22
+ /** The game's seen flag in my games list: `true` seen, `false` listed unseen, `undefined` not listed or unread. */
23
+ async function seenInList(ctx, gameId) {
24
+ try {
25
+ const g = (await fetchMyGames(ctx)).games.find((x) => x.id === gameId);
26
+ return g ? g.seenEndGame === true : undefined;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ export function registerCloseFinishedGameTool(server, ctx) {
33
+ defineGatedWrite(server, {
34
+ title: 'Close out a finished war.app game',
35
+ _meta: mintMeta('change', ['close finished game', 'hide finished game', 'remove from my games', 'clear ended game', 'dismiss defeat screen']),
36
+ }, {
37
+ name: 'warapp_close_finished_game',
38
+ description: "Close out a finished war.app (Warzone) game of yours so the app's My Games stops listing it — what viewing its " +
39
+ "Victory / Defeat window does: war.app's GetEndGameWindowData, which marks your seat SeenEndGameWindow (the app's " +
40
+ 'My Games lists a finished game only while that is clear). Reaches no other player and changes nothing in the ' +
41
+ 'game. Refuses a game not finished, one you did not play, and one already closed out. Reported `closed` only once ' +
42
+ 'your games list shows it seen; `unconfirmed` otherwise, `unknown` when war.app did not answer (never resend ' +
43
+ `blindly). Verified live: closing a finished game was confirmed by the games-list read-back. ${BRIDGE_NOTE} ${CONFIRM_INJECTION_RULE}`,
44
+ annotations: toolAnnotations({
45
+ title: 'Close out a finished war.app game',
46
+ readOnly: false,
47
+ destructive: false,
48
+ idempotent: true,
49
+ openWorld: true,
50
+ }),
51
+ inputSchema: z.object({ game_id: gameIdArg }),
52
+ async plan({ game_id }) {
53
+ const game = await ctx.client.getGame(parseGameId(game_id), { map: false });
54
+ const token = await requireMe(ctx);
55
+ if (game.state !== 'Finished') {
56
+ refuse(`Game ${game.id} is not finished (game state: ${game.state}), so there is nothing to close out and nothing was sent.`, 'Only a finished game leaves My Games this way.');
57
+ }
58
+ const seat = game.players.find((p) => p.id === token);
59
+ if (!seat || !holdsSeat(seat.state)) {
60
+ refuse(`You did not play game ${game.id} (no seat of yours there), so it is not in your games and nothing was sent.`, 'Check warapp_my_games.');
61
+ }
62
+ if ((await seenInList(ctx, game.id)) === true) {
63
+ refuse(`Game ${game.id} is already closed out: your games list shows its end-of-game window seen, so the app's My Games no longer lists it. Nothing was sent.`, 'If the app still shows it, refresh the app: its list is cached.');
64
+ }
65
+ return {
66
+ gate: {
67
+ action: 'warapp.close_finished_game',
68
+ summary: `Close out finished war.app game ${game.id} (mark its end-of-game window seen) so My Games stops listing it`,
69
+ account: writeAccount(seat.id),
70
+ target: game.id,
71
+ payload: { method: 'GetEndGameWindowData', gameId: game.id },
72
+ willSend: { game: game.id },
73
+ preview: {
74
+ note: 'Reaches no other player and changes nothing in the game; the game stays readable (warapp_get_game, its history).',
75
+ account: shownAccount(seat.name, seat.id),
76
+ game: { id: game.id, state: game.state, myState: seat.state ?? null },
77
+ verification: 'Verified live (2026-11-23).',
78
+ },
79
+ },
80
+ state: { gameId: game.id, me: seat.id },
81
+ };
82
+ },
83
+ async execute({ gameId, me }) {
84
+ await requireApprovedAccount(ctx, writeAccount(me));
85
+ const game = { id: gameId };
86
+ const check = 'Check warapp_my_games before doing anything else.';
87
+ return sendAndVerify({
88
+ send: async () => {
89
+ await ctx.rpc.call('GetEndGameWindowData', Method.GetEndGameWindowData, (w) => writeGetEndGameWindowDataParams(w, gameId));
90
+ },
91
+ unanswered: (failure) => ({
92
+ status: 'unknown',
93
+ outcome: 'unknown',
94
+ game,
95
+ warning: `war.app did not answer (${failure}), so the game may already be closed out. ${check}`,
96
+ }),
97
+ readBack: () => seenInList(ctx, gameId),
98
+ unreadable: () => ({ status: 'unconfirmed', outcome: 'unconfirmed', game, warning: check }),
99
+ classify: (seen) => seen === true
100
+ ? { status: 'closed', outcome: 'confirmed', game }
101
+ : {
102
+ status: 'unconfirmed',
103
+ outcome: 'unconfirmed',
104
+ game,
105
+ warning: `war.app accepted the request, but your games list ${seen === false ? 'still shows the end-of-game window unseen' : 'does not list the game'}. ${check}`,
106
+ },
107
+ });
108
+ },
109
+ });
110
+ }
@@ -4,8 +4,15 @@
4
4
  // larger of its estimate and my income (and enemy_deploy, a what-if floor; an untrusted opponent's at
5
5
  // least at the figure its #275 tripwire gave it, as the stress test sizes it), both move orders, the
6
6
  // free-for-all lead (#180), Order Priority and my Airlifts. No I/O: the callers load the boards.
7
+ import { z } from 'zod';
8
+ import { DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE } from '../analysis/combat.js';
9
+ import { defaultFoggedAttackers, foggedCommanderCheck } from '../analysis/commander-fog.js';
10
+ import { isTeamGame } from '../teams.js';
11
+ /** The most fogged attackers a caller may ask for. */
12
+ const MAX_FOGGED_ATTACKERS = 8;
7
13
  import { gameBaseIncome } from '../analysis/player.js';
8
- import { commanderSafety } from '../analysis/commander-safety.js';
14
+ import { commanderSafety, myCommanderTerritory } from '../analysis/commander-safety.js';
15
+ import { simulateTurn } from '../analysis/turn-sim.js';
9
16
  /**
10
17
  * Card plays that turn my territory over, which the commander check does not simulate (an Airlift it
11
18
  * does): played on a territory my commander stands on before or after my orders, they may lose it,
@@ -102,3 +109,75 @@ export function guessKeepsCommander(plan, guess) {
102
109
  return false;
103
110
  return guess.safety.killers <= plan.safety.killers && (!guess.safety.lostUnanswered || plan.safety.lostUnanswered);
104
111
  }
112
+ /**
113
+ * Part 5 (mega game): my commander after these orders (nobody answering) against `count` unknown
114
+ * opponents in the fog striking it together (`src/analysis/commander-fog.ts`): every fogged territory
115
+ * within two moves of where it ends may hide one, `stack` armies plus a whole deploy of `deploy` (my
116
+ * income). A report beside the commander check, never a refusal. Undefined when `count` is 0, my
117
+ * commander is not on the board, or no fogged territory is in reach.
118
+ */
119
+ export function foggedCommanderOn(a) {
120
+ if (a.count <= 0 || myCommanderTerritory(a.board, a.me) === undefined)
121
+ return undefined;
122
+ const after = simulateTurn({
123
+ graph: a.graph,
124
+ board: a.board,
125
+ deploys: a.deploys.map((d) => ({ player: a.me, territoryId: d.territoryId, armies: d.armies })),
126
+ orders: [{ player: a.me, orders: a.moves.map((m) => ({ ...m })) }],
127
+ moveOrder: [a.me],
128
+ settings: a.settings,
129
+ }).territories;
130
+ const at = [...after].find(([, t]) => t.commander === a.me)?.[0];
131
+ if (at === undefined)
132
+ return undefined;
133
+ const start = new Map(a.board.territories.map((t) => [t.territoryId, t]));
134
+ const view = {
135
+ mine: (t) => after.get(t)?.owner === a.me,
136
+ fogged: (t) => {
137
+ const st = start.get(t);
138
+ return !st || st.owner.kind === 'unknown' || (st.armies === null && !(st.owner.kind === 'player' && st.owner.playerId === a.me));
139
+ },
140
+ armies: (t) => {
141
+ const st = start.get(t);
142
+ return st && st.owner.kind !== 'unknown' && st.armies !== null ? (after.get(t)?.armies ?? st.armies) : null;
143
+ },
144
+ };
145
+ const c = foggedCommanderCheck(a.graph, view, at, after.get(at).armies, {
146
+ count: a.count,
147
+ stack: a.stackAt ?? a.stack,
148
+ deploy: a.deploy,
149
+ offensiveKillRate: a.settings.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE,
150
+ defensiveKillRate: a.settings.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE,
151
+ });
152
+ return c ? { ...c, stack: a.stack, deploy: a.deploy, ...(a.stackAt ? { likelyOnly: true } : {}) } : undefined;
153
+ }
154
+ /** The fogged check in one sentence (check_plan's summary and the plan's warning). */
155
+ export function foggedCommanderText(c) {
156
+ const n = c.attackers;
157
+ const each = c.likelyOnly
158
+ ? `each a deploy of ${c.deploy} plus ${c.stack} armies where a start could be or a player was last seen, else the territory's usual estimate`
159
+ : `each ${c.stack} armies plus a deploy of ${c.deploy}`;
160
+ return c.safe
161
+ ? `Your commander on territory ${c.territory} holds against ${n} unknown opponent${n === 1 ? '' : 's'} the fog may hide within two moves (${each}) striking together.`
162
+ : `Your commander on territory ${c.territory} (${c.armies} armies after your orders) could fall to ${n} unknown opponent${n === 1 ? '' : 's'} the fog may hide within two moves (territories ${c.from.map((f) => f.territory).join(', ')}; ${each}) striking together: it needs ${c.needs} there.`;
163
+ }
164
+ /** The `fogged_attackers` argument of warapp_plan_turn and warapp_check_plan (each tool describes its default). */
165
+ export const foggedAttackersArg = z.coerce.number().int().min(0).max(MAX_FOGGED_ATTACKERS).optional();
166
+ /**
167
+ * The default `fogged_attackers` of warapp_plan_turn and warapp_check_plan, one rule for both (#531):
168
+ * {@link defaultFoggedAttackers} on the game — 2 in a Commanders free-for-all of eight or more players
169
+ * still playing under fog, else 0 (off).
170
+ */
171
+ export function defaultFoggedCount(game) {
172
+ const s = game.settings;
173
+ return defaultFoggedAttackers({
174
+ commanders: !!s?.commanders,
175
+ fog: s?.fog !== undefined && s.fog !== 'NoFog',
176
+ teams: isTeamGame(game.players),
177
+ players: game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').length,
178
+ });
179
+ }
180
+ /** The most armies on one territory of mine on `board` (0 with none). */
181
+ export function myLargestStack(board, me) {
182
+ return board.territories.reduce((n, t) => (t.owner.kind === 'player' && t.owner.playerId === me ? Math.max(n, t.armies ?? 0) : n), 0);
183
+ }