@chrischall/warapp-mcp 0.1.0 → 0.2.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 (74) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +28 -17
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +12392 -9245
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/finished-store.js +357 -0
  22. package/dist/index.js +1 -1
  23. package/dist/lessons-store.js +356 -0
  24. package/dist/live.js +9 -0
  25. package/dist/map-details.js +127 -0
  26. package/dist/map-stats.js +14 -6
  27. package/dist/map-store.js +44 -6
  28. package/dist/my-games.js +44 -6
  29. package/dist/normalize.js +34 -2
  30. package/dist/notifications.js +143 -0
  31. package/dist/outlook-log.js +28 -1
  32. package/dist/player-record-store.js +2 -0
  33. package/dist/profile-store.js +61 -11
  34. package/dist/protocol/methods.js +86 -2
  35. package/dist/replay.js +16 -4
  36. package/dist/stats.js +26 -4
  37. package/dist/strategy/notes.js +64 -9
  38. package/dist/surrender-pending.js +126 -0
  39. package/dist/tools/accept-surrender.js +311 -0
  40. package/dist/tools/chat-inbox.js +17 -5
  41. package/dist/tools/chat-read-mark.js +179 -0
  42. package/dist/tools/chat.js +50 -8
  43. package/dist/tools/check-plan.js +1 -0
  44. package/dist/tools/commander-check.js +1 -0
  45. package/dist/tools/end-of-game.js +384 -0
  46. package/dist/tools/game.js +31 -6
  47. package/dist/tools/index.js +15 -5
  48. package/dist/tools/live-context.js +1 -1
  49. package/dist/tools/map-details.js +88 -0
  50. package/dist/tools/map-stats.js +15 -2
  51. package/dist/tools/map.js +10 -2
  52. package/dist/tools/my-games.js +77 -7
  53. package/dist/tools/notifications.js +484 -0
  54. package/dist/tools/opponents.js +14 -2
  55. package/dist/tools/past-games.js +94 -0
  56. package/dist/tools/picks.js +15 -2
  57. package/dist/tools/profile-opponents.js +1 -1
  58. package/dist/tools/profile-reads.js +3 -3
  59. package/dist/tools/push.js +72 -12
  60. package/dist/tools/strategy.js +65 -8
  61. package/dist/tools/stress-opponents.js +1 -1
  62. package/dist/tools/surrender-pending.js +74 -0
  63. package/dist/tools/surrender.js +10 -3
  64. package/dist/tools/team.js +1 -5
  65. package/dist/tools/turn.js +79 -15
  66. package/dist/tools/where.js +42 -17
  67. package/dist/tools/write-kit.js +6 -0
  68. package/dist/trend.js +145 -20
  69. package/dist/version.js +1 -1
  70. package/manifest.json +22 -2
  71. package/mint.yaml +14 -9
  72. package/package.json +1 -1
  73. package/server.json +2 -2
  74. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -5,6 +5,7 @@ import { registerBeginTurnTool } from './begin-turn.js';
5
5
  import { registerBoardTool } from './board.js';
6
6
  import { registerChatTools } from './chat.js';
7
7
  import { registerChatInboxTool } from './chat-inbox.js';
8
+ import { registerMarkChatReadTool } from './chat-read-mark.js';
8
9
  import { registerCheckPlanTool } from './check-plan.js';
9
10
  import { registerGameTool } from './game.js';
10
11
  import { registerHealthcheckTool } from './healthcheck.js';
@@ -14,6 +15,7 @@ import { registerLiveTools } from './live.js';
14
15
  import { registerMapTool } from './map.js';
15
16
  import { registerMapStatsTool } from './map-stats.js';
16
17
  import { registerMyGamesTool } from './my-games.js';
18
+ import { registerNotificationTools } from './notifications.js';
17
19
  import { registerOpenGamesTool } from './open-games.js';
18
20
  import { registerOpponentsTool } from './opponents.js';
