@chrischall/warapp-mcp 0.1.0 → 0.3.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 (86) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -20
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +13214 -9759
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/direct/link.js +9 -5
  22. package/dist/direct/session.js +60 -6
  23. package/dist/direct/sign-in.js +296 -0
  24. package/dist/direct/transport.js +59 -24
  25. package/dist/finished-store.js +357 -0
  26. package/dist/hosted.js +6 -4
  27. package/dist/index.js +1 -1
  28. package/dist/lessons-store.js +356 -0
  29. package/dist/live.js +9 -0
  30. package/dist/map-details.js +127 -0
  31. package/dist/map-stats.js +14 -6
  32. package/dist/map-store.js +44 -6
  33. package/dist/my-games.js +44 -6
  34. package/dist/normalize.js +34 -2
  35. package/dist/notifications.js +143 -0
  36. package/dist/outlook-log.js +28 -1
  37. package/dist/player-record-store.js +2 -0
  38. package/dist/profile-store.js +61 -11
  39. package/dist/protocol/methods.js +86 -2
  40. package/dist/replay.js +16 -4
  41. package/dist/stats.js +26 -4
  42. package/dist/strategy/notes.js +64 -9
  43. package/dist/surrender-pending.js +126 -0
  44. package/dist/tools/accept-surrender.js +311 -0
  45. package/dist/tools/chat-inbox.js +17 -5
  46. package/dist/tools/chat-read-mark.js +179 -0
  47. package/dist/tools/chat.js +50 -8
  48. package/dist/tools/check-plan.js +1 -0
  49. package/dist/tools/commander-check.js +1 -0
  50. package/dist/tools/end-of-game.js +384 -0
  51. package/dist/tools/game.js +31 -6
  52. package/dist/tools/healthcheck.js +7 -1
  53. package/dist/tools/index.js +24 -8
  54. package/dist/tools/join-game.js +1 -1
  55. package/dist/tools/live-context.js +3 -1
  56. package/dist/tools/map-details.js +88 -0
  57. package/dist/tools/map-stats.js +15 -2
  58. package/dist/tools/map.js +10 -2
  59. package/dist/tools/my-games.js +78 -8
  60. package/dist/tools/notifications.js +484 -0
  61. package/dist/tools/open-games.js +5 -2
  62. package/dist/tools/opponents.js +14 -2
  63. package/dist/tools/past-games.js +94 -0
  64. package/dist/tools/picks.js +15 -2
  65. package/dist/tools/profile-opponents.js +1 -1
  66. package/dist/tools/profile-reads.js +3 -3
  67. package/dist/tools/push.js +72 -12
  68. package/dist/tools/session.js +50 -18
  69. package/dist/tools/sign-in.js +56 -0
  70. package/dist/tools/strategy.js +65 -8
  71. package/dist/tools/stress-opponents.js +1 -1
  72. package/dist/tools/surrender-pending.js +74 -0
  73. package/dist/tools/surrender.js +10 -3
  74. package/dist/tools/team-brief.js +1 -1
  75. package/dist/tools/team.js +2 -6
  76. package/dist/tools/turn.js +79 -15
  77. package/dist/tools/where.js +42 -17
  78. package/dist/tools/write-kit.js +16 -3
  79. package/dist/trend.js +145 -20
  80. package/dist/version.js +1 -1
  81. package/docs/examples/warapp-auth-flow.json +31 -0
  82. package/manifest.json +22 -2
  83. package/mint.yaml +44 -22
  84. package/package.json +3 -2
  85. package/server.json +2 -2
  86. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -1,10 +1,11 @@
1
1
  // Strategy notes (docs/PLAN-STRATEGY.md, S5): the community heuristics that fit a game's
2
- // profile, plus notes computed from its map. Read-only: one GameFeed read with a game,
3
- // none without. Also served as MCP resources: `warapp://strategy` (every general note)
2
+ // profile, plus notes computed from its map. Read-only: one GameFeed read with a game, and
3
+ // (#309) the live board for my seat when the signed-in account is seated in it; none without. Also served as MCP resources: `warapp://strategy` (every general note)
4
4
  // and `warapp://strategy/map/{mapId}` (a map this process has loaded).
5
5
  import { McpToolError } from '@chrischall/mcp-utils';
6
6
  import { ResourceTemplate } from '@modelcontextprotocol/server';
7
7
  import { z } from 'zod';
8
+ import { boardStateFromLive } from '../live.js';
8
9
  import { mapNotes, mapNotesMarkdown } from '../strategy/map-notes.js';
9
10
  import { feedProfile, generalNotes, hasCostlyBonus, NOTE_TOPICS, noteContext, notesFor, notesMarkdown, TOPIC_TITLES, } from '../strategy/notes.js';
10
11
  import { cardClock } from '../strategy/card-clock.js';
@@ -14,6 +15,7 @@ import { lookupMeta } from './hints.js';
14
15
  import { DEFAULT_TERRITORY_LIMIT, PICK_PHASE_STATE, pickSettings } from './picks.js';
15
16
  import { mapOf } from './map.js';
16
17
  import { currentTurn } from './turn.js';
