@chrischall/warapp-mcp 0.4.0 → 0.5.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.
@@ -77,6 +77,7 @@
77
77
  // and hoisted names it declares.
78
78
  import { parseExpressionAt, } from 'acorn';
79
79
  import { PROTOCOL_VERSION, ProtocolError, Reader } from './codec.js';
80
+ import { bundleProtocol, deriveDialect } from './dialect.js';
80
81
  /** A reader the interpreter cannot evaluate, or one that failed on the bytes. */
81
82
  export class InterpError extends Error {
82
83
  kind;
@@ -168,69 +169,119 @@ function list(r, item) {
168
169
  const f = callback(item);
169
170
  return asReader(r).list(() => f());
170
171
  }
171
- /** The names used by client v6.07 (protocol 242). */
172
- export const DEFAULT_DIALECT = {
172
+ /** The built-in natives for each reader-method role (`a.Tg()`). */
173
+ const READER_NATIVES = {
174
+ bool: (r) => r.bool(),
175
+ int32: (r) => r.int32(),
176
+ u8: (r) => r.u8(),
177
+ string: (r) => strBody(r),
178
+ // The client's 8-byte read is a float64 (its two int32 halves reassembled as a double), not an
179
+ // int64: kill rates, luck and TimeSpans (milliseconds) all arrive through it.
180
+ float64: (r) => r.float64(),
181
+ float32: (r) => r.float32(),
182
+ uint16: (r) => r.uint16(),
183
+ int16: (r) => r.int16(),
184
+ raw: (r, n) => {
185
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 0)
186
+ throw new InterpError('bad-value', `bad byte count ${String(n)}`);
187
+ return r.raw(n);
188
+ },
189
+ varint: (r) => r.varint(),
190
+ };
191
+ /** The built-in natives for each static-helper role (`P.Ya(a)`, `E.Za(xs, f)`, …). */
192
+ const STATIC_NATIVES = {
193
+ int32: (r) => asReader(r).int32(),
194
+ string: (r) => asReader(r).string(),
195
+ bool: (r) => asReader(r).bool(),
196
+ u8: (r) => asReader(r).u8(),
197
+ float32: (r) => asReader(r).float32(),
198
+ float64: (r) => asReader(r).float64(),
199
+ timespan: (r) => asReader(r).float64(),
200
+ date: (r) => asReader(r).date(),
201
+ guid: (r) => asReader(r).guid(),
202
+ uint16: (r) => asReader(r).uint16(),
203
+ bytes: (r) => readBytes(asReader(r)),
204
+ list,
205
+ dict: (r, k, v) => {
206
+ const fk = callback(k);
207
+ const fv = callback(v);
208
+ return asReader(r).list(() => [fk(), fv()]);
209
+ },
210
+ identity: (x) => x,
211
+ // Enumerable helpers (special-unit lists): Range → Select → ToArray.
212
+ range,
213
+ select: (xs, f) => {
214
+ const fn = callback(f);
215
+ return asArray(xs).map((x) => fn(x));
216
+ },
217
+ toArray: (xs) => [...asArray(xs)],
218
+ };
219
+ /** A derived (or built-in) dialect's names → roles, as the natives the interpreter calls. */
220
+ function dialectFrom(names) {
221
+ const readerMethods = {};
222
+ for (const [n, role] of Object.entries(names.readerMethods))
223
+ readerMethods[n] = READER_NATIVES[role];
224
+ const statics = {};
225
+ for (const [cls, fns] of Object.entries(names.statics)) {
226
+ statics[cls] = {};
227
+ for (const [n, role] of Object.entries(fns))
228
+ statics[cls][n] = STATIC_NATIVES[role];
229
+ }
230
+ return { readerMethods, statics, wrappers: [...names.wrappers] };
231
+ }
232
+ /**
233
+ * The names client v6.07.0.1 (protocol 242) used, by role: the fallback when a bundle's own names
234
+ * cannot be derived (`deriveDialect`), and the dialect of the test mini-bundles.
235
+ */
236
+ const V607_NAMES = {
173
237
  readerMethods: {
174
- Ua: (r) => r.bool(),
175
- Og: (r) => r.int32(),
176
- bc: (r) => r.u8(),
177
- FJ: (r) => strBody(r),
178
- // The client's 8-byte read is a float64 (its two int32 halves reassembled as a double), not an
179
- // int64: kill rates, luck and TimeSpans (milliseconds) all arrive through it.
180
- E3a: (r) => r.float64(),
181
- Om: (r) => r.float32(),
182
- NGb: (r) => r.uint16(),
183
- S3c: (r) => r.int16(),
184
- MGb: (r) => r.u8(),
185
- JS: (r, n) => {
186
- if (typeof n !== 'number' || !Number.isInteger(n) || n < 0)
187
- throw new InterpError('bad-value', `bad byte count ${String(n)}`);
188
- return r.raw(n);
189
- },
190
- I3c: (r) => r.varint(),
238
+ Ua: 'bool',
239
+ Og: 'int32',
240
+ bc: 'u8',
241
+ FJ: 'string',
242
+ E3a: 'float64',
243
+ Om: 'float32',
244
+ NGb: 'uint16',
245
+ S3c: 'int16',
246
+ MGb: 'u8',
247
+ JS: 'raw',
248
+ I3c: 'varint',
191
249
  },
192
250
  statics: {
193
251
  P: {
194
- Ya: (r) => asReader(r).int32(),
195
- wc: (r) => asReader(r).string(),
196
- Yc: (r) => asReader(r).bool(),
197
- uq: (r) => asReader(r).u8(),
198
- Ao: (r) => asReader(r).float32(),
199
- ak: (r) => asReader(r).float64(),
200
- uy: (r) => asReader(r).float64(),
201
- Td: (r) => asReader(r).date(),
202
- tL: (r) => asReader(r).guid(),
203
- Z5: (r) => asReader(r).uint16(),
204
- sL: (r) => readBytes(asReader(r)),
205
- Sd: list,
206
- ms: list,
207
- uL: list,
208
- ef: (r, k, v) => {
209
- const fk = callback(k);
210
- const fv = callback(v);
211
- return asReader(r).list(() => [fk(), fv()]);
212
- },
213
- },
214
- O: { fA: (x) => x, Fy: (x) => x, rc: (x) => x },
215
- za: { rc: (x) => x },
216
- // Enumerable helpers (special-unit lists): Range → Select → ToArray.
217
- E: {
218
- Range: range,
219
- Za: (xs, f) => {
220
- const fn = callback(f);
221
- return asArray(xs).map((x) => fn(x));
222
- },
223
- Sa: (xs) => [...asArray(xs)],
252
+ Ya: 'int32',
253
+ wc: 'string',
254
+ Yc: 'bool',
255
+ uq: 'u8',
256
+ Ao: 'float32',
257
+ ak: 'float64',
258
+ uy: 'timespan',
259
+ Td: 'date',
260
+ tL: 'guid',
261
+ Z5: 'uint16',
262
+ sL: 'bytes',
263
+ Sd: 'list',
264
+ ms: 'list',
265
+ uL: 'list',
266
+ ef: 'dict',
224
267
  },
268
+ O: { fA: 'identity', Fy: 'identity', rc: 'identity' },
269
+ za: { rc: 'identity' },
270
+ E: { Range: 'range', Za: 'select', Sa: 'toArray' },
225
271
  },
226
272
  wrappers: ['Z', 'Yb', 'uc', 'dc', 'oc', 'ec', 'fc'],
227
273
  };
228
- /** The class whose statics are the reader helpers (`P.Ya(a)`), checked by `verifyDialect`. */
274
+ /** The names used by client v6.07 (protocol 242): the fallback when a bundle's own names cannot be derived. */
275
+ export const DEFAULT_DIALECT = dialectFrom(V607_NAMES);
276
+ /** The Serializer roles every board count, flag and unit count is read through (see {@link REQUIRED_HELPERS}). */
277
+ const REQUIRED_ROLES = ['int32', 'bool', 'u8'];
278
+ /** The class whose statics are the reader helpers (`P.Ya(a)`) in the built-in dialect, checked by `verifyDialect`. */
229
279
  export const READER_HELPERS = 'P';
230
280
  /**
231
- * The helpers every board count, flag and unit count is read through (int32, bool, byte). A bundle
232
- * whose own definition of one of these cannot be verified is refused at load: an unverified one could
233
- * be a swapped same-width read, which decodes a wrong board without an error (#148).
281
+ * The helpers every board count, flag and unit count is read through (int32, bool, byte), in the
282
+ * built-in dialect. A bundle whose own definition of one of these cannot be verified is refused at
283
+ * load: an unverified one could be a swapped same-width read, which decodes a wrong board without an
284
+ * error (#148). A derived dialect names its own (`BundleInterpreter.requiredHelpers`), by role.
234
285
  */
235
286
  export const REQUIRED_HELPERS = ['Ya', 'Yc', 'uq'];
236
287
  /**
@@ -470,6 +521,14 @@ export class BundleInterpreter {
470
521
  opts;
471
522
  version;
472
523
  dialect;
524
+ /** The class whose statics are the reader helpers `verifyDialect` checks (the Serializer). */
525
+ helperClass;
526
+ /** The reader helpers that must verify for the bundle to load (int32, bool and byte, by role). */
527
+ requiredHelpers;
528
+ /** The dialect was derived from this bundle (false: the built-in v6.07 names). */
529
+ derived;
530
+ /** The protocol version the bundle's readers default to, when clear (`null==d&&(d=243)`). */
531
+ bundleProtocol;
473
532
  wrappers;
474
533
  /** Resolved functions by `Cls.fn` / `new Cls`: a hit, `null` (no constructor) or the cached failure. */
475
534
  fnCache = new Map();
@@ -500,12 +559,30 @@ export class BundleInterpreter {
500
559
  this.maxDepth = opts.maxDepth ?? DEFAULT_MAX_DEPTH;
501
560
  this.maxMillis = opts.maxMillis ?? DEFAULT_MAX_MILLIS;
502
561
  this.now = opts.now ?? (() => performance.now());
503
- const d = opts.dialect ?? {};
504
- this.dialect = {
505
- readerMethods: { ...DEFAULT_DIALECT.readerMethods, ...d.readerMethods },
506
- statics: { ...DEFAULT_DIALECT.statics, ...d.statics },
507
- wrappers: d.wrappers ?? DEFAULT_DIALECT.wrappers,
508
- };
562
+ // The bundle's own names, derived from its structure (every build renames them: #340); the
563
+ // built-in v6.07 names when they cannot be, or when the caller gives a dialect (the tests' mini-bundles).
564
+ const derived = opts.dialect ? null : deriveDialect(bundle);
565
+ if (derived) {
566
+ this.dialect = dialectFrom(derived);
567
+ this.helperClass = derived.serializer;
568
+ const helpers = derived.statics[derived.serializer] ?? {};
569
+ this.requiredHelpers = Object.keys(helpers)
570
+ .filter((n) => REQUIRED_ROLES.includes(helpers[n]))
571
+ .sort();
572
+ this.derived = true;
573
+ }
574
+ else {
575
+ const d = opts.dialect ?? {};
576
+ this.dialect = {
577
+ readerMethods: { ...DEFAULT_DIALECT.readerMethods, ...d.readerMethods },
578
+ statics: { ...DEFAULT_DIALECT.statics, ...d.statics },
579
+ wrappers: d.wrappers ?? DEFAULT_DIALECT.wrappers,
580
+ };
581
+ this.helperClass = READER_HELPERS;
582
+ this.requiredHelpers = REQUIRED_HELPERS;
583
+ this.derived = false;
584
+ }
585
+ this.bundleProtocol = derived ? derived.protocol : bundleProtocol(bundle.src);
509
586
  this.wrappers = new Set(this.dialect.wrappers);
510
587
  }
511
588
  /** The class var for a registered type name, or the argument itself if it is a var. */
@@ -573,18 +650,18 @@ export class BundleInterpreter {
573
650
  verifyDialect() {
574
651
  const out = { verified: [], unverified: [], mismatched: [] };
575
652
  const reasons = {};
576
- const natives = Object.hasOwn(this.dialect.statics, READER_HELPERS) ? this.dialect.statics[READER_HELPERS] : {};
653
+ const natives = Object.hasOwn(this.dialect.statics, this.helperClass) ? this.dialect.statics[this.helperClass] : {};
577
654
  // The bundle's definitions run like any interpreted code: contained, and under one step budget
578
655
  // shared by the whole check, so a hostile bundle cannot spend more than one read's worth here.
579
656
  // Past the budget, a probe is unevaluable (the helper unverified), never a mismatch.
580
657
  const budget = { spent: 0 };
581
- const forms = this.helperForms(READER_HELPERS, Object.keys(natives), budget);
658
+ const forms = this.helperForms(this.helperClass, Object.keys(natives), budget);
582
659
  // The required helpers are probed first: a runaway definition of another cannot spend the budget
583
660
  // they need. Object literals assigned to P are parsed under a bound of their own (see helperForms).
584
- const order = [...forms.keys()].sort((a, b) => Number(REQUIRED_HELPERS.includes(b)) - Number(REQUIRED_HELPERS.includes(a)) || (a < b ? -1 : 1));
661
+ const order = [...forms.keys()].sort((a, b) => Number(this.requiredHelpers.includes(b)) - Number(this.requiredHelpers.includes(a)) || (a < b ? -1 : 1));
585
662
  for (const name of order) {
586
663
  const native = natives[name];
587
- const key = `${READER_HELPERS}.${name}`;
664
+ const key = `${this.helperClass}.${name}`;
588
665
  let mismatch = false;
589
666
  let why;
590
667
  for (const form of forms.get(name)) {
@@ -627,14 +704,14 @@ export class BundleInterpreter {
627
704
  // and the built-in would decode every read through it unchecked. Absent from the check is not
628
705
  // verified (#148).
629
706
  const src = this.bundle.src;
630
- const esc = READER_HELPERS.replace(/\$/g, '\\$');
631
- for (const name of REQUIRED_HELPERS) {
707
+ const esc = this.helperClass.replace(/\$/g, '\\$');
708
+ for (const name of this.requiredHelpers) {
632
709
  if (forms.has(name) || !Object.hasOwn(natives, name))
633
710
  continue;
634
711
  const ref = new RegExp(`(?<![\\w$.])${esc}\\s*(?:\\.\\s*${name}(?![\\w$])|\\[\\s*(["'\`])${name}\\1\\s*\\])`);
635
712
  if (!ref.test(src))
636
713
  continue;
637
- const key = `${READER_HELPERS}.${name}`;
714
+ const key = `${this.helperClass}.${name}`;
638
715
  out.unverified.push(key);
639
716
  reasons[key] = 'the bundle reads through it, but no definition was found in a form this check can follow';
640
717
  }
@@ -1,37 +1,39 @@
1
1
  // war.app web-client method ids (the int32 in every frame header) and the
2
- // parameter writers this server uses. The name is also the `m=` query value of
2
+ // parameter writers this server uses. The ids are protocol 243's: 243 inserted six methods
3
+ // (ChangeCommitConfirmation 26, TeamSurrender 70, TournamentGroup 94, UploadSharedImage 129,
4
+ // ChatRoomReactionsChanged 247, SetReaction 285) and renumbered everything after each. The name is also the `m=` query value of
3
5
  // https://war.app/Services?m=<name>&js=1.
4
6
  export const Method = {
5
7
  /** Exists in the client's method table, but the web client never calls it (open games come from a page). */
6
8
  GetOpenGames: 10,
7
- GetGameDetails: 38,
8
- GameRefresh: 39,
9
- GetLatestGameInfo: 40,
10
- SendChat: 42,
11
- RegisterChatView: 43,
12
- GetGameSettings: 48,
13
- GetMyGames: 50,
14
- AcceptGame: 60,
15
- AcceptOpenSeat: 61,
16
- AcceptOpenAutoGame: 62,
17
- GetOpenAutoGame: 63,
18
- DeclineGame: 64,
19
- Surrender: 67,
20
- AcceptSurrender: 68,
21
- GetMapDetails: 73,
22
- SendOrders: 74,
23
- SendInProgressOrders: 75,
24
- SendTerritoryPicks: 76,
25
- SendInProgressPicks: 77,
26
- BeginFirstTurn: 78,
27
- GetTerritoryPicks: 79,
28
- UnCommit: 80,
29
- GetTurns: 81,
30
- Subscribe: 238,
31
- GameUpdated: 241,
32
- GetInAppNotifications: 317,
33
- DeleteInAppNotification: 318,
34
- AcknowledgeInAppNotifications: 319,
9
+ GetGameDetails: 39,
10
+ GameRefresh: 40,
11
+ GetLatestGameInfo: 41,
12
+ SendChat: 43,
13
+ RegisterChatView: 44,
14
+ GetGameSettings: 49,
15
+ GetMyGames: 51,
16
+ AcceptGame: 61,
17
+ AcceptOpenSeat: 62,
18
+ AcceptOpenAutoGame: 63,
19
+ GetOpenAutoGame: 64,
20
+ DeclineGame: 65,
21
+ Surrender: 68,
22
+ AcceptSurrender: 69,
23
+ GetMapDetails: 75,
24
+ SendOrders: 76,
25
+ SendInProgressOrders: 77,
26
+ SendTerritoryPicks: 78,
27
+ SendInProgressPicks: 79,
28
+ BeginFirstTurn: 80,
29
+ GetTerritoryPicks: 81,
30
+ UnCommit: 82,
31
+ GetTurns: 83,
32
+ Subscribe: 242,
33
+ GameUpdated: 245,
34
+ GetInAppNotifications: 323,
35
+ DeleteInAppNotification: 324,
36
+ AcknowledgeInAppNotifications: 325,
35
37
  };
36
38
  const NAMES = new Map(Object.entries(Method).map(([name, id]) => [id, name]));
37
39
  /** The method's name for a known id, or undefined. */
@@ -271,6 +273,8 @@ export function writeGameRefreshParams(w, p) {
271
273
  .string(NO_CHAT_MARKER)
272
274
  .bool(p.lobby)
273
275
  .bool(false)
276
+ .bool(false)
277
+ // Protocol 243 added a last, optional value (a nullable number the client sends as text): absent.
274
278
  .bool(false);
275
279
  }
276
280
  /** A chat read mark: a message id as decimal text, or `-1` (the client's "no mark"). */
@@ -317,6 +321,8 @@ export function writeSendChatParams(w, p) {
317
321
  .string(null)
318
322
  .string(null)
319
323
  .bool(false)
324
+ .bool(false)
325
+ // Protocol 243 added a last, optional list of strings (the shared images a message carries): absent.
320
326
  .bool(false);
321
327
  }
322
328
  // ---------------------------------------------------------------------------
@@ -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.07.0.1';
11
+ export const CLIENT_VERSION = 'v6.08.0.2';
12
12
  /** EnumSerialization_Platform: the website. */
13
13
  export const PLATFORM_WEBSITE = 15;
14
14
  /**
@@ -67,8 +67,8 @@ export class ProtocolVersionError extends McpToolError {
67
67
  export class WarappServerError extends McpToolError {
68
68
  code;
69
69
  name = 'WarappServerError';
70
- constructor(code, message) {
71
- super(message, { kind: 'unknown' });
70
+ constructor(code, message, hint) {
71
+ super(message, { kind: 'unknown', ...(hint ? { hint } : {}) });
72
72
  this.code = code;
73
73
  }
74
74
  }
@@ -202,7 +202,31 @@ export class WarappRpc {
202
202
  this.state.kFa = down.unreadMail.kFa;
203
203
  }
204
204
  }
205
+ /** war.app's `ClientOutOfDate`: the protocol this server speaks is older than war.app still accepts. */
206
+ export const CLIENT_OUT_OF_DATE = 48;
207
+ /** war.app's `ClientVersionTooHigh`: the client version this server sends is newer than war.app knows. */
208
+ export const CLIENT_VERSION_TOO_HIGH = 49;
209
+ /**
210
+ * war.app refused this server's client as out of date (48) or too new (49). Probed live 2026-11-17: war.app
211
+ * keeps answering about 21 older protocols, and a request below that window gets 48 — the sign that war.app
212
+ * has retired the protocol this server speaks, which no retry or relink fixes: only the update in
213
+ * docs/CLIENT-RELEASES.md ("Updating to a new client") does.
214
+ */
215
+ export class ClientOutOfDateError extends WarappServerError {
216
+ name = 'ClientOutOfDateError';
217
+ constructor(methodName, code) {
218
+ super(code, code === CLIENT_OUT_OF_DATE
219
+ ? `war.app refused ${methodName} as ClientOutOfDate (war.app error 48): it no longer accepts protocol ` +
220
+ `${PROTOCOL_VERSION}, the one this server speaks, so every war.app call through the web protocol will fail ` +
221
+ 'until this server is updated to war.app’s current client.'
222
+ : `war.app refused ${methodName} as ClientVersionTooHigh (war.app error 49): it does not know client ` +
223
+ `${CLIENT_VERSION}, the version this server sends.`, 'This server needs an update to war.app’s current client: see docs/CLIENT-RELEASES.md, "Updating to a new ' +
224
+ 'client". Retrying or signing in again will not help.');
225
+ }
226
+ }
205
227
  function serverError(methodName, code, message, email) {
228
+ if (code === CLIENT_OUT_OF_DATE || code === CLIENT_VERSION_TOO_HIGH)
229
+ return new ClientOutOfDateError(methodName, code);
206
230
  const known = SERVER_ERROR_MESSAGES[code];
207
231
  if (known)
208
232
  return new WarappServerError(code, `${known} (war.app error ${code})`);
@@ -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 238, no auth block) as the uppercase hex a message packet carries. */
7
+ /** A Subscribe frame (method 242 in protocol 243, 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 (241) starts with the game id,
19
+ * frame (MessageExtrasUp, no auth): GameUpdated (245 in protocol 243) 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.
@@ -2,10 +2,10 @@
2
2
  // UNVERIFIED live (docs/WEB-PROTOCOL.md, "Accepting a surrender").
3
3
  //
4
4
  // GameFeed keeps a player who asked to surrender `Playing`, and neither GetMyGames nor
5
- // LatestGameInfo says anything about it: only the game details do. GameRefresh (39) asked with
5
+ // LatestGameInfo says anything about it: only the game details do. GameRefresh (40) asked with
6
6
  // `nonChat` answers `warlight.shared.GameDetailsAndChat`, whose second field is the game
7
7
  // (`warlight.shared.GameWL`); the game's eighth field is its players, a dict of in-game id →
8
- // `warlight.shared.GamePlayer`. Of a player's 36 fields this reads the AI id, "human turned into
8
+ // `warlight.shared.GamePlayer`. Of a player's 37 fields this reads the AI id, "human turned into
9
9
  // an AI", the in-game id, who accepted its surrender, its state and the `Surrendered` flag.
10
10
  //
11
11
  // The client's player reader first sets a link back to the game being read (only when it is read
@@ -22,8 +22,8 @@ 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
- /** GamePlayer: its field count and the positions read, in read order. */
26
- export const GAME_PLAYER_FIELDS = 36;
25
+ /** GamePlayer: its field count (protocol 243 added an int32 at 31) and the positions read, in read order. */
26
+ export const GAME_PLAYER_FIELDS = 37;
27
27
  const GPL = { aiId: 0, turnedAI: 14, id: 20, accepted: 21, state: 28, surrendered: 29 };
28
28
  /** Whether a details seat is still playing (GamePlayerState `Playing`, src/player-states.ts). */
29
29
  export const seatPlaying = (s) => playerStateName(s.state) === 'Playing';
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { CHAT_CHANNELS } from '../chat.js';
3
- import { chatGameIds, unflaggedFinished } from '../my-games.js';
3
+ import { chatGameIds, GAME_FINISHED, unflaggedFinished } from '../my-games.js';
4
4
  import { playersByInGameId } from '../live.js';
5
5
  import { CHAT_SOURCE_NOTES, chatMe, chatUnread, feedFillFields, markChatSeen, readChat, shown } from './chat.js';
6
6
  import { parseGameId } from '../client.js';
@@ -8,6 +8,23 @@ import { gameIdArg, readAnnotations, respond, untrustedDescription, untrustedTex
8
8
  import { mintMeta } from './hints.js';
9
9
  import { BRIDGE_NOTE } from './live.js';
10
10
  import { fetchMyGames } from './my-games.js';
11
+ /**
12
+ * #322: a finished game whose chat flags read clear is still read when it is among this many newest finished games
13
+ * (by id) in the list. A message GameFeed alone holds (a surrender "gg" sent as the game ended) leaves war.app's unread
14
+ * flag clear, and such a message comes as a game ends, so the newest finished games are where it hides; older ones stay
15
+ * judged by the flag. A bound, not a scan: at most this many extra reads over a whole sweep.
16
+ */
17
+ export const FINISHED_CLEAR_WINDOW = 3;
18
+ /** The newest `FINISHED_CLEAR_WINDOW` finished games (by id) whose flags read clear, which `chatGameIds` leaves out. */
19
+ export function recentClearFinished(games) {
20
+ const listed = new Set(chatGameIds(games));
21
+ return games
22
+ .filter((g) => g.stateCode === GAME_FINISHED && !listed.has(g.id))
23
+ .map((g) => g.id)
24
+ .sort((a, b) => b - a)
25
+ .slice(0, FINISHED_CLEAR_WINDOW)
26
+ .sort((a, b) => a - b);
27
+ }
11
28
  /** Games read per call, at most (each costs a GameFeed read and a GameRefresh). */
12
29
  export const MAX_INBOX_GAMES = 10;
13
30
  /** The most game ids a call may name. */
@@ -77,7 +94,8 @@ export function registerChatInboxTool(server, ctx) {
77
94
  const list = given ? undefined : await fetchMyGames(ctx);
78
95
  const me = await chatMe(ctx);
79
96
  const after = cursor === undefined ? undefined : Number(cursor);
80
- const ids = (given ?? chatGameIds(list.games)).filter((id) => after === undefined || id > after);
97
+ const clearFinished = list ? recentClearFinished(list.games) : [];
98
+ const ids = (given ?? [...chatGameIds(list.games), ...clearFinished].sort((a, b) => a - b)).filter((id) => after === undefined || id > after);
81
99
  const batch = ids.slice(0, max_games ?? MAX_INBOX_GAMES);
82
100
  const n = limit ?? DEFAULT_INBOX_LIMIT;
83
101
  const channels = [...CHAT_CHANNELS];
@@ -107,9 +125,12 @@ export function registerChatInboxTool(server, ctx) {
107
125
  }
108
126
  sources.add(read.source);
109
127
  const messages = fresh_.slice(-n).map((l) => shown(l, true, game.players, byInGame, me));
128
+ const name = game.name === undefined ? null : untrustedText(game.name);
110
129
  withNew.push({
130
+ // #322/#323: the game as warapp_get_chat nests it; the top-level keys stay for existing callers.
131
+ game: { id: game.id, name, state: game.state },
111
132
  id: game.id,
112
- name: game.name === undefined ? null : untrustedText(game.name),
133
+ name,
113
134
  state: game.state,
114
135
  source: read.source,
115
136
  ...feedFillFields(read),
@@ -152,6 +173,14 @@ export function registerChatInboxTool(server, ctx) {
152
173
  'are read like the rest rather than left out (the flags are not yet verified against war.app).',
153
174
  }
154
175
  : {}),
176
+ ...(clearFinished.length
177
+ ? {
178
+ finishedClearChecked: clearFinished.length,
179
+ finishedClearNote: `${clearFinished.length} recent finished game(s) are read although war.app's unread flag for their chat ` +
180
+ 'is clear: a message GameFeed alone holds (a surrender line, say) leaves that flag clear (#322). Only the ' +
181
+ `${FINISHED_CLEAR_WINDOW} newest finished games are read so; older ones go by the flag.`,
182
+ }
183
+ : {}),
155
184
  ...(sources.size ? { sourceNotes: Object.fromEntries([...sources].map((s) => [s, CHAT_SOURCE_NOTES[s]])) } : {}),
156
185
  }));
157
186
  });
@@ -79,7 +79,9 @@ export function registerMarkChatReadTool(server, ctx) {
79
79
  const read = await readChat(ctx, game, me);
80
80
  // A filled web read (#313) still carries the web messages' ids; GameFeed's added lines carry none and mark nothing.
81
81
  if (!read || read.source === 'gamefeed') {
82
- refuse(`The chat of game ${game.id} could be read only from GameFeed, which gives no message ids, so nothing was sent.`, 'Make sure your war.app tab is open and signed in (reload or focus it if it is frozen), then retry.');
82
+ refuse(`The chat of game ${game.id} could be read only from GameFeed, which gives no message ids, so nothing was sent.`, 'A message read from GameFeed carries no id, so war.app has nothing to mark for it. Read the game with ' +
83
+ 'warapp_get_chat: if its `source` is `web`, those messages can be marked; if it stays `gamefeed`, the web ' +
84
+ 'read failed or the signed-in account could not be read, and marking waits until it reads.');
83
85
  }
84
86
  // #313: the web read answered with no message at all while GameFeed holds some (a finished game's chat,
85
87
  // seen live). Every line is then GameFeed's, with no id; a retry reads the same, so it says why instead.
@@ -83,7 +83,9 @@ export const MAX_SURRENDER_READS = 20;
83
83
  const SURRENDER_READ_BATCH = 4;
84
84
  /**
85
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.
86
+ * still plays (at most {@link MAX_SURRENDER_READS}, war.app's order; `null` when unreadable, and absent —
87
+ * so `null` — past the bound); every other game is an empty list, read from nothing (#327: a lobby or a
88
+ * finished game has none, and a game I am out of owes none from me).
87
89
  * GetMyGames carries no GameFeed id, so `player` is `null`; the name is the list's, untrusted.
88
90
  */
89
91
  export async function myGamesSurrenders(ctx, games, me) {
@@ -92,6 +94,9 @@ export async function myGamesSurrenders(ctx, games, me) {
92
94
  const mine = g.players.find((p) => p.id === me);
93
95
  return surrenderMayBePending(gameStateName(g.stateCode), mine ? playerStateName(mine.stateCode) : undefined);
94
96
  });
97
+ for (const g of games)
98
+ if (!eligible.includes(g))
99
+ byGame.set(g.id, []);
95
100
  const read = eligible.slice(0, MAX_SURRENDER_READS);
96
101
  for (let i = 0; i < read.length; i += SURRENDER_READ_BATCH) {
97
102
  const batch = read.slice(i, i + SURRENDER_READ_BATCH);
@@ -129,7 +134,8 @@ export function registerMyGamesTool(server, ctx, deps = {}) {
129
134
  'they have committed this turn) and waitingOnYou — true when the game is being played or distributing ' +
130
135
  'territories, you are still playing, and you have not committed — and surrenderPending: the surrenders other ' +
131
136
  '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 ' +
137
+ 'the game details (unverified live; null when not read or unreadable, never "none"; empty without a read ' +
138
+ 'for a lobby, a finished game or a game you no longer play in, where none can wait on you); the top-level ' +
133
139
  'surrenderPending counts the games where one waits on you, and those games come first too. ' +
134
140
  'Finished games are left out unless ' +
135
141
  '`include_finished` (`finishedLeftOut` counts them). `listed` is how many games war.app returned and ' +
@@ -163,7 +169,8 @@ export function registerMyGamesTool(server, ctx, deps = {}) {
163
169
  if (view === 'brief')
164
170
  return briefResult(summary, partial ? raw.length : undefined);
165
171
  const finishedLeftOut = raw.length - kept.length;
166
- // #317: the surrenders pending in each game (the game details; null: not read or unreadable, never "none").
172
+ // #317: the surrenders pending in each game (the game details; null: not read or unreadable, never "none";
173
+ // #327: [] without a read where none can wait on me).
167
174
  const { byGame, skipped } = await myGamesSurrenders(ctx, kept, me);
168
175
  const withSurrenders = summary.map((g) => ({ ...g, surrenderPending: byGame.get(g.id) ?? null }));
169
176
  // A game waiting on my acceptance waits on me too: it goes first with the turns waiting on me.
@@ -1,6 +1,6 @@
1
1
  // warapp_get_notifications, warapp_dismiss_notification and warapp_delete_notification (#311): war.app's
2
- // in-app notifications (the client's "In App Notifications" screen), read with GetInAppNotifications (317),
3
- // marked read with AcknowledgeInAppNotifications (319) and deleted with DeleteInAppNotification (318, the
2
+ // in-app notifications (the client's "In App Notifications" screen), read with GetInAppNotifications (323),
3
+ // marked read with AcknowledgeInAppNotifications (325) and deleted with DeleteInAppNotification (324, the
4
4
  // client's Delete button). All read from the client bundle, UNVERIFIED live (docs/WEB-PROTOCOL.md,
5
5
  // Notifications and read marks).
6
6
  //
@@ -274,7 +274,8 @@ export function registerPushTools(server, ctx, push, deps = {}) {
274
274
  'through your signed-in war.app tab (ContextMint Bridge) — and re-checks a game whenever war.app says it ' +
275
275
  'changed, and every game after the push socket reconnects. It also returns (status `surrender_pending`) when ' +
276
276
  'another player\'s surrender waits for you to accept it (each game\'s `surrenderPending`, read from the game ' +
277
- 'details, unverified live: null when unreadable, never "none"; after one failed read it stops asking for the ' +
277
+ 'details, unverified live: null when unreadable, never "none"; empty without a read for a lobby, a finished ' +
278
+ 'game or one you no longer play in; after one failed read it stops asking for the ' +
278
279
  'rest of the wait and says why in `surrenderUnread`), unless `ignore_surrenders`. ' +
279
280
  'Pass the game ids to watch (1–20), or omit them to watch every game ' +
280
281
  'of yours being played or picked (the first 20, as warapp_my_games lists them). Reports progress while it ' +