19
21
  import { registerPickTools } from './picks.js';
@@ -25,6 +27,7 @@ import { registerScoutTool } from './scout.js';
25
27
  import { registerSessionTools } from './session.js';
26
28
  import { registerStrategyTool } from './strategy.js';
27
29
  import { registerSurrenderTool } from './surrender.js';
30
+ import { registerAcceptSurrenderTool } from './accept-surrender.js';
28
31
  import { registerTeamTool } from './team.js';
29
32
  import { registerTeamBriefTool } from './team-brief.js';
30
33
  import { registerTurnTools } from './turn.js';
@@ -73,8 +76,9 @@ export function registerAllTools(server, deps = {}) {
73
76
  identity: () => bridge.identityState(),
74
77
  });
75
78
  registerHealthcheckTool(server, fetchproxy, bridge, deps);
76
- registerGameTool(server, client, () => dataDir(deps.env), deps.env);
77
- registerMapTool(server, client);
79
+ // The signed-in account names a finished game's player for its end-of-game pass when no board was cached (#312).
80
+ registerGameTool(server, client, () => dataDir(deps.env), deps.env, () => live.myInviteToken());
81
+ registerMapTool(server, client, live);
78
82
  // Opt-in (WARAPP_STATS=1), never hosted: the tool refuses before any request
79
83
  // when off. One collector per registration, so its 1 s throttle spans calls.
80
84
  registerMapStatsTool(server, {
@@ -84,18 +88,20 @@ export function registerAllTools(server, deps = {}) {
84
88
  ...(deps.sleep ? { sleep: deps.sleep } : {}),
85
89
  }),
86
90
  mapCache: deps.mapCache ?? defaultMapCache,
91
+ dataDir: () => dataDir(deps.env),
87
92
  ...(deps.env ? { env: deps.env } : {}),
88
93
  });
89
94
  registerBoardTool(server, client, live);
90
95
  registerRouteTool(server, client);
91
- registerStrategyTool(server, client);
96
+ registerStrategyTool(server, client, live);
92
97
  registerLiveTools(server, live);
93
- registerPickTools(server, live);
94
- registerMyGamesTool(server, live);
98
+ registerPickTools(server, live, deps.env ? { env: deps.env } : {});
99
+ registerMyGamesTool(server, live, deps.env ? { env: deps.env } : {});
95
100
  registerOpenGamesTool(server, live);
96
101
  registerJoinGameTool(server, live);
97
102
  registerLeaveGameTool(server, live);
98
103
  registerSurrenderTool(server, live);
104
+ registerAcceptSurrenderTool(server, live);
99
105
  registerBeginTurnTool(server, live);
100
106
  registerScoutTool(server, live, deps.env ? { env: deps.env } : {});
101
107
  registerTurnTools(server, live, deps.env ? { env: deps.env } : {});
@@ -108,6 +114,10 @@ export function registerAllTools(server, deps = {}) {
108
114
  registerUncommitTool(server, live);
109
115
  registerChatTools(server, live, deps.env ? { env: deps.env } : {});
110
116
  registerChatInboxTool(server, live);
117
+ // Local and hosted: war.app's own chat read mark, confirm-gated (#311).
118
+ registerMarkChatReadTool(server, live);
119
+ // Local and hosted: the account's own notifications, through its war.app tab.
120
+ registerNotificationTools(server, live, deps.env ? { env: deps.env } : {});
111
121
  registerTeamTool(server, live);
112
122
  // C4: the team brief, read-only — the facts for a team-chat message, never sent.
113
123
  registerTeamBriefTool(server, live);
@@ -123,7 +123,7 @@ export function bundleFetcher(bridge, fetchImpl = fetch, limits = {}) {
123
123
  };
124
124
  }
125
125
  /** What to do about a frozen tab, said on every bridged `/Services` timeout (#130). */
