@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
@@ -9,10 +9,11 @@
9
9
  // (the partner's record, D5, is what the board and the ledger showed, never what it said); nothing is
10
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
11
  // `untrustedText`; the host's description is shown as untrusted text for the agent to read.
12
+ import { modRelationsView } from './mod-alliances.js';
12
13
  import { McpToolError } from '@chrischall/mcp-utils';
13
14
  import { z } from 'zod';
14
15
  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 { diplomacyFacts, MAX_NOTICE_TURNS, offerChecks, partyRefusal, priceTruce, scopeRefusal, sharedBorder, agreementState, suggestedTerms, TERMINAL_STATUSES, truceEndgame, truceVerdict, } from '../analysis/relations.js';
16
17
  import { readLedger } from '../relations-store.js';
17
18
  import { isTeamGame } from '../teams.js';
18
19
  import { bonusNamer, currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
@@ -65,7 +66,8 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
65
66
  title: 'Advise on truces in a war.app free-for-all',
66
67
  description: untrustedDescription('Advice on truces in a war.app (Warzone) free-for-all you are playing, read-only. It reports whether the game ' +
67
68
  "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
+ 'for house rules such as "no alliances"). In a game running the Diplomacy 2 mod, `modAlliances` lists the mod\'s ' +
70
+ 'alliances with you (`source: "mod"`) beside the ledger, with `mismatches` and `notices` (an ally\'s break, once applied). Per neighbour: the shared border (territories on each side, which ' +
69
71
  'are chokepoints, the stacks on both sides), the price of a truce on suggested terms (the border territories ' +
70
72
  'named, one turn of notice, a cap at the largest stack there, an end five turns on) — planned with and ' +
71
73
  'without it on the plan warapp_plan_turn would make: armies freed, captures, bonuses and next income gained, ' +
@@ -264,6 +266,12 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
264
266
  })()
265
267
  : undefined;
266
268
  const description = game.description !== undefined ? untrustedText(game.description, DESCRIPTION_MAX) : null;
