@chrischall/warapp-mcp 0.3.1 → 0.4.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.
@@ -43,6 +43,7 @@ import { detectEdgeBlock, EdgeBlockedError, McpToolError } from '@chrischall/mcp
43
43
  import { createDirectFirstTransport, readTransportMode, } from '@chrischall/mcp-utils/fetchproxy';
44
44
  import { fetchPublic } from '@chrischall/mcp-utils/netguard';
45
45
  import { egressDispatcher } from './egress.js';
46
+ import { decodeReplyEnvelope, fromHex } from '../protocol/codec.js';
46
47
  import { isHosted } from '../hosted.js';
47
48
  import { hostedSession, SESSION_HOST, scrubError } from './session.js';
48
49
  /** The env var pinning the transport: `direct` | `fetchproxy` | `auto` (default). */
@@ -287,9 +288,75 @@ export function looksSignedOut(requestedUrl, res) {
287
288
  return true;
288
289
  return false;
289
290
  }
291
+ /**
292
+ * The page that says whether the session is signed in (live 2026-11-17): signed in it
293
+ * answers 200 "Your invite token is N"; signed out, a 302 to `/LogIn?AuthNeeded=true`.
294
+ */
295
+ export const SIGNED_IN_PROBE_URL = `${SESSION_ORIGIN}/InviteToken`;
296
+ /** war.app's `AuthFailed` server error: its `/Services` answer to a signed-out (or unknown) AuthToken. */
297
+ export const AUTH_FAILED_CODE = 3;
298
+ const INVITE_TOKEN_TEXT = /Your invite token is\s*\d{5,20}/;
299
+ /** Read a reply to {@link SIGNED_IN_PROBE_URL} (pure). Never decides on a reply that says neither. */
300
+ export function signInVerdict(res) {
301
+ let path = '';
302
+ try {
303
+ path = new URL(res.url).pathname;
304
+ }
305
+ catch {
306
+ path = '';
307
+ }
308
+ if (SIGNIN_PATH.test(path))
309
+ return 'signed-out';
310
+ if (res.status !== 200)
311
+ return 'unknown';
312
+ if (INVITE_TOKEN_TEXT.test(res.body))
313
+ return 'signed-in';
314
+ if (hasPasswordInput(res.body))
315
+ return 'signed-out';
316
+ return 'unknown';
317
+ }
318
+ /**
319
+ * Whether a `/Services` reply is war.app's own "not signed in" answer: a valid reply frame
320
+ * carrying server error {@link AUTH_FAILED_CODE} (live 2026-11-17: with no AuthToken, or a
321
+ * bogus one, war.app answers exactly that — never a non-frame body).
322
+ */
323
+ export function isAuthFailedReply(body) {
324
+ if (!looksLikeHexFrame(body))
325
+ return false;
326
+ try {
327
+ return decodeReplyEnvelope(fromHex(body.trim())).error?.code === AUTH_FAILED_CODE;
328
+ }
329
+ catch {
330
+ return false;
331
+ }
332
+ }
333
+ const isServicesUrl = (url) => {
334
+ try {
335
+ return /\/services\b/i.test(new URL(url).pathname);
336
+ }
337
+ catch {
338
+ return false;
339
+ }
340
+ };
341
+ const isProbeUrl = (url) => {
342
+ try {
343
+ const u = new URL(url);
344
+ return u.origin === SESSION_ORIGIN && u.pathname === new URL(SIGNED_IN_PROBE_URL).pathname;
345
+ }
346
+ catch {
347
+ return false;
348
+ }
349
+ };
290
350
  /**
291
351
  * The direct leg: a plain HTTPS request to war.app carrying the linked
292
352
  * AuthToken cookie, mapped to the bridge's `.fetch(init)` surface.
353
+ *
354
+ * A reply that only SUGGESTS a sign-out (a sign-in redirect or form, a 401/403, a
355
+ * `/Services` reply that is not a frame, or war.app's AuthFailed frame) is confirmed with one
356
+ * GET of {@link SIGNED_IN_PROBE_URL} before it is called one: a probe that shows the
357
+ * session signed in passes the reply through as an ordinary failure, so one odd answer no
358
+ * longer walls a good session; a probe that shows it signed out, or cannot tell, keeps the
359
+ * old reading.
293
360
  */
