@chrischall/warapp-mcp 0.25.0 → 0.26.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.
@@ -712,13 +712,32 @@ export async function recordCheck(dir, gameId, playerId, turn, summary, opts = {
712
712
  return false;
713
713
  }
714
714
  }
715
+ /**
716
+ * #698: keep the low end of the plan's next income on that turn's entry (`incomeLow`; the plan's `nextIncome` is the
717
+ * best case), to be scored against the next turn's income. Only on an entry with a decision. Never throws.
718
+ */
719
+ export async function recordIncomeLow(dir, gameId, playerId, turn, low, opts = {}) {
720
+ try {
721
+ return await updateDecisionLog(dir, gameId, playerId, (log) => {
722
+ const was = log.turns[String(turn)];
723
+ // A plan logged after the orders went is not logged (recordDecision keeps the sent turn's): neither is its low end.
724
+ if (!was?.decision || was.sent)
725
+ return log;
726
+ const incomeLow = { low: low.low, falls: [...low.falls], belowEstimate: [...low.belowEstimate] };
727
+ return { ...log, turns: { ...log.turns, [String(turn)]: { ...was, incomeLow } } };
728
+ }, opts);
729
+ }
730
+ catch {
731
+ return false;
732
+ }
733
+ }
715
734
  /**
716
735
  * #570: keep the resolved turn's visible orders on that turn's entry (an entry is started when none exists).
717
736
  * Read again, the newest read wins. `true` when written. Never throws.
718
737
  */