126
- const FROZEN_TAB_HINT = 'Chrome freezes background tabs, and war.app calls are relayed through a page tab: a frozen tab stalls them ' +
126
+ export const FROZEN_TAB_HINT = 'Chrome freezes background tabs, and war.app calls are relayed through a page tab: a frozen tab stalls them ' +
127
127
  'while page reads still work. Reload or focus a war.app tab, then check the game before retrying.';
128
128
  /** A bridge timeout (fetchproxy's `FetchproxyTimeoutError`, matched by name across package copies). */
129
129
  const isBridgeTimeout = (e) => e instanceof Error && e.name === 'FetchproxyTimeoutError';
@@ -0,0 +1,88 @@
1
+ // A map's distribution modes with the territories each lets a player start on (#328), read lazily from war.app's
2
+ // map details (GetMapDetails, method 73, no auth) through the web-client channel and kept with the map
3
+ // (src/map-store.ts). Asked only when a caller needs a mode's territories and the map lacks them, at most once
4
+ // per map per process (a failure is never retried in a loop); a failure leaves them unknown (`null`), never `[]`.
5
+ // UNVERIFIED live beyond #328's trace (src/map-details.ts).
6
+ import { applyModeTerritories, readMapDetailsModes } from '../map-details.js';
7
+ import { Method, writeGetMapDetailsParams } from '../protocol/methods.js';
8
+ import { failureText } from './live-context.js';
9
+ const known = (d) => Array.isArray(d.territories);
10
+ /** `map` with every mode not known marked unknown (`null`). */
11
+ const unknownRest = (map) => ({
12
+ ...map,
13
+ distributionModes: map.distributionModes.map((d) => (known(d) ? d : { ...d, territories: null })),
14
+ });
15
+ const UNKNOWN = (map, why) => `The starting territories of map ${map.id}'s distribution modes could not be read from war.app's map details (${why}); ` +
16
+ 'they stay unknown and are not asked again until the server restarts.';
17
+ /**
18
+ * `map` (the game's, overrides applied or not) with its modes' territories: what the cached map already has,
19
+ * else read from war.app's map details and kept (the cached base map and the store). Never throws.
20
+ */
21
+ export async function withModeTerritories(ctx, map) {
22
+ if (map.distributionModes.every(known))
23
+ return { map, warnings: [] };
24
+ if (ctx.client.mapDetailsTried(map.id)) {
25
+ return { map: unknownRest(map), warnings: [UNKNOWN(map, 'an earlier read this session did not give them')] };
26
+ }
27
+ ctx.client.markMapDetailsTried(map.id);
28
+ let byMode;
29
+ try {
30
+ const env = await ctx.rpc.call('GetMapDetails', Method.GetMapDetails, (w) => writeGetMapDetailsParams(w, map.id));
31
+ byMode = readMapDetailsModes(await ctx.bundle(), env.body);
32
+ }
33
+ catch (e) {
34
+ return { map: unknownRest(map), warnings: [UNKNOWN(map, failureText(e))] };
35
+ }
36
+ if (byMode === null)
37
+ return { map: unknownRest(map), warnings: [UNKNOWN(map, 'the reply carried no result')] };
38
+ const read = applyModeTerritories(map, byMode);
39
+ if (read.found.size)
40
+ await ctx.client.keepModeTerritories(map.id, read.found).catch(() => { });
41
+ const missing = read.map.distributionModes.filter((d) => d.territories === null).map((d) => d.id);
42
+ const warnings = [...read.warnings];
43
+ if (missing.length)
44
+ warnings.push(UNKNOWN(map, `none listed for mode${missing.length === 1 ? '' : 's'} ${missing.join(', ')}`));
45
+ return { map: read.map, warnings };
46
+ }
47
+ /** One mode as warapp_get_map's full view lists it: its territory count and ids, `null` both when unknown. */
48
+ export function modeRow(d) {
49
+ const ids = Array.isArray(d.territories) ? d.territories : null;
50
+ return {
51
+ id: d.id,
52
+ name: d.name,
53
+ ...(d.type !== undefined ? { type: d.type } : {}),
54
+ territoryCount: ids ? ids.length : null,
55
+ territories: ids,
56
+ };
57
+ }
58
+ /**
59
+ * The map distribution mode an automatically distributed game dealt its starts from (#328): its settings say
60
+ * `AutomaticTerritoryDistribution` "Automatic" and name, as `DistributionMode`, a mode of the map. `undefined`
61
+ * otherwise — manual picks (the live board's pickable territories say where then), full distribution (-1),
62
+ * random or custom distributions (no map mode), or settings that do not say.
63
+ */
64
+ export function dealtMode(settings, map) {
65
+ if (settings?.raw.AutomaticTerritoryDistribution !== 'Automatic' || settings.distributionMode === undefined)
66
+ return undefined;
67
+ return map.distributionModes.find((d) => d.id === settings.distributionMode);
68
+ }
69
+ /**
70
+ * The territories `mode` (a mode of `map`) dealt starts among: what the map already has, else read once from
71
+ * war.app's map details ({@link withModeTerritories}). Unknown (`null`, with the reasons) when the read failed or
72
+ * listed none for it. Never throws.
73
+ */
74
+ export async function modeStarts(ctx, map, mode) {
75
+ const read = await withModeTerritories(ctx, map);
76
+ const ids = read.map.distributionModes.find((d) => d.id === mode)?.territories;
77
+ if (Array.isArray(ids) && ids.length)
78
+ return { mode, territories: ids };
79
+ return {
80
+ mode,
81
+ territories: null,
82
+ warnings: [
83
+ `The game dealt its starts automatically from the map's distribution mode ${mode}, whose territories are unknown, ` +
84
+ 'so they are not used as start candidates.',
85
+ ...read.warnings,
86
+ ],
87
+ };
88
+ }
@@ -8,6 +8,7 @@ import { MIN_RATE_SAMPLE, MIN_SAMPLE, mapStats } from '../map-stats.js';
8
8
  import { DEFAULT_NEW_GAMES, MAX_NEW_GAMES, STATS_ENV, statsGate } from '../stats.js';