294
361
  export class DirectBridge {
295
362
  store;
@@ -302,6 +369,27 @@ export class DirectBridge {
302
369
  this.fetchImpl = fetchImpl;
303
370
  this.hostSignIn = hostSignIn;
304
371
  }
372
+ /** One GET of {@link SIGNED_IN_PROBE_URL} with the session; `none` when no session is linked. Never throws. */
373
+ async checkSignedIn(signal) {
374
+ const sess = await this.store.read();
375
+ if (!sess)
376
+ return 'none';
377
+ return this.probe(sess.authToken, signal);
378
+ }
379
+ async probe(token, signal) {
380
+ try {
381
+ const res = await this.fetchImpl(SIGNED_IN_PROBE_URL, {
382
+ method: 'GET',
383
+ headers: { cookie: `AuthToken=${token}` },
384
+ ...(signal ? { signal } : {}),
385
+ });
386
+ return signInVerdict(res);
387
+ }
388
+ catch {
389
+ // Nothing from a failed probe reaches a caller: the token cannot leak through it.
390
+ return 'unknown';
391
+ }
392
+ }
305
393
  async fetch(init, signal) {
306
394
  const sess = await this.store.read();
307
395
  if (!sess)
@@ -337,8 +425,13 @@ export class DirectBridge {
337
425
  });
338
426
  }
339
427
  }
340
- if (looksSignedOut(url, res)) {
341
- throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === 'host' });
428
+ const suspect = looksSignedOut(url, res) || (answered && isServicesUrl(url) && isAuthFailedReply(res.body));
429
+ if (suspect) {
430
+ // A GET of the probe page is its own probe; anything else asks once.
431
+ const verdict = isProbeUrl(url) && isSafeToReplay(init.method) ? signInVerdict(res) : await this.probe(token, signal);
432
+ if (verdict !== 'signed-in') {
433
+ throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === 'host' });
434
+ }
342
435
  }
343
436
  return { status: res.status, body: res.body, url: res.url };
344
437
  }
@@ -348,6 +441,16 @@ export class DirectBridge {
348
441
  * another process) at most once per this many ms, not on every bridged call.
349
442
  */
350
443
  export const RELINK_CHECK_MS = 5_000;
