@chrischall/warapp-mcp 0.25.0 → 0.27.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.
@@ -10,7 +10,7 @@ import { advanceCursor, markedChannels, markNew, readChatCursor, unreadCounts, w
10
10
  import { parseGameId } from '../client.js';
11
11
  import { inGameId, inGameOf, playersByInGameId } from '../live.js';
12
12
  import { decodeChatLinks, encodeChatLinks, hasChatLinkMarkers } from '../chat-links.js';
13
- import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeCreateGameGroupParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
13
+ import { CHAT_CHANNEL_PUBLIC, Method, writeGameRefreshParams, writeRetrieveChatParams, writeCreateGameGroupParams, writeRetrieveGameGroupMessageHistoryParams, writeRetrievePrivateMessageHistoryParams, writeSendChatParams, } from '../protocol/methods.js';
14
14
  import { carriesTeam } from '../teams.js';
15
15
  import { gameIdArg, readAnnotations, respond, UNTRUSTED_PREVIEW_NOTE, untrustedBody, untrustedDescription, untrustedText, } from './common.js';
16
16
  import { checkMessageCommitments, commitmentsArg, COMMITMENTS_NOTE, DEFAULT_PLAN_CHECKED } from './commitments.js';
@@ -194,9 +194,11 @@ export async function readChat(ctx, game, me) {
194
194
  if (me) {
195
195
  try {
196
196
  const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId: game.id, chat: true, nonChat: false, lobby: game.state === 'WaitingForPlayers' }));
197
- const refreshed = readGameRefreshChat(await ctx.bundle(), env.body);
197
+ const bundle = await ctx.bundle();
198
+ const groups = readGameGroups(bundle, env.body.fork());
199
+ const refreshed = readGameRefreshChat(bundle, env.body);
198
200
  if (refreshed) {
199
- const { lines, olderUnread } = await withOlder(ctx, game, me, refreshed);
201
+ const { lines, olderUnread } = await withOlder(ctx, game, me, refreshed, groups);
200
202
  const read = lines.length < (feed?.length ?? 0) ? withFeed(lines, feed) : { source: 'web', lines };
201
203
  return olderUnread.length ? { ...read, olderUnread } : read;
202
204
  }
@@ -209,6 +211,19 @@ export async function readChat(ctx, game, me) {
209
211
  }
210
212
  /** The most private conversations whose history one chat read asks for (one request each). */
211
213
  export const MAX_PRIVATE_HISTORY = 8;
214
+ /** The most game groups whose history one chat read asks for (one request each, #697). */
215
+ export const MAX_GROUP_HISTORY = 8;
216
+ /**
217
+ * The ids of the game's groups I am in, newest first (#697): those the chat lines name, and those a groups list
218
+ * names (a group whose members cannot be read is kept: war.app lists a player's own groups).
219
+ */
220
+ export function myGroupIds(lines, groups, gameId, meInGame) {
221
+ const ids = new Set(lines.flatMap((l) => (l.group !== undefined ? [l.group] : [])));
222
+ for (const g of groups ?? [])
223
+ if (g.gameId === gameId && (g.members === null || g.members.includes(meInGame)))
224
+ ids.add(g.id);
225
+ return [...ids].sort((a, b) => b - a);
226
+ }
212
227
  /**
213
228
  * GameRefresh's chat with the messages it leaves out added (#363, #387). Sent `-1` markers (as the client
214
229
  * sends on a first load), GameRefresh leaves out messages war.app counts as seen — live, an own team message
@@ -218,7 +233,7 @@ export const MAX_PRIVATE_HISTORY = 8;
218
233
  * private one per other human seat with an in-game id (at most {@link MAX_PRIVATE_HISTORY}) unless the game
219
234
  * turns private messaging off. A read that fails or does not decode adds nothing and names its channels.
220
235
  */
221
- async function withOlder(ctx, game, me, refreshed) {
236
+ async function withOlder(ctx, game, me, refreshed, groupsRead) {
222
237
  let lines = refreshed;
223
238
  const olderUnread = [];
224
239
  const history = async (name, method, write) => {
@@ -258,8 +273,45 @@ async function withOlder(ctx, game, me, refreshed) {
258
273
  if (failed)
259
274
  olderUnread.push('private');
260
275
  }
276
+ // #697: GameRefresh leaves out a game group's messages once war.app counts them as seen (live 2026-12-01: a group
277
+ // message the client showed was missing). The group's history button sends RetrieveGameGroupMessageHistory (47),
278
+ // per group I am in. The chat read names a group only by its lines, so when it names none and no groups list came
279
+ // with it, one details read (GameRefresh, chat off) gives the game's groups. Groups are private conversations of
280
+ // several players, so a game that turns private messaging off, or with fewer than two other human seats, is not asked.
281
+ const others = game.players.filter((p) => !p.isAI && inGameOf(p) !== undefined && inGameOf(p) !== me.inGameId).length;
282
+ if (game.settings?.privateMessaging !== false && others >= 2) {
283
+ let groups = groupsRead;
284
+ let ids = myGroupIds(lines, groups, game.id, me.inGameId);
285
+ if (!ids.length && groups === undefined) {
286
+ try {
287
+ const env = await ctx.rpc.call('GameRefresh', Method.GameRefresh, (w) => writeGameRefreshParams(w, { gameId: game.id, chat: false, nonChat: true, lobby: game.state === 'WaitingForPlayers' }));
288
+ groups = readGameGroups(await ctx.bundle(), env.body);
289
+ }
290
+ catch {
291
+ // No groups read: none asked.
292
+ }
293
+ ids = myGroupIds(lines, groups, game.id, me.inGameId);
294
+ }
295
+ let failed = false;
296
+ for (const group of ids.slice(0, MAX_GROUP_HISTORY)) {
297
+ const got = await history('RetrieveGameGroupMessageHistory', Method.RetrieveGameGroupMessageHistory, (w) => writeRetrieveGameGroupMessageHistoryParams(w, { gameId: game.id, before: oldestId(lines, (l) => l.group === group), group }));
298
+ // A history line names its group; one that does not (read as public: the client sends a group message on channel
299
+ // -1) is the group asked for.
300
+ if (got)
301
+ lines = mergeChatLines(lines, got.map((l) => (l.group === undefined && l.to === undefined ? inGroup(l, group) : l)));
302
+ else
303
+ failed = true;
304
+ }
305
+ if (failed)
306
+ olderUnread.push('unknown');
307
+ }
261
308
  return { lines, olderUnread };
262
309
  }
310
+ /** A line of a group's history that does not name its group, as a message in it. */
311
+ function inGroup(l, group) {
312
+ const { team: _team, ...rest } = l;
313
+ return { ...rest, channel: 'unknown', group };
314
+ }
263
315
  /** A web read shorter than GameFeed's list, filled from it (#313). */
264
316
  function withFeed(web, feed) {
265
317
  const counts = `The web client's read returned fewer messages (${web.length}) than GameFeed's chat (${feed.length})`;
@@ -465,13 +517,15 @@ export function shown(line, isNew, players, byInGame, me, map) {
465
517
  }
466
518
  /** A message's #415 fields: its `intent`, and `advice` when it was advised on; none for mine or a system line. */
467
519
  export const readingFields = (r) => r ? { intent: r.intent, ...(r.advice ? { advice: r.advice } : {}) } : {};
468
- const CHANNEL_ARGS = ['all', ...CHAT_CHANNELS];
520
+ // #697: `group` picks the game-group messages (their channel is `unknown`, each with its `group`).
521
+ const CHANNEL_ARGS = ['all', ...CHAT_CHANNELS, 'group'];
469
522
  export function registerChatTools(server, ctx, opts = {}) {
470
523
  server.registerTool('warapp_get_chat', {
471
524
  title: 'Read a war.app game chat',
472
525
  description: untrustedDescription('Read the chat of a war.app (Warzone) game: the most recent messages, oldest first, each with its sender ' +
473
526
  '(`from`, a delimited name; `fromId`, the GameFeed id), `text` (delimited), `time` (plus `localTime` when WARAPP_TIMEZONE is set), `turn`, `channel` ' +
474
- '(`public`, `team` with its `team`, `private` with its recipient `to`, or `unknown`), `mine`, and `new` ' +
527
+ '(`public`, `team` with its `team`, `private` with its recipient `to`, or `unknown`; a game-group message is `unknown` ' +
528
+ 'with its `group` id), `mine`, and `new` ' +
475
529
  '(not yet marked seen, and not mine), plus `unread` per channel over the whole chat. The chat is read ' +
476
530
  "through your signed-in war.app tab or linked session (the web client's GameRefresh, which tells the " +
477
531
  'channels apart), else from GameFeed (channels `unknown`); when the web read has fewer messages than ' +
@@ -496,7 +550,7 @@ export function registerChatTools(server, ctx, opts = {}) {
496
550
  .max(1000)
497
551
  .optional()
498
552
  .describe(`Most recent messages to return (default ${DEFAULT_LIMIT}).`),
499
- channel: z.enum(CHANNEL_ARGS).optional().describe('Only this channel: public, team, private or unknown (default all).'),
553
+ channel: z.enum(CHANNEL_ARGS).optional().describe('Only this channel: public, team, private, unknown, or group (the game-group messages, part of unknown) (default all).'),
500
554
  mark_seen: z
501
555
  .boolean()
502
556
  .optional()
@@ -518,13 +572,13 @@ export function registerChatTools(server, ctx, opts = {}) {
518
572
  }
519
573
  const { fresh, unread, cursor } = await chatUnread(ctx, game.id, me, read.lines);
520
574
  const byInGame = playersByInGameId(game.players);
521
- const wanted = (l) => channel === undefined || channel === 'all' || l.channel === channel;
575
+ const wanted = (l) => channel === undefined || channel === 'all' || (channel === 'group' ? l.group !== undefined : l.channel === channel);
522
576
  const picked = read.lines.map((l, i) => [l, fresh[i], i]).filter(([l]) => wanted(l));
523
577
  // #415: each message another player sent is labelled, and an unread one advised on (this machine's logs only).
524
578
  const reading = chatReader(read.lines, game, me, await chatAdviceContext(ctx, game, me));
525
579
  const messages = picked.slice(-n).map(([l, isNew, i]) => ({ ...shown(l, isNew, game.players, byInGame, me, game.map), ...readingFields(reading(i, isNew)) }));
526
580
  const marked = mark_seen
527
- ? await markChatSeen(ctx, game.id, me, read, cursor, channel === undefined || channel === 'all' ? [...CHAT_CHANNELS] : [channel])
581
+ ? await markChatSeen(ctx, game.id, me, read, cursor, channel === undefined || channel === 'all' ? [...CHAT_CHANNELS] : [channel === 'group' ? 'unknown' : channel])
528
582
  : undefined;
529
583
  // Unread messages the mark covered that `limit` kept out of `messages`.
530
584
  const markedUnshown = marked ? picked.slice(0, Math.max(0, picked.length - n)).filter(([, isNew]) => isNew).length : 0;
@@ -15,7 +15,7 @@ import { z } from 'zod';
15
15
  import { findChokepoints, planTurn } from '../analysis/index.js';
16
16
  import { diplomacyFacts, MAX_NOTICE_TURNS, offerChecks, partyRefusal, priceTruce, scopeRefusal, sharedBorder, agreementState, suggestedTerms, TERMINAL_STATUSES, truceEndgame, truceVerdict, } from '../analysis/relations.js';
17
17
  import { ledgerTruces, readLedger } from '../relations-store.js';
18
- import { atPeaceWith, pactLabel, pactsInForce } from '../analysis/pacts.js';
18
+ import { atPeaceWith, pactLabel, pactsInForce, peersOf } from '../analysis/pacts.js';
19
19
  import { isTeamGame } from '../teams.js';
20
20
  import { bonusNamer, currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
21
21
  import { lookupMeta } from './hints.js';
@@ -282,11 +282,15 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
282
282
  const pacts = setup.truces?.pacts ?? [];
283
283
  const peaceOf = (partner) => {
284
284
  // #686: a broken pact no longer counts as peace.
285
- const with_ = pactsInForce(pacts).filter((k) => k.parties.includes(partner));
285
+ // #686 (owner, 2026-12-01): only the parties it has not broken with.
286
+ const with_ = pactsInForce(pacts)
287
+ .filter((k) => k.parties.includes(partner))
288
+ .map((k) => ({ k, peers: peersOf(k, partner) }))
289
+ .filter((x) => x.peers.length > 0);
286
290
  if (!with_.length)
287
291
  return undefined;
288
292
  return `Player ${partner} is already at peace with ${with_
289
- .map((k) => `player${k.parties.length > 2 ? 's' : ''} ${k.parties.filter((x) => x !== partner).join(', ')} (${pactLabel(k)})`)
293
+ .map(({ k, peers }) => `player${peers.length > 1 ? 's' : ''} ${peers.join(', ')} (${pactLabel(k)})`)
290
294
  .join('; ')}: a truce with it does not free it from them, and they may act together (#680, report only).`;
291
295
  };
292
296
  return respond(view, VIEWS, (rung) => {
@@ -335,6 +339,7 @@ export function registerDiplomacyTool(server, ctx, opts = {}) {
335
339
  ...(k.endsTurn !== undefined ? { endsTurn: k.endsTurn } : {}),
336
340
  // #686: a party broke it in view: it no longer counts (report only).
337
341
  ...(k.broken ? { broken: true } : {}),
342
+ ...(k.brokenPairs ? { brokenPairs: k.brokenPairs.map((pr) => pr.map(playerRef)) } : {}),
338
343
  ...(k.flags?.length ? { flags: k.flags.map((f) => ({ ...f, by: playerRef(f.by), against: playerRef(f.against), territories: f.territories.map(name) })) } : {}),
339
344
  })),
340
345
  }
@@ -0,0 +1,35 @@
1
+ // #568 (owner decision 2026-12-01): keep my fogged view of every turn of a game while it is played (src/fog-history.ts),
2
+ // by one GetTurns request for the turns not kept yet. warapp_plan_turn starts it alongside the plan's own work and awaits
3
+ // it before answering (so the answer waits for this request at most), never failing the plan; a game not in play, no
4
+ // data dir, or any failure: nothing kept. Never throws.
5
+ import { readFogHistory, missingTurns, mergeFogHistory, readTurnsReturn } from '../fog-history.js';
6
+ import { Method, writeGetTurnsParams } from '../protocol/methods.js';
7
+ import { turnsCompleted } from './common.js';
8
+ const GET_TURNS_RETURN = 'warlight.shared.GetTurnsReturn';
9
+ /** The turns kept by this call (`0`: none needed or none read). */
10
+ export async function captureFogHistory(ctx, game, me) {
11
+ try {
12
+ if (!ctx.dataDir || game.state !== 'Playing')
13
+ return 0;
14
+ const completed = turnsCompleted(game) ?? 0;
15
+ if (completed < 1)
16
+ return 0;
17
+ const have = await readFogHistory(ctx.dataDir, game.id, me);
18
+ const missing = missingTurns(have, completed);
19
+ if (!missing.length)
20
+ return 0;
21
+ const env = await ctx.rpc.call('GetTurns', Method.GetTurns, (w) => writeGetTurnsParams(w, { gameId: game.id, turns: missing.map((n) => n - 1) }));
22
+ if (!env.body.bool())
23
+ return 0;
24
+ const got = readTurnsReturn((await ctx.bundle()).readClass(GET_TURNS_RETURN, env.body));
25
+ if (!got)
26
+ return 0;
27
+ const turns = Object.fromEntries(Object.entries(got.turns).filter(([n]) => Number(n) <= completed));
28
+ if (!Object.keys(turns).length && !got.start)
29
+ return 0;
30
+ return (await mergeFogHistory(ctx.dataDir, game.id, me, { ...(got.start ? { start: got.start } : {}), turns })) ? Object.keys(turns).length : 0;
31
+ }
32
+ catch {
33
+ return 0;
34
+ }
35
+ }
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { leavers } from '../normalize.js';
3
3
  import { recordFinalResult } from '../outlook-log.js';
4
+ import { historyWindow } from '../history-window.js';
4
5
  import { historyReport } from '../trend.js';
5
6
  import { currentTurn, gameIdArg, mapSummary, readAnnotations, respond, turnsCompleted, untrustedDescription, viewArg } from './common.js';
6
7
  import { lookupMeta } from './hints.js';
@@ -8,6 +9,8 @@ import { lossReport } from './how-lost.js';
8
9
  import { endOfGame, finishedAccount } from './end-of-game.js';
9
10
  import { foldFinished } from './profile-hook.js';
10
11
  import { NO_BOOT_MINUTES } from './boot-player.js';
12
+ import { readDecisionLog } from '../decision-log.js';
13
+ import { turnOrderFor } from './turn-order.js';
11
14
  const VIEWS = ['compact', 'full', 'raw'];
12
15
  function settingsDigest(s) {
13
16
  if (!s)
@@ -121,7 +124,12 @@ cards) {
121
124
  'pieces toward the next one and `of` how many make one; read by shape, UNVERIFIED live; `null` when unread), and ' +
122
125
  '`settings` (each card in play with a `duration`, and Sanctions\' `percentage` — negative raises the target\'s income — ' +
123
126
  'with its `effect` and `targets`: opponents, or your side when negative) — a ' +
124
- 'failed read is `cardsUnread`, never an error. For the map\'s bonuses and chokepoints use warapp_get_map. Read-only.'),
127
+ 'failed read is `cardsUnread`, never an error. ' +
128
+ 'While the game is played and this server kept turns of it, `turnOrder` (#693) says who moves before me: per ' +
129
+ 'turn (the last turns read, this one and the next five) the order when known, else `beforeMe`/`afterMe`/`unknown` by ' +
130
+ 'player id, each row `known` (read from that turn) or `projected` (Cycle: the order reverses every turn); ' +
131
+ '`perOpponent` for this turn; `firstMover` only when every opponent agrees; Random games project nothing. ' +
132
+ 'For the map\'s bonuses and chokepoints use warapp_get_map. Read-only.'),
125
133
  _meta: lookupMeta(['warzone game', 'war.app game', 'whose turn is it', 'game status']),
126
134
  annotations: readAnnotations('Get a war.app game'),
127
135
  inputSchema: z.object({
@@ -131,14 +139,38 @@ cards) {
131
139
  .optional()
132
140
  .describe('Also fetch past turns (GetHistory; war.app documents it for finished games). The result then says ' +
133
141
  'whether the history read (`historyRead`: boards, first and last turn, layout) or why not ' +
134
- '(`historyUnreadable`: reason and the reply\'s top-level key names); the raw turns themselves only in ' +
135
- 'view "full" or "raw" (they can run to megabytes). Default false.'),
142
+ '(`historyUnreadable`: reason and the reply\'s top-level key names); the turns themselves only in ' +
143
+ 'view "raw", for an analysis of your own, bounded (#709): whole turns, oldest first, while they fit in about 2.5 MB, with ' +
144
+ '`historyWindow` saying which turns came and, when more did not fit, `next` to pass as `history_from`; `history_player` ' +
145
+ 'keeps one player\'s orders and `history_boards: false` leaves the boards out. Default false.'),
136
146
  include_chat: z.boolean().optional().describe('Also fetch the game chat (GetChat). Default false.'),
147
+ history_from: z.coerce
148
+ .number()
149
+ .int()
150
+ .min(0)
151
+ .optional()
152
+ .describe('With include_history in view "raw": the first turn of history to include (default the first; #709).'),
153
+ history_to: z.coerce
154
+ .number()
155
+ .int()
156
+ .min(0)
157
+ .optional()
158
+ .describe('With include_history in view "raw": the last turn of history to include (default the last).'),
159
+ history_player: z.coerce
160
+ .number()
161
+ .int()
162
+ .positive()
163
+ .optional()
164
+ .describe('With include_history in view "raw": only this player\'s orders (GameFeed id); the boards stay whole.'),
165
+ history_boards: z
166
+ .boolean()
167
+ .optional()
168
+ .describe('With include_history in view "raw": false leaves out the per-turn boards, the orders alone (default true).'),
137
169
  view: viewArg(VIEWS, 'compact (default) keeps the game state and turn, players with committed flags, a settings digest and a map ' +
138
170
  'summary; "full" is every normalized field (all settings as sent, the board standing) with the map ' +
139
171
  'summarized; "raw" is the whole normalized game including the full map.'),
140
172
  }),
141
- }, async ({ game_id, include_history, include_chat, view }) => {
173
+ }, async ({ game_id, include_history, include_chat, view, history_from, history_to, history_player, history_boards }) => {
142
174
  const game = await client.getGame(game_id, {
143
175
  settings: true,
144
176
  ...(include_history ? { history: true } : {}),
@@ -163,8 +195,13 @@ cards) {
163
195
  }
164
196
  }
165
197
  const cardRead = cards ? await cards(game) : {};
198
+ // #693: the move order this turn and the next ones, from the turns this server kept (no request). The account is
199
+ // the decision log's own.
200
+ const log = dir && game.state === 'Playing' ? await readDecisionLog(dir(), game.id).catch(() => undefined) : undefined;
201
+ const turnOrder = log ? await turnOrderFor({ dataDir: dir(), game, me: log.playerId, log }) : undefined;
166
202
  const folded = {
167
203
  ...cardRead,
204
+ ...(turnOrder ? { turnOrder } : {}),
168
205
  ...(fold && fold.status !== 'off' ? { profileFold: fold } : {}),
169
206
  ...(lost ? { howLost: lost } : {}),
170
207
  ...(end && end.status !== 'off' ? { endOfGame: end } : {}),
@@ -172,12 +209,30 @@ cards) {
172
209
  // #302: with the history asked for, whether it read, and if not why (key names and counts only).
173
210
  const report = include_history ? historyReport(game) : undefined;
174
211
  const historyRead = report ? ('read' in report ? { historyRead: report.read } : { historyUnreadable: report.unreadable }) : {};
212
+ // #709: the raw turns bounded to a window a client can read in one message.
213
+ const bounded = () => {
214
+ if (game.history === undefined)
215
+ return { game };
216
+ const w = historyWindow(game.history, {
217
+ ...(history_from !== undefined ? { from: history_from } : {}),
218
+ ...(history_to !== undefined ? { to: history_to } : {}),
219
+ // The history names players by in-game id: the GameFeed id less two check digits each end.
220
+ ...(history_player !== undefined ? { player: String(history_player).slice(2, -2) } : {}),
221
+ ...(history_boards === false ? { boards: false } : {}),
222
+ });
223
+ return { game: { ...game, history: w.history }, ...(w.window ? { historyWindow: w.window } : {}) };
224
+ };
175
225
  return respond(view, VIEWS, (rung) => {
176
226
  if (rung === 'compact')
177
227
  return { ...compact(game), ...folded, ...historyRead };
178
- if (rung === 'full')
179
- return { game: { ...game, map: game.map ? mapSummary(game.map) : undefined }, ...folded, ...historyRead };
180
- return { game };
228
+ // The history is for the server to store and analyse (the end-of-game pass reads it whole); the model gets its
229
+ // summary (`historyRead`) unless it asks for the turns themselves with view "raw" (owner, 2026-12-01).
230
+ if (rung === 'full') {
231
+ const { history: _h, ...rest } = game;
232
+ return { game: { ...rest, map: game.map ? mapSummary(game.map) : undefined }, ...folded, ...historyRead };
233
+ }
234
+ const b = bounded();
235
+ return { game: b.game, ...(b.historyWindow ? { historyWindow: b.historyWindow } : {}) };
181
236
  });
182
237
  });
183
238
  }
@@ -709,6 +709,8 @@ export function registerRelationsTools(server, ctx, opts = {}) {
709
709
  ...(k.endsTurn !== undefined ? { endsTurn: k.endsTurn } : {}),
710
710
  // #686: what my boards show of the parties keeping it; `broken`: it no longer counts as a pact.
711
711
  ...(k.broken ? { broken: true } : {}),
712
+ // #686 (owner, 2026-12-01): the pairs that broke with each other; the pact's other pairs still hold.
713
+ ...(k.brokenPairs ? { brokenPairs: k.brokenPairs.map((pr) => pr.map(playerName)) } : {}),
712
714
  ...(k.flags?.length
713
715
  ? { flags: k.flags.map((f) => ({ ...f, by: playerName(f.by), against: playerName(f.against), territories: f.territories.map(name) })) }
714
716
  : {}),
@@ -0,0 +1,53 @@
1
+ // #693: the turn order for a game, from this server's decision log (the visible orders of each resolved turn it kept,
2
+ // #570) and, when given, the live board's own last turn — no request of its own. Pure model: src/analysis/turn-order.ts.
3
+ import { factOfTurn, readTurnOrder } from '../analysis/turn-order.js';
4
+ import { readDecisionLog } from '../decision-log.js';
5
+ import { readSeenTurn } from '../turn-orders.js';
6
+ import { currentTurn } from './common.js';
7
+ /** Turns projected after the one being played. */
8
+ export const TURN_ORDER_HORIZON = 5;
9
+ export const TURN_ORDER_NOTE = 'From the client code: a Cycle or No-luck Cycle game keeps one cycle, taken forward and backward on alternate turns ' +
10
+ '(whoever moved first moves last next turn; a seat that leaves drops out), and an Order Priority or Order Delay play ' +
11
+ 're-sorts its own turn only. Under Random every turn is drawn afresh. `known` rows are read from that turn: war.app\'s ' +
12
+ 'own MoveOrder when sent, else inferred from the order the visible moves ran in: moves run one per player per round ' +
13
+ 'and the order reverses after every round (A B C, C B A, …), so a player\'s j-th visible move before my j-th move puts ' +
14
+ 'it before me when j is odd, after me when j is even. `projected` rows apply the rule. Players by GameFeed id.';
15
+ /** The facts the log (and the live board's last turn, which wins for its turn) hold. */
16
+ export function orderFacts(log, me, info) {
17
+ const out = new Map();
18
+ for (const [k, e] of Object.entries(log?.turns ?? {})) {
19
+ if (!/^\d+$/.test(k) || !e.seen)
20
+ continue;
21
+ const f = factOfTurn({ turn: Number(k), ...e.seen }, me, e.sent ? { sentMoves: e.sent.moves.length } : {});
22
+ if (f)
23
+ out.set(f.turn, f);
24
+ }
25
+ const live = info?.seen;
26
+ if (live) {
27
+ const sent = log?.turns[String(live.turn)]?.sent;
28
+ const f = factOfTurn(live, me, sent ? { sentMoves: sent.moves.length } : {});
29
+ if (f)
30
+ out.set(f.turn, f);
31
+ }
32
+ return [...out.values()];
33
+ }
34
+ /**
35
+ * The turn order for `me` in `game` while it is played; `undefined` when not playing, my seat is out, or no data dir.
36
+ * `log` saves a read when the caller holds it; `info` is the live LatestGameInfo when the caller read one.
37
+ */
38
+ export async function turnOrderFor(a) {
39
+ const { game, me } = a;
40
+ const turn = currentTurn(game);
41
+ if (!a.dataDir || turn === null || game.state !== 'Playing')
42
+ return undefined;
43
+ if (game.players.find((p) => p.id === me)?.state !== 'Playing')
44
+ return undefined;
45
+ const log = a.log ?? (await readDecisionLog(a.dataDir, game.id, me).catch(() => undefined));
46
+ const seen = a.info !== undefined ? readSeenTurn(a.info, game.players) : undefined;
47
+ const facts = orderFacts(log, me, seen && seen.turn === turn - 1 ? { seen } : {});
48
+ const playing = game.players.filter((p) => p.id !== me && p.state === 'Playing').map((p) => p.id);
49
+ return {
50
+ ...readTurnOrder({ moveOrder: game.settings?.moveOrder, turn, me, playing, facts, horizon: TURN_ORDER_HORIZON }),
51
+ note: TURN_ORDER_NOTE,
52
+ };
53
+ }
@@ -22,6 +22,7 @@ import { SERVER_ERROR_MESSAGES } from '../protocol/rpc.js';
22
22
  import { inferFirstMover } from '../move-order.js';
23
23
  import { KNOWN_MODS } from '../known-mods.js';
24
24
  import { assumedWarning, awardView, firstMoverFor, loadAward, openingThreat } from './award.js';
25
+ import { turnOrderFor } from './turn-order.js';
25
26
  import { boardCardsInEffect, CARDS_IN_EFFECT_UNVERIFIED, sanctionMyIncome } from './card-effects.js';
26
27
  import { sanctionPercentage } from '../analysis/cards-in-effect.js';
27
28
  import { myOrdersOf as committedOrdersOf, readMyOrderList } from '../my-orders.js';
@@ -98,6 +99,10 @@ import { myCommanderTerritory } from '../analysis/commander-safety.js';
98
99
  import { commanderCheckOn, defaultFoggedCount, foggedAttackersArg, foggedCommanderOn, foggedCommanderText, guessKeepsCommander, myLargestStack, } from './commander-check.js';
99
100
  import { foggedStack, likelyStackAt } from '../analysis/commander-fog.js';
100
101
  import { VACATED_FOG_ARMIES } from '../analysis/plan/vacated.js';
102
+ import { nextIncomeLow } from '../analysis/income-range.js';
103
+ import { captureFogHistory } from './fog-capture.js';
104
+ import { incomeRules } from '../analysis/player.js';
105
+ import { recordIncomeLow } from '../decision-log.js';
101
106
  import { HEADROOM_COMPACT, headroomView, headroomWarnings, keepTripwires, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
102
107
  const VIEWS = ['compact', 'full'];
103
108
  /** #415 task 4b: the chat-blocks-the-turn gate, the context's when set, else read from the environment. */
@@ -1449,7 +1454,11 @@ export async function livePlanSetup(ctx, a) {
1449
1454
  orderPriorityPossible: opponentCanHold(game.settings, 'Order Priority', turn - 1),
1450
1455
  })
1451
1456
  : null;
1452
- const mover = await firstMoverFor(ctx.dataDir, game, me, turn, first_mover, award, { write, ...(inferred ? { inferred } : {}) });
1457
+ const keptMover = await firstMoverFor(ctx.dataDir, game, me, turn, first_mover, award, { write, ...(inferred ? { inferred } : {}) });
1458
+ // #693: the move order of every seat, from the turns kept and this board's last turn (no request). It fills the
1459
+ // first mover only when nothing above gave one and every opponent still playing reads the same way; never verified.
1460
+ const turnOrder = await turnOrderFor({ dataDir: ctx.dataDir, game, me: me.id, info }).catch(() => undefined);
1461
+ const mover = keptMover.firstMover === undefined && turnOrder?.firstMover ? fromTurnOrder(turnOrder.firstMover, keptMover.warnings) : keptMover;
1453
1462
  const settings = plannerSettings(game.settings);
1454
1463
  const rules = cardRules(game.settings);
1455
1464
  // A team shares one hand (#163): mine and my teammates' cards.
@@ -1703,6 +1712,22 @@ export async function livePlanSetup(ctx, a) {
1703
1712
  seenPlays: playsShown ? lastPlays : undefined,
1704
1713
  // #606: the earlier boards (and my orders on them) for the strategy view's summary of past turns.
1705
1714
  pastBoards: history.boards,
1715
+ // #693: who moves before me, this turn and the next ones (plan_turn's full view).
1716
+ turnOrder,
1717
+ };
1718
+ }
1719
+ /** #693: the plan's first mover from the turn order: inferred, never verified (it orders moves, never sizes a hold). */
1720
+ function fromTurnOrder(f, warnings) {
1721
+ const said = f.basis === 'move-order' ? "war.app's move order for an earlier turn" : 'the order earlier turns\' visible moves ran in';
1722
+ return {
1723
+ firstMover: f.who,
1724
+ verified: false,
1725
+ view: {
1726
+ who: f.who === 'me' ? 'you' : 'opponent',
1727
+ source: 'inferred',
1728
+ line: `${f.who === 'me' ? 'You move' : 'Every opponent moves'} first on turn ${f.turn} (the move order alternates every turn; from ${said}, not verified).`,
1729
+ },
1730
+ warnings,
1706
1731
  };
1707
1732
  }
1708
1733
  /** The Airlift card's type id. */
@@ -2249,7 +2274,10 @@ export function registerTurnTools(server, ctx, opts = {}) {
2249
2274
  'keep only the opponents in view or holding land within 2 steps of yours, and `scale` sums the rest: their count, ' +
2250
2275
  'summed deploy estimate and the biggest; the orders are planned as before): your income, deploys and attacks/transfers by territory name and id (each attack with ' +
2251
2276
  '`winChance`, its exact capture probability), the expected captures, completed bonuses and next income ' +
2252
- '(with `nextIncomeIfConcededFall` and `bonusesAtRisk` when the plan concedes borders of a bonus you hold), ' +
2277
+ '(with `nextIncomeIfConcededFall` and `bonusesAtRisk` when the plan concedes borders of a bonus you hold; ' +
2278
+ '#698: `nextIncome` is the best case, every capture landing and nothing falling, and `nextIncomeLow` with ' +
2279
+ '`nextIncomeLowFalls` the low end, the conceded borders and those the headroom says fall to less than their ' +
2280
+ "opponent's estimate gone), " +
2253
2281
  'the borders given up (`conceded`), the `frontier` budget, `incomeTrend` (my income over the last five turns, its slope per turn and whether it is flat; #303), in a 1v1 the `gates` (every border facing the opponent against its one floating deploy: what they need, what stands on them, the shortfall), your cards (plays and discards when you must), ' +
2254
2282
  'warnings and the reasoning. Its `orders` array is exactly what warapp_submit_turn takes — review it with ' +
2255
2283
  'the user first. Every plan reads the game profile (`profile`: format 1v1/ffa/teams, phase, standing ' +
@@ -2347,7 +2375,10 @@ export function registerTurnTools(server, ctx, opts = {}) {
2347
2375
  'neither takes alone) are advice, never in `orders`; `cards.team` says who plays each card, leaving theirs to them. ' +
2348
2376
  '`firstMover` is who the plan takes to move first this turn (null when unknown) and its `source`: ' +
2349
2377
  '"explicit" (`first_mover`), "award", or "remembered" — a turn this server kept, alternated (two players, ' +
2350
- 'cyclic order). ' +
2378
+ 'cyclic order) — or "inferred" (#693: from the move order of earlier turns, any number of players, only when every ' +
2379
+ 'opponent still playing moves on the same side of you; never verified, so it orders moves but sizes no hold). ' +
2380
+ 'View "full" adds `turnOrder`: who moves before you on the last turns read, this one and the next five (as ' +
2381
+ 'warapp_get_game reports it). ' +
2351
2382
  'When one opponent touches two or more of your borders and no fixed split of the deploys there holds them all, ' +
2352
2383
  '`guess` is a randomized split, weighted by what each border is worth, against an opponent who would read a fixed ' +
2353
2384
  'one, and `guessOrders` the plan\'s `orders` with that split — optional (the user chooses; `orders` stay the ' +
@@ -2648,6 +2679,9 @@ export function registerTurnTools(server, ctx, opts = {}) {
2648
2679
  nextIncome: plan.expected.nextIncome,
2649
2680
  })
2650
2681
  : { view: {}, warnings: [] };
2682
+ // #568: my fogged view of every turn kept while the game is played (one GetTurns for the turns not kept yet),
2683
+ // started here so it overlaps the rest of the plan, and awaited before the answer (never failing it).
2684
+ let fogCapture;
2651
2685
  // #412: the decision log — this turn's decision (a what-if plan is only an observation of the board,
2652
2686
  // never the turn's decision), and the previous turn's outcome from this board and income.
2653
2687
  if (ctx.dataDir && turn !== null) {
@@ -2673,6 +2707,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
2673
2707
  cards: { hand: handLog(myCards), advice: cardAdviceLog(advice.view) },
2674
2708
  times: bootTimes(game),
2675
2709
  });
2710
+ if (!whatIf)
2711
+ fogCapture = captureFogHistory(ctx, game, me.id);
2676
2712
  }
2677
2713
  // B4: the planner does not read what my chat messages promised (words change no estimate), so a
2678
2714
  // plan that breaks a commitment still in force says so here; warapp_submit_turn warns again.
@@ -2954,6 +2990,21 @@ export function registerTurnTools(server, ctx, opts = {}) {
2954
2990
  ...(mover.firstMover !== undefined && mover.verified ? { firstMover: mover.firstMover } : {}),
2955
2991
  ...(advised ? { orderPriority: true } : {}),
2956
2992
  });
2993
+ // #698: the low end of next income — the conceded borders and those the headroom says fall to less than
2994
+ // their opponent's own estimate gone (report only; kept in the decision log to be scored against the outcome).
2995
+ const incomeLow = nextIncomeLow({
2996
+ graph,
2997
+ rules: incomeRules(game.settings),
2998
+ board,
2999
+ me: me.id,
3000
+ captures: plan.expected.captures,
3001
+ conceded: plan.conceded,
3002
+ nextIncome: plan.expected.nextIncome,
3003
+ headroom,
3004
+ estimateOf: (p) => estimates.find((e) => e.playerId === p)?.estimate,
3005
+ });
3006
+ if (incomeLow && ctx.dataDir && turn !== null && !whatIf)
3007
+ await recordIncomeLow(ctx.dataDir, game.id, me.id, turn, incomeLow, ctx.decisionLog ? { mode: ctx.decisionLog } : {});
2957
3008
  const guessOrders = guess ? guessOrdersOf(orders, guess) : undefined;
2958
3009
  // Owner request 2026-11-24: with Airlift cards in hand, the best plan that plays them, ALONGSIDE the plain
2959
3010
  // plan (whose orders never change): candidates scored by the plain plan's own measure (airlift-plan.ts).
@@ -3122,6 +3173,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
3122
3173
  const scaleAllies = new Set(teammatesOf(game.players, me).map((p) => p.id));
3123
3174
  const scope = opponentScope(graph, seen, me.id, [...new Set([...estimates.map((e) => e.playerId), ...game.players.filter((p) => (p.state ?? 'Playing') === 'Playing').map((p) => p.id)])].filter((p) => p !== me.id && !scaleAllies.has(p)));
3124
3175
  const inScope = (p) => !scope.large || scope.near.includes(p);
3176
+ await fogCapture;
3125
3177
  return respond(view, VIEWS, (rung) => ({
3126
3178
  game: { id: game.id, name: game.name ?? null, turn: currentTurn(game) },
3127
3179
  player: { id: me.id, name: me.name },
@@ -3241,6 +3293,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
3241
3293
  })(),
3242
3294
  // #127: who moves first this turn and how it is known; null when unknown.
3243
3295
  firstMover: mover.view,
3296
+ // #693: who moves before me this turn and the next ones (full view only).
3297
+ ...(rung === 'full' && setup.turnOrder ? { turnOrder: setup.turnOrder } : {}),
3244
3298
  // #166: what the award of picks showed (absent when no pick list is kept for this game).
3245
3299
  ...(award ? { award: awardView(award, game, turn, name) } : {}),
3246
3300
  trendSource: trend?.source ?? null,
@@ -3391,6 +3445,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
3391
3445
  return { id, name: b.name, value: b.value };
3392
3446
  }),
3393
3447
  nextIncome: plan.expected.nextIncome,
3448
+ // #698: the low end, when a border falling would cost income (conceded, or below its opponent's estimate).
3449
+ ...(incomeLow ? { nextIncomeLow: incomeLow.low, nextIncomeLowFalls: incomeLow.falls.map(name) } : {}),
3394
3450
  // #109: present only when the plan's concessions put income at risk.
3395
3451
  ...(plan.expected.nextIncomeIfConcededFall !== undefined
3396
3452
  ? {
@@ -8,13 +8,32 @@
8
8
  // (its own fields hold in-game ids not mapped here); any other order kind (a card received, an active card worn
9
9
  // off, …) is kept by its class name only. Attack results (the `…Result` records) are not decoded: what an attack
10
10
  // achieved shows on the next board. Ids and counts only, never a name. Pure; tolerant: nothing throws.
11
+ // #693: the GameTurn's first field is its MoveOrder (the bundle's reader: an optional list of int32 in-game player ids
12
+ // in the order they moved, then the orders, the turn number and the time). Live it has been null on every read so far
13
+ // (Cycle games, where war.app leaves the cycle for players to deduce); when it is sent it is kept as `moveOrder`.
14
+ // A move's result is read for one figure only, the armies it actually moved (`actual`): an order that could not run
15
+ // moved 0 and is still listed, beside the player's next order that ran in its slot.
11
16
  import { playersByInGameId } from './live.js';
12
17
  import { fields, isObj } from './protocol/decoded.js';
13
- import { decodeOrder, orderClass } from './team-orders.js';
18
+ import { armiesOf, decodeOrder, orderClass } from './team-orders.js';
14
19
  /** Orders kept per turn at most (a mega game can show hundreds); the rest are counted. */
15
20
  export const MAX_SEEN_ORDERS = 3000;
16
21
  const GAME_TURN = /\.GameTurn$/;
17
22
  const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
23
+ const ATTACK_RESULT = /\.GameOrderAttackTransferResult$/;
24
+ /**
25
+ * The armies a move actually moved: its result record (the base order's optional result, after the player) read by
26
+ * the bundle's reader as ActualArmies, AttackingArmiesKilled, …, each an `Armies` — the first is ActualArmies.
27
+ * `undefined` without a result or its armies. In a finished game's GameFeed history the same field is
28
+ * `result.armies`, "0" on the orders that moved nothing.
29
+ */
30
+ function actualArmies(o) {
31
+ const result = fields(o).find((v) => isObj(v) && typeof v.$type === 'string' && ATTACK_RESULT.test(v.$type));
32
+ if (!result)
33
+ return undefined;
34
+ const first = fields(result).find((v) => armiesOf(v) !== undefined);
35
+ return first === undefined ? undefined : armiesOf(first).count;
36
+ }
18
37
  /** The resolved turn in a decoded LatestGameInfo, its players mapped to GameFeed ids; `undefined` without one. */
19
38
  export function readSeenTurn(info, players) {
20
39
  if (!isObj(info))
@@ -24,10 +43,14 @@ export function readSeenTurn(info, players) {
24
43
  return undefined;
25
44
  const own = fields(turn);
26
45
  const ints = own.filter(isInt);
27
- const list = own.find((v) => Array.isArray(v));
46
+ // The order list is the last list; a list before it is the MoveOrder (#693).
47
+ const lists = own.filter((v) => Array.isArray(v));
48
+ const list = lists.at(-1);
28
49
  if (ints.length !== 1 || !list)
29
50
  return undefined;
30
51
  const byInGame = playersByInGameId(players);
52
+ const order = lists.length === 2 ? lists[0] : undefined;
53
+ const moveOrder = order && order.length > 0 && order.every((v) => isInt(v) && byInGame.has(v)) ? order.map((v) => byInGame.get(v).id) : undefined;
31
54
  const orders = [];
32
55
  let omitted = 0;
33
56
  for (const o of list) {
@@ -54,11 +77,12 @@ export function readSeenTurn(info, players) {
54
77
  mode: d.mode,
55
78
  ...(d.percent ? { percent: true } : {}),
56
79
  ...(d.commander ? { commander: true } : {}),
80
+ ...((n) => (n === undefined ? {} : { actual: n }))(actualArmies(o)),
57
81
  });
58
82
  else if (d.kind === 'card')
59
83
  orders.push({ player, kind: 'card', card: d.name });
60
84
  else
61
85
  orders.push({ player, kind: 'discard' });
62
86
  }
63
- return { turn: ints[0] + 1, orders, ...(omitted ? { omitted } : {}) };
87
+ return { turn: ints[0] + 1, orders, ...(omitted ? { omitted } : {}), ...(moveOrder ? { moveOrder } : {}) };
64
88
  }
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Single source of truth for the server version. release-please bumps the
2
2
  // literal on the marked line (registered in release-please-config.json
3
3
  // extra-files); every other module imports VERSION from here.
4
- export const VERSION = '0.25.0'; // x-release-please-version
4
+ export const VERSION = '0.27.0'; // x-release-please-version
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "warapp-mcp",
5
5
  "display_name": "war.app (Warzone)",
6
- "version": "0.25.0",
6
+ "version": "0.27.0",
7
7
  "description": "war.app (Warzone) game advisor for Claude — your games, maps, bonuses, board analysis and routes via the GameFeed API, plus your games list (waiting on you first), opponent scouting with your head-to-head, the live board, territory picks, cards, turn planning and submission, turn notifications, and chat through your signed-in war.app tab (ContextMint Bridge). Creating, joining, leaving or surrendering a game, accepting game invitations, closing out a finished game, accepting another player's surrender, a team surrender, a vote to end a game, booting a stalled player, Begin on a speed first turn, picks, turn orders, withdrawing them, chat sends, nudging a player, joining or leaving a ladder, answering a clan invite, joining or leaving a clan, changing quickmatch settings, voting on quickmatch templates, joining or declining a tournament, showing a tournament among your favourites, mail (new threads, replies, adding players, deleting threads), forum posts (new threads, replies, votes, watching a thread), chat reactions, marking notifications and chat read, deleting notifications, importing local history into a hosted server and linking a session (local only) are confirm-gated.",
8
8
  "author": {
9
9
  "name": "Chris Hall",