@chrischall/warapp-mcp 0.3.0 → 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.
@@ -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}.`, {
@@ -1,3 +1,4 @@
1
+ import { egressProxyConfigured } from '../direct/egress.js';
1
2
  import { scrubToken } from '../direct/session.js';
2
3
  import { DirectBridge } from '../direct/transport.js';
3
4
  import { parseHandshake, parsePacket, SOCKET_URL } from './packets.js';
@@ -37,10 +38,16 @@ export function websocketUrl(sid) {
37
38
  * The leg for the process's direct-first bridge: the WebSocket is selected
38
39
  * only while the active transport is `direct` (pinned `direct`, or `auto`
39
40
  * still on the direct leg); otherwise the push stays on xhr-polling.
41
+ *
42
+ * Never with an egress proxy configured (HTTPS_PROXY: mcp-host's only way out,
43
+ * src/direct/egress.ts). Node's built-in WebSocket opens its own socket, which
44
+ * the proxy would not carry (a direct socket is silently dropped there), so the
45
+ * push stays on xhr-polling over the direct-first router, whose direct leg goes
46
+ * through the proxy. Read on each attempt.
40
47
  */
41
- export function pushWebSocketLeg(bridge, readSession, seams = {}) {
48
+ export function pushWebSocketLeg(bridge, readSession, seams = {}, env = process.env) {
42
49
  return {
43
- select: () => bridge.status().transport === 'direct',
50
+ select: () => bridge.status().transport === 'direct' && !egressProxyConfigured(env),
44
51
  session: readSession,
45
52
  ...seams,
46
53
  };
@@ -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, {
@@ -17,7 +17,7 @@ import { assumedWarning, awardView, loadAward, openingThreat } from './award.js'
17
17
  import { gameIdArg, graphOf, namer, readAnnotations, respond, untrustedDescription, untrustedText, viewArg } from './common.js';
18
18
  import { lookupMeta } from './hints.js';
19
19
  import { HEADROOM_COMPACT, headroomView, readTripwires, safeHeadroom, teamsOf, tripwireWarnings, untrustedDeploy } from './survival.js';
20
- import { loadLiveGame } from './live-context.js';
20
+ import { loadLiveGame, standInLine, standInOf } from './live-context.js';
21
21
  import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
22
22
  import { mapOf } from './map.js';
23
23
  import { resolveTerritory } from './resolve.js';
@@ -540,6 +540,8 @@ export function registerCheckPlanTool(server, ctx) {
540
540
  // #275 pattern 3: each border these orders leave below what the default plan leaves there (one plan per call).
541
541
  const belowPlan = await bordersBelowPlan(ctx, { game, map, me, turn, territories, info, history, teamsKnown, given: { deploys, moves } });
542
542
  const warnings = [
543
+ // The owner, 2026-11-17: while an older build stands in for a client this server cannot read, say so first.
544
+ ...[standInLine(standInOf(ctx))].filter((w) => w !== undefined),
543
545
  // #275 (b): an untrusted estimate is the first thing said (not under an explicit enemy_deploy).
544
546
  ...(enemy_deploy === undefined ? tripwireWarnings(trip.tripwires, (w) => untrustedOf.get(w.player) ?? untrustedDeploy(w, income), (p) => estimates.find((x) => x.playerId === p)?.estimate) : []),
545
547
  ...(award ? assumedWarning(award) : []),
@@ -3,6 +3,7 @@ import { registerAdaptiveHealthcheckTool, } from '@chrischall/mcp-utils/fetchpro
3
3
  import { AUTH_FAILED_HINT, PROBE_GAME_ID, WarappClient } from '../client.js';
4
4
  import { readCredentials, TOKEN_URL, WarappConfigError } from '../config.js';
5
5
  import { readSessionSync } from '../direct/session.js';
6
+ import { HOST_SIGN_IN_ADVICE, SessionExpiredError } from '../direct/transport.js';
6
7
  /**
7
8
  * `warapp_healthcheck` — does war.app accept the configured email + token?
8
9
  *
@@ -21,11 +22,24 @@ import { readSessionSync } from '../direct/session.js';
21
22
  * which is the whole time the direct leg is serving calls ("on direct, the
22
23
  * credential probe"). Either way the result carries which leg is active and
23
24
  * whether a direct session is linked and how old it is — never the token.
25
+ *
26
+ * with a direct session (linked, or captured by mcp-host when hosted) the
27
+ * credential arm also asks war.app whether that SESSION is signed in — one GET
28
+ * of the invite-token page with it (`sessionCheck`: signed-in / signed-out /
29
+ * unknown) — and reports the router's `wall` (why it left the direct leg, when,
30
+ * and when it tries again). A session war.app shows signed out fails the check
31
+ * as `session_expired`, even when the API token is fine: before, a hosted
32
+ * healthcheck said ok while every live tool failed.
24
33
  */
25
34
  export { PROBE_GAME_ID };
26
35
  const PROBE_PATH = `/API/GameFeed?GameID=${PROBE_GAME_ID}&GetMap=false`;
27
36
  /** The page the bridge arm round-trips through the user's war.app tab. */
28
37
  export const BRIDGE_PROBE_PATH = '/';
38
+ /** `health` with the open stand-in window beside it, when one is open. */
39
+ function withStandIn(health, deps) {
40
+ const w = deps.standIn?.();
41
+ return w ? { ...health, standIn: w } : health;
42
+ }
29
43
  /**
30
44
  * The non-secret facts about the linked direct session — never the token. The
31
45
  * session mcp-host captured at sign-in (hosted, #333) is `linked: true` with `linkedBy: 'host'` (`linked` stays a boolean), with
@@ -46,6 +60,33 @@ function transportHealth(status, env, now) {
46
60
  }
47
61
  export function registerHealthcheckTool(server, bridge, direct, deps = {}) {
48
62
  const now = deps.now ?? Date.now;
63
+ /** What this call's session check found, echoed in the result; reset at each check. */
64
+ let lastCheck = {};
65
+ /** Check the direct session when there is one and the router may use it; never throws. */
66
+ const checkSession = async () => {
67
+ lastCheck = {};
68
+ if (!direct.checkSession || direct.status().mode === 'fetchproxy')
69
+ return undefined;
70
+ if (!readSessionSync(deps.env))
71
+ return undefined;
72
+ const verdict = await direct.checkSession().catch(() => 'unknown');
73
+ if (verdict === 'none')
74
+ return undefined;
75
+ const wall = direct.wall?.() ?? null;
76
+ lastCheck = { sessionCheck: verdict, ...(wall ? { wall } : {}) };
77
+ return verdict;
78
+ };
79
+ const health = () => withStandIn({ ...transportHealth(direct.status(), deps.env, now), ...lastCheck }, deps);
80
+ const signedOut = () => new SessionExpiredError({ hostSignIn: readSessionSync(deps.env)?.origin === 'host' });
81
+ const classifySignedOut = (err) => err instanceof SessionExpiredError
82
+ ? {
83
+ kind: 'session_expired',
84
+ hint: 'war.app shows the session the live tools use as signed out. ' +
85
+ (err.hostSignIn ? HOST_SIGN_IN_ADVICE : 'Run warapp_link_session to relink.'),
86
+ }
87
+ : undefined;
88
+ /** The session check this call's resolver made, read by its probe. */
89
+ let resolvedVerdict;
49
90
  registerAdaptiveHealthcheckTool({
50
91
  server,
51
92
  prefix: 'warapp',
@@ -60,36 +101,51 @@ export function registerHealthcheckTool(server, bridge, direct, deps = {}) {
60
101
  bridge: {
61
102
  probePath: BRIDGE_PROBE_PATH,
62
103
  transport: () => bridge.transport(),
63
- path: () => transportHealth(direct.status(), deps.env, now),
104
+ path: health,
64
105
  probeFn: async (path) => {
65
- const res = await (await bridge.ready()).fetch({ method: 'GET', path });
106
+ // Off the direct leg with a session: ask war.app about the session first. Signed
107
+ // out is the answer; signed in lifts the wall, and the probe then rides the direct leg.
108
+ const verdict = await checkSession();
109
+ if (verdict === 'signed-out')
110
+ throw signedOut();
111
+ const viaRouter = verdict === 'signed-in' && direct.ready !== undefined;
112
+ const leg = viaRouter ? await direct.ready() : await bridge.ready();
113
+ const res = await leg.fetch({ method: 'GET', path });
66
114
  if (res.status !== 200) {
67
- throw new McpToolError(`war.app answered HTTP ${res.status} through the bridge.`, {
115
+ throw new McpToolError(`war.app answered HTTP ${res.status}${viaRouter ? '' : ' through the bridge'}.`, {
68
116
  status: res.status,
69
117
  kind: 'http',
70
118
  });
71
119
  }
72
120
  return res.body;
73
121
  },
122
+ classifyThrown: classifySignedOut,
74
123
  },
75
124
  credential: {
76
125
  probePath: PROBE_PATH,
77
126
  resolveCredential: async () => {
78
- const health = transportHealth(direct.status(), deps.env, now);
127
+ resolvedVerdict = await checkSession();
128
+ const detail = health();
79
129
  try {
80
130
  readCredentials(deps.env);
81
- return { source: 'env', detail: health };
131
+ return { source: 'env', detail };
82
132
  }
83
133
  catch (e) {
84
134
  if (e instanceof WarappConfigError)
85
- return { source: null, detail: { ...health, reason: e.message } };
135
+ return { source: null, detail: { ...detail, reason: e.message } };
86
136
  throw e;
87
137
  }
88
138
  },
89
- probeFn: () => new WarappClient(deps).probeAuth(),
139
+ probeFn: async () => {
140
+ const res = await new WarappClient(deps).probeAuth();
141
+ // The API token works; the live tools ride the session, which war.app says is signed out.
142
+ if (resolvedVerdict === 'signed-out')
143
+ throw signedOut();
144
+ return res;
145
+ },
90
146
  classifyThrown: (err) => err instanceof McpToolError && err.kind === 'credential_rejected'
91
147
  ? { kind: 'credential_rejected', hint: AUTH_FAILED_HINT }
92
- : undefined,
148
+ : classifySignedOut(err),
93
149
  hints: { no_credential: `Set WARAPP_EMAIL and WARAPP_API_TOKEN (token from ${TOKEN_URL}).` },
94
150
  },
95
151
  });
@@ -77,7 +77,7 @@ export function registerAllTools(server, deps = {}) {
77
77
  // The cached signed-in account is discarded whenever the account behind the router may have changed.
78
78
  identity: () => bridge.identityState(),
79
79
  });
80
- registerHealthcheckTool(server, fetchproxy, bridge, deps);
80
+ registerHealthcheckTool(server, fetchproxy, bridge, { ...deps, standIn: () => live.decoderReport()?.standIn });
81
81
  // The signed-in account names a finished game's player for its end-of-game pass when no board was cached (#312).
82
82
  registerGameTool(server, client, () => dataDir(deps.env), deps.env, () => live.myInviteToken());
83
83
  registerMapTool(server, client, live);
@@ -135,13 +135,14 @@ export function registerAllTools(server, deps = {}) {
135
135
  const push = deps.push ??
136
136
  pushListenerFor(fetchproxy, {
137
137
  transport: () => bridge.ready(),
138
- webSocket: pushWebSocketLeg(bridge, () => readSession(deps.env)),
138
+ webSocket: pushWebSocketLeg(bridge, () => readSession(deps.env), {}, deps.env ?? process.env),
139
139
  extras: () => live.rpc.extras,
140
140
  });
141
141
  registerSessionTools(server, {
142
142
  transport: {
143
143
  activeLeg: () => bridge.status().transport,
144
144
  sessionStale: () => bridge.sessionStale(),
145
+ wall: () => bridge.wall(),
145
146
  sessionLinked: () => bridge.sessionLinked(),
146
147
  },
147
148
  pushTransport: () => push.status().transport,