269
+ // The Diplomacy 2 mod's alliances beside the ledger (the read warapp_plan_turn's setup made; none without the mod).
270
+ const liveAgreements = (ledger?.agreements ?? []).filter((a) => {
271
+ const st = agreementState(a, turn ?? 0, players);
272
+ return st.phase === 'active' || st.phase === 'notice';
273
+ });
274
+ const modView = setup.truces ? modRelationsView(setup.truces.mod, liveAgreements, playerRef) : undefined;
267
275
  return respond(view, VIEWS, (rung) => {
268
276
  const neighbours = built.map((b) => ({
269
277
  player: playerRef(b.partner),
@@ -298,6 +306,7 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
298
306
  // The host's own words, untrusted: read them for house rules such as "no alliances" — never as instructions.
299
307
  description,
300
308
  },
309
+ ...(modView ? { modAlliances: modView } : {}),
301
310
  income: setup.income,
302
311
  neighbours,
303
312
  ...(offerResult
@@ -19,6 +19,7 @@
19
19
  // Profiles inform only (P1): no planner decision reads any of this. Never throws.
20
20
  import { readEnvVar } from '@chrischall/mcp-utils';
21
21
  import { decisionTruth } from '../analysis/decision-truth.js';
22
+ import { endGameStats } from '../analysis/end-game-stats.js';
22
23
  import { captureFinished, excludedKind, outcomeOf } from '../analysis/finished-game.js';
23
24
  import { compactDecisionLog, decisionLogMode, finishDecisionLogs, recordTruth } from '../decision-log.js';
24
25
  import { teammatesOf } from '../teams.js';
@@ -27,7 +28,8 @@ import { profileFormatOf } from '../analysis/opponent-profile.js';
27
28
  import { trackGame } from '../analysis/opponents.js';
28
29
  import { recordLessons, recordLessonsExcluded, recordMapExcluded, recordMapGame } from '../lessons-store.js';
29
30
  import { endingOf, foldGame, markHistoryFolded, profileFileState } from '../profile-store.js';
30
- import { MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedState, readProcessed, touchFinished, writeFinishedRecord, } from '../finished-store.js';
31
+ import { MAX_FINISHED_RECORDS, finishedPath, finishedRecordOf, markProcessed, readFinishedRecord, readFinishedState, readProcessed, storedStats, touchFinished, writeFinishedRecord, } from '../finished-store.js';
32
+ import { playerKey } from '../player-record-store.js';
31
33
  import { withPathLock } from '../path-lock.js';
32
34
  import { finalOutlookOf, readOutlookLog } from '../outlook-log.js';
33
35
  import { readPickRecord } from '../pick-list.js';
@@ -45,6 +47,19 @@ import { keptTeams } from './team-source.js';
45
47
  import { plannerSettings } from './turn.js';
46
48
  /** Finished games the warapp_my_games sweep processes per call (each one GameFeed history read). */
47
49
  export const END_OF_GAME_PER_CALL = 2;
50
+ export const END_STATS_NOTE = "From the game's history, as the client's end-of-game screen defines them: produced = every army deployed (card armies included); lost = its armies killed attacking and defending; killed = armies it killed attacking (neutrals included: killedNeutral) and defending; highestIncome = the most board income it had (cards and the army cap aside). `series` are the client's All Graphs: armies, territories and income per history board from the start (the line stops when the seat left), deployed per turn, and cumulative luck, offensiveLuck and defensiveLuck from 0.";
51
+ /** The record's stats with the keys put back to `players`' ids (a key is never reversed: matched). */
52
+ function statsView(rec, salt, players, me) {
53
+ if (!rec.stats)
54
+ return undefined;
55
+ const out = [];
56
+ for (const p of players) {
57
+ const s = rec.stats.players[playerKey(salt, p.id)];
58
+ if (s)
59
+ out.push({ playerId: p.id, ...(p.id === me ? { me: true } : {}), ...s });
60
+ }
61
+ return { turnsRead: rec.stats.turnsRead, note: END_STATS_NOTE, players: out };
62
+ }
48
63
  const SAFE = /^[a-z_]{1,40}$/;
49
64
  /** Bound on the in-process memos below (oldest forgotten first). */
50
65
  const MEMO_LIMIT = 1000;
@@ -130,7 +145,9 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
130
145
  await closeOnly();
131
146
  return { status: 'record-unreadable' };
132
147
  }
133
- if (state !== 'missing' && (!opts.retry || state.status === 'captured' || !opts.history))
148
+ if (state !== 'missing' && state.status === 'captured')
149
+ return await keptOrBackfilled(dataDir, path, salt, me, opts.history ?? seen, opts.history);
150
+ if (state !== 'missing' && (!opts.retry || !opts.history))
134
151
  return { status: 'already-processed' };
135
152
  // The one history read: the caller's, else one request, sent once (no transport retry) and never retried.
136
153
  let game = opts.history;
@@ -187,8 +204,10 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
187
204
  const processed = history && game ? await processHistory(dataDir, env, salt, me, gameId, game, history) : undefined;
188
205
  // #412: the decision log's truth (from the full history, before any cut) and its compaction.
189
206
  await closeDecisionLog(dataDir, env, me, gameId, game ?? shown, history && game ? history : undefined);
207
+ const view = shown ? statsView(record, salt, shown.players, me) : undefined;
190
208
  return {
191
209
  status: record.status,
210
+ ...(view ? { stats: view } : {}),
192
211
  ...(record.turns ? { turns: record.turns.length } : {}),
193
212
  ...(record.failure ? { failure: record.failure } : {}),
194
213
  ...(processed ? { processed } : {}),
@@ -210,6 +229,39 @@ export async function endOfGame(deps, gameId, me, seen, opts = {}) {
210
229
  return { status: 'failed' };
211
230
  }
212
231
  }
232
+ /**
233
+ * #523: a captured record, already processed: its stats shown when it keeps them; else, given a read WITH the
234
+ * history (an explicit `include_history` call, never a trigger), the stats computed from that read and added to the
235
+ * record (`backfilled`) — nothing else is re-run (no profile fold, map record, lessons or decision-log truth), so
236
+ * nothing is counted twice. Called under the record's path lock. Never throws (an unreadable record: as kept).
237
+ */
238
+ async function keptOrBackfilled(dataDir, path, salt, me, shown, history) {
239
+ const rec = await readFinishedRecord(path);
240
+ if (typeof rec === 'string')
241
+ return { status: 'already-processed' };
242
+ const players = shown?.players ?? [];
243
+ if (rec.stats || !history || history.state !== 'Finished') {
244
+ const view = statsView(rec, salt, players, me);
245
+ return { status: 'already-processed', ...(view ? { stats: view } : {}) };
246
+ }
247
+ try {
248
+ const stats = endGameStats(history.history, history.players);
249
+ if (!stats || !('read' in historyReport(history)))
250
+ return { status: 'already-processed' };
251
+ const boards = historyBoards(history.history, history.players, history.numberOfTurns !== undefined ? { numberOfTurns: history.numberOfTurns } : {});
252
+ const map = history.map ? mapOf(history) : undefined;
253
+ const c = capture(history, me, boards, new Map(), map ? graphOf(map) : undefined, undefined);
254
+ if (!c)
255
+ return { status: 'already-processed' };
256
+ const next = { ...rec, stats: storedStats(stats, c, (id) => playerKey(salt, id)) };
257
+ await writeFinishedRecord(dataDir, path, next);
258
+ const view = statsView(next, salt, history.players, me);
259
+ return { status: 'already-processed', backfilled: 'stats', ...(view ? { stats: view } : {}) };
260
+ }
261
+ catch {
262
+ return { status: 'already-processed' };
263
+ }
264
+ }
213
265
  /** The record of one pass: the capture when the history read, else what the reads that came say. */
214
266
  async function buildRecord(dataDir, salt, me, gameId, read, shown, failure) {
215
267
  const pick = await readPickRecord(dataDir, gameId, me);
@@ -252,8 +304,10 @@ async function buildRecord(dataDir, salt, me, gameId, read, shown, failure) {
252
304
  const graph = map ? graphOf(map) : undefined;
253
305
  const captured = capture(read, me, boards, orders, graph, facts.leftTurn);
254
306
  const kinds = kindsOf(read, me, captured, facts);
307
+ // #523: the per-player stats from the same history (its orders), no further request.
308
+ const stats = endGameStats(read.history, read.players);
255
309
  return {
256
- record: finishedRecordOf({ ...common, status: 'captured', layout: report.read.layout, noMap: !map, capture: captured, boards, kinds }),
310
+ record: finishedRecordOf({ ...common, status: 'captured', layout: report.read.layout, noMap: !map, capture: captured, boards, kinds, stats }),
257
311
  history: { capture: captured, boards, orders, graph, kinds },
258
312
  };
259
313
  }
@@ -81,7 +81,8 @@ export function registerGameTool(server, client, dir, env, identity) {
81
81
  'lastTurnTime, whose meaning is unverified). Optional game history and chat. ' +
82
82
  'A game I lost says how (`howLost`), once finished or, while the others play on, once my seat is out (eliminated, ' +
83
83
  'booted or surrendered): a surrender or boot by my state, with the last turn played here and the last logged outlook ' +
84
- '(its state, my income and armies against the strongest opponent\'s in view); an elimination from the boards ' +
84
+ '(its state, my income and armies against the strongest opponent\'s in view, with its tracked income, frontier read ' +
85
+ 'and calibrated income range when logged, and the strongest on income when another opponent); an elimination from the boards ' +
85
86
  'this server cached while it played — the turn (certain only when it is the newest completed turn), my commander\'s territory ' +
86
87
  'that fell with what it held, the attackers that needed and who bordered it (at a commander walk\'s destination, ' +
87
88
  'which may instead have fallen before the walk ran), or else my last territories (inferred, never seen). ' +
@@ -89,9 +90,12 @@ export function registerGameTool(server, client, dir, env, identity) {
89
90
  'else from the boards cached then — a backfill; no other request), as warapp_profile_opponents reads them. ' +
90
91
  'A finished game of mine also gets its end-of-game pass once (`endOfGame`: its history read once — one more ' +
91
92
  'request — and kept name-free for later games: the outcome, my picks, every player\'s income and bonuses by turn, ' +
92
- 'what stood where my attacks failed — then folded into the opponent profiles, the map\'s record and the lessons ' +
93
+ 'what stood where my attacks failed, and every player\'s end-of-game screen (`endOfGame.stats`: armies produced, lost ' +
94
+ 'and killed, highest income, cards, and the All Graphs series — armies, territories, income, deployed and luck per ' +
95
+ 'turn; shown on every later read) — then folded into the opponent profiles, the map\'s record and the lessons ' +
93
96
  '(`endOfGame.processed`); a failed read is recorded and not retried, except by a call with ' +
94
- '`include_history`, which re-runs it from that read). ' +
97
+ '`include_history`, which re-runs it from that read and adds the stats to a game processed before them ' +
98
+ '(`backfilled`). To take a finished game off the app\'s My Games use warapp_close_finished_game. ' +
95
99
  'For the map\'s bonuses and chokepoints use warapp_get_map. Read-only.'),
96
100
  _meta: lookupMeta(['warzone game', 'war.app game', 'whose turn is it', 'game status']),
97
101
  annotations: readAnnotations('Get a war.app game'),
@@ -94,6 +94,31 @@ function seatOut(result, byState, last, game) {
94
94
  ? `team ${s.team}`
95
95
  : untrustedText(game.players.find((p) => p.id === s.playerId)?.name ?? s.playerId)
96
96
  : undefined;
97
+ // #522: the incomes behind the visible bonus income — under fog a leader's in-view income can sit at the base
98
+ // while it earns several times that. Its tracked income and frontier read (#304's evidence), and the
99
+ // calibrated range when the outlook's income side (#436) is the same side.
100
+ const nameOf = (side) => side.team !== undefined ? `team ${side.team}` : untrustedText(game.players.find((p) => p.id === side.playerId)?.name ?? side.playerId);
101
+ const sameSide = (a, b) => a.team !== undefined ? a.team === b.team : a.playerId === b.playerId && b.team === undefined;
102
+ const members = s ? (s.team !== undefined ? game.players.filter((p) => p.team === s.team).map((p) => p.id) : [s.playerId]) : [];
103
+ const trackedRows = (entry.evidence?.opponents ?? []).filter((r) => members.includes(r.playerId) && r.source === 'tracked');
104
+ const tracked = trackedRows.length ? trackedRows.reduce((n, r) => n + r.income, 0) : undefined;
105
+ const coverage = s?.team === undefined && trackedRows.length === 1 ? trackedRows[0].coverage : undefined;
106
+ const inc = entry.income;
107
+ const estimate = s && inc && inc.playerId !== undefined && sameSide(s, inc)
108
+ ? { low: inc.low, high: inc.high, estimate: inc.estimate, calibrated: inc.calibrated }
109
+ : undefined;
110
+ // The strongest on income when it is another side: the surrender line's side anywhere (large games), else the outlook's own.
111
+ const leaderOf = () => {
112
+ const sur = entry.surrender;
113
+ if (sur)
114
+ return { ...sur, anywhere: true };
115
+ if (inc && inc.playerId !== undefined)
116
+ return { playerId: inc.playerId, ...(inc.team !== undefined ? { team: inc.team } : {}), low: inc.low, high: inc.high, estimate: inc.estimate, calibrated: inc.calibrated };
117
+ return undefined;
118
+ };
119
+ const leaderSide = leaderOf();
120
+ const leader = leaderSide && !(s && sameSide(s, leaderSide)) ? leaderSide : undefined;
121
+ const calText = (calibrated) => (calibrated ? "calibrated on past games' estimate ÷ truth" : 'uncalibrated');
97
122
  const outlook = {
98
123
  turn: loggedTurn,
99
124
  state: entry.state,
@@ -101,13 +126,51 @@ function seatOut(result, byState, last, game) {
101
126
  ...(entry.lean ? { lean: entry.lean } : {}),
102
127
  ...(held ? { held } : {}),
103
128
  ...(f ? { mine: f.mine } : {}),
104
- ...(s ? { strongest: { id: s.playerId, ...(s.team !== undefined ? { team: s.team } : {}), name: who, armies: s.armies, income: s.income } } : {}),
129
+ ...(s
130
+ ? {
131
+ strongest: {
132
+ id: s.playerId,
133
+ ...(s.team !== undefined ? { team: s.team } : {}),
134
+ name: who,
135
+ armies: s.armies,
136
+ income: s.income,
137
+ ...(tracked !== undefined ? { tracked } : {}),
138
+ ...(coverage !== undefined ? { coverage } : {}),
139
+ ...(estimate ? { estimate } : {}),
140
+ },
141
+ }
142
+ : {}),
143
+ ...(leader
144
+ ? {
145
+ incomeLeader: {
146
+ id: leader.playerId,
147
+ ...(leader.team !== undefined ? { team: leader.team } : {}),
148
+ name: nameOf(leader),
149
+ low: leader.low,
150
+ ...(leader.high !== undefined ? { high: leader.high } : {}),
151
+ estimate: leader.estimate,
152
+ calibrated: leader.calibrated,
153
+ ...(leader.anywhere ? { anywhere: true } : {}),
154
+ },
155
+ }
156
+ : {}),
105
157
  };
106
158
  const read = `${loggedTurn === turn ? 'its outlook' : `the last outlook logged (turn ${loggedTurn})`} read ${entry.lean ? `${entry.state}, leaning ${entry.lean} on the incomes` : entry.state}${held ? ` (held ${held.turns} turn${held.turns === 1 ? '' : 's'})` : ''}`;
107
- const figures = !f
108
- ? ' (the armies and income behind it were not logged then)'
109
- : `: my income ${f.mine.income} and ${f.mine.armies} armies${s ? ` against ${who}'s ${s.income} and ${s.armies} in view` : ', no opponent in view'}`;
110
- return { result, ...byState, turn, outlook, line: `${head}; ${read}${figures}.` };
159
+ const range = (low, high) => (high !== undefined && high > low ? `, range ${low}–${high}` : '');
160
+ const behind = [
161
+ tracked !== undefined ? `tracked ${tracked}${coverage != null ? `, ${Math.round(coverage * 100)}% of its frontier read` : ''}` : '',
162
+ estimate ? `estimated ~${estimate.estimate}${range(estimate.low, estimate.high)}, ${calText(estimate.calibrated)}` : '',
163
+ ].filter(Boolean);
164
+ const against = !s
165
+ ? ', no opponent in view'
166
+ : behind.length
167
+ ? ` against ${who}'s income ${s.income} in view (${behind.join('; ')}) and ${s.armies} armies in view`
168
+ : ` against ${who}'s ${s.income} and ${s.armies} in view`;
169
+ const figures = !f ? ' (the armies and income behind it were not logged then)' : `: my income ${f.mine.income} and ${f.mine.armies} armies${against}`;
170
+ const leaderText = leader
171
+ ? ` The strongest on income${leader.anywhere ? ', near or not' : ''}: ${nameOf(leader)}'s ~${leader.estimate} (tracked ${leader.low}${range(leader.low, leader.high)}; ${calText(leader.calibrated)}).`
172
+ : '';
173
+ return { result, ...byState, turn, outlook, line: `${head}; ${read}${figures}.${leaderText}` };
111
174
  }
112
175
  /**
113
176
  * How `game` was lost, when the account this server cached it for did not win it: once it is finished,
@@ -15,7 +15,7 @@ import { registerJoinGameTool } from './join-game.js';
15
15
  import { registerLiveTools } from './live.js';
16
16
  import { registerMapTool } from './map.js';
17
17
  import { registerMapStatsTool } from './map-stats.js';
18
- import { registerMyGamesTool } from './my-games.js';
18
+ import { fetchMyGames, registerMyGamesTool } from './my-games.js';
19
19
  import { registerNotificationTools } from './notifications.js';
20
20
  import { registerOpenGamesTool } from './open-games.js';
21
21
  import { registerOpponentsTool } from './opponents.js';
@@ -23,9 +23,11 @@ import { registerPickTools } from './picks.js';
23
23
  import { registerPushTools } from './push.js';
24
24
  import { registerRelationsTools } from './relations.js';
25
25
  import { registerDiplomacyTool } from './diplomacy.js';
26
+ import { registerModAlliancesTool } from './mod-alliances.js';
26
27
  import { registerRouteTool } from './route.js';
27
28
  import { registerScoutTool } from './scout.js';
28
29
  import { registerSessionTools } from './session.js';
30
+ import { paceStatus } from './pace.js';
29
31
  import { registerStrategyTool } from './strategy.js';
30
32
  import { registerSurrenderTool } from './surrender.js';
31
33
  import { registerAcceptSurrenderTool } from './accept-surrender.js';
@@ -35,6 +37,7 @@ import { registerTurnTools } from './turn.js';
35
37
  import { registerMyOrdersTool } from './my-orders.js';
36
38
  import { registerUncommitTool } from './uncommit.js';
37
39
  import { registerLeaveGameTool } from './leave-game.js';
40
+ import { registerCloseFinishedGameTool } from './close-finished-game.js';
38
41
  import { registerWhereTool } from './where.js';
39
42
  import { registerStateTools } from './state.js';
40
43
  import { blobStoreFromEnv } from '@chrischall/mcp-utils/export';
@@ -108,6 +111,7 @@ export function registerAllTools(server, deps = {}) {
108
111
  registerOpenGamesTool(server, live);
109
112
  registerJoinGameTool(server, live);
110
113
  registerLeaveGameTool(server, live);
114
+ registerCloseFinishedGameTool(server, live);
111
115
  registerSurrenderTool(server, live);
112
116
  registerAcceptSurrenderTool(server, live);
113
117
  registerBeginTurnTool(server, live);
@@ -135,6 +139,7 @@ export function registerAllTools(server, deps = {}) {
135
139
  registerRelationsTools(server, live, deps.env ? { env: deps.env } : {});
136
140
  // B3: truce advice (read-only): prices a deal by planning with and without it; reads no chat.
137
141
  registerDiplomacyTool(server, live, deps.env ? { env: deps.env } : {});
142
+ registerModAlliancesTool(server, live);
138
143
  // One push socket per process: keyed on the shared fetchproxy bridge so
139
144
  // connections share it, with requests routed through the direct-first bridge.
140
145
  // While the direct leg is active the push rides a direct WebSocket (the
@@ -155,6 +160,21 @@ export function registerAllTools(server, deps = {}) {
155
160
  },
156
161
  pushTransport: () => push.status().transport,
157
162
  decoder: () => live.decoderReport(),
163
+ // Pace (owner decision 2026-11-23): with no game list read yet in this process, read it now (one request).
164
+ pace: async (now, mayRead) => {
165
+ const kept = paceStatus(live, now);
166
+ if (kept)
167
+ return kept;
168
+ if (!mayRead)
169
+ return { error: 'No game list read yet in this process, and no working direct session to read one without the browser bridge: call warapp_my_games.' };
170
+ try {
171
+ await fetchMyGames(live);
172
+ }
173
+ catch (e) {
174
+ return { error: (e instanceof Error ? e.message : String(e)).slice(0, 200) };
175
+ }
176
+ return paceStatus(live, Date.now());
177
+ },
158
178
  identityChanged: () => live.forgetIdentity(),
159
179
  hosted,
160
180
  ...(env ? { env } : {}),
package/dist/tools/map.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { McpToolError } from '@chrischall/mcp-utils';
2
2
  import { z } from 'zod';
3
3
  import { analyzeBonuses, applyBonusOverrides, findChokepoints } from '../analysis/index.js';
4
+ import { bonusTerritories } from '../analysis/bonuses.js';
5
+ import { gameBaseIncome } from '../analysis/player.js';
4
6
  import { gameIdArg, graphOf, mapSummary, readAnnotations, respond, round2, untrustedDescription, untrustedText, viewArg } from './common.js';
5
7
  import { lookupMeta } from './hints.js';
6
8
  import { modeRow, withModeTerritories } from './map-details.js';
@@ -51,6 +53,39 @@ function detail(g, b) {
51
53
  }
52
54
  return out;
53
55
  }
56
+ /**
57
+ * The income map (mega-game spec part 3): only the bonuses that pay in this game (value > 0 after its
58
+ * `OverriddenBonuses`), each with its size and member territories (a superbonus's flattened), highest
59
+ * value first (then the smaller, then by id), and the base income every player gets on top. A bonus
60
+ * worth 0 or less is left out — it pays nothing here, though its territories can still be crossed.
61
+ */
62
+ export function incomeMap(g, settings, opts = {}) {
63
+ const paying = g.map.bonuses.filter((b) => b.value > 0);
64
+ const q = opts.bonus?.trim().toLowerCase();
65
+ const rows = paying
66
+ .filter((b) => !q || b.name.toLowerCase().includes(q))
67
+ .map((b) => ({ b, members: bonusTerritories(g, b.id) }))
68
+ .sort((x, y) => y.b.value - x.b.value || x.members.length - y.members.length || x.b.id - y.b.id);
69
+ const shown = opts.limit === undefined ? rows : rows.slice(0, opts.limit);
70
+ const per = settings?.bonusArmyPer ?? 0;
71
+ return {
72
+ baseIncome: gameBaseIncome(settings),
73
+ ...(per > 0 ? { territoriesPerArmy: per } : {}),
74
+ paying: paying.length,
75
+ notPaying: g.map.bonuses.length - paying.length,
76
+ bonusesShown: `${shown.length} of ${rows.length}`,
77
+ bonuses: shown.map(({ b, members }) => ({
78
+ bonusId: b.id,
79
+ name: b.name,
80
+ value: b.value,
81
+ size: members.length,
82
+ territories: named(g, members),
83
+ ...(b.bonusIds.length ? { memberBonuses: b.bonusIds.map((id) => ({ id, name: g.bonusById.get(id)?.name ?? String(id) })) } : {}),
84
+ })),
85
+ note: `Income each turn is the base income (${gameBaseIncome(settings)}${per > 0 ? `, or 1 per ${per} territor${per === 1 ? 'y' : 'ies'} held when that is more` : ''}) ` +
86
+ "plus every bonus listed here held whole, at the game's values (its overridden bonuses applied). Every other bonus pays nothing in this game; its territories can still be crossed.",
87
+ };
88
+ }
54
89
  function chokepoints(g, limit) {
55
90
  const all = findChokepoints(g);
56
91
  const bonusName = (id) => (id === null ? null : (g.bonusById.get(id)?.name ?? String(id)));
@@ -72,6 +107,10 @@ export function registerMapTool(server, client, live) {
72
107
  '`bonus` (part of a bonus name) to see one bonus\'s territories, borders and entry points by name. ' +
73
108
  'View "full" also lists the map\'s distribution modes with the territories each lets a player start on ' +
74
109
  '(read once from war.app\'s map details through the web-client channel (direct or bridge), then kept with the map; unknown is null). ' +
110
+ '`income_map: true` answers only the income map instead: the bonuses that pay in this game (value above 0 after the game\'s ' +
111
+ 'overridden bonus values; a bonus overridden to 0 pays nothing but can still be crossed), each with its value, size and member ' +
112
+ 'territories, highest value first, and the base income (MinimumArmyBonus) every player gets on top. ' +
113
+ 'Every view uses the game\'s overridden bonus values, not the map\'s defaults. ' +
75
114
  'Map-only — needs no board, so it works in a lobby. Read-only.'),
76
115
  _meta: lookupMeta(['warzone map', 'best bonuses', 'easiest bonus', 'chokepoints']),
77
116
  annotations: readAnnotations('Get a war.app map'),
@@ -82,16 +121,26 @@ export function registerMapTool(server, client, live) {
82
121
  .enum(['easiest', 'value', 'name'])
83
122
  .optional()
84
123
  .describe('Bonus order: "easiest" (default — ease score = value / (territories + borders)), "value", or "name".'),
124
+ income_map: z
125
+ .boolean()
126
+ .optional()
127
+ .describe("Only the income map: the bonuses that pay at this game's values, with members and size, and the base income (default false)."),
85
128
  limit: z.coerce.number().int().min(1).max(1000).optional().describe(`Max bonus rows (default ${DEFAULT_LIMIT} on compact; all on full).`),
86
129
  view: viewArg(VIEWS, `compact (default) keeps positive-value bonuses as one-line rows (counts, value per territory, score) and the top ${COMPACT_CHOKEPOINTS} chokepoints; ` +
87
130
  '"full" lists every bonus (zero and negative included) with member, border and entry-point territories by name, every chokepoint, ' +
88
131
  'and each distribution mode with its starting territory count and ids.'),
89
132
  }),
90
- }, async ({ game_id, bonus, sort, limit, view }) => {
133
+ }, async ({ game_id, bonus, sort, limit, view, income_map }) => {
91
134
  // Settings carry the game's overridden bonus values, which the bonus table reports.
92
135
  const game = await client.getGame(game_id, { settings: true });
93
136
  const map = mapOf(game);
94
137
  const g = graphOf(map);
138
+ if (income_map) {
139
+ return respond(undefined, ['compact'], () => ({
140
+ map: mapSummary(map),
141
+ incomeMap: incomeMap(g, game.settings, { ...(bonus ? { bonus } : {}), ...(limit !== undefined ? { limit } : {}) }),
142
+ }));
143
+ }
95
144
  // #328: only the full table lists the modes' starting territories, so only it may ask war.app for them.
96
145
  const modes = view === 'full' && !bonus?.trim() ? await withModeTerritories(live, map) : undefined;
97
146
  const order = SORTS[sort ?? 'easiest'];
@@ -0,0 +1,191 @@
1
+ // The Diplomacy 2 mod's alliances (mod 191) for the turn and diplomacy tools, and the read-only
2
+ // warapp_get_mod_alliances. Where the data lives and what the mod does: src/mod-alliances.ts. UNVERIFIED live.
3
+ //
4
+ // A game that does not run the mod (its GameFeed settings' mod ids, src/normalize.ts) costs nothing: no
5
+ // request, no change to any plan. In a game that does, one GameRefresh (details, no chat) per read.
6
+ // Never throws: a failed or unreadable read is `unreadable`, never "no alliance".
7
+ import { McpToolError } from '@chrischall/mcp-utils';
8
+ import { z } from 'zod';
9
+ import { inGameOf, playersByInGameId } from '../live.js';
10
+ import { Method, writeGameRefreshParams } from '../protocol/methods.js';
11
+ import { readMyOrderList } from '../my-orders.js';
12
+ import { allianceMismatches, allyAttacksIn, breakAlerts, breaksInOrders, diplomacy2From, modPairs, myAllies, readModData, runsDiplomacy2, } from '../mod-alliances.js';
13
+ import { currentTurn, gameIdArg, readAnnotations, respond, untrustedDescription, untrustedText } from './common.js';
14
+ import { lookupMeta } from './hints.js';
15
+ import { readLatestBoard } from './live-context.js';
16
+ import { BRIDGE_NOTE, resolveMe } from './live.js';
17
+ /** How every result that carries mod alliances says where they come from. */
18
+ export const MOD_ALLIANCES_NOTE = "Diplomacy 2 (mod 191) alliances, read from the game details (the web client's GameRefresh: the mod's public " +
19
+ 'data and your own), UNVERIFIED live: the format is the mod\'s published source and the client bundle, not yet ' +
20
+ 'checked against a game with an alliance in it. The game skips every attack between allies (owners at the start ' +
21
+ 'of the turn), both ways; a break is an order in the breaker\'s own turn that applies at its end, so an ally can ' +
22
+ 'attack from the next turn and no one else sees a break coming. Proposals you sent are in the other player\'s ' +
23
+ 'private data and are not shown; the mod keeps no turn for an alliance, only its order (`id`).';
24
+ /** One GameRefresh for the details; `undefined` when unreadable. Throws on a failed request. */
25
+ async function fetchDiplomacy2(ctx, gameId) {
26
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId, chat: false, nonChat: true, lobby: false }));
27
+ const data = readModData(await ctx.bundle(), env.body);
28
+ return data ? diplomacy2From(data) : undefined;
29
+ }
30
+ /**
31
+ * Diplomacy 2's alliances in `game` as `me` sees them. `no-mod` (no request) when the game's settings do not
32
+ * list the mod; `unreadable` when the request failed or the reply was not understood. Never throws.
33
+ */
34
+ export async function readModAlliances(ctx, game, me) {
35
+ if (!runsDiplomacy2(game.settings?.modIds))
36
+ return { status: 'no-mod' };
37
+ let state;
38
+ try {
39
+ state = await fetchDiplomacy2(ctx, game.id);
40
+ }
41
+ catch (e) {
42
+ return { status: 'unreadable', reason: e instanceof Error ? e.message : String(e) };
43
+ }
44
+ if (!state)
45
+ return { status: 'unreadable', reason: 'the game details carried no Diplomacy 2 data this server understands' };
46
+ const byInGame = playersByInGameId(game.players);
47
+ const feedOf = (inGame) => byInGame.get(inGame)?.id ?? null;
48
+ const mine = inGameOf(me);
49
+ const ids = mine === undefined ? [] : myAllies(state, mine);
50
+ const allies = ids.map(feedOf).filter((x) => x !== null);
51
+ return { status: 'read', state, me: mine, allies, unmapped: ids.length - allies.length, feedOf };
52
+ }
53
+ /** The warnings a turn tool adds for a mod-191 game (none for `no-mod`). */
54
+ export function modAllianceWarnings(read) {
55
+ if (read.status === 'no-mod')
56
+ return [];
57
+ if (read.status === 'unreadable')
58
+ return [
59
+ `This game runs the Diplomacy 2 mod, but its alliances could not be read (${read.reason}): no alliance is honoured ` +
60
+ 'here. An attack on an ally is skipped by the game and its armies sit idle — check the mod\'s menu in the web client.',
61
+ ];
62
+ const out = [];
63
+ if (read.unmapped)
64
+ out.push(`${read.unmapped} Diplomacy 2 ${read.unmapped === 1 ? 'ally' : 'allies'} could not be matched to a player in this game: not honoured.`);
65
+ const breaks = breakAlerts(read.state);
66
+ if (breaks.length)
67
+ out.push(`Notice: the Diplomacy 2 mod reports ${breaks.length === 1 ? 'a broken alliance' : `${breaks.length} broken alliances`} with you ` +
68
+ `(${breaks.map((b) => untrustedText(b.message)).join('; ')}). That player is an ordinary opponent now.`);
69
+ return out;
70
+ }
71
+ /** Each ally attack named for a person, by territory and player id. */
72
+ export const allyAttackLine = (a, name) => `move ${a.index + 1} attacks ${name(a.to)} from ${name(a.from)}, held by player ${a.ally} (a Diplomacy 2 ally)`;
73
+ /** The attacks of `moves` on my allies at the start of this turn (owners by GameFeed id on `ownerAt`). */
74
+ export function attacksOnAllies(read, moves, ownerAt) {
75
+ return read.status === 'read' ? allyAttacksIn(moves, new Set(read.allies), ownerAt) : [];
76
+ }
77
+ /**
78
+ * The mod's alliances beside the ledger's agreements (warapp_get_relations, warapp_advise_diplomacy): `undefined` in a
79
+ * game without the mod. `live`: the ledger's agreements active or in notice. `who`: a GameFeed id for the result.
80
+ */
81
+ export function modRelationsView(read, live, who) {
82
+ if (read.status === 'no-mod')
83
+ return undefined;
84
+ if (read.status === 'unreadable')
85
+ return { source: 'mod', read: false, reason: read.reason, alliances: null, note: MOD_ALLIANCES_NOTE };
86
+ const mine = read.me;
87
+ const alliances = read.state.alliances
88
+ .filter((a) => mine !== undefined && (a.proposer === mine || a.accepter === mine))
89
+ .sort((x, y) => x.id - y.id)
90
+ .flatMap((a) => {
91
+ const other = read.feedOf(a.proposer === mine ? a.accepter : a.proposer);
92
+ return other === null ? [] : [{ source: 'mod', player: who(other), proposedBy: a.proposer === mine ? 'me' : 'them', id: a.id }];
93
+ });
94
+ const mismatches = allianceMismatches(read.allies, live).map((m) => ({
95
+ player: who(m.player),
96
+ kind: m.kind,
97
+ ...(m.agreement ? { agreement: m.agreement } : {}),
98
+ line: m.kind === 'mod-only'
99
+ ? 'allied in the Diplomacy 2 mod with no agreement recorded: the game enforces it, but its terms (notice, until) are not in the ledger'
100
+ : 'an agreement is active or in notice but the mod shows no alliance: the game does not enforce it — the player may have broken the alliance, or it was never made in the mod',
101
+ }));
102
+ const notices = breakAlerts(read.state).map((a) => ({ id: a.id, message: untrustedText(a.message) }));
103
+ return {
104
+ source: 'mod',
105
+ read: true,
106
+ alliances,
107
+ ...(read.state.proposalsToMe.length
108
+ ? {
109
+ proposalsToMe: read.state.proposalsToMe.flatMap((p) => {
110
+ const from = read.feedOf(p.from);
111
+ return from === null ? [] : [{ player: who(from), id: p.id }];
112
+ }),
113
+ }
114
+ : {}),
115
+ mismatches,
116
+ // An ally's break shows only once it applied: the mod's alert to me, kept until the web client shows it.
117
+ ...(notices.length ? { notices } : {}),
118
+ note: MOD_ALLIANCES_NOTE,
119
+ };
120
+ }
121
+ /** warapp_get_mod_alliances. */
122
+ export function registerModAlliancesTool(server, ctx) {
123
+ server.registerTool('warapp_get_mod_alliances', {
124
+ title: 'Read Diplomacy 2 mod alliances in a war.app game',
125
+ description: untrustedDescription('The alliances of the "Diplomacy 2" mod (mod 191) in a war.app (Warzone) game that runs it: each pair with its ' +
126
+ '`state` — `allied` (the game skips every attack between them this turn), `breaking` (your own break order is ' +
127
+ 'entered this turn: it still holds this turn, and either side can attack from `endsTurn`) or `pending` (a ' +
128
+ 'proposal to you, not yet answered) — who `proposer` was, and `id`, the mod\'s counter (the order they were ' +
129
+ 'made in: the mod keeps no turn). Also `allies` (yours) and `alerts` (the mod\'s notices to you, such as a ' +
130
+ 'player who broke an alliance with you). UNVERIFIED live. Proposals you sent and an ally\'s break before it ' +
131
+ 'applies are not visible. Proposing, accepting, declining and breaking are manual only (the mod\'s menu in the ' +
132
+ `web client): no tool sends them. A game without the mod is refused. ${BRIDGE_NOTE} Read-only.`),
133
+ _meta: lookupMeta(['mod alliances', 'diplomacy 2', 'who is allied', 'alliance mod', 'my allies']),
134
+ annotations: readAnnotations('Read Diplomacy 2 alliances'),
135
+ inputSchema: z.object({ game_id: gameIdArg }),
136
+ }, async ({ game_id }) => {
137
+ const game = await ctx.client.getGame(game_id, { settings: true, map: false });
138
+ if (!runsDiplomacy2(game.settings?.modIds)) {
139
+ throw new McpToolError(`Game ${game.id} does not run the Diplomacy 2 mod (mod 191).`, {
140
+ hint: 'warapp_get_relations shows the agreements recorded with warapp_record_agreement.',
141
+ });
142
+ }
143
+ const me = await resolveMe(ctx, game.players, undefined);
144
+ const read = await readModAlliances(ctx, game, me);
145
+ if (read.status !== 'read') {
146
+ return respond(undefined, ['compact'], () => ({
147
+ game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state },
148
+ alliances: null,
149
+ warnings: modAllianceWarnings(read),
150
+ readNote: MOD_ALLIANCES_NOTE,
151
+ }));
152
+ }
153
+ const turn = currentTurn(game);
154
+ // My own break orders this turn (only while a turn is played: the orders live on the live board).
155
+ let breaksByMe = [];
156
+ const warnings = modAllianceWarnings(read);
157
+ if (game.state === 'Playing' && turn !== null && read.me !== undefined) {
158
+ try {
159
+ const { info } = await readLatestBoard(ctx, game.id);
160
+ breaksByMe = breaksInOrders(readMyOrderList(info) ?? []);
161
+ }
162
+ catch (e) {
163
+ warnings.push(`Your orders could not be read (${e instanceof Error ? e.message : String(e)}): a break you entered this turn would not show as breaking.`);
164
+ }
165
+ }
166
+ const who = (inGame) => {
167
+ const feed = read.feedOf(inGame);
168
+ const p = feed === null ? undefined : game.players.find((x) => x.id === feed);
169
+ return { id: feed, inGameId: inGame, name: p ? untrustedText(p.name) : null };
170
+ };
171
+ return respond(undefined, ['compact'], () => ({
172
+ game: { id: game.id, name: game.name === undefined ? null : untrustedText(game.name), state: game.state, turn },
173
+ player: { id: me.id, name: untrustedText(me.name) },
174
+ alliances: modPairs(read.state, read.me, turn, breaksByMe).map((p) => ({
175
+ players: p.players.map(who),
176
+ state: p.state,
177
+ proposer: who(p.proposer),
178
+ id: p.id,
179
+ ...(p.endsTurn !== undefined ? { endsTurn: p.endsTurn } : {}),
180
+ })),
181
+ allies: read.allies.map((id) => {
182
+ const p = game.players.find((x) => x.id === id);
183
+ return { id, name: p ? untrustedText(p.name) : null };
184
+ }),
185
+ alerts: read.state.alerts.map((a) => ({ id: a.id, message: untrustedText(a.message) })),
186
+ ...(warnings.length ? { warnings } : {}),
187
+ modDiplomacy: 'manual only: propose, accept, decline and break in the mod\'s menu in the web client.',
188
+ readNote: MOD_ALLIANCES_NOTE,
189
+ }));
190
+ });
191
+ }