18
+ import { FROZEN_TAB_HINT, loadLiveGame } from './live-context.js';
17
19
  const VIEWS = ['compact', 'full'];
18
20
  const STRATEGY_URI = 'warapp://strategy';
19
21
  const STRATEGY_MAP_URI = 'warapp://strategy/map/{mapId}';
@@ -75,8 +77,53 @@ function gameMapNotes(game, map) {
75
77
  : {}),
76
78
  });
77
79
  }
80
+ /**
81
+ * #309: the seat and board the profile is judged on. GameFeed's board for a game in progress carries
82
+ * no standing, so with GameFeed alone the phase never reads contact or late. When the signed-in
83
+ * account is seated and playing in a game being played, the live board is read (as warapp_plan_turn
84
+ * reads it; read-only, nothing kept) for that seat: `live`. Otherwise, or on any failure, GameFeed's
85
+ * standing as before — for the signed-in seat when it is known and still playing: `gamefeed`; when the
86
+ * live board read was tried and failed, `liveError` says why ({@link liveErrorText}). Never throws.
87
+ */
88
+ async function profileBoard(live, game) {
89
+ const feed = { source: 'gamefeed', ...(game.standing ? { board: game.standing } : {}) };
90
+ if (!live)
91
+ return feed;
92
+ try {
93
+ const token = await live.myInviteToken();
94
+ const seat = token === undefined ? undefined : game.players.find((p) => p.id === token);
95
+ if (!seat)
96
+ return feed;
97
+ // A seat that is out is judged as without an account: it has no opponents of its own.
98
+ if ((seat.state ?? 'Playing') !== 'Playing')
99
+ return feed;
100
+ if (game.state !== 'Playing')
101
+ return { ...feed, me: seat.id };
102
+ try {
103
+ const { territories } = await loadLiveGame(live, game);
104
+ return { source: 'live', me: seat.id, board: boardStateFromLive(territories, seat, game.players) };
105
+ }
106
+ catch (e) {
107
+ return { ...feed, me: seat.id, liveError: liveErrorText(e) };
108
+ }
109
+ }
110
+ catch {
111
+ return feed;
112
+ }
113
+ }
114
+ /** The longest reason `profile.liveError` gives before the frozen-tab hint. */
115
+ const LIVE_ERROR_MAX = 160;
116
+ /**
117
+ * Why the live board read failed, short: the error's message capped at {@link LIVE_ERROR_MAX}, with
118
+ * {@link FROZEN_TAB_HINT} after it when it was a bridged `/Services` timeout.
119
+ */
120
+ function liveErrorText(e) {
121
+ const message = (e instanceof Error ? e.message : String(e)).replace(/\s+/g, ' ').trim();
122
+ const short = message.length > LIVE_ERROR_MAX ? `${message.slice(0, LIVE_ERROR_MAX - 1)}…` : message;
123
+ return e instanceof McpToolError && e.hint === FROZEN_TAB_HINT ? `${short} ${FROZEN_TAB_HINT}` : short;
124
+ }
78
125
  const MAP_ONLY_NOTE = "Bonus values are the map's own; a game can override them (pass its game_id to see its values).";