719
738
  export async function recordSeenTurn(dir, gameId, playerId, seen, opts = {}) {
720
739
  try {
721
- const kept = { orders: seen.orders, ...(seen.omitted ? { omitted: seen.omitted } : {}) };
740
+ const kept = { orders: seen.orders, ...(seen.omitted ? { omitted: seen.omitted } : {}), ...(seen.moveOrder ? { moveOrder: seen.moveOrder } : {}) };
722
741
  return await updateDecisionLog(dir, gameId, playerId, (log) => {
723
742
  const was = log.turns[String(seen.turn)] ?? {};
724
743
  return { ...log, turns: { ...log.turns, [String(seen.turn)]: { ...was, seen: kept } } };
@@ -21,6 +21,7 @@ export const Method = {
21
21
  RegisterChatView: 44,
22
22
  RetrieveChat: 45,
23
23
  RetrievePrivateMessageHistory: 46,
24
+ RetrieveGameGroupMessageHistory: 47,
24
25
  GetGameSettings: 49,
25
26
  GetMyGames: 51,
26
27
  AcceptGame: 61,
@@ -845,6 +846,14 @@ export function writeRetrieveChatParams(w, p) {
845
846
  export function writeRetrievePrivateMessageHistoryParams(w, p) {
846
847
  w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.counterpart);
847
848
  }
849
+ /**
850
+ * RetrieveGameGroupMessageHistory(auth, …) — the history button of a game group's chat (#697). READ FROM THE CLIENT
851
+ * BUNDLE's writer, the same as RetrievePrivateMessageHistory's: the int32 game id, the lowest message id received in
852
+ * the group (string; 9999E14 when none), the group's int32 id. Reply as RetrieveChat's.
853
+ */
854
+ export function writeRetrieveGameGroupMessageHistoryParams(w, p) {
855
+ w.int32(p.gameId).string(beforeMarker(p.before)).int32(p.group);
856
+ }
848
857
  /**
849
858
  * SendChat(auth, …) per docs/WEB-PROTOCOL.md (read from the client's
850
859
  * serializer; the owner verifies it live): game id, text, channel, optional
@@ -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
  }
@@ -8,6 +8,8 @@ import { lossReport } from './how-lost.js';
8
8
  import { endOfGame, finishedAccount } from './end-of-game.js';
9
9
  import { foldFinished } from './profile-hook.js';
10
10
  import { NO_BOOT_MINUTES } from './boot-player.js';
11
+ import { readDecisionLog } from '../decision-log.js';
12
+ import { turnOrderFor } from './turn-order.js';
11
13
  const VIEWS = ['compact', 'full', 'raw'];
12
14
  function settingsDigest(s) {
13
15
  if (!s)
@@ -121,7 +123,12 @@ cards) {
121
123
  'pieces toward the next one and `of` how many make one; read by shape, UNVERIFIED live; `null` when unread), and ' +
122
124
  '`settings` (each card in play with a `duration`, and Sanctions\' `percentage` — negative raises the target\'s income — ' +
123
125
  '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.'),
126
+ 'failed read is `cardsUnread`, never an error. ' +
127
+ 'While the game is played and this server kept turns of it, `turnOrder` (#693) says who moves before me: per ' +
128
+ 'turn (the last turns read, this one and the next five) the order when known, else `beforeMe`/`afterMe`/`unknown` by ' +
129
+ 'player id, each row `known` (read from that turn) or `projected` (Cycle: the order reverses every turn); ' +
130
+ '`perOpponent` for this turn; `firstMover` only when every opponent agrees; Random games project nothing. ' +
131
+ 'For the map\'s bonuses and chokepoints use warapp_get_map. Read-only.'),
125
132
  _meta: lookupMeta(['warzone game', 'war.app game', 'whose turn is it', 'game status']),
126
133
  annotations: readAnnotations('Get a war.app game'),
127
134
  inputSchema: z.object({
@@ -163,8 +170,13 @@ cards) {
163
170
  }
164
171
  }
165
172
  const cardRead = cards ? await cards(game) : {};
173
+ // #693: the move order this turn and the next ones, from the turns this server kept (no request). The account is
174
+ // the decision log's own.
175
+ const log = dir && game.state === 'Playing' ? await readDecisionLog(dir(), game.id).catch(() => undefined) : undefined;
176
+ const turnOrder = log ? await turnOrderFor({ dataDir: dir(), game, me: log.playerId, log }) : undefined;
166
177
  const folded = {
167
178
  ...cardRead,
179
+ ...(turnOrder ? { turnOrder } : {}),
168
180
  ...(fold && fold.status !== 'off' ? { profileFold: fold } : {}),
169
181
  ...(lost ? { howLost: lost } : {}),
170
182
  ...(end && end.status !== 'off' ? { endOfGame: end } : {}),
@@ -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,9 @@ 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 { incomeRules } from '../analysis/player.js';
104
+ import { recordIncomeLow } from '../decision-log.js';
101
105
  import { HEADROOM_COMPACT, headroomView, headroomWarnings, keepTripwires, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
102
106
  const VIEWS = ['compact', 'full'];
103
107
  /** #415 task 4b: the chat-blocks-the-turn gate, the context's when set, else read from the environment. */
@@ -1449,7 +1453,11 @@ export async function livePlanSetup(ctx, a) {
1449
1453
  orderPriorityPossible: opponentCanHold(game.settings, 'Order Priority', turn - 1),
1450
1454
  })
1451
1455
  : null;
1452
- const mover = await firstMoverFor(ctx.dataDir, game, me, turn, first_mover, award, { write, ...(inferred ? { inferred } : {}) });
1456
+ const keptMover = await firstMoverFor(ctx.dataDir, game, me, turn, first_mover, award, { write, ...(inferred ? { inferred } : {}) });
1457
+ // #693: the move order of every seat, from the turns kept and this board's last turn (no request). It fills the
1458
+ // first mover only when nothing above gave one and every opponent still playing reads the same way; never verified.
1459
+ const turnOrder = await turnOrderFor({ dataDir: ctx.dataDir, game, me: me.id, info }).catch(() => undefined);
1460
+ const mover = keptMover.firstMover === undefined && turnOrder?.firstMover ? fromTurnOrder(turnOrder.firstMover, keptMover.warnings) : keptMover;
1453
1461
  const settings = plannerSettings(game.settings);
1454
1462
  const rules = cardRules(game.settings);
1455
1463
  // A team shares one hand (#163): mine and my teammates' cards.
@@ -1703,6 +1711,22 @@ export async function livePlanSetup(ctx, a) {
1703
1711
  seenPlays: playsShown ? lastPlays : undefined,
1704
1712
  // #606: the earlier boards (and my orders on them) for the strategy view's summary of past turns.
1705
1713
  pastBoards: history.boards,
1714
+ // #693: who moves before me, this turn and the next ones (plan_turn's full view).
1715
+ turnOrder,
1716
+ };
1717
+ }
1718
+ /** #693: the plan's first mover from the turn order: inferred, never verified (it orders moves, never sizes a hold). */
1719
+ function fromTurnOrder(f, warnings) {
1720
+ const said = f.basis === 'move-order' ? "war.app's move order for an earlier turn" : 'the order earlier turns\' visible moves ran in';
1721
+ return {
1722
+ firstMover: f.who,
1723
+ verified: false,
1724
+ view: {
1725
+ who: f.who === 'me' ? 'you' : 'opponent',
1726
+ source: 'inferred',
1727
+ line: `${f.who === 'me' ? 'You move' : 'Every opponent moves'} first on turn ${f.turn} (the move order alternates every turn; from ${said}, not verified).`,
1728
+ },
1729
+ warnings,
1706
1730
  };
1707
1731
  }
1708
1732
  /** The Airlift card's type id. */
@@ -2249,7 +2273,10 @@ export function registerTurnTools(server, ctx, opts = {}) {
2249
2273
  'keep only the opponents in view or holding land within 2 steps of yours, and `scale` sums the rest: their count, ' +
2250
2274
  '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
2275
  '`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), ' +
2276
+ '(with `nextIncomeIfConcededFall` and `bonusesAtRisk` when the plan concedes borders of a bonus you hold; ' +
2277
+ '#698: `nextIncome` is the best case, every capture landing and nothing falling, and `nextIncomeLow` with ' +
2278
+ '`nextIncomeLowFalls` the low end, the conceded borders and those the headroom says fall to less than their ' +
2279
+ "opponent's estimate gone), " +
2253
2280
  '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
2281
  'warnings and the reasoning. Its `orders` array is exactly what warapp_submit_turn takes — review it with ' +
2255
2282
  'the user first. Every plan reads the game profile (`profile`: format 1v1/ffa/teams, phase, standing ' +
@@ -2347,7 +2374,10 @@ export function registerTurnTools(server, ctx, opts = {}) {
2347
2374
  'neither takes alone) are advice, never in `orders`; `cards.team` says who plays each card, leaving theirs to them. ' +
2348
2375
  '`firstMover` is who the plan takes to move first this turn (null when unknown) and its `source`: ' +
2349
2376
  '"explicit" (`first_mover`), "award", or "remembered" — a turn this server kept, alternated (two players, ' +
2350
- 'cyclic order). ' +
2377
+ 'cyclic order) — or "inferred" (#693: from the move order of earlier turns, any number of players, only when every ' +
2378
+ 'opponent still playing moves on the same side of you; never verified, so it orders moves but sizes no hold). ' +
2379
+ 'View "full" adds `turnOrder`: who moves before you on the last turns read, this one and the next five (as ' +
2380
+ 'warapp_get_game reports it). ' +
2351
2381
  'When one opponent touches two or more of your borders and no fixed split of the deploys there holds them all, ' +
2352
2382
  '`guess` is a randomized split, weighted by what each border is worth, against an opponent who would read a fixed ' +
2353
2383
  'one, and `guessOrders` the plan\'s `orders` with that split — optional (the user chooses; `orders` stay the ' +
@@ -2954,6 +2984,21 @@ export function registerTurnTools(server, ctx, opts = {}) {
2954
2984
  ...(mover.firstMover !== undefined && mover.verified ? { firstMover: mover.firstMover } : {}),
2955
2985
  ...(advised ? { orderPriority: true } : {}),
2956
2986
  });
2987
+ // #698: the low end of next income — the conceded borders and those the headroom says fall to less than
2988
+ // their opponent's own estimate gone (report only; kept in the decision log to be scored against the outcome).
2989
+ const incomeLow = nextIncomeLow({
2990
+ graph,
2991
+ rules: incomeRules(game.settings),
2992
+ board,
2993
+ me: me.id,
2994
+ captures: plan.expected.captures,
2995
+ conceded: plan.conceded,
2996
+ nextIncome: plan.expected.nextIncome,
2997
+ headroom,
2998
+ estimateOf: (p) => estimates.find((e) => e.playerId === p)?.estimate,
2999
+ });
3000
+ if (incomeLow && ctx.dataDir && turn !== null && !whatIf)
3001
+ await recordIncomeLow(ctx.dataDir, game.id, me.id, turn, incomeLow, ctx.decisionLog ? { mode: ctx.decisionLog } : {});
2957
3002
  const guessOrders = guess ? guessOrdersOf(orders, guess) : undefined;
2958
3003
  // Owner request 2026-11-24: with Airlift cards in hand, the best plan that plays them, ALONGSIDE the plain
2959
3004
  // plan (whose orders never change): candidates scored by the plain plan's own measure (airlift-plan.ts).
@@ -3241,6 +3286,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
3241
3286
  })(),
3242
3287
  // #127: who moves first this turn and how it is known; null when unknown.
3243
3288
  firstMover: mover.view,
3289
+ // #693: who moves before me this turn and the next ones (full view only).
3290
+ ...(rung === 'full' && setup.turnOrder ? { turnOrder: setup.turnOrder } : {}),
3244
3291
  // #166: what the award of picks showed (absent when no pick list is kept for this game).
3245
3292
  ...(award ? { award: awardView(award, game, turn, name) } : {}),
3246
3293
  trendSource: trend?.source ?? null,
@@ -3391,6 +3438,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
3391
3438
  return { id, name: b.name, value: b.value };
3392
3439
  }),
3393
3440
  nextIncome: plan.expected.nextIncome,
3441
+ // #698: the low end, when a border falling would cost income (conceded, or below its opponent's estimate).
3442
+ ...(incomeLow ? { nextIncomeLow: incomeLow.low, nextIncomeLowFalls: incomeLow.falls.map(name) } : {}),
3394
3443
  // #109: present only when the plan's concessions put income at risk.
3395
3444
  ...(plan.expected.nextIncomeIfConcededFall !== undefined
3396
3445
  ? {
@@ -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.26.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.26.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",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrischall/warapp-mcp",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "mcpName": "io.github.chrischall/warapp-mcp",
5
5
  "description": "war.app (Warzone) game advisor MCP server for Claude — games, maps, bonuses and board analysis via the GameFeed API, plus your games list, opponent scouting, the live board, territory picks, cards, turn planning and submission, turn notifications and chat through your signed-in war.app tab. Developed and maintained by AI (Claude Code).",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/warapp-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.25.0",
9
+ "version": "0.26.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@chrischall/warapp-mcp",
14
- "version": "0.25.0",
14
+ "version": "0.26.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },