@chrischall/warapp-mcp 0.22.0 → 0.23.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 (73) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -3
  4. package/dist/analysis/coalition.js +3 -2
  5. package/dist/analysis/guard-off.js +7 -0
  6. package/dist/analysis/headroom.js +1 -0
  7. package/dist/analysis/outlook.js +42 -2
  8. package/dist/analysis/plan/captures.js +2 -0
  9. package/dist/analysis/plan/holds.js +25 -8
  10. package/dist/analysis/plan/report.js +2 -2
  11. package/dist/analysis/plan/targets.js +15 -5
  12. package/dist/analysis/plan/threats.js +55 -2
  13. package/dist/analysis/planner.js +12 -1
  14. package/dist/bundle.js +10245 -3743
  15. package/dist/chat.js +93 -3
  16. package/dist/clans.js +308 -0
  17. package/dist/forums.js +70 -0
  18. package/dist/friends.js +83 -0
  19. package/dist/index.js +1 -1
  20. package/dist/invite-code.js +46 -0
  21. package/dist/join-color.js +23 -13
  22. package/dist/ladders.js +360 -0
  23. package/dist/lessons-store.js +2 -2
  24. package/dist/mail.js +295 -0
  25. package/dist/my-games.js +18 -1
  26. package/dist/notifications.js +22 -4
  27. package/dist/open-games.js +29 -2
  28. package/dist/outlook-log.js +1 -0
  29. package/dist/protocol/bundle.js +4 -4
  30. package/dist/protocol/codec.js +1 -1
  31. package/dist/protocol/methods.js +690 -8
  32. package/dist/protocol/rpc.js +28 -3
  33. package/dist/push/socketio.js +2 -2
  34. package/dist/quickmatch.js +264 -0
  35. package/dist/surrender-pending.js +62 -2
  36. package/dist/templates.js +451 -0
  37. package/dist/tools/bait.js +6 -2
  38. package/dist/tools/boot-player.js +165 -0
  39. package/dist/tools/chat.js +19 -0
  40. package/dist/tools/check-plan.js +5 -3
  41. package/dist/tools/clan-writes.js +208 -0
  42. package/dist/tools/clans.js +181 -0
  43. package/dist/tools/end-game-common.js +49 -0
  44. package/dist/tools/forums.js +535 -0
  45. package/dist/tools/friends.js +50 -0
  46. package/dist/tools/game.js +21 -3
  47. package/dist/tools/index.js +39 -0
  48. package/dist/tools/invites.js +347 -0
  49. package/dist/tools/join-game.js +4 -4
  50. package/dist/tools/ladders.js +418 -0
  51. package/dist/tools/leave-game.js +85 -27
  52. package/dist/tools/live-context.js +2 -2
  53. package/dist/tools/mail.js +600 -0
  54. package/dist/tools/my-games.js +50 -6
  55. package/dist/tools/notifications.js +12 -3
  56. package/dist/tools/nudge.js +178 -0
  57. package/dist/tools/past-games.js +23 -0
  58. package/dist/tools/quickmatch.js +481 -0
  59. package/dist/tools/react.js +177 -0
  60. package/dist/tools/session.js +6 -2
  61. package/dist/tools/team-surrender.js +206 -0
  62. package/dist/tools/templates.js +342 -0
  63. package/dist/tools/tournaments.js +495 -0
  64. package/dist/tools/turn.js +18 -8
  65. package/dist/tools/vote-to-end.js +142 -0
  66. package/dist/tools/write-kit.js +22 -1
  67. package/dist/tournaments.js +321 -0
  68. package/dist/version.js +1 -1
  69. package/manifest.json +190 -2
  70. package/mint.yaml +3 -4
  71. package/package.json +1 -1
  72. package/server.json +2 -2
  73. package/skills/warapp-mcp/SKILL.md +39 -6
@@ -8,7 +8,7 @@ import { scrubSecrets } from '../redact.js';
8
8
  import { decodeReplyEnvelope, encodeRequest, PROTOCOL_VERSION, fromHex, ProtocolError, toHex, } from './codec.js';
9
9
  import { Method } from './methods.js';
10
10
  /** The client version string the current web client sends. */
11
- export const CLIENT_VERSION = 'v6.08.0.2';
11
+ export const CLIENT_VERSION = 'v6.09.0';
12
12
  /** EnumSerialization_Platform: the website. */