9
9
  import { readAnnotations, respond, untrustedDescription } from './common.js';
10
10
  import { lookupMeta } from './hints.js';
11
+ import { mapRecordFor, mapRecordView } from './past-games.js';
11
12
  function refusal(gate) {
12
13
  if (gate.reason === 'hosted') {
13
14
  return new McpToolError('Map statistics are off on a hosted server.', {
@@ -49,7 +50,9 @@ export function registerMapStatsTool(server, deps) {
49
50
  'could not be read are counted apart, never cached. Each call reads the ladder’s game-ID feed and fetches up to ' +
50
51
  `max_new_games new games (default ${DEFAULT_NEW_GAMES}, max ${MAX_NEW_GAMES}, one request a second); ` +
51
52
  'finished games are cached forever, so stats grow across calls. OPT-IN: off unless the server runs ' +
52
- `locally with ${STATS_ENV}=1, and always off when hosted. Read-only.`),
53
+ `locally with ${STATS_ENV}=1, and always off when hosted. ` +
54
+ '`myGames` adds your own finished games on the map, from their histories (no request): results, your results by start bonus, the ' +
55
+ "bonuses winners started in, and the pace — the median income after turns 4 and 8 of the winners and of you. Read-only."),
53
56
  _meta: lookupMeta(['map stats', 'best starting picks', 'ladder statistics', 'which bonus wins']),
54
57
  annotations: readAnnotations('war.app map statistics'),
55
58
  inputSchema: z.object({
@@ -96,10 +99,20 @@ export function registerMapStatsTool(server, deps) {
96
99
  }
97
100
  const [stats] = mapStats(records);
98
101
  const map = deps.mapCache.get(map_id);
102
+ // #312 E3: my own finished games on the map (the end-of-game record; no request).
103
+ const mine = await mapRecordFor(deps.dataDir?.(), deps.env, map_id);
104
+ const names = new Map(map?.bonuses.map((b) => [b.id, b.name]));
99
105
  return respond(undefined, ['compact'], () => ({
100
106
  map: map ? { id: map.id, name: map.name } : { id: map_id },
101
107
  ...(collected ? { collected } : {}),
102
108
  ...(warning ? { warning } : {}),
109
+ ...(mine
110
+ ? {
111
+ myGames: mine === 'unreadable'
112
+ ? mine
113
+ : mapRecordView(mine, { bonusName: (id) => ({ id, name: names.get(id) ?? String(id) }), full: true }),
114
+ }
115
+ : {}),
103
116
  ...(stats
104
117
  ? { stats: named(stats, map) }
105
118
  : {
@@ -108,7 +121,7 @@ export function registerMapStatsTool(server, deps) {
108
121
  }),
109
122
  assumptions: 'Starting territories are read from the first history board where players hold land (a game with no ' +
110
123
  'such board is left out of every figure and never cached; `collected.unreadable` says how many this call skipped, ' +
111
- 'across the ladder), a player counts toward every bonus holding one ' +
124
+ 'across the ladder, and `collected.unreadableGames` why, by key name), a player counts toward every bonus holding one ' +
112
125
  'of its starts, and a bonus ' +
113
126
  'turn is the history entry (completed turns) on which a player first held a whole positive bonus. ' +
114
127
  'The game-ID feed and history shapes are unverified (docs/WARAPP-API.md).',
package/dist/tools/map.js CHANGED
@@ -3,6 +3,7 @@ import { z } from 'zod';
3
3
  import { analyzeBonuses, applyBonusOverrides, findChokepoints } from '../analysis/index.js';
4
4
  import { gameIdArg, graphOf, mapSummary, readAnnotations, respond, round2, untrustedDescription, untrustedText, viewArg } from './common.js';
5
5
  import { lookupMeta } from './hints.js';
6
+ import { modeRow, withModeTerritories } from './map-details.js';
6
7
  const VIEWS = ['compact', 'full'];
7
8
  const DEFAULT_LIMIT = 25;
8
9
  const COMPACT_CHOKEPOINTS = 20;
@@ -62,13 +63,15 @@ function chokepoints(g, limit) {
62
63
  connects: c.connectsBonusIds.map((id) => bonusName(id)),
63
64
  }));
64
65
  }
65
- export function registerMapTool(server, client) {
66
+ export function registerMapTool(server, client, live) {
66
67
  server.registerTool('warapp_get_map', {
67
68
  title: 'Get a war.app game map: bonuses and chokepoints',
68
69
  description: untrustedDescription('Analyze the map of a war.app (Warzone) game: a bonus table ranked easiest-to-take first (army value, ' +
69
70
  'territory count, border territories to defend, entry points, value per territory, ease score) and the ' +
70
71
  'map\'s chokepoints (articulation points, bridges between regions, narrow connectors). Filter with ' +
71
72
  '`bonus` (part of a bonus name) to see one bonus\'s territories, borders and entry points by name. ' +
73
+ 'View "full" also lists the map\'s distribution modes with the territories each lets a player start on ' +
74
+ '(read once from war.app\'s map details through the web-client channel (direct or bridge), then kept with the map; unknown is null). ' +
72
75
  'Map-only — needs no board, so it works in a lobby. Read-only.'),
73
76
  _meta: lookupMeta(['warzone map', 'best bonuses', 'easiest bonus', 'chokepoints']),
74
77
  annotations: readAnnotations('Get a war.app map'),
@@ -81,13 +84,16 @@ export function registerMapTool(server, client) {
81
84
  .describe('Bonus order: "easiest" (default — ease score = value / (territories + borders)), "value", or "name".'),
82
85
  limit: z.coerce.number().int().min(1).max(1000).optional().describe(`Max bonus rows (default ${DEFAULT_LIMIT} on compact; all on full).`),
83
86
  view: viewArg(VIEWS, `compact (default) keeps positive-value bonuses as one-line rows (counts, value per territory, score) and the top ${COMPACT_CHOKEPOINTS} chokepoints; ` +
84
- '"full" lists every bonus (zero and negative included) with member, border and entry-point territories by name, and every chokepoint.'),
87
+ '"full" lists every bonus (zero and negative included) with member, border and entry-point territories by name, every chokepoint, ' +
88
+ 'and each distribution mode with its starting territory count and ids.'),
85
89
  }),
86
90
  }, async ({ game_id, bonus, sort, limit, view }) => {
87
91
  // Settings carry the game's overridden bonus values, which the bonus table reports.
88
92
  const game = await client.getGame(game_id, { settings: true });
89
93
  const map = mapOf(game);
90
94
  const g = graphOf(map);
95
+ // #328: only the full table lists the modes' starting territories, so only it may ask war.app for them.
96
+ const modes = view === 'full' && !bonus?.trim() ? await withModeTerritories(live, map) : undefined;
91
97
  const order = SORTS[sort ?? 'easiest'];
92
98
  return respond(view, VIEWS, (rung) => {
93
99
  const all = analyzeBonuses(g);
@@ -111,6 +117,8 @@ export function registerMapTool(server, client) {
111
117
  bonuses: shown.map((b) => detail(g, b)),
112
118
  bonusesShown: `${shown.length} of ${sorted.length}`,
113
119
  chokepoints: chokepoints(g),
120
+ distributionModes: (modes?.map ?? map).distributionModes.map(modeRow),
121
+ ...(modes?.warnings.length ? { warnings: modes.warnings } : {}),
114
122
  };
115
123
  }
116
124
  const positive = all.filter((b) => b.value >= 1).sort(order);
@@ -10,12 +10,16 @@
10
10
  // games together and that the server honours a count above 10.
11
11
  import { untrustedEnvelope } from '@chrischall/mcp-utils';
12
12
  import { z } from 'zod';
13
- import { briefGameLine, isFinished, readMyGames, summarizeMyGames } from '../my-games.js';
13
+ import { briefGameLine, gameStateName, isFinished, readMyGames, summarizeMyGames } from '../my-games.js';
14
14
  import { Method, MY_GAMES_DEFAULT_SORT, MyGamesFilterType, writeGetMyGamesParams } from '../protocol/methods.js';
15
- import { readAnnotations, respond, untrustedDescription, WARAPP_UNTRUSTED_NOTE } from './common.js';
15
+ import { readAnnotations, respond, untrustedDescription, untrustedText, WARAPP_UNTRUSTED_NOTE } from './common.js';
16
16
  import { canonicalMeta } from './hints.js';
17
17
  import { BRIDGE_NOTE } from './live.js';
18
+ import { holdsSeat, playerStateName } from '../player-states.js';
19
+ import { sweepFinished } from './end-of-game.js';
18
20
  import { accountUnknown } from './write-kit.js';
21
+ import { pendingSurrenders, surrenderOwed } from '../surrender-pending.js';
22
+ import { readDetailsSeats, SURRENDER_PENDING_NOTE, surrenderMayBePending } from './surrender-pending.js';
19
23
  const VIEWS = ['compact', 'brief'];
20
24
  /** The note line a brief answer ends with when the list may be partial (a `-- ` line is never a game). */
21
25
  const partialLine = (listed) => `-- the list may be partial: war.app returned ${listed} games, the most this server asks for`;
@@ -73,15 +77,65 @@ export async function fetchMyGames(ctx) {
73
77
  const [me, list] = await Promise.all([myInGameId(ctx), listMyGames(read)]);
74
78
  return { me, ...list };
75
79
  }
76
- export function registerMyGamesTool(server, ctx) {
80
+ /** #317: the most games whose details one call reads for a pending surrender (the rest are `null`). */
81
+ export const MAX_SURRENDER_READS = 20;
82
+ /** Details read at once. */
83
+ const SURRENDER_READ_BATCH = 4;
84
+ /**
85
+ * #317: each game's pending surrenders, by game id: read for a game being played or picked where my seat
86
+ * still plays (at most {@link MAX_SURRENDER_READS}, war.app's order), `null` elsewhere or when unreadable.
87
+ * GetMyGames carries no GameFeed id, so `player` is `null`; the name is the list's, untrusted.
88
+ */
89
+ export async function myGamesSurrenders(ctx, games, me) {
90
+ const byGame = new Map();
91
+ const eligible = games.filter((g) => {
92
+ const mine = g.players.find((p) => p.id === me);
93
+ return surrenderMayBePending(gameStateName(g.stateCode), mine ? playerStateName(mine.stateCode) : undefined);
94
+ });
95
+ const read = eligible.slice(0, MAX_SURRENDER_READS);
96
+ for (let i = 0; i < read.length; i += SURRENDER_READ_BATCH) {
97
+ const batch = read.slice(i, i + SURRENDER_READ_BATCH);
98
+ const seats = await Promise.all(batch.map((g) => readDetailsSeats(ctx, g.id)));
99
+ batch.forEach((g, j) => {
100
+ const s = seats[j];
101
+ const names = new Map(g.players.map((p) => [p.id, p.name]));
102
+ byGame.set(g.id, s
103
+ ? pendingSurrenders(s, me).map((p) => ({ ...p, name: names.has(p.inGameId) ? untrustedText(names.get(p.inGameId)) : null }))
104
+ : null);
105
+ });
106
+ }
107
+ return { byGame, skipped: eligible.length - read.length };
108
+ }
109
+ /**
110
+ * The finished games of `me` (in-game id) in a GetMyGames list where its seat was held, newest first: the
111
+ * end-of-game sweep's candidates (#312).
112
+ */
113
+ export function finishedGamesOf(games, me) {
114
+ return games
115
+ .filter((g) => isFinished(g) && g.players.some((p) => p.id === me && holdsSeat(playerStateName(p.stateCode))))
116
+ .map((g) => g.id)
117
+ .sort((a, b) => b - a);
118
+ }
119
+ /**
120
+ * Also the end-of-game sweep (#312, src/tools/end-of-game.ts): the account's finished games not yet
121
+ * processed get their pass, at most `END_OF_GAME_PER_CALL` per call (`endOfGame` in the compact answer).
122
+ */
123
+ export function registerMyGamesTool(server, ctx, deps = {}) {
124
+ const env = deps.env ?? process.env;
77
125
  server.registerTool('warapp_my_games', {
78
126
  title: 'List my war.app games and which need me',
79
127
  description: untrustedDescription('Your war.app (Warzone) games, games waiting on you first: each with its id, name, state ' +
80
128
  '(WaitingForPlayers, DistributingTerritories, Playing, Finished), turn, players (name, state, whether ' +
81
129
  'they have committed this turn) and waitingOnYou — true when the game is being played or distributing ' +
82
- 'territories, you are still playing, and you have not committed. Finished games are left out unless ' +
130
+ 'territories, you are still playing, and you have not committed — and surrenderPending: the surrenders other ' +
131
+ 'players asked for that are still pending, each with owedByMe (true: waiting for you to accept it), read from ' +
132
+ 'the game details (unverified live; null when not read or unreadable, never "none"); the top-level ' +
133
+ 'surrenderPending counts the games where one waits on you, and those games come first too. ' +
134
+ 'Finished games are left out unless ' +
83
135
  '`include_finished` (`finishedLeftOut` counts them). `listed` is how many games war.app returned and ' +
84
136
  '`complete` false (with a `warning`) means the list may be partial. Use the id with the other warapp tools. ' +
137
+ 'Each call also gives up to two of your newest 250 finished games not yet processed their end-of-game pass (`endOfGame`: ' +
138
+ 'each game\'s history read once from GameFeed and kept name-free for later games; `pending` counts the rest). ' +
85
139
  `${BRIDGE_NOTE} Read-only.`),
86
140
  _meta: canonicalMeta('whats-new', ['my games', 'warzone', 'whose turn', 'games waiting on me', 'which games need me']),
87
141
  annotations: readAnnotations('List my war.app games'),
@@ -92,7 +146,7 @@ export function registerMyGamesTool(server, ctx) {
92
146
  .describe('"compact" (default): the games as described. "brief": one line per game — name — "turn N" (or the ' +
93
147
  'state when not being played) — "waiting on you" or "waiting on others", inside the untrusted-data ' +
94
148
  'envelope as data: string[]; "-- none" when there are no games, and a last "-- the list may be ' +
95
- 'partial…" line when it may be.'),
149
+ 'partial…" line when it may be. Brief reads no game details, so it says nothing of pending surrenders.'),
96
150
  include_finished: z
97
151
  .boolean()
98
152
  .optional()
@@ -100,18 +154,34 @@ export function registerMyGamesTool(server, ctx) {
100
154
  }),
101
155
  }, async ({ view, include_finished }) => {
102
156
  const { me, games: raw, partial } = await fetchMyGames(ctx);
157
+ // #312: the end-of-game sweep, bounded per call; best effort, never throws.
158
+ const token = ctx.dataDir ? await ctx.myInviteToken().catch(() => undefined) : undefined;
159
+ const sweep = token !== undefined ? await sweepFinished({ client: ctx.client, dataDir: ctx.dataDir, env }, token, finishedGamesOf(raw, me)) : undefined;
160
+ const endOfGame = sweep && (sweep.processed.length || sweep.pending) ? { endOfGame: sweep } : {};
103
161
  const kept = include_finished ? raw : raw.filter((g) => !isFinished(g));
104
- const games = summarizeMyGames(kept, me);
162
+ const summary = summarizeMyGames(kept, me);
105
163
  if (view === 'brief')
106
- return briefResult(games, partial ? raw.length : undefined);
164
+ return briefResult(summary, partial ? raw.length : undefined);
107
165
  const finishedLeftOut = raw.length - kept.length;
166
+ // #317: the surrenders pending in each game (the game details; null: not read or unreadable, never "none").
167
+ const { byGame, skipped } = await myGamesSurrenders(ctx, kept, me);
168
+ const withSurrenders = summary.map((g) => ({ ...g, surrenderPending: byGame.get(g.id) ?? null }));
169
+ // A game waiting on my acceptance waits on me too: it goes first with the turns waiting on me.
170
+ const first = (g) => g.waitingOnYou || surrenderOwed(g.surrenderPending);
171
+ const games = [...withSurrenders.filter(first), ...withSurrenders.filter((g) => !first(g))];
172
+ const unread = games.filter((g) => g.surrenderPending === null && byGame.has(g.id)).length;
108
173
  return respond(undefined, ['compact'], () => ({
109
174
  games,
110
175
  count: games.length,
111
176
  waitingOnYou: games.filter((g) => g.waitingOnYou).length,
177
+ surrenderPending: games.filter((g) => surrenderOwed(g.surrenderPending)).length,
178
+ surrenderNote: SURRENDER_PENDING_NOTE +
179
+ (unread ? ` The details of ${unread} game(s) could not be read.` : '') +
180
+ (skipped ? ` ${skipped} more game(s) were not read (at most ${MAX_SURRENDER_READS} per call).` : ''),
112
181
  listed: raw.length,
113
182
  ...(finishedLeftOut ? { finishedLeftOut } : {}),
114
183
  complete: !partial,
184
+ ...endOfGame,
115
185
  ...(partial
116
186
  ? {
117
187
  warning: `The list may be partial: war.app returned ${raw.length} games, the most this server asks for. ` +