79
- export function registerStrategyTool(server, client) {
126
+ export function registerStrategyTool(server, client, live) {
80
127
  server.registerTool('warapp_strategy', {
81
128
  title: 'war.app strategy notes for a game or a map',
82
129
  description: untrustedDescription('Strategy notes for war.app (Warzone), each a short heuristic in our own words with the community guide or ' +
@@ -85,7 +132,10 @@ export function registerStrategyTool(server, client) {
85
132
  'reading the game (fog, picks, counting armies), opening (picks and the first turns), timing (the order ' +
86
133
  'of orders within a turn), fighting (stacks in contact, ahead and behind) and the map. With `game_id`: ' +
87
134
  'the notes that fit the game (its format, phase, fog, move order, distribution, kill rates and the cards ' +
88
- 'in play, read from GameFeed — standing is left to warapp_plan_turn), its `cardClock` (per card: pieces, ' +
135
+ 'in play, read from GameFeed; the phase from your own seat on the live board when the signed-in account plays ' +
136
+ 'in the game, else from GameFeed, `profile.source` live or gamefeed, `profile.liveError` why the live board ' +
137
+ 'did not read — standing is left to warapp_plan_turn), ' +
138
+ 'its `cardClock` (per card: pieces, ' +
89
139
  'and the first turn it can be played, fastest and guaranteed) and map notes: bonuses ranked by value per ' +
90
140
  'army to take at its settings with their entry points, chokepoints, and in the picking stage income ' +
91
141
  "targets by turn from the pick advisor's opening over the territories the game lists as pickable. With " +
@@ -136,6 +186,7 @@ export function registerStrategyTool(server, client) {
136
186
  });
137
187
  }
138
188
  const s = game.settings;
189
+ const seen = await profileBoard(live, game);
139
190
  const profile = feedProfile({
140
191
  graph: graphOf(map),
141
192
  players: game.players.map((p) => ({
@@ -157,7 +208,8 @@ export function registerStrategyTool(server, client) {
157
208
  },
158
209
  turn: currentTurn(game),
159
210
  picking: game.state === PICK_PHASE_STATE,
160
- ...(game.standing ? { board: game.standing } : {}),
211
+ ...(seen.board ? { board: seen.board } : {}),
212
+ ...(seen.me !== undefined ? { me: seen.me } : {}),
161
213
  });
162
214
  // The map is the game's own (bonus overrides applied), so a bonus made negative here counts.
163
215
  const notes = notesFor(profile, topic, { ...noteContext(s), negativeBonus: hasCostlyBonus(graphOf(map)) });
@@ -166,9 +218,14 @@ export function registerStrategyTool(server, client) {
166
218
  return respond(view, VIEWS, (rung) => ({
167
219
  scope: 'game',
168
220
  game: { id: game.id, name: game.name ?? null, state: game.state, turn: currentTurn(game) },
169
- profile: rung === 'full'
170
- ? profile
171
- : { format: profile.format, opponents: profile.opponents, phase: profile.phase, standing: profile.standing },
221
+ // #309: `source` says which board the phase was read on: `live` (my seat's) or `gamefeed`;
222
+ // `liveError` why the live board, when tried, did not read (the GameFeed fallback stands).
223
+ profile: {
224
+ ...(rung === 'full'
225
+ ? { ...profile, source: seen.source }
226
+ : { format: profile.format, opponents: profile.opponents, phase: profile.phase, standing: profile.standing, source: seen.source }),
227
+ ...(seen.liveError !== undefined ? { liveError: seen.liveError } : {}),
228
+ },
172
229
  notes: notes.map(noteView(rung === 'full')),
173
230
  // When each card can first be in a hand, from the game's card settings (absent with no cards).
174
231
  ...(clock ? { cardClock: clock } : {}),
@@ -68,7 +68,7 @@ export function stressOpponents(input) {
68
68
  .sort((a, b) => a - b)
69
69
  .map((id) => {
70
70
  const e = estimates.find((x) => x.playerId === id);
71
- return { id, deploy: input.enemyDeploy ?? e?.estimate ?? base, base: e?.base ?? base };
71
+ return { id, deploy: input.enemyDeploy ?? e?.estimate ?? base, base: e?.base ?? base, ...(e?.card ? { card: e.card.armies } : {}) };
72
72
  });
73
73
  const teams = new Map();
74
74
  for (const p of game.players)
@@ -0,0 +1,74 @@
1
+ // Reading the surrenders pending in a game (#317), for warapp_my_games, warapp_wait_for_turn and
2
+ // warapp_plan_turn. A pending surrender lives only in the game details (src/surrender-pending.ts):
3
+ // one GameRefresh (39) asked for the details and not the chat. UNVERIFIED live.
4
+ //
5
+ // Never throws: a failed or unreadable read is `null` (unknown), never an empty list — an empty list
6
+ // is a game whose details were read and showed no surrender pending.
7
+ import { inGameOf } from '../live.js';
8
+ import { Method, writeGameRefreshParams } from '../protocol/methods.js';
9
+ import { pendingSurrenders, readGameDetailsSeats } from '../surrender-pending.js';
10
+ import { untrustedText } from './common.js';
11
+ /** Where the read comes from, for a result's note. */
12
+ export const SURRENDER_PENDING_NOTE = "Read from the game details (the web client's GameRefresh), UNVERIFIED live: a list is what the details showed " +
13
+ '(empty: no surrender pending); null means they could not be read, not that none is pending. owedByMe true: the ' +
14
+ 'player is waiting for you to accept its surrender. Accepting is the owner\'s decision (it hands that player\'s land ' +
15
+ 'on and can end the game).';
16
+ /** Game states in which a surrender can be pending. */
17
+ const IN_PLAY = new Set(['Playing', 'DistributingTerritories']);
18
+ /**
19
+ * Whether a pending surrender can matter to me in a game: it is being played or picked and my seat is
20
+ * still playing. Elsewhere no read is made (and the answer is `null`).
21
+ */
22
+ export function surrenderMayBePending(state, mySeatState) {
23
+ return IN_PLAY.has(state) && mySeatState === 'Playing';
24
+ }
25
+ /**
26
+ * Read the game details' seats: one GameRefresh for the details only. `undefined` when the reply is
27
+ * unreadable; a failed request (a timeout, a call not sent, a refusal) throws, so a caller that reads
28
+ * many times can stop asking (warapp_wait_for_turn: a frozen tab stalls every call until it times out).
29
+ */
30
+ export async function fetchDetailsSeats(ctx, gameId) {
31
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId, chat: false, nonChat: true, lobby: false }));
32
+ return readGameDetailsSeats(await ctx.bundle(), env.body);
33
+ }
34
+ /** {@link fetchDetailsSeats} that never throws: any failure is `undefined` (unknown). */
35
+ export async function readDetailsSeats(ctx, gameId) {
36
+ try {
37
+ return await fetchDetailsSeats(ctx, gameId);
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ /**
44
+ * The surrenders pending in a GameFeed game (`me`: my GameFeed seat), each with the player's GameFeed id
45
+ * and name; `null` when the details could not be read, or when no surrender can matter to me there (the
46
+ * game not being played or picked, or my seat out).
47
+ */
48
+ export async function readPendingSurrenders(ctx, game, me, read = (id) => readDetailsSeats(ctx, id)) {
49
+ if (!me || !surrenderMayBePending(game.state, me.state))
50
+ return null;
51
+ const seats = await read(game.id);
52
+ if (!seats)
53
+ return null;
54
+ const byInGame = new Map();
55
+ for (const p of game.players) {
56
+ const id = inGameOf(p);
57
+ if (id !== undefined)
58
+ byInGame.set(id, p);
59
+ }
60
+ return pendingSurrenders(seats, inGameOf(me), (id) => byInGame.get(id)?.id ?? null).map((p) => {
61
+ const player = byInGame.get(p.inGameId);
62
+ return { ...p, name: player ? untrustedText(player.name) : null };
63
+ });
64
+ }
65
+ /** The line a result leads with when a surrender waits on my acceptance; undefined when none does. */
66
+ export function surrenderOwedLine(pending) {
67
+ const owed = (pending ?? []).filter((p) => p.owedByMe === true);
68
+ if (!owed.length)
69
+ return undefined;
70
+ const who = owed.map((p) => `${p.name ?? 'a player'} (${p.player ?? `in-game ${p.inGameId}`})`).join(', ');
71
+ return (`A surrender is waiting for you to accept it: ${who} asked to surrender, and the game details show your ` +
72
+ 'acceptance still owed (read from the client bundle, UNVERIFIED live). Accepting is the owner\'s decision: ' +
73
+ 'ask before accepting, unless accepting simply wins the game.');
74
+ }
@@ -89,8 +89,8 @@ export function registerSurrenderTool(server, ctx) {
89
89
  description: 'Surrender a war.app (Warzone) game as the signed-in account: you lose it and cannot rejoin. When the ' +
90
90
  "game's InstantSurrender setting asks for acceptance (unread with more than two players: it may) the surrender " +
91
91
  'waits for the others to accept it (reported `pending`); `undo: true` takes back such a pending ' +
92
- 'surrender. The preview shows what bears on the decision: the outlook warapp_plan_turn last logged and ' +
93
- 'its basis, AI opponents, whether acceptance is needed (`acceptance.needed`: true, false, or null when the setting is unread and it may be), what your land becomes (AI or neutral) and ' +
92
+ 'surrender. The preview shows what bears on the decision: the outlook warapp_plan_turn last logged, ' +
93
+ 'its basis and its `evidence` (the incomes compared, how much of each opponent\'s frontier was read, `thin` when little), AI opponents, whether acceptance is needed (`acceptance.needed`: true, false, or null when the setting is unread and it may be), what your land becomes (AI or neutral) and ' +
94
94
  'opponents close to a boot. The game is read from GameFeed first (finished games and games you are not ' +
95
95
  'playing are refused) and the outcome is read back from GameFeed.' +
96
96
  `${noBrowserNote(ctx.hosted)} ${CONFIRM_INJECTION_RULE}`,
@@ -123,7 +123,14 @@ export function registerSurrenderTool(server, ctx) {
123
123
  // opponents, what my land becomes, and opponents close to a boot.
124
124
  const log = ctx.dataDir ? await readOutlookLog(ctx.dataDir, gameId, me) : undefined;
125
125
  const outlook = log?.latest
126
- ? { turn: log.latest.turn, state: log.latest.state, heldTurns: log.latest.heldTurns, basis: log.latest.basis }
126
+ ? {
127
+ turn: log.latest.turn,
128
+ state: log.latest.state,
129
+ heldTurns: log.latest.heldTurns,
130
+ basis: log.latest.basis,
131
+ // #304: the incomes compared and each opponent's frontier read; `thin` when the state rested on little.
132
+ ...(log.latest.evidence ? { evidence: log.latest.evidence } : {}),
133
+ }
127
134
  : { state: null, note: 'No outlook logged for this game: warapp_plan_turn records one each turn it plans.' };
128
135
  const aiOpponents = game.players
129
136
  .filter((p) => p.id !== me && p.state === PLAYING && (p.isAI || p.humanTurnedIntoAI))
@@ -67,7 +67,7 @@ export function registerTeamBriefTool(server, ctx) {
67
67
  const gameId = parseGameId(game_id);
68
68
  const identity = await ctx.myIdentity().catch(() => undefined);
69
69
  if (!identity)
70
- throw accountUnknown(ctx.hosted, 'your team brief cannot be read');
70
+ throw accountUnknown(ctx, 'your team brief cannot be read');
71
71
  const feed = await ctx.client.getGame(gameId, { settings: true });
72
72
  if (feed.state !== PLAYING && feed.state !== DISTRIBUTING) {
73
73
  throw new McpToolError(`Game ${feed.id} is not being picked or played (game state: ${feed.state}), so there is nothing to brief.`, {
@@ -11,7 +11,7 @@ import { z } from 'zod';
11
11
  import { visibleIncomeFor } from '../analysis/plan/shared.js';
12
12
  import { cardRules, handReadable, readHand } from '../cards.js';
13
13
  import { parseGameId } from '../client.js';
14
- import { boardStateFromLive, playersByInGameId } from '../live.js';
14
+ import { boardStateFromLive, inGameOf } from '../live.js';
15
15
  import { withTeammateOrders } from '../team-orders.js';
16
16
  import { carriesTeam, teammatesOf } from '../teams.js';
17
17
  import { handOwners } from './card-advice.js';
@@ -34,10 +34,6 @@ const NOTES = [
34
34
  ];
35
35
  const DISTRIBUTING = 'DistributingTerritories';
36
36
  const BOARD_STATES = new Set(['Playing', DISTRIBUTING]);
37
- /** A teammate's in-game id; `undefined` for a seat without a GameFeed player id (an AI). */
38
- function inGameOf(p) {
39
- return [...playersByInGameId([p]).keys()][0];
40
- }
41
37
  /**
42
38
  * A teammate's pick list: the live board's TeammateOrders entry first (V5), else GetTerritoryPicks with the
43
39
  * teammate's in-game id (V6). `null` is unknown — an AI seat, or a read war.app refused. Never throws.
@@ -71,7 +67,7 @@ export function registerTeamTool(server, ctx) {
71
67
  const gameId = parseGameId(game_id);
72
68
  const identity = await ctx.myIdentity().catch(() => undefined);
73
69
  if (!identity)
74
- throw accountUnknown(ctx.hosted, 'your team cannot be read');
70
+ throw accountUnknown(ctx, 'your team cannot be read');
75
71
  const read = await ctx.client.getGame(gameId, { settings: true, chat: true });
76
72
  const { game, source } = await resolveTeams(ctx, read);
77
73
  const me = game.players.find((p) => p.id === identity.token);
@@ -12,14 +12,15 @@ import { holdsBelowPlan } from '../analysis/hold-diff.js';
12
12
  import { guardCase } from '../analysis/profile.js';
13
13
  import { boardStateFromLive, inGameId, playersByInGameId } from '../live.js';
14
14
  import { checkMoveOptions, MOVE_MODES } from './order-options.js';
15
- import { AttackTransferMode, Method, UNVERIFIED_CARD_PLAYS, writeSendOrdersParams, } from '../protocol/methods.js';
15
+ import { AttackTransferMode, Method, TARGETED_CARD_PLAYS, UNVERIFIED_CARD_PLAYS, writeSendOrdersParams, } from '../protocol/methods.js';
16
16
  import { SERVER_ERROR_MESSAGES } from '../protocol/rpc.js';
17
17
  import { assumedWarning, awardView, firstMoverFor, loadAward, openingThreat } from './award.js';
18
18
  import { boardCardsInEffect, CARDS_IN_EFFECT_UNVERIFIED, sanctionMyIncome } from './card-effects.js';
19
19
  import { adviseCards, cardGame, cardPieceOption, handOwners, opponentCanHold, opponentReinforcement, TEAM_HAND } from './card-advice.js';
20
- import { currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText, viewArg, } from './common.js';
20
+ import { currentTurn, turnsCompleted, gameIdArg, graphOf, namer, readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText, viewArg, } from './common.js';
21
21
  import { lookupMeta, mintMeta } from './hints.js';
22
22
  import { chatSummary } from './chat.js';
23
+ import { readPendingSurrenders, surrenderOwedLine } from './surrender-pending.js';
23
24
  import { failureText, loadLiveGame, requireApprovedAccount, writeAccount } from './live-context.js';
24
25
  import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
25
26
  import { guessOrdersOf, guessView } from './guess-view.js';
@@ -27,6 +28,8 @@ import { guessSalt, peekGuessSalt } from '../guess-salt.js';
27
28
  import { recordProfile } from './profile-hook.js';
28
29
  import { confidentHabits, counterOf, neighboursOf, readOpponents } from './profile-reads.js';
29
30
  import { mapOf } from './map.js';
31
+ import { PACE_TURNS } from '../analysis/game-lessons.js';
32
+ import { mapRecordFor, paceView } from './past-games.js';
30
33
  import { defineGatedWrite, requireMySeat, sendAndVerify } from './write-kit.js';
31
34
  import { resolveBonus, resolveTerritory } from './resolve.js';
32
35
  import { checkCardFields, newCardPlaySeen, resolveCardTargets, } from './card-plays.js';
@@ -35,6 +38,7 @@ import { writeGameRecord } from '../replay.js';
35
38
  import { gameOutlook } from '../analysis/outlook.js';
36
39
  import { neutralizeSeats, seatEndRules, staticSeats } from '../analysis/static-seats.js';
37
40
  import { cardArmyCeiling, cardClock } from '../strategy/card-clock.js';
41
+ import { hasCostlyBonus, noteContext, notesFor } from '../strategy/notes.js';
38
42
  import { sinceLastTurn } from '../analysis/since-last.js';
39
43
  import { recordOutlook } from '../outlook-log.js';
40
44
  import { readPickRecord } from '../pick-list.js';
@@ -205,6 +209,11 @@ export function plannerSettings(s) {
205
209
  const bombFrom = cardClock(s)?.cards.find((c) => c.card === 'Bomb')?.firstPlayableTurn.fastest;
206
210
  if (bombFrom !== undefined && bombFrom !== null)
207
211
  out.bombFrom = bombFrom;
212
+ // #293 review: an opponent's fixed Reinforcement card on the clock (no hand here: a progressive one
213
+ // is unknown), which the observed deploy counts in its free income under Local Deployment.
214
+ const reinforcement = opponentReinforcement(s, []);
215
+ if (reinforcement)
216
+ out.opponentReinforcement = reinforcement;
208
217
  // AllowTransferOnly is deliberately not mapped: it toggles the per-order
209
218
  // "transfer only" mode, while every planned move is sent as AttackTransfer
210
219
  // (mode 3), which transfers between my own territories in any game. The
@@ -401,6 +410,12 @@ export function validateTurn(args) {
401
410
  const t = standing.get(id);
402
411
  return t !== undefined && !t.fogged && t.owner === myInGameId;
403
412
  };
413
+ // #292: whether a move's armies arrive at its target, given the territories moves earlier in the
414
+ // list went into: Attack Only between my own territories and Transfer Only into one not mine move nothing.
415
+ const lands = (m, entered) => {
416
+ const ours = mine(m.to.id) || entered.has(m.to.id);
417
+ return m.mode === 'attack-only' ? !ours : m.mode === 'transfer-only' ? ours : true;
418
+ };
404
419
  // Under Multi-Attack a territory not mine at the start may move on once a move earlier in the list went in.
405
420
  const chained = new Set();
406
421
  if (args.multiAttack) {
@@ -410,7 +425,8 @@ export function validateTurn(args) {
410
425
  if (!mine(m.from.id) && !movedOut.has(m.from.id) && reached.has(m.from.id))
411
426
  chained.add(m.from.id);
412
427
  movedOut.add(m.from.id);
413
- reached.add(m.to.id);
428
+ if (lands(m, reached))
429
+ reached.add(m.to.id);
414
430
  }
415
431
  }
416
432
  // Deploys land before any attack, so only a move's source may be a territory captured earlier in the list.
@@ -505,32 +521,51 @@ export function validateTurn(args) {
505
521
  }
506
522
  // Walk the moves in order: each source's total sent so far against its armies, its deploys and,
507
523
  // under Multi-Attack, every army moved in earlier in the list (an attack, a transfer in, then
508
- // another attack is fine). Without Multi-Attack, armies moved in do not move on this turn.
524
+ // another attack is fine). Without Multi-Attack, armies moved in do not move on this turn, but
525
+ // one of them can stand guard (#292: the wiki's guard, turn-sim and the bundle's validator), so a
526
+ // source with an arrival earlier in the list may send all of its own — a warning, since whether
527
+ // war.app accepts it live is unverified.
509
528
  const sent = new Map();
510
529
  const inflow = new Map();
530
+ const arrived = new Map();
531
+ const guardedByArrival = new Map();
511
532
  let over;
533
+ const entered = new Set();
512
534
  for (const m of moves) {
513
535
  const start = chained.has(m.from.id) ? 0 : atMoves(m.from.id);
514
- const max = start + (inflow.get(m.from.id) ?? 0) - (args.guard ? 1 : 0);
536
+ const strict = start + (inflow.get(m.from.id) ?? 0) - (args.guard ? 1 : 0);
537
+ const arrivalGuard = args.guard && !args.multiAttack && (arrived.get(m.from.id) ?? 0) > 0;
538
+ const max = arrivalGuard ? start : strict;
515
539
  // A percentage order takes a share of what is left when it runs: it never over-sends, and what
516
540
  // it moves on is at most what the source could move (#165).
517
- const moved = m.percent ? Math.max(0, max - (sent.get(m.from.id) ?? 0)) : m.armies;
541
+ const moved = m.percent ? Math.max(0, strict - (sent.get(m.from.id) ?? 0)) : m.armies;
518
542
  if (!m.percent) {
519
543
  const armies = (sent.get(m.from.id) ?? 0) + m.armies;
520
544
  sent.set(m.from.id, armies);
521
545
  if (armies > max && !over)
522
- over = { from: m.from, armies, max };
546
+ over = { from: m.from, armies, max, arrivalGuard };
547
+ else if (armies > strict)
548
+ guardedByArrival.set(m.from.id, armies);
523
549
  }
550
+ if (!lands(m, entered))
551
+ continue;
552
+ entered.add(m.to.id);
524
553
  if (args.multiAttack)
525
554
  inflow.set(m.to.id, (inflow.get(m.to.id) ?? 0) + moved);
555
+ else if (moved > 0)
556
+ arrived.set(m.to.id, (arrived.get(m.to.id) ?? 0) + moved);
526
557
  }
527
558
  if (over) {
528
- const { from, armies, max } = over;
559
+ const { from, armies, max, arrivalGuard } = over;
529
560
  throw new McpToolError(`These orders send ${armies} armies from ${label(from)}, which can send at most ${max} this turn` +
530
- `${args.guard ? ' (one army stands guard)' : ''}` +
561
+ `${arrivalGuard ? ' (an army moved in earlier in the list may stand guard)' : args.guard ? ' (one army stands guard)' : ''}` +
531
562
  `${airlifted.has(from.id) ? ', counting this turn\'s Airlift' : ''}` +
532
563
  `${inflow.has(from.id) ? '; that counts every army moved in earlier in the list, an upper bound: an attack\'s survivors are fewer' : ''}.`, { hint: 'A territory sends at most its armies plus what is deployed there this turn.' });
533
564
  }
565
+ for (const [id, armies] of guardedByArrival)
566
+ warnings.push(`Territory ${id} sends all ${armies} of its own armies: this relies on an army moved in earlier in the list ` +
567
+ 'standing guard there, as the game rules allow (unverified live). If war.app keeps one of its own armies back, ' +
568
+ 'it may refuse the orders or send one fewer.');
534
569
  // No-Split moves the whole stack (#124: the wiki, and a live turn that left every source at 0):
535
570
  // an order for fewer armies still sends them all, so say what will actually move. A source captured
536
571
  // earlier in the list (Multi-Attack) is left out: the armies standing there at the start were the
@@ -889,7 +924,7 @@ export async function boardHistory(ctx, game, me, turn, opts = {}) {
889
924
  for (let k = Math.max(1, turn - CACHED_TURNS); k < turn; k++) {
890
925
  if (byTurn.has(k))
891
926
  continue;
892
- const board = boardFromHistory(withHistory.history, k - 1, game.players);
927
+ const board = boardFromHistory(withHistory.history, k - 1, game.players, withHistory.numberOfTurns !== undefined ? { numberOfTurns: withHistory.numberOfTurns } : {});
893
928
  if (board)
894
929
  byTurn.set(k, { source: 'history', board });
895
930
  }
@@ -1443,7 +1478,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1443
1478
  'warnings and the reasoning. Its `orders` array is exactly what warapp_submit_turn takes — review it with ' +
1444
1479
  'the user first. Every plan reads the game profile (`profile`: format 1v1/ffa/teams, phase, standing ' +
1445
1480
  'ahead/even/behind/unknown on income) and returns the `outlook` (winning/losing/even/stalemate from ' +
1446
- 'armies + 3 × income held over 3 turns of boards, with its `basis`; thresholds unmeasured, so advice, not a verdict; ' +
1481
+ 'armies + 3 × income held over 3 turns of boards, with its `basis` and `evidence`: the two incomes compared and how much of each opponent\'s frontier was read, `thin` when under half, so even is not safe; thresholds unmeasured, so advice, not a verdict; ' +
1447
1482
  'an opponent is bounded above by all it can have received (its start, or an even share of the map; each turn\'s most it could earn; ' +
1448
1483
  'a fixed Reinforcement card by the card clock) — a scenario\'s starts, a Gift card or a progressive Reinforcement card leave it unbounded, and then `winning` is never read; ' +
1449
1484
  'once winning or losing, payback tests count the turns the game has left instead of 10). With no `goal` the profile picks and tunes it (`goalSource` ' +
@@ -1518,6 +1553,11 @@ export function registerTurnTools(server, ctx, opts = {}) {
1518
1553
  '`reads` (opponent profiles, as warapp_profile_opponents reads them; reported only, the plan never uses them): ' +
1519
1554
  'each opponent in contact with a habit at the confidence bar or a label — its labels, `lastAttackTurn` (the last turn it attacked you), those habits with `n` and ' +
1520
1555
  '`basis`, `gamesMet` — a likelihood, never a certainty, and never to be quoted to another player. ' +
1556
+ '`surrenderPending` lists the surrenders other players asked for that are still pending (from the game details, ' +
1557
+ 'unverified live; null when they could not be read, never "none"), each with `owedByMe`; when one waits on your ' +
1558
+ 'acceptance the first warning says so. ' +
1559
+ '`pace` (after turns 4 and 8, when you have finished games on this map; reported only): your income beside the median ' +
1560
+ "winner's and your own past median there. " +
1521
1561
  `Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it never submits orders.`),
1522
1562
  _meta: lookupMeta(['plan my turn', 'warzone turn plan', 'what should i deploy', 'suggest my orders']),
1523
1563
  annotations: readAnnotations('Plan a war.app turn'),
@@ -1594,11 +1634,13 @@ export function registerTurnTools(server, ctx, opts = {}) {
1594
1634
  requirePlayingSeat(feed, seat);
1595
1635
  // The teams: GameFeed's, else the game list's (asked once per game, kept).
1596
1636
  const { game, me, source: teamSource, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
1597
- const [{ territories, info }, history, chat] = await Promise.all([
1637
+ const [{ territories, info }, history, chat, surrenders] = await Promise.all([
1598
1638
  loadLiveGame(ctx, game),
1599
1639
  boardHistory(ctx, game, me, turn),
1600
1640
  // Unread chat per channel (counts only), so the agent reads chat before it submits.
1601
1641
  chatSummary(ctx, game),
1642
+ // #317: a surrender waiting on my acceptance (the game details; null when unreadable). Never throws.
1643
+ readPendingSurrenders(ctx, game, me),
1602
1644
  ]);
1603
1645
  const setup = await livePlanSetup(ctx, {
1604
1646
  game, map, me, turn, territories, info, history, teamsKnown,
@@ -1858,11 +1900,23 @@ export function registerTurnTools(server, ctx, opts = {}) {
1858
1900
  ...(advised ? { orderPriority: true } : {}),
1859
1901
  });
1860
1902
  const guessOrders = guess ? guessOrdersOf(orders, guess) : undefined;
1903
+ // #317: a surrender waiting on my acceptance is the first thing said, before the commander's line.
1904
+ const owedLine = surrenderOwedLine(surrenders);
1905
+ if (owedLine)
1906
+ warnings.unshift(owedLine);
1907
+ // #312 E3: after turns 4 and 8, my income beside the pace my finished games on this map set
1908
+ // (reported only: read after the plan is made, never an input to it).
1909
+ const paceRecord = PACE_TURNS.includes(turnsCompleted(game))
1910
+ ? await mapRecordFor(ctx.dataDir, opts.env, game.settings?.mapId)
1911
+ : undefined;
1912
+ const pace = paceRecord && paceRecord !== 'unreadable' ? paceView(paceRecord, turnsCompleted(game), myIncome) : undefined;
1861
1913
  return respond(view, VIEWS, (rung) => ({
1862
1914
  game: { id: game.id, name: game.name ?? null, turn: currentTurn(game) },
1863
1915
  player: { id: me.id, name: me.name },
1864
1916
  // Part A1: messages not yet marked seen (warapp_get_chat reads them); absent when no chat can be read.
1865
1917
  ...(chat ? { chat } : {}),
1918
+ // #317: the surrenders pending (the game details; null: unreadable, never "none").
1919
+ surrenderPending: surrenders,
1866
1920
  goal: plan.goal,
1867
1921
  goalSource: goal !== undefined ? 'explicit' : 'profile',
1868
1922
  // #276: the guard case first, on or off, with what it means for interior defence.
@@ -1876,8 +1930,16 @@ export function registerTurnTools(server, ctx, opts = {}) {
1876
1930
  ...(plan.profile.standingSource === 'tracked' ? { standingSource: 'tracked' } : {}),
1877
1931
  ...(plan.profile.endsWith !== null ? { endsWith: plan.profile.endsWith } : {}),
1878
1932
  },
1933
+ // #309: full only — the ids of the strategy notes this plan's own profile matches (warapp_strategy
1934
+ // serves their text). Reported only: the plan never reads them.
1935
+ ...(rung === 'full'
1936
+ ? { notes: notesFor(plan.profile, undefined, { ...noteContext(game.settings), negativeBonus: hasCostlyBonus(graph) }).map((n) => n.id) }
1937
+ : {}),
1879
1938
  // #178: the outlook and its basis; full adds each turn judged.
1880
- outlook: rung === 'full' ? outlook : { state: outlook.state, basis: outlook.basis },
1939
+ // #304: the compact view keeps what the state rests on beside it (`evidence`).
1940
+ outlook: rung === 'full'
1941
+ ? outlook
1942
+ : { state: outlook.state, basis: outlook.basis, ...(outlook.evidence ? { evidence: outlook.evidence } : {}) },
1881
1943
  // Part D: the opponent reads (reported only, never planned on); absent when none is at the bar.
1882
1944
  ...(reads?.length
1883
1945
  ? {
@@ -1893,6 +1955,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
1893
1955
  }
1894
1956
  : {}),
1895
1957
  income,
1958
+ // #312 E3: the pace beside my income after turns 4 and 8 (my finished games on this map).
1959
+ ...(pace ? { pace } : {}),
1896
1960
  // #253: the army cap's arithmetic (min(income, round(cap × income) − my armies on the board)), when the game has one.
1897
1961
  ...(setup.incomeCap ? { incomeCapped: setup.incomeCap } : {}),
1898
1962
  enemyDeploy: plan.enemyDeploy,
@@ -2205,7 +2269,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2205
2269
  '(`target`), Surveillance (`bonus`), Airlift (`from` yours, `to` yours or a teammate\'s, `armies`, optional ' +
2206
2270
  '`commander`), Gift (`target` yours, `player`), Diplomacy (`players`: two), Sanctions (`player`), Bomb (`target` ' +
2207
2271
  "next to yours, not yours or a teammate's) and Emergency Blockade (`target` yours, never your commander's), encoded " +
2208
- 'as the client does but not yet verified live, each refused where war.app would refuse it (a commander is never ' +
2272
+ 'as the client does (the Airlift verified live; the others not yet), each refused where war.app would refuse it (a commander is never ' +
2209
2273
  'gifted or airlifted to a teammate, no Spy or Sanctions on yourself or a teammate, no Diplomacy between ' +
2210
2274
  'teammates); discards any card (`{ kind: "discard", card }`); refuses ' +
2211
2275
  'when your hand is over the hold limit and the orders do not play or discard enough cards; in a team game warns ' +
@@ -2366,7 +2430,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2366
2430
  seen: newCardPlaySeen(),
2367
2431
  };
2368
2432
  for (const p of plays) {
2369
- if (UNVERIFIED_CARD_PLAYS.has(p.kind))
2433
+ if (TARGETED_CARD_PLAYS.has(p.kind))
2370
2434
  p.targets = resolveCardTargets(p.kind, p.card.name, p.input, cardContext);
2371
2435
  }
2372
2436
  // An Emergency Blockade (phase 37) turns its territory neutral before an Airlift (phase 43) runs.