13
13
  export const PLATFORM_WEBSITE = 15;
14
14
  /**
@@ -20,7 +20,21 @@ export const INITIAL_SERVER_INFO_B = 88732;
20
20
  const SERVICES_URL = 'https://war.app/Services';
21
21
  const CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=UTF-8';
22
22
  /** Methods whose frame carries no auth block. */
23
- const NO_AUTH_METHODS = new Set([Method.GetMapDetails]);
23
+ const NO_AUTH_METHODS = new Set([
24
+ Method.GetMapDetails,
25
+ // #637: the client sends these ladder reads without one (anyone may view a ladder).
26
+ Method.GetLadderSeasons,
27
+ Method.GetLadderPlayers,
28
+ Method.GetLadderGames,
29
+ Method.GetTemplate,
30
+ // #639: the client writes nothing after the header for these (bundle-read, UNVERIFIED live).
31
+ Method.GetClans,
32
+ Method.GetOpenClans,
33
+ Method.GetClanWars,
34
+ // #638: the client writes no auth block for these two (read from the 6.09 bundle, UNVERIFIED live).
35
+ Method.GetTemplateLengths,
36
+ Method.GetQuickmatchLeaderboards,
37
+ ]);
24
38
  /** Whether a method's parameters start with the auth (email) block. */