444
+ /**
445
+ * Hosted, the direct leg is tried again this long after the router leaves it: a hosted
446
+ * child cannot be relinked in-process (its session is the one mcp-host injected at spawn, whose
447
+ * capture time never changes), so without a retry one odd answer — or a passing edge challenge —
448
+ * kept it off the direct leg until the process restarted. Each wall in a row doubles the wait,
449
+ * up to {@link WALL_RETRY_MAX_MS}; a direct success starts it over.
450
+ */
451
+ export const WALL_RETRY_BASE_MS = 60_000;
452
+ /** The longest wait before a hosted child tries the direct leg again. */
453
+ export const WALL_RETRY_MAX_MS = 30 * 60_000;
351
454
  /**
352
455
  * Wire the direct leg and the fetchproxy bridge into a direct-first router,
353
456
  * returning an object shaped like today's bridge (`ready()` → `{ fetch }`) plus
@@ -377,18 +480,24 @@ export function createDirectFirstBridge(opts) {
377
480
  let wall = null;
378
481
  let stale = false;
379
482
  let lastRelinkCheck = Number.NEGATIVE_INFINITY;
483
+ /** Walls in a row since the direct leg last answered 200: the hosted backoff's exponent. */
484
+ let wallsInARow = 0;
380
485
  const onFallback = ({ error }) => {
381
- const next = error instanceof SessionExpiredError
382
- ? { kind: 'session', capturedAt: error.capturedAt ?? null }
383
- : error instanceof SessionNotLinkedError
384
- ? { kind: 'session', capturedAt: null }
385
- : { kind: 'edge' };
386
- wall = next;
387
486
  const why = error instanceof SessionExpiredError
388
487
  ? 'the linked war.app session is signed out'
389
488
  : error instanceof SessionNotLinkedError
390
489
  ? 'no war.app session is linked'
391
490
  : 'the site edge refused the direct request';
491
+ const since = now();
492
+ wallsInARow += 1;
493
+ const retryAt = hosted ? since + Math.min(WALL_RETRY_BASE_MS * 2 ** (wallsInARow - 1), WALL_RETRY_MAX_MS) : null;
494
+ const timing = { reason: why, since, retryAt };
495
+ const next = error instanceof SessionExpiredError
496
+ ? { kind: 'session', capturedAt: error.capturedAt ?? null, ...timing }
497
+ : error instanceof SessionNotLinkedError
498
+ ? { kind: 'session', capturedAt: null, ...timing }
499
+ : { kind: 'edge', ...timing };
500
+ wall = next;
392
501
  log(`[warapp-mcp] Direct transport unavailable (${why}) — switching to the ContextMint Bridge browser bridge. ` +
393
502
  `Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` +
394
503
  (next.kind !== 'session'
@@ -410,12 +519,18 @@ export function createDirectFirstBridge(opts) {
410
519
  onFallback,
411
520
  });
412
521
  let legs = build();
522
+ /** Lift any wall: a fresh router, back on the direct leg. */
523
+ const liftWall = () => {
524
+ if (!wall)
525
+ return;
526
+ wall = null;
527
+ legs = build();
528
+ };
413
529
  /** Lift a session-caused wall: a fresh router, back on the direct leg. An edge wall stays. */
414
530
  const liftSessionWall = () => {
415
531
  if (wall?.kind !== 'session')
416
532
  return;
417
- wall = null;
418
- legs = build();
533
+ liftWall();
419
534
  };
420
535
  /** Behind a session wall: has a DIFFERENT session been linked since (e.g. by another process)? */
421
536
  const relinkedSinceWall = async () => {
@@ -433,6 +548,10 @@ export function createDirectFirstBridge(opts) {
433
548
  liftSessionWall();
434
549
  stale = false;
435
550
  }
551
+ // Hosted: past the backoff, the direct leg is tried again. A write that reaches
552
+ // war.app signed out on it is still never re-sent over the bridge (below).
553
+ if (mode === 'auto' && wall?.retryAt != null && now() >= wall.retryAt)
554
+ liftWall();
436
555
  // A non-GET whose direct attempt reached war.app (it answered signed-out)
437
556
  // is never re-sent over the bridge: a write must never be sent twice.
438
557
  let reached;
@@ -441,8 +560,10 @@ export function createDirectFirstBridge(opts) {
441
560
  try {
442
561
  const res = await direct.fetch(init, ctx.signal);
443
562
  // Only a 200 proves the session works; a 5xx says nothing about it.
444
- if (res.status === 200)
563
+ if (res.status === 200) {
445
564
  stale = false;
565
+ wallsInARow = 0;
566
+ }
446
567
  return res;
447
568
  }
448
569
  catch (err) {
@@ -466,6 +587,27 @@ export function createDirectFirstBridge(opts) {
466
587
  bridgeTransport: () => legs.bridgeTransport(),
467
588
  stats: () => legs.stats(),
468
589
  sessionStale: () => stale,
590
+ wall: () => wall
591
+ ? {
592
+ kind: wall.kind,
593
+ reason: wall.reason,
594
+ since: new Date(wall.since).toISOString(),
595
+ retryAt: wall.retryAt === null ? null : new Date(wall.retryAt).toISOString(),
596
+ }
597
+ : null,
598
+ checkSession: async () => {
599
+ const verdict = await direct.checkSignedIn();
600
+ if (verdict === 'signed-in') {
601
+ stale = false;
602
+ wallsInARow = 0;
603
+ if (mode === 'auto')
604
+ liftWall();
605
+ }
606
+ else if (verdict === 'signed-out') {
607
+ stale = true;
608
+ }
609
+ return verdict;
610
+ },
469
611
  sessionLinked: () => {
470
612
  stale = false;
471
613
  if (mode === 'auto')
@@ -23,6 +23,7 @@
23
23
  import { createHash, randomBytes } from 'node:crypto';
24
24
  import { chmod, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
25
25
  import { join } from 'node:path';
26
+ import { withPathLock } from '../path-lock.js';
26
27
  import { BundleInterpreter, parseBundle, READER_HELPERS, REQUIRED_HELPERS, } from './interp.js';
27
28
  /** A page that loads the game client (the homepage does not). */
28
29
  const DEFAULT_PAGE_URL = 'https://war.app/MultiPlayer';
@@ -83,6 +84,26 @@ export class WarappBundle {
83
84
  interp;
84
85
  /** Loaded from the cache because the current version could not be looked up. */
85
86
  fallback = false;
87
+ /** Set when this is the pinned known-good client standing in for a refused current one. */
88
+ standInFor;
89
+ /** Set while this build stands in for a refused current client: the window (see {@link StandInWindow}). */
90
+ standIn;
91
+ /** The SHA-256 of this build's bytes (set by {@link loadBundle}); a build without one is never recorded. */
92
+ digest;
93
+ /** Records this build as one that decoded a live board (set by {@link loadBundle}). */
94
+ recorder;
95
+ recorded;
96
+ /**
97
+ * A live board decoded with this build, every byte consumed: record it as a build that works, so a
98
+ * later client this server cannot read is stood in for by it (the owner, 2026-11-17: fall back
99
+ * gracefully). Once per loaded bundle; never throws.
100
+ */
101
+ markDecoded() {
102
+ if (this.recorded)
103
+ return this.recorded.then((r) => (r === 'recorded' ? 'unchanged' : r));
104
+ this.recorded = this.recorder ? this.recorder().catch(() => 'failed') : Promise.resolve('unchanged');
105
+ return this.recorded;
106
+ }
86
107
  constructor(src, version, opts = {}) {
87
108
  this.version = version;
88
109
  this.interp = new BundleInterpreter(parseBundle(src), opts);
@@ -111,6 +132,8 @@ export class WarappBundle {
111
132
  bundleVersion: this.version,
112
133
  fallback: this.fallback,
113
134
  helpers: { verified: [...verified], unverified: [...unverified], ...(reasons ? { reasons: { ...reasons } } : {}) },
135
+ ...(this.standInFor ? { standInFor: { ...this.standInFor } } : {}),
136
+ ...(this.standIn ? { standIn: { ...this.standIn } } : {}),
114
137
  };
115
138
  }
116
139
  /** Whether a type name is registered in this bundle. */
@@ -133,6 +156,19 @@ export class WarappBundle {
133
156
  return this.interp.readClass(typeNameOrVar, reader, budget);
134
157
  }
135
158
  }
159
+ /**
160
+ * The client release the built-in readers (src/protocol/interp.ts `DEFAULT_DIALECT`) and every
161
+ * hand-written encoder are written for: client v6.07, protocol 242. war.app's CDN still serves it by
162
+ * version, byte for byte, and war.app still answers a protocol-242 request in 242's layout. So when
163
+ * the current client is refused (2026-11-17: 639304451701341657 renamed every reader on protocol
164
+ * 243), this one stands in and decodes those replies exactly. Only bytes with this digest are used.
165
+ */
166
+ export const KNOWN_GOOD_BUNDLE = {
167
+ version: '639294131571648437',
168
+ digest: 'dec5cf174f6affb9e4c08802534cf8c6c6496eff977847aaf1497535e3371404',
169
+ };
170
+ /** The CDN URL of a client release, by version (the location {@link discoverBundleUrl} pins). */
171
+ const bundleUrlOf = (version) => `https://${BUNDLE_HOST}${BUNDLE_PATH}?v=${version}`;
136
172
  /** A cached bundle: `<version>.<sha256 of its bytes>.js`. */
137
173
  const BUNDLE_FILE = /^([A-Za-z0-9._-]{1,64})\.([0-9a-f]{64})\.js$/;
138
174
  /** A cache file of the earlier layouts, never read, only pruned: `<version>.js` and `<version>.js.sha256`. */
@@ -182,7 +218,7 @@ async function abandoned(file, pid) {
182
218
  async function pruneBundles(dir, keep) {
183
219
  try {
184
220
  for (const name of await readdir(dir)) {
185
- if (name === keep)
221
+ if (keep.includes(name))
186
222
  continue;
187
223
  const partial = PARTIAL_FILE.exec(name);
188
224
  if (!partial && !BUNDLE_FILE.test(name) && !LEGACY_FILE.test(name))
@@ -288,10 +324,172 @@ async function readVerified(file, digest) {
288
324
  await rm(file, { force: true });
289
325
  return null;
290
326
  }
327
+ /** Whether `e` is the load-time refusal of a client this server cannot read (#131, #148). */
328
+ const isDialectRefusal = (e) => e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified');
329
+ /** Write `src` into the cache as `name` (`0700` directories, an atomic `0600` file). */
330
+ async function cacheBundle(dataDir, dir, name, src) {
331
+ await ensurePrivateDir(dataDir);
332
+ await ensurePrivateDir(dir);
333
+ await writePrivateAtomic(join(dir, name), Buffer.from(src, 'utf8'));
334
+ }
335
+ /** The record of client builds that decoded a live board, in `<dataDir>/bundle/`. */
336
+ export const KNOWN_GOOD_FILE = 'known-good.json';
337
+ /** The open stand-in window (the refused client and when it was first refused), in `<dataDir>/bundle/`. */
338
+ export const STAND_IN_FILE = 'stand-in.json';
339
+ /** How many recorded builds are kept, newest first (each keeps its ~16 MB copy on disk). */
340
+ export const MAX_KNOWN_GOOD = 3;
341
+ const DIGEST = /^[0-9a-f]{64}$/;
342
+ const isRecorded = (v) => {
343
+ if (typeof v !== 'object' || v === null)
344
+ return false;
345
+ const r = v;
346
+ return (typeof r.version === 'string' &&
347
+ SAFE_VERSION.test(r.version) &&
348
+ typeof r.digest === 'string' &&
349
+ DIGEST.test(r.digest) &&
350
+ typeof r.verifiedAt === 'string');
351
+ };
352
+ /**
353
+ * The recorded builds in the bundle directory `dir`, newest first: `[]` when there is no record,
354
+ * `'unreadable'` when the file exists but does not parse (never overwritten). Malformed entries are skipped.
355
+ */
356
+ export async function readKnownGood(dir) {
357
+ let text;
358
+ try {
359
+ text = await readFile(join(dir, KNOWN_GOOD_FILE), 'utf8');
360
+ }
361
+ catch (e) {
362
+ return e.code === 'ENOENT' ? [] : 'unreadable';
363
+ }
364
+ try {
365
+ const parsed = JSON.parse(text);
366
+ const builds = parsed?.builds;
367
+ if (!Array.isArray(builds))
368
+ return 'unreadable';
369
+ return builds.filter(isRecorded);
370
+ }
371
+ catch {
372
+ return 'unreadable';
373
+ }
374
+ }
375
+ /**
376
+ * Record `entry` as a build that decoded a live board: newest first, one entry per version and digest, at
377
+ * most {@link MAX_KNOWN_GOOD}; written `0600` through a temporary file and a rename, under the in-process
378
+ * path lock. A record that does not parse is never overwritten (`'unreadable'`).
379
+ */
380
+ export async function recordKnownGood(dataDir, entry) {
381
+ if (!isRecorded(entry))
382
+ return 'failed';
383
+ const dir = join(dataDir, 'bundle');
384
+ const file = join(dir, KNOWN_GOOD_FILE);
385
+ return withPathLock(file, async () => {
386
+ const builds = await readKnownGood(dir);
387
+ if (builds === 'unreadable')
388
+ return 'unreadable';
389
+ const rest = builds.filter((b) => !(b.version === entry.version && b.digest === entry.digest));
390
+ const next = [entry, ...rest].slice(0, MAX_KNOWN_GOOD);
391
+ try {
392
+ await ensurePrivateDir(dataDir);
393
+ await ensurePrivateDir(dir);
394
+ await writePrivateAtomic(file, `${JSON.stringify({ builds: next }, null, 2)}\n`);
395
+ return 'recorded';
396
+ }
397
+ catch {
398
+ return 'failed';
399
+ }
400
+ });
401
+ }
402
+ /** The open stand-in window on disk, or undefined (none, or not readable). */
403
+ async function readWindow(dir) {
404
+ try {
405
+ const w = JSON.parse(await readFile(join(dir, STAND_IN_FILE), 'utf8'));
406
+ if (typeof w.refusedVersion === 'string' && typeof w.since === 'string' && !Number.isNaN(Date.parse(w.since))) {
407
+ return { refusedVersion: w.refusedVersion, since: w.since };
408
+ }
409
+ }
410
+ catch {
411
+ // None yet.
412
+ }
413
+ return undefined;
414
+ }
415
+ /**
416
+ * When `refusedVersion` was first refused here: the time kept on disk for that version, else `now`
417
+ * (written, so the window survives a restart). Best effort: a write that fails still returns `now`.
418
+ */
419
+ async function openWindow(dataDir, dir, refusedVersion, reason, now) {
420
+ const kept = await readWindow(dir);
421
+ if (kept?.refusedVersion === refusedVersion)
422
+ return kept.since;
423
+ const since = new Date(now).toISOString();
424
+ try {
425
+ await ensurePrivateDir(dataDir);
426
+ await ensurePrivateDir(dir);
427
+ await writePrivateAtomic(join(dir, STAND_IN_FILE), `${JSON.stringify({ refusedVersion, since, reason }, null, 2)}\n`);
428
+ }
429
+ catch {
430
+ // The window is still reported for this load.
431
+ }
432
+ return since;
433
+ }
434
+ /** The current client loads: the window is closed. Best effort. */
435
+ async function closeWindow(dir) {
436
+ await rm(join(dir, STAND_IN_FILE), { force: true }).catch(() => undefined);
437
+ }
438
+ /**
439
+ * A build pinned by version and digest, from the cache or downloaded by version and kept only when its bytes
440
+ * hash to that digest, loaded; `undefined` when it cannot be had or this server refuses it too.
441
+ */
442
+ async function loadPinned(opts, dir, kg) {
443
+ const name = bundleName(kg.version, kg.digest);
444
+ let src = await readVerified(join(dir, name), kg.digest);
445
+ if (src === null) {
446
+ let fetched;
447
+ try {
448
+ fetched = await opts.fetchText(bundleUrlOf(kg.version));
449
+ }
450
+ catch {
451
+ return undefined;
452
+ }
453
+ if (sha256(Buffer.from(fetched, 'utf8')) !== kg.digest || !looksLikeBundle(fetched))
454
+ return undefined;
455
+ try {
456
+ await cacheBundle(opts.dataDir, dir, name, fetched);
457
+ }
458
+ catch {
459
+ return undefined;
460
+ }
461
+ src = fetched;
462
+ }
463
+ try {
464
+ const bundle = new WarappBundle(src, kg.version, opts.interp);
465
+ bundle.digest = kg.digest;
466
+ return { bundle, name };
467
+ }
468
+ catch {
469
+ return undefined;
470
+ }
471
+ }
472
+ /** Wire `bundle` to record itself once a live board decodes with it. */
473
+ function withRecorder(opts, bundle) {
474
+ const now = opts.now ?? Date.now;
475
+ bundle.recorder = async () => {
476
+ if (!bundle.digest)
477
+ return 'unchanged';
478
+ return recordKnownGood(opts.dataDir, { version: bundle.version, digest: bundle.digest, verifiedAt: new Date(now()).toISOString() });
479
+ };
480
+ return bundle;
481
+ }
482
+ /** The cache names of every recorded build (they stay on disk: a later refusal may need any of them). */
483
+ async function recordedNames(dir) {
484
+ const builds = await readKnownGood(dir);
485
+ return builds === 'unreadable' ? [] : builds.map((b) => bundleName(b.version, b.digest));
486
+ }
291
487
  /** Discover, fetch (or reuse the verified cached copy of) and load the current client bundle. */
292
488
  export async function loadBundle(opts) {
293
489
  const pageUrl = opts.pageUrl ?? DEFAULT_PAGE_URL;
294
490
  const dir = join(opts.dataDir, 'bundle');
491
+ const kg = opts.knownGood === undefined ? KNOWN_GOOD_BUNDLE : opts.knownGood;
492
+ const now = opts.now ?? Date.now;
295
493
  let source;
296
494
  try {
297
495
  source = discoverBundleUrl(await opts.fetchText(pageUrl), pageUrl);
@@ -299,13 +497,24 @@ export async function loadBundle(opts) {
299
497
  catch (e) {
300
498
  // The page naming the current version could not be read (a frozen tab, a signed-out page):
301
499
  // a copy already on disk still decodes, rather than failing every live read (#131).
302
- // Only a copy that still matches its recorded digest stands in.
303
- const cached = await newestVerified(dir);
304
- if (!cached)
305
- throw e;
306
- const b = new WarappBundle(cached.src, cached.version, opts.interp);
307
- b.fallback = true;
308
- return b;
500
+ // Only a copy that still matches its recorded digest stands in, newest first, skipping one
501
+ // this server refuses to read (a client it was never written for).
502
+ for (const c of await cachedNewestFirst(dir)) {
503
+ const src = await readVerified(c.file, c.digest);
504
+ if (src === null)
505
+ continue;
506
+ try {
507
+ const b = new WarappBundle(src, c.version, opts.interp);
508
+ b.fallback = true;
509
+ b.digest = c.digest;
510
+ return withRecorder(opts, b);
511
+ }
512
+ catch (err) {
513
+ if (!isDialectRefusal(err))
514
+ throw err;
515
+ }
516
+ }
517
+ throw e;
309
518
  }
310
519
  const { url, version } = source;
311
520
  const cached = await newestVerified(dir, version);
@@ -319,22 +528,54 @@ export async function loadBundle(opts) {
319
528
  if (!looksLikeBundle(src)) {
320
529
  throw new BundleError('bad-bundle', `${url} does not look like the war.app client bundle`);
321
530
  }
322
- await ensurePrivateDir(opts.dataDir);
323
- await ensurePrivateDir(dir);
324
- const bytes = Buffer.from(src, 'utf8');
325
531
  // One file, its digest in its name, made visible by one rename: never a bundle without its digest.
326
- name = bundleName(version, sha256(bytes));
327
- await writePrivateAtomic(join(dir, name), bytes);
532
+ name = bundleName(version, sha256(Buffer.from(src, 'utf8')));
533
+ await cacheBundle(opts.dataDir, dir, name, src);
328
534
  }
329
- const bundle = new WarappBundle(src, version, opts.interp);
330
- await pruneBundles(dir, name);
331
- return bundle;
535
+ const keepKnownGood = kg ? [bundleName(kg.version, kg.digest)] : [];
536
+ const keepRecorded = await recordedNames(dir);
537
+ let bundle;
538
+ try {
539
+ bundle = new WarappBundle(src, version, opts.interp);
540
+ }
541
+ catch (e) {
542
+ if (!isDialectRefusal(e))
543
+ throw e;
544
+ // Stand-ins, best first: every build that decoded a live board here (newest first), then the pin.
545
+ const recorded = await readKnownGood(dir);
546
+ const candidates = [
547
+ ...(recorded === 'unreadable' ? [] : recorded.map(({ version: v, digest }) => ({ version: v, digest }))),
548
+ ...(kg ? [kg] : []),
549
+ ].filter((c, i, all) => c.version !== version && all.findIndex((o) => o.version === c.version && o.digest === c.digest) === i);
550
+ for (const c of candidates) {
551
+ const standIn = await loadPinned(opts, dir, c);
552
+ if (!standIn)
553
+ continue;
554
+ const since = await openWindow(opts.dataDir, dir, version, e.message, now());
555
+ standIn.bundle.standInFor = { version, reason: e.message };
556
+ standIn.bundle.standIn = { version: c.version, refusedVersion: version, since, reason: e.message };
557
+ // All stay: the refused copy so the next lookup does not download it again, the stand-in in use,
558
+ // and every recorded build.
559
+ await pruneBundles(dir, [name, standIn.name, ...keepKnownGood, ...keepRecorded]);
560
+ return withRecorder(opts, standIn.bundle);
561
+ }
562
+ throw e;
563
+ }
564
+ bundle.digest = name.slice(version.length + 1, -'.js'.length);
565
+ await closeWindow(dir);
566
+ await pruneBundles(dir, [name, ...keepKnownGood, ...keepRecorded]);
567
+ return withRecorder(opts, bundle);
332
568
  }
333
569
  /**
334
570
  * How long a fallback bundle is used, or a refused (dialect-mismatch) bundle is remembered, before
335
571
  * the current version is looked up again.
336
572
  */
337
573
  const FALLBACK_RETRY_MS = 5 * 60_000;
574
+ /**
575
+ * How long the known-good stand-in is used before the current version is looked up again: re-checking
576
+ * a refused ~16 MB bundle costs seconds of parsing, and a client release changes rarely.
577
+ */
578
+ const STAND_IN_RETRY_MS = 60 * 60_000;
338
579
  /**
339
580
  * Loads the bundle once per process; a failed load is retried on the next call, except a bundle
340
581
  * refused as a dialect mismatch, which is retried after {@link FALLBACK_RETRY_MS}.
@@ -356,14 +597,18 @@ export class BundleProvider {
356
597
  this.pending = p;
357
598
  p.then((b) => {
358
599
  // A cached copy stands in only until the version can be looked up again.
359
- if (b.fallback && this.pending === p)
600
+ if (this.pending !== p)
601
+ return;
602
+ if (b.standInFor)
603
+ this.fallbackUntil = now() + STAND_IN_RETRY_MS;
604
+ else if (b.fallback)
360
605
  this.fallbackUntil = now() + FALLBACK_RETRY_MS;
361
606
  }, (e) => {
362
607
  if (this.pending !== p)
363
608
  return;
364
609
  // A bundle this server cannot read stays unreadable: remember the refusal for a while
365
610
  // instead of re-reading and re-checking ~16 MB on every live call (#131).
366
- if (e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified')) {
611
+ if (isDialectRefusal(e)) {
367
612
  this.fallbackUntil = now() + FALLBACK_RETRY_MS;
368
613
  }
369
614
  else
@@ -32,6 +32,8 @@ export function methodTakesAuth(methodId) {
32
32
  * 51 (`MustUseCard`, verified live) has no client wording; this is ours.
33
33
  */
34
34
  export const SERVER_ERROR_MESSAGES = {
35
+ // AuthFailed (live 2026-11-17): war.app's answer when the request's session is not signed in.
36
+ 3: 'war.app refused the request as not signed in (AuthFailed): the war.app session this server uses is signed out.',
35
37
  10: 'war.app refused the order sequence — card plays must come in turn-phase order.',
36
38
  11: 'Your orders deploy more or fewer armies than you are receiving this turn. Please verify your orders deploy the correct number.',
37
39
  51: 'You hold more cards than this game allows, so war.app requires you to play or discard one this turn.',
@@ -46,6 +48,21 @@ export const SERVER_ERROR_MESSAGES = {
46
48
  };
47
49
  /** The longest slice of an unmapped server message shown to the caller. */
48
50
  const MAX_SERVER_MESSAGE = 200;
51
+ /**
52
+ * war.app answered in another protocol version than the one every reader here reads: a reply framed for
53
+ * another version would decode into wrong values, not an error (#131), so it is never decoded.
54
+ */
55
+ export class ProtocolVersionError extends McpToolError {
56
+ answered;
57
+ name = 'ProtocolVersionError';
58
+ constructor(methodName, answered) {
59
+ super(`war.app answered ${methodName} in protocol version ${answered}; this server reads version ${PROTOCOL_VERSION}.`, {
60
+ kind: 'unknown',
61
+ hint: 'The war.app client may have changed; this server needs an update to read it.',
62
+ });
63
+ this.answered = answered;
64
+ }
65
+ }
49
66
  /** A ServerException reply (envelope kind 5). */
50
67
  export class WarappServerError extends McpToolError {
51
68
  code;
@@ -141,7 +158,7 @@ export class WarappRpc {
141
158
  if (env.version !== PROTOCOL_VERSION) {
142
159
  // Every reader (the bundle's, and methods.ts) reads the layout of PROTOCOL_VERSION: a reply
143
160
  // framed for another version would decode into wrong values, not an error (#131).
144
- throw new McpToolError(`war.app answered ${methodName} in protocol version ${env.version}; this server reads version ${PROTOCOL_VERSION}.`, { kind: 'unknown', hint: 'The war.app client may have changed; this server needs an update to read it.' });
161
+ throw new ProtocolVersionError(methodName, env.version);
145
162
  }
146
163
  if (env.method !== methodId) {
147
164
  throw new McpToolError(`war.app answered ${methodName} (method ${methodId}) with method ${env.method}.`, {
@@ -9,11 +9,10 @@
9
9
  import { CONFIRM_INJECTION_RULE, toolAnnotations } from '@chrischall/mcp-utils';
10
10
  import { z } from 'zod';
11
11
  import { parseGameId } from '../client.js';
12
- import { readLatestGameInfo, standingFromInfo } from '../live.js';
13
- import { Method, writeBeginFirstTurnParams, writeGetLatestGameInfoParams } from '../protocol/methods.js';
12
+ import { Method, writeBeginFirstTurnParams } from '../protocol/methods.js';
14
13
  import { gameIdArg, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedText } from './common.js';
15
14
  import { mintMeta } from './hints.js';
16
- import { requireApprovedAccount, SPEED_FIRST_TURN_MOVE_ORDER, writeAccount } from './live-context.js';
15
+ import { readLatestBoard, requireApprovedAccount, SPEED_FIRST_TURN_MOVE_ORDER, writeAccount } from './live-context.js';
17
16
  import { defineGatedWrite, mySeat, refuse, requireMe, requirePlaying, sendAndVerify } from './write-kit.js';
18
17
  const PLAYING = 'Playing';
19
18
  const DISTRIBUTING = 'DistributingTerritories';
@@ -42,8 +41,7 @@ function beginnable(game, me) {
42
41
  }
43
42
  /** The live board, or undefined while war.app withholds it. */
44
43
  async function liveBoard(ctx, gameId) {
45
- const env = await ctx.rpc.call('GetLatestGameInfo', Method.GetLatestGameInfo, (w) => writeGetLatestGameInfoParams(w, gameId));
46
- return standingFromInfo(readLatestGameInfo(await ctx.bundle(), env.body)) ?? undefined;
44
+ return (await readLatestBoard(ctx, gameId)).territories ?? undefined;
47
45
  }
48
46
  export function registerBeginTurnTool(server, ctx) {
49
47
  defineGatedWrite(server, {