25
39
  export function methodTakesAuth(methodId) {
26
40
  return !NO_AUTH_METHODS.has(methodId);
@@ -104,6 +118,8 @@ export class WarappRpc {
104
118
  bridge;
105
119
  email;
106
120
  nextMsgNum = 1;
121
+ /** #629: the newest UnreadMailCheckResults a reply carried (its two flags and date). */
122
+ lastUnreadMail = null;
107
123
  state = {
108
124
  dict: new Map(),
109
125
  client: CLIENT_VERSION,
@@ -117,6 +133,13 @@ export class WarappRpc {
117
133
  this.bridge = opts.bridge;
118
134
  this.email = opts.email ?? (() => readEmail(opts.env));
119
135
  }
136
+ /**
137
+ * #629: the newest unread-mail check war.app piggybacked on a reply (`MessageExtrasDown`'s UnreadMailCheckResults),
138
+ * `null` until one has: its two flags in read order, its date and when it arrived.
139
+ */
140
+ get unreadMail() {
141
+ return this.lastUnreadMail ? { ...this.lastUnreadMail, flags: [...this.lastUnreadMail.flags] } : null;
142
+ }
120
143
  /** A copy of the MessageExtrasUp the next request will carry. */
121
144
  get extras() {
122
145
  return { ...this.state, dict: this.state.dict === null ? null : new Map(this.state.dict) };
@@ -206,8 +229,10 @@ export class WarappRpc {
206
229
  this.state.serverInfoVersionA = down.serverInfo.serverInfoVersionA;
207
230
  this.state.serverInfoVersionB = down.serverInfo.serverInfoVersionB;
208
231
  }
209
- if (down.unreadMail)
232
+ if (down.unreadMail) {
210
233
  this.state.kFa = down.unreadMail.kFa;
234
+ this.lastUnreadMail = { flags: [down.unreadMail.cYa, down.unreadMail.h9], checked: down.unreadMail.kFa, receivedAt: new Date() };
235
+ }
211
236
  }
212
237
  }
213
238
  /** war.app's `ClientOutOfDate`: the protocol this server speaks is older than war.app still accepts. */
@@ -4,7 +4,7 @@ import { parseHandshake, parsePacket, SOCKET_URL, splitPayload } from './packets
4
4
  import { realSetTimer, runWebSocketSession, WebSocketUnavailableError } from './websocket.js';
5
5
  export { parseHandshake, parsePacket, SOCKET_URL, splitPayload } from './packets.js';
6
6
  export const POST_CONTENT_TYPE = 'text/plain;charset=UTF-8';
7
- /** A Subscribe frame (method 242 in protocol 243, no auth block) as the uppercase hex a message packet carries. */
7
+ /** A Subscribe frame (method 243 in protocol 244, no auth block) as the uppercase hex a message packet carries. */
8
8
  export function subscribeFrameHex(topics, msgNum, extras) {
9
9
  return toHex(encodeRequest({
10
10
  method: Method.Subscribe,
@@ -16,7 +16,7 @@ export function subscribeFrameHex(topics, msgNum, extras) {
16
16
  }
17
17
  /**
18
18
  * Decode a frame from a message packet. A server push is a request-shaped
19
- * frame (MessageExtrasUp, no auth): GameUpdated (245 in protocol 243) starts with the game id,
19
+ * frame (MessageExtrasUp, no auth): GameUpdated (246 in protocol 244) starts with the game id,
20
20
  * then two bools the client logs as `chat` and `nonChat` (read from the bundle's
21
21
  * handler; UNVERIFIED live), then an optional dict this server does not read.
22
22
  * The flags are read only when present: a push without them is a plain update.
@@ -0,0 +1,264 @@
1
+ // Quickmatch (#638): my quickmatch settings, the templates and their votes, and the leaderboards. Read from the
2
+ // 6.09 client bundle, UNVERIFIED live (docs/WEB-PROTOCOL.md, "Quickmatch").
3
+ //
4
+ // Every reply is decoded by the client bundle's own readers by stable type name
5
+ // (`warlight.shared.quickmatch.*`, `warlight.shared.GameTemplateInfo`, `warlight.shared.PlayerInfo2`), fields by
6
+ // read order and count. Each parser projects an ALLOWLIST: ids, counts, settings and ratings, and of a player only
7
+ // the id and the name (a PlayerInfo2's other fields — its clan and the rest — never leave this file). My ratings
8
+ // are kept only for the categories the game is played in (global, real-time, multi-day, 1v1, team, free-for-all,
9
+ // per template): the client also keeps a rating per country, which says where a player is, and is dropped here.
10
+ import { McpToolError } from '@chrischall/mcp-utils';
11
+ import { fields, isObj } from './protocol/decoded.js';
12
+ import { QUICKMATCH_TEMPLATE_SETTINGS } from './protocol/methods.js';
13
+ const NS = 'warlight.shared.quickmatch.';
14
+ export const GET_SETTINGS_RETURN = `${NS}GetQuickmatchSettingsReturn`;
15
+ export const PLAYER_SETTINGS = `${NS}QuickmatchPlayerSettings`;
16
+ export const GET_TEMPLATES_RETURN = `${NS}GetQuickmatchTemplatesReturn`;
17
+ export const QUICKMATCH_TEMPLATE = `${NS}QuickmatchTemplate`;
18
+ export const TEMPLATE_VOTE = `${NS}QuickmatchTemplateVote`;
19
+ export const GET_VOTES_RETURN = `${NS}GetQuickmatchTemplateVotesReturn`;
20
+ export const LEADERBOARD = `${NS}QuickmatchLeaderboard`;
21
+ export const LEADERBOARD_PLAYER = `${NS}QuickmatchLeaderboardPlayer`;
22
+ export const GAME_TEMPLATE_INFO = 'warlight.shared.GameTemplateInfo';
23
+ export const PLAYER_INFO2 = 'warlight.shared.PlayerInfo2';
24
+ /** Field counts (read order), as the 6.09 readers read them. */
25
+ export const COUNTS = {
26
+ settingsReturn: 3,
27
+ settings: 15,
28
+ templatesReturn: 4,
29
+ template: 11,
30
+ vote: 3,
31
+ votesReturn: 2,
32
+ leaderboard: 3,
33
+ leaderboardPlayer: 3,
34
+ templateInfo: 14,
35
+ playerInfo2: 8,
36
+ };
37
+ /** QuickmatchPlayerSettings' positions read (read order). */
38
+ const PS = {
39
+ wins: 0,
40
+ maxCoins: 2,
41
+ multiDayGames: 3,
42
+ minCoins: 4,
43
+ newTemplatesOnByDefault: 5,
44
+ playerId: 6,
45
+ ratings: 8,
46
+ speed: 10,
47
+ templateRank: 11,
48
+ templates: 12,
49
+ votesUnlocked: 14,
50
+ };
51
+ /** QuickmatchTemplate's positions read. */
52
+ const QT = { votes: 0, created: 2, rank: 7, fixedRank: 8, templateId: 10 };
53
+ /** GameTemplateInfo's positions read: the template id, its map and its name. */
54
+ const TI = { id: 4, mapId: 6, name: 8 };
55
+ /** PlayerInfo2's name (as src/mail.ts reads it). */
56
+ const PI2_NAME = 4;
57
+ /** The rating categories reported; any other (the client's per-country ratings) is dropped. */
58
+ const RATING_CATEGORIES = new Set(['Global', 'RT', 'MD', '1v1', 'Team', 'FFA']);
59
+ const TEMPLATE_CATEGORY = /^Template (\d+)$/;
60
+ /** The client's names for the real-time speed (`QuickmatchSpeed`). */
61
+ export const QUICKMATCH_SPEEDS = ['normal', 'blitz', 'any'];
62
+ /** A quickmatch reply arrived in a shape this server does not understand. */
63
+ export class QuickmatchFormatError extends McpToolError {
64
+ constructor(detail) {
65
+ super(`war.app's quickmatch reply arrived in an unexpected shape (${detail}).`, {
66
+ kind: 'unknown',
67
+ hint: 'The war.app client may have changed; quickmatch can still be read on war.app (Multiplayer → Quickmatch).',
68
+ });
69
+ this.name = 'QuickmatchFormatError';
70
+ }
71
+ }
72
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
73
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
74
+ const short = (type) => type.split('.').pop();
75
+ function record(v, type, count) {
76
+ if (!isObj(v) || v.$type !== type)
77
+ throw new QuickmatchFormatError(`expected a ${short(type)}`);
78
+ const f = fields(v);
79
+ if (f.length !== count)
80
+ throw new QuickmatchFormatError(`a ${short(type)} has ${f.length} fields, not ${count}`);
81
+ return f;
82
+ }
83
+ function int(f, i, what) {
84
+ const v = f[i];
85
+ if (!isInt(v))
86
+ throw new QuickmatchFormatError(`no ${what}`);
87
+ return v;
88
+ }
89
+ const listOf = (v) => (Array.isArray(v) ? v.filter((x) => x !== null && x !== undefined) : []);
90
+ /** A PlayerInfo2's name, and nothing else of it. */
91
+ function nameOf(v) {
92
+ if (v === null || v === undefined)
93
+ return null;
94
+ const name = record(v, PLAYER_INFO2, COUNTS.playerInfo2)[PI2_NAME];
95
+ return typeof name === 'string' ? name : null;
96
+ }
97
+ function templateInfoOf(v) {
98
+ const f = record(v, GAME_TEMPLATE_INFO, COUNTS.templateInfo);
99
+ const name = f[TI.name];
100
+ const mapId = f[TI.mapId];
101
+ return { id: int(f, TI.id, 'template id'), name: typeof name === 'string' ? name : null, mapId: isInt(mapId) ? mapId : null };
102
+ }
103
+ const SETTING_NAMES = new Map(Object.entries(QUICKMATCH_TEMPLATE_SETTINGS).map(([k, v]) => [v, k]));
104
+ /** A setting's name; an unknown value reads as `null`. */
105
+ export const settingName = (v) => SETTING_NAMES.get(v) ?? null;
106
+ /** Whether a setting plays real-time (`rt`) or multi-day games — the client's own rule. */
107
+ export const settingPlays = (v, rt) => v === 1 || (rt ? v === 3 : v === 4);
108
+ /**
109
+ * The templates dict the settings carry as JSON (template id → setting), read the client's way: a number is the
110
+ * setting, `true` is on and `false` off. Anything else, or JSON that does not parse, is left out.
111
+ */
112
+ export function parseTemplateSettings(json) {
113
+ const out = new Map();
114
+ if (typeof json !== 'string')
115
+ return out;
116
+ let parsed;
117
+ try {
118
+ parsed = JSON.parse(json);
119
+ }
120
+ catch {
121
+ return out;
122
+ }
123
+ if (!isObj(parsed))
124
+ return out;
125
+ for (const [k, v] of Object.entries(parsed)) {
126
+ if (!/^\d+$/.test(k))
127
+ continue;
128
+ const setting = typeof v === 'number' ? v : v === true ? 1 : v === false ? 2 : undefined;
129
+ if (setting !== undefined && settingName(setting))
130
+ out.set(Number(k), setting);
131
+ }
132
+ return out;
133
+ }
134
+ /** My ratings by category (the allowlist above; a template's under `template:<id>`), rating only. */
135
+ export function parseRatings(json) {
136
+ const out = {};
137
+ if (typeof json !== 'string')
138
+ return out;
139
+ let parsed;
140
+ try {
141
+ parsed = JSON.parse(json);
142
+ }
143
+ catch {
144
+ return out;
145
+ }
146
+ if (!isObj(parsed))
147
+ return out;
148
+ for (const [k, v] of Object.entries(parsed)) {
149
+ const r = isObj(v) ? v.r : undefined;
150
+ if (!isNum(r))
151
+ continue;
152
+ const t = TEMPLATE_CATEGORY.exec(k);
153
+ if (t)
154
+ out[`template:${t[1]}`] = r;
155
+ else if (RATING_CATEGORIES.has(k))
156
+ out[k] = r;
157
+ }
158
+ return out;
159
+ }
160
+ function settingsOf(v) {
161
+ const f = record(v, PLAYER_SETTINGS, COUNTS.settings);
162
+ const flag = f[PS.newTemplatesOnByDefault];
163
+ return {
164
+ playerId: int(f, PS.playerId, 'player id'),
165
+ wins: int(f, PS.wins, 'win count'),
166
+ templateRank: int(f, PS.templateRank, 'template rank'),
167
+ votesUnlocked: int(f, PS.votesUnlocked, 'vote count'),
168
+ multiDayGames: int(f, PS.multiDayGames, 'multi-day game count'),
169
+ coins: { min: int(f, PS.minCoins, 'coin minimum'), max: int(f, PS.maxCoins, 'coin maximum') },
170
+ newTemplatesOnByDefault: flag === true,
171
+ speed: int(f, PS.speed, 'speed'),
172
+ templates: parseTemplateSettings(f[PS.templates]),
173
+ ratings: parseRatings(f[PS.ratings]),
174
+ };
175
+ }
176
+ /** Read a GetQuickmatchSettings result (the body positioned at the result-present flag). */
177
+ export function readQuickmatchSettings(bundle, body) {
178
+ if (!body.bool())
179
+ throw new QuickmatchFormatError('no result');
180
+ const f = record(bundle.readClass(GET_SETTINGS_RETURN, body), GET_SETTINGS_RETURN, COUNTS.settingsReturn);
181
+ if (f[1] === null || f[1] === undefined)
182
+ throw new QuickmatchFormatError('no settings');
183
+ return { settings: settingsOf(f[1]), unlocked: listOf(f[2]).map(templateInfoOf) };
184
+ }
185
+ function voteOf(v) {
186
+ const f = record(v, TEMPLATE_VOTE, COUNTS.vote);
187
+ return { votes: int(f, 0, 'vote count'), playerId: int(f, 1, 'voter id'), templateId: int(f, 2, 'template id') };
188
+ }
189
+ function votingTemplateOf(v) {
190
+ const f = record(v, QUICKMATCH_TEMPLATE, COUNTS.template);
191
+ const rank = f[QT.rank];
192
+ const created = f[QT.created];
193
+ return {
194
+ templateId: int(f, QT.templateId, 'template id'),
195
+ votes: int(f, QT.votes, 'vote count'),
196
+ rank: isInt(rank) ? rank : null,
197
+ fixedRank: f[QT.fixedRank] === true,
198
+ created: created instanceof Date && Number.isFinite(created.getTime()) ? created.toISOString() : null,
199
+ };
200
+ }
201
+ /** Read a GetQuickmatchTemplates result. */
202
+ export function readQuickmatchTemplates(bundle, body) {
203
+ if (!body.bool())
204
+ throw new QuickmatchFormatError('no result');
205
+ const f = record(bundle.readClass(GET_TEMPLATES_RETURN, body), GET_TEMPLATES_RETURN, COUNTS.templatesReturn);
206
+ const info = new Map(listOf(f[0]).map((t) => {
207
+ const i = templateInfoOf(t);
208
+ return [i.id, i];
209
+ }));
210
+ return {
211
+ templates: listOf(f[1]).map(votingTemplateOf),
212
+ info,
213
+ settings: f[2] === null || f[2] === undefined ? null : settingsOf(f[2]),
214
+ myVotes: listOf(f[3]).map(voteOf),
215
+ };
216
+ }
217
+ /** Read a GetQuickmatchTemplateVotes result: who voted, and how many votes each (zero votes left out). */
218
+ export function readTemplateVoters(bundle, body) {
219
+ if (!body.bool())
220
+ return [];
221
+ const f = record(bundle.readClass(GET_VOTES_RETURN, body), GET_VOTES_RETURN, COUNTS.votesReturn);
222
+ const names = new Map();
223
+ for (const e of Array.isArray(f[0]) ? f[0] : []) {
224
+ if (Array.isArray(e) && e.length === 2 && isInt(e[0]))
225
+ names.set(e[0], nameOf(e[1]));
226
+ }
227
+ return listOf(f[1])
228
+ .map(voteOf)
229
+ .filter((v) => v.votes !== 0)
230
+ .map((v) => ({ playerId: v.playerId, name: names.get(v.playerId) ?? null, votes: v.votes }));
231
+ }
232
+ /** Read a GetQuickmatchLeaderboards result. */
233
+ export function readLeaderboard(bundle, body) {
234
+ if (!body.bool())
235
+ throw new QuickmatchFormatError('no result');
236
+ const f = record(bundle.readClass(LEADERBOARD, body), LEADERBOARD, COUNTS.leaderboard);
237
+ const first = int(f, 0, 'start rank') + 1;
238
+ const rows = listOf(f[1]).map((p, i) => {
239
+ const g = record(p, LEADERBOARD_PLAYER, COUNTS.leaderboardPlayer);
240
+ const rating = g[2];
241
+ if (!isNum(rating))
242
+ throw new QuickmatchFormatError('a leaderboard row has no rating');
243
+ return { rank: first + i, playerId: int(g, 1, 'player id'), name: nameOf(g[0]), rating };
244
+ });
245
+ return { rows, total: int(f, 2, 'player count') };
246
+ }
247
+ /**
248
+ * Read a GetTemplateLengths result: template id → the average game length in minutes (the client shows it as
249
+ * "Average game length"). No class: after the result-present flag, a dict of int32 → float64 (an int32 count, -1
250
+ * for none, then the pairs).
251
+ */
252
+ export function readTemplateLengths(body) {
253
+ const out = new Map();
254
+ if (!body.bool())
255
+ return out;
256
+ const n = body.int32();
257
+ for (let i = 0; i < n; i++) {
258
+ const id = body.int32();
259
+ const minutes = body.float64();
260
+ if (Number.isFinite(minutes))
261
+ out.set(id, minutes);
262
+ }
263
+ return out;
264
+ }
@@ -22,9 +22,11 @@ export const GAME_PLAYER = 'warlight.shared.GamePlayer';
22
22
  /** GameWL: its field count and where the players are, in read order. */
23
23
  export const GAME_WL_FIELDS = 14;
24
24
  const GW_PLAYERS = 7;
25
+ /** #631: the votes to end the game (an optional dict of in-game id → time), last. */
26
+ const GW_END_VOTES = 13;
25
27
  /** GamePlayer: its field count (protocol 243 added an int32 at 31) and the positions read, in read order. */
26
28
  export const GAME_PLAYER_FIELDS = 37;
27
- const GPL = { aiId: 0, turnedAI: 14, id: 20, accepted: 21, state: 28, surrendered: 29 };
29
+ const GPL = { aiId: 0, turnedAI: 14, id: 20, accepted: 21, state: 28, surrendered: 29, team: 30, teamVote: 31 };
28
30
  /** Whether a details seat is still playing (GamePlayerState `Playing`, src/player-states.ts). */
29
31
  export const seatPlaying = (s) => playerStateName(s.state) === 'Playing';
30
32
  const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
@@ -64,7 +66,14 @@ function seatOf(p) {
64
66
  const seatId = id ?? aiId;
65
67
  if (seatId === null)
66
68
  return undefined;
67
- return { id: seatId, ai: aiId !== null, turnedAI, state, surrendered, acceptedBy };
69
+ const seat = { id: seatId, ai: aiId !== null, turnedAI, state, surrendered, acceptedBy };
70
+ const team = f[GPL.team];
71
+ const teamVote = f[GPL.teamVote];
72
+ if (isInt(team))
73
+ seat.team = team;
74
+ if (isInt(teamVote))
75
+ seat.teamVote = teamVote;
76
+ return seat;
68
77
  }
69
78
  /**
70
79
  * The seats of a GameRefresh reply asked with `nonChat` (the body positioned at the result-present
@@ -87,6 +96,8 @@ export function readGameDetailsSeats(bundle, body) {
87
96
  const players = gf[GW_PLAYERS];
88
97
  if (!Array.isArray(players))
89
98
  return undefined;
99
+ // #631: the end votes' dict reads like the accepted-by one; a shape not understood leaves them unknown.
100
+ const endVotes = acceptedIds(gf[GW_END_VOTES]);
90
101
  const seats = [];
91
102
  for (const pair of players) {
92
103
  if (!Array.isArray(pair) || pair.length !== 2)
@@ -96,6 +107,8 @@ export function readGameDetailsSeats(bundle, body) {
96
107
  const seat = seatOf(pair[1]);
97
108
  if (!seat)
98
109
  return undefined;
110
+ if (endVotes)
111
+ seat.votedToEnd = endVotes.includes(seat.id);
99
112
  seats.push(seat);
100
113
  }
101
114
  return seats.length ? seats : undefined;
@@ -124,3 +137,50 @@ export function pendingSurrenders(seats, me, feedIdOf = () => null) {
124
137
  }
125
138
  /** Whether any of `pending` waits on my acceptance. */
126
139
  export const surrenderOwed = (pending) => (pending ?? []).some((p) => p.owedByMe === true);
140
+ // ---------- #630: the team surrender; #631: the votes to end the game ----------
141
+ /** The client's team-surrender vote codes (a GamePlayer's field 31). */
142
+ export const TEAM_VOTE = { none: 0, proposed: 1, yes: 2, no: 3 };
143
+ const VOTE_NAMES = new Map(Object.entries(TEAM_VOTE).map(([k, v]) => [v, k]));
144
+ /** A seat that takes part in a vote: playing, neither an AI nor turned into one. */
145
+ const voter = (s) => seatPlaying(s) && !s.ai && !s.turnedAI;
146
+ /**
147
+ * My team's surrender vote from the game details (`me`: my in-game id): unavailable when my team has fewer
148
+ * than two seats still playing (the client offers it only then); `undefined` when my seat, a team or a vote
149
+ * did not read. Never throws.
150
+ */
151
+ export function teamSurrenderOf(seats, me) {
152
+ const mine = me === undefined ? undefined : seats.find((s) => s.id === me);
153
+ if (!mine || mine.team === undefined)
154
+ return undefined;
155
+ if (mine.team === -1 || !voter(mine))
156
+ return { available: false };
157
+ const team = seats.filter((s) => voter(s) && s.team === mine.team);
158
+ if (team.length < 2)
159
+ return { available: false };
160
+ if (team.some((s) => s.teamVote === undefined || !VOTE_NAMES.has(s.teamVote)))
161
+ return undefined;
162
+ const ids = (vote) => team.filter((s) => vote.includes(s.teamVote)).map((s) => s.id);
163
+ const proposer = team.find((s) => s.teamVote === TEAM_VOTE.proposed)?.id ?? null;
164
+ const open = proposer !== null;
165
+ return {
166
+ available: true,
167
+ team: team.map((s) => s.id),
168
+ open,
169
+ proposer,
170
+ yes: ids([TEAM_VOTE.proposed, TEAM_VOTE.yes]),
171
+ no: ids([TEAM_VOTE.no]),
172
+ waiting: open ? ids([TEAM_VOTE.none]) : [],
173
+ myVote: VOTE_NAMES.get(mine.teamVote),
174
+ };
175
+ }
176
+ /** {@link EndVotes} from the game details; `undefined` when the votes did not read. Never throws. */
177
+ export function endVotesOf(seats, me) {
178
+ if (seats.some((s) => s.votedToEnd === undefined))
179
+ return undefined;
180
+ const mine = me === undefined ? undefined : seats.find((s) => s.id === me);
181
+ return {
182
+ voted: seats.filter((s) => s.votedToEnd).map((s) => s.id),
183
+ notYet: seats.filter((s) => !s.votedToEnd && voter(s)).map((s) => s.id),
184
+ myVote: mine ? mine.votedToEnd === true : null,
185
+ };
186
+ }