@chrischall/warapp-mcp 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +49 -20
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +13214 -9759
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/direct/link.js +9 -5
  22. package/dist/direct/session.js +60 -6
  23. package/dist/direct/sign-in.js +296 -0
  24. package/dist/direct/transport.js +59 -24
  25. package/dist/finished-store.js +357 -0
  26. package/dist/hosted.js +6 -4
  27. package/dist/index.js +1 -1
  28. package/dist/lessons-store.js +356 -0
  29. package/dist/live.js +9 -0
  30. package/dist/map-details.js +127 -0
  31. package/dist/map-stats.js +14 -6
  32. package/dist/map-store.js +44 -6
  33. package/dist/my-games.js +44 -6
  34. package/dist/normalize.js +34 -2
  35. package/dist/notifications.js +143 -0
  36. package/dist/outlook-log.js +28 -1
  37. package/dist/player-record-store.js +2 -0
  38. package/dist/profile-store.js +61 -11
  39. package/dist/protocol/methods.js +86 -2
  40. package/dist/replay.js +16 -4
  41. package/dist/stats.js +26 -4
  42. package/dist/strategy/notes.js +64 -9
  43. package/dist/surrender-pending.js +126 -0
  44. package/dist/tools/accept-surrender.js +311 -0
  45. package/dist/tools/chat-inbox.js +17 -5
  46. package/dist/tools/chat-read-mark.js +179 -0
  47. package/dist/tools/chat.js +50 -8
  48. package/dist/tools/check-plan.js +1 -0
  49. package/dist/tools/commander-check.js +1 -0
  50. package/dist/tools/end-of-game.js +384 -0
  51. package/dist/tools/game.js +31 -6
  52. package/dist/tools/healthcheck.js +7 -1
  53. package/dist/tools/index.js +24 -8
  54. package/dist/tools/join-game.js +1 -1
  55. package/dist/tools/live-context.js +3 -1
  56. package/dist/tools/map-details.js +88 -0
  57. package/dist/tools/map-stats.js +15 -2
  58. package/dist/tools/map.js +10 -2
  59. package/dist/tools/my-games.js +78 -8
  60. package/dist/tools/notifications.js +484 -0
  61. package/dist/tools/open-games.js +5 -2
  62. package/dist/tools/opponents.js +14 -2
  63. package/dist/tools/past-games.js +94 -0
  64. package/dist/tools/picks.js +15 -2
  65. package/dist/tools/profile-opponents.js +1 -1
  66. package/dist/tools/profile-reads.js +3 -3
  67. package/dist/tools/push.js +72 -12
  68. package/dist/tools/session.js +50 -18
  69. package/dist/tools/sign-in.js +56 -0
  70. package/dist/tools/strategy.js +65 -8
  71. package/dist/tools/stress-opponents.js +1 -1
  72. package/dist/tools/surrender-pending.js +74 -0
  73. package/dist/tools/surrender.js +10 -3
  74. package/dist/tools/team-brief.js +1 -1
  75. package/dist/tools/team.js +2 -6
  76. package/dist/tools/turn.js +79 -15
  77. package/dist/tools/where.js +42 -17
  78. package/dist/tools/write-kit.js +16 -3
  79. package/dist/trend.js +145 -20
  80. package/dist/version.js +1 -1
  81. package/docs/examples/warapp-auth-flow.json +31 -0
  82. package/manifest.json +22 -2
  83. package/mint.yaml +44 -22
  84. package/package.json +3 -2
  85. package/server.json +2 -2
  86. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -0,0 +1,75 @@
1
+ import { normalizeSettings } from './normalize.js';
2
+ import { anonymousHistoryOfRecord, finishedPath, historyOfRecord, listFinishedRecords, readFinishedRecord } from './finished-store.js';
3
+ import { readStoredMap } from './map-store.js';
4
+ import { playerRecordSalt } from './player-record-store.js';
5
+ import { gamesDir, loadReplay } from './replay.js';
6
+ import { readdir } from 'node:fs/promises';
7
+ const count = (o, k) => {
8
+ o[k] = (o[k] ?? 0) + 1;
9
+ };
10
+ async function settingsRecordIds(dir) {
11
+ const names = await readdir(gamesDir(dir)).catch(() => []);
12
+ return names
13
+ .filter((n) => /^\d+\.json$/.test(n))
14
+ .map((n) => Number(n.slice(0, -5)))
15
+ .sort((a, b) => a - b);
16
+ }
17
+ /** Every finished game the data directory can score, and what it cannot. Never throws. */
18
+ export async function calibrationSources(dir) {
19
+ const out = { inputs: [], statuses: {}, skipped: {} };
20
+ const salt = await playerRecordSalt(dir).catch(() => undefined);
21
+ // The settings records by the record path they would match.
22
+ const byPath = new Map();
23
+ for (const id of await settingsRecordIds(dir)) {
24
+ const replay = await loadReplay(dir, id);
25
+ if (!salt || !replay || replay.playerId === undefined) {
26
+ count(out.statuses, 'missing');
27
+ continue;
28
+ }
29
+ byPath.set(finishedPath(dir, salt, replay.playerId, id), replay);
30
+ }
31
+ const paths = salt ? await listFinishedRecords(dir) : [];
32
+ const seen = new Set();
33
+ for (const path of paths) {
34
+ seen.add(path);
35
+ const rec = await readFinishedRecord(path);
36
+ if (typeof rec === 'string') {
37
+ count(out.statuses, rec);
38
+ continue;
39
+ }
40
+ count(out.statuses, rec.status);
41
+ if (rec.status !== 'captured')
42
+ continue;
43
+ const replay = byPath.get(path);
44
+ const matched = replay ? historyOfRecord(rec, salt, [replay.playerId, ...replay.game.players.map((p) => p.id)]) : undefined;
45
+ const history = matched && typeof matched === 'object' ? matched : anonymousHistoryOfRecord(rec);
46
+ if (typeof history === 'string') {
47
+ count(out.skipped, 'captured-without-boards');
48
+ continue;
49
+ }
50
+ const fromReplay = matched !== undefined && typeof matched === 'object';
51
+ const settings = fromReplay ? replay.settings : rec.settings ? normalizeSettings(rec.settings) : undefined;
52
+ if (!settings) {
53
+ count(out.skipped, 'no-settings');
54
+ continue;
55
+ }
56
+ const mapId = rec.mapId ?? settings.mapId;
57
+ const map = (fromReplay ? replay.map : undefined) ?? (mapId !== undefined ? await readStoredMap(dir, mapId, { maxAgeMs: Number.POSITIVE_INFINITY }) : undefined);
58
+ if (!map) {
59
+ count(out.skipped, 'no-map');
60
+ continue;
61
+ }
62
+ const cached = fromReplay && replay.playerId === history.me
63
+ ? replay.boards.map((b) => {
64
+ const o = replay.orders.get(b.turn);
65
+ return { turn: b.turn, board: b.board, ...(o ? { orders: o } : {}) };
66
+ })
67
+ : [];
68
+ out.inputs.push({ source: fromReplay ? 'settings-record' : 'record-only', history, settings, map, cached });
69
+ }
70
+ // A settings record whose game has no record: its pass has not run (or the record was pruned).
71
+ for (const path of byPath.keys())
72
+ if (!seen.has(path))
73
+ count(out.statuses, 'missing');
74
+ return out;
75
+ }
package/dist/chat.js CHANGED
@@ -58,6 +58,7 @@ function webLine(m) {
58
58
  }
59
59
  else if (group !== null) {
60
60
  line.channel = 'unknown';
61
+ line.group = group;
61
62
  }
62
63
  else if (channel === PUBLIC_CHANNEL) {
63
64
  line.channel = 'public';
@@ -126,6 +127,42 @@ export function readSendChatReply(bundle, body) {
126
127
  return undefined;
127
128
  }
128
129
  }
130
+ const MESSAGE_ID = /^\d{1,20}$/;
131
+ const higher = (a, b) => (a === undefined || BigInt(b) > BigInt(a) ? b : a);
132
+ /**
133
+ * The read marks of web-client `lines` on `channels` (pure): per channel the highest message id among
134
+ * them, mine included, as the client keeps it. A private conversation is keyed by its counterpart — the
135
+ * recipient of a message I sent, else its sender — and a game group (`unknown`) by its group. Lines
136
+ * without a message id (GameFeed's) mark nothing. `undefined` when nothing would be marked.
137
+ */
138
+ export function chatViewMarks(lines, meInGame, channels) {
139
+ const want = new Set(channels);
140
+ const out = { private: new Map(), groups: new Map(), channels: [] };
141
+ for (const l of lines) {
142
+ if (l.id === undefined || !MESSAGE_ID.test(l.id) || !want.has(l.channel))
143
+ continue;
144
+ if (l.channel === 'public')
145
+ out.public = higher(out.public, l.id);
146
+ else if (l.channel === 'team')
147
+ out.team = higher(out.team, l.id);
148
+ else if (l.channel === 'private') {
149
+ const other = l.sender === meInGame ? l.to : l.sender;
150
+ if (other === undefined || other === null)
151
+ continue;
152
+ out.private.set(other, higher(out.private.get(other), l.id));
153
+ }
154
+ else if (l.group !== undefined)
155
+ out.groups.set(l.group, higher(out.groups.get(l.group), l.id));
156
+ }
157
+ const has = {
158
+ public: out.public !== undefined,
159
+ team: out.team !== undefined,
160
+ private: out.private.size > 0,
161
+ unknown: out.groups.size > 0,
162
+ };
163
+ out.channels = CHAT_CHANNELS.filter((c) => has[c]);
164
+ return out.channels.length ? out : undefined;
165
+ }
129
166
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
130
167
  const pick = (r, keys) => {
131
168
  for (const k of keys)
@@ -190,3 +227,39 @@ export function feedChatLines(raw) {
190
227
  }
191
228
  return out;
192
229
  }
230
+ // ---------- A short web read, filled from GameFeed (#313) ----------
231
+ /** Two times this close (ms) are one message's: GameFeed may give whole seconds where the web client gives ms. */
232
+ const SAME_MESSAGE_MS = 1000;
233
+ const sameMessage = (web, feed) => {
234
+ if (web.sender !== feed.sender)
235
+ return false;
236
+ if (web.timeMs !== undefined && feed.timeMs !== undefined)
237
+ return Math.abs(web.timeMs - feed.timeMs) < SAME_MESSAGE_MS;
238
+ return web.text === feed.text;
239
+ };
240
+ /**
241
+ * The web client's `web` lines with GameFeed's `feed` lines that no web line matches (same sender, and
242
+ * times within a second — or the same text when either has no time), each match used once. The added
243
+ * lines keep GameFeed's `unknown` channel and go in by time (after every web line of the same or an
244
+ * earlier time); one with no time goes last. Pure: `added` is how many GameFeed lines were added.
245
+ */
246
+ export function fillFromFeed(web, feed) {
247
+ const used = new Set();
248
+ const extra = [];
249
+ for (const f of feed) {
250
+ const k = web.findIndex((w, i) => !used.has(i) && sameMessage(w, f));
251
+ if (k >= 0)
252
+ used.add(k);
253
+ else
254
+ extra.push({ ...f, channel: 'unknown' });
255
+ }
256
+ const lines = [...web];
257
+ for (const e of extra) {
258
+ const at = e.timeMs === undefined ? -1 : lines.findIndex((l) => l.timeMs !== undefined && l.timeMs > e.timeMs);
259
+ if (at < 0)
260
+ lines.push(e);
261
+ else
262
+ lines.splice(at, 0, e);
263
+ }
264
+ return { lines, added: extra.length };
265
+ }
package/dist/client.js CHANGED
@@ -25,9 +25,10 @@
25
25
  import { createApiClient, ERROR_REDACTION_INPUT_MAX, McpToolError, truncateErrorMessage, } from '@chrischall/mcp-utils';
26
26
  import { readCredentials, TOKEN_URL, WarappConfigError } from './config.js';
27
27
  import { feedErrorOf, normalizeGame, normalizeMap } from './normalize.js';
28
- import { readGameMapId, readStoredMap, rememberGameMap, touchStoredMap, writeStoredMap } from './map-store.js';
28
+ import { readGameMapId, readStoredMap, readStoredMapEntry, rememberGameMap, touchStoredMap, writeStoredMap, writeStoredModeTerritories } from './map-store.js';
29
29
  import { scrubSecrets } from './redact.js';
30
30
  import { asInt } from './scalars.js';
31
+ import { safeKeys } from './trend.js';
31
32
  const BASE_URL = 'https://war.app';
32
33
  const SERVICE = 'war.app';
33
34
  /** A game id war.app will not have: the largest positive int32. */
@@ -69,6 +70,7 @@ export class MapCache {
69
70
  #maps = new Map();
70
71
  #gameMaps = new Map();
71
72
  #refreshed = new Set();
73
+ #detailsTried = new Set();
72
74
  get(mapId) {
73
75
  return this.#maps.get(mapId);
74
76
  }
@@ -115,13 +117,67 @@ export class MapCache {
115
117
  */
116
118
  async store(map, dir, replace = false) {
117
119
  const known = this.#maps.has(map.id);
118
- this.set(map);
120
+ // #328: a map new to this process may already be stored with its modes' territories (read from war.app's
121
+ // map details, not GameFeed): the same map within its age, so they are kept rather than read again.
122
+ const carried = !known && !replace && dir !== undefined ? await this.#withStoredModes(map, dir) : undefined;
123
+ const kept = carried?.map ?? map;
124
+ this.set(kept);
119
125
  if (dir === undefined)
120
126
  return;
127
+ // Carried ids keep the age of the copy they were read with, so they age out on its clock, not this download's.
121
128
  if (!known || replace)
122
- await writeStoredMap(dir, map);
129
+ await writeStoredMap(dir, kept, carried?.storedAt);
123
130
  else
124
- await touchStoredMap(dir, map);
131
+ await touchStoredMap(dir, kept);
132
+ }
133
+ /**
134
+ * `map` with the mode territories its stored copy carries, where it has none of its own, and that copy's
135
+ * `storedAt`; `undefined` when nothing is carried. A mode whose stored ids are not all territories of
136
+ * `map` (its maker edited it since) is not carried: it reads as not read yet, so war.app is asked again
137
+ * and the fresh reply's ids are checked (and any the map lacks dropped with a warning) as on a first read.
138
+ */
139
+ async #withStoredModes(map, dir) {
140
+ const stored = await readStoredMapEntry(dir, map.id);
141
+ if (!stored || stored.storedAt === undefined)
142
+ return undefined;
143
+ const land = new Set(map.territories.map((t) => t.id));
144
+ const byMode = new Map(stored.map.distributionModes
145
+ .filter((d) => Array.isArray(d.territories) && d.territories.length > 0 && d.territories.every((id) => land.has(id)))
146
+ .map((d) => [d.id, d.territories]));
147
+ let any = false;
148
+ const distributionModes = map.distributionModes.map((d) => {
149
+ if (d.territories !== undefined || !byMode.has(d.id))
150
+ return d;
151
+ any = true;
152
+ return { ...d, territories: byMode.get(d.id) };
153
+ });
154
+ return any ? { map: { ...map, distributionModes }, storedAt: stored.storedAt } : undefined;
155
+ }
156
+ /**
157
+ * Lay the territories read for `mapId`'s modes (#328, by mode id) on the cached base map (a new object:
158
+ * the graph cache is keyed by map object) and keep them under `dir`. Nothing when the map is not cached.
159
+ */
160
+ async setModeTerritories(mapId, given, dir) {
161
+ const base = this.#maps.get(mapId);
162
+ if (!base)
163
+ return;
164
+ // An empty list is no knowledge (unknown is never `[]`): it is neither laid on the map nor kept.
165
+ const byMode = new Map([...given].filter(([, ids]) => ids.length > 0));
166
+ if (!byMode.size)
167
+ return;
168
+ this.set({
169
+ ...base,
170
+ distributionModes: base.distributionModes.map((d) => (byMode.has(d.id) ? { ...d, territories: [...byMode.get(d.id)] } : d)),
171
+ });
172
+ if (dir !== undefined)
173
+ await writeStoredModeTerritories(dir, mapId, byMode);
174
+ }
175
+ /** Whether war.app's map details were already asked for `mapId` this process (#328: once per map, never in a loop). */
176
+ mapDetailsTried(mapId) {
177
+ return this.#detailsTried.has(mapId);
178
+ }
179
+ markMapDetailsTried(mapId) {
180
+ this.#detailsTried.add(mapId);
125
181
  }
126
182
  /** Whether `mapId` was already downloaded again this process because the feed named land it lacked. */
127
183
  wasRefreshed(mapId) {
@@ -141,6 +197,7 @@ export class MapCache {
141
197
  this.#maps.clear();
142
198
  this.#gameMaps.clear();
143
199
  this.#refreshed.clear();
200
+ this.#detailsTried.clear();
144
201
  }
145
202
  }
146
203
  /** Whether the game's standing names a territory `map` does not have. */
@@ -158,16 +215,18 @@ export class WarappClient {
158
215
  #cache;
159
216
  #dataDir;
160
217
  #api;
218
+ /** The same client with no retry, for a request that must go out at most once (`noRetry`). */
219
+ #apiOnce;
161
220
  #secrets = [];
162
221
  constructor(opts = {}) {
163
222
  this.#env = opts.env;
164
223
  this.#cache = opts.mapCache ?? defaultMapCache;
165
224
  this.#dataDir = opts.dataDir;
166
- this.#api = createApiClient({
225
+ const build = (count) => createApiClient({
167
226
  baseUrl: BASE_URL,
168
227
  serviceName: SERVICE,
169
228
  baseHeaders: { accept: 'application/json' },
170
- retry: { count: 1, delayMs: 2000, statuses: [429, 500, 502, 503, 504], honorRetryAfter: true },
229
+ retry: { count, delayMs: 2000, statuses: [429, 500, 502, 503, 504], honorRetryAfter: true },
171
230
  redirect: 'same-origin',
172
231
  ...(opts.timeoutMs !== undefined ? { timeout: opts.timeoutMs } : {}),
173
232
  ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),
@@ -179,6 +238,8 @@ export class WarappClient {
179
238
  }),
180
239
  onErrorResponse: ({ status, body }) => new McpToolError(`war.app GameFeed answered HTTP ${status}${body.trim() ? `: ${this.#redact(body)}` : ''}`, { kind: 'http', status }),
181
240
  });
241
+ this.#api = build(1);
242
+ this.#apiOnce = build(0);
182
243
  }
183
244
  #redact(text) {
184
245
  // Scrub by value before the shape redactor and the cut (as `values` would),
@@ -214,7 +275,8 @@ export class WarappClient {
214
275
  path += '&GetChat=true';
215
276
  if (flags.noMap)
216
277
  path += '&GetMap=false';
217
- const body = await this.#api.fetchJson('POST', path, {
278
+ const api = flags.noRetry ? this.#apiOnce : this.#api;
279
+ const body = await api.fetchJson('POST', path, {
218
280
  rawBody: new URLSearchParams({ Email: email, APIToken: token }).toString(),
219
281
  contentType: 'application/x-www-form-urlencoded',
220
282
  // A read sent as POST: safe to repeat.
@@ -265,6 +327,8 @@ export class WarappClient {
265
327
  const fresh = normalizeMap(rawMap);
266
328
  map = replace ? fresh : (this.#cache.get(fresh.id) ?? fresh);
267
329
  await this.#cache.store(map, dir, replace);
330
+ // The cache may hold it with what the store kept for it (#328: its modes' territories).
331
+ map = this.#cache.get(map.id) ?? map;
268
332
  }
269
333
  if (!map && game.settings?.mapId !== undefined)
270
334
  map = await this.#cache.load(game.settings.mapId, dir);
@@ -276,8 +340,22 @@ export class WarappClient {
276
340
  await this.#cache.storeGame(gameId, map.id, index ? dir : undefined);
277
341
  game.map = map;
278
342
  }
343
+ // #302: what came instead of a history that does not read, by key name only.
344
+ if (opts.history)
345
+ game.feedKeys = safeKeys(Object.keys(body));
279
346
  return game;
280
347
  }
348
+ /** Keep the territories read for a map's distribution modes (#328) on the cached map and in the store. */
349
+ async keepModeTerritories(mapId, byMode) {
350
+ await this.#cache.setModeTerritories(mapId, byMode, this.#dir());
351
+ }
352
+ /** Whether war.app's map details were already asked for `mapId` this process (#328). */
353
+ mapDetailsTried(mapId) {
354
+ return this.#cache.mapDetailsTried(mapId);
355
+ }
356
+ markMapDetailsTried(mapId) {
357
+ this.#cache.markMapDetailsTried(mapId);
358
+ }
281
359
  /** The data directory for the map store, or `undefined` (memory only); never throws. */
282
360
  #dir() {
283
361
  try {
@@ -13,8 +13,10 @@
13
13
  // returns it, never logs it, never puts it in an error: it returns only when
14
14
  // the capture happened ({@link LinkResult} is `capturedAt` + `host`). Every
15
15
  // cookie but `AuthToken` is discarded. A capture that yields no AuthToken
16
- // throws {@link NoAuthTokenError} and stores nothing. Direct mode is
17
- // LOCAL-ONLY — the hosted path keeps the browser bridge and stores no token.
16
+ // throws {@link NoAuthTokenError} and stores nothing. Linking is LOCAL-ONLY: a
17
+ // hosted child rides the direct transport only from the session captured at
18
+ // sign-in (mcp-host's authFlow, WARAPP_AUTH_TOKEN, held in memory: #333,
19
+ // src/direct/session.ts) and never links or stores one.
18
20
  import { McpToolError, readPortEnv } from '@chrischall/mcp-utils';
19
21
  import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
20
22
  import { isHosted } from '../hosted.js';
@@ -77,10 +79,12 @@ function captureWarappCookie(opts) {
77
79
  * when the captured cookie carries no `AuthToken`.
78
80
  */
79
81
  export async function linkSession(opts = {}) {
80
- // Local-only: a hosted child never pulls the full-account cookie into memory
81
- // (the tool is not registered there, and writeSession refuses too).
82
+ // Local-only: a hosted child never pulls the cookie off a tab; it reaches war.app
83
+ // directly only from the session captured at sign-in (the tool is not
84
+ // registered there, and writeSession refuses too).
82
85
  if (isHosted(opts.env ?? process.env)) {
83
- throw new McpToolError('The direct transport is local-only: a hosted server never links a war.app session.', {
86
+ throw new McpToolError('Linking a war.app session is local-only: a hosted server reaches war.app directly only from the session ' +
87
+ 'captured at sign-in, and never links one.', {
84
88
  kind: 'unknown',
85
89
  });
86
90
  }
@@ -20,8 +20,12 @@
20
20
  // import time, the server boots without a session, and a missing OR corrupt
21
21
  // file reads as `null` — never a throw.
22
22
  //
23
- // LOCAL-ONLY: on a hosted child (src/hosted.ts) the store reads as empty — a
24
- // session file already in the data dir is never read — and refuses to write.
23
+ // Hosted (src/hosted.ts) the FILE is never read or written: a session file
24
+ // already in the data dir is ignored and {@link writeSession} refuses. The one
25
+ // session a hosted child has is the AuthToken mcp-host captured at sign-in and
26
+ // injects as {@link HOST_TOKEN_ENV} (#333): {@link hostedSession} reads it into
27
+ // memory, read-only, never stored. Without it the store reads as empty, as
28
+ // before. Locally the variable is ignored: only the session file counts.
25
29
  import { execFile } from 'node:child_process';
26
30
  import { randomBytes } from 'node:crypto';
27
31
  import { readFileSync } from 'node:fs';
@@ -35,6 +39,55 @@ import { isHosted } from '../hosted.js';
35
39
  import { scrubSecrets } from '../redact.js';
36
40
  /** The only host a session is ever stored for. */
37
41
  export const SESSION_HOST = 'war.app';
42
+ /**
43
+ * The env var mcp-host's sign-in flow captures war.app's AuthToken into on a
44
+ * hosted child (an `authFlow` `capture`, stored as a per-user secret). Hosted
45
+ * only; a local process ignores it.
46
+ */
47
+ export const HOST_TOKEN_ENV = 'WARAPP_AUTH_TOKEN';
48
+ /** The `capturedAt` of the host's session: the time is not known to this process. */
49
+ export const HOST_CAPTURED_AT = 'captured by the host';
50
+ /** Loose bounds on a captured AuthToken: a cookie value, nothing a header could split on. */
51
+ const HOST_TOKEN_SHAPE = /^[\x21-\x7e]{16,4096}$/;
52
+ const HOST_TOKEN_FORBIDDEN = /[;,"\\]/;
53
+ /** The env value as a bare cookie value: trimmed, a leading `AuthToken=` dropped. */
54
+ function hostTokenValue(env) {
55
+ const raw = readEnvVar(HOST_TOKEN_ENV, { env });
56
+ if (raw === undefined)
57
+ return undefined;
58
+ return raw.trim().replace(/^AuthToken=/, '');
59
+ }
60
+ /**
61
+ * Whether a hosted child has a usable host-captured token: `none` (not hosted,
62
+ * or the variable unset), `ok`, or `malformed` (set, but not a plausible cookie
63
+ * value — treated as absent, and never echoed).
64
+ */
65
+ export function hostedTokenState(env = process.env) {
66
+ if (!isHosted(env))
67
+ return 'none';
68
+ const v = hostTokenValue(env);
69
+ if (v === undefined)
70
+ return 'none';
71
+ return isPlausibleAuthToken(v) ? 'ok' : 'malformed';
72
+ }
73
+ /**
74
+ * Whether `v` is a plausible bare AuthToken cookie value (the loose bounds the
75
+ * hosted child accepts in {@link HOST_TOKEN_ENV}). warapp_sign_in returns only a
76
+ * token that passes, so a capture never stores one the child would ignore.
77
+ */
78
+ export function isPlausibleAuthToken(v) {
79
+ return HOST_TOKEN_SHAPE.test(v) && !HOST_TOKEN_FORBIDDEN.test(v);
80
+ }
81
+ /**
82
+ * The hosted child's session: the AuthToken mcp-host captured at sign-in
83
+ * ({@link HOST_TOKEN_ENV}), in memory and read-only, or `null` when not hosted,
84
+ * unset or malformed. Never throws, never stores anything.
85
+ */
86
+ export function hostedSession(env = process.env) {
87
+ if (hostedTokenState(env) !== 'ok')
88
+ return null;
89
+ return { authToken: hostTokenValue(env), capturedAt: HOST_CAPTURED_AT, host: SESSION_HOST, origin: 'host' };
90
+ }
38
91
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
39
92
  /**
40
93
  * Where the session is stored: `WARAPP_SESSION_FILE` if set, else
@@ -60,11 +113,12 @@ function parseSession(raw) {
60
113
  }
61
114
  /**
62
115
  * The linked session, or `null` when none is linked or the file is missing or
63
- * unusable (wrong shape, wrong host, not JSON). Never throws.
116
+ * unusable (wrong shape, wrong host, not JSON). Hosted: {@link hostedSession},
117
+ * never the file. Never throws.
64
118
  */
65
119
  export async function readSession(env = process.env) {
66
120
  if (isHosted(env))
67
- return null;
121
+ return hostedSession(env);
68
122
  try {
69
123
  return parseSession(JSON.parse(await readFile(sessionFilePath(env), 'utf8')));
70
124
  }
@@ -80,7 +134,7 @@ export async function readSession(env = process.env) {
80
134
  */
81
135
  export function readSessionSync(env = process.env) {
82
136
  if (isHosted(env))
83
- return null;
137
+ return hostedSession(env);
84
138
  try {
85
139
  return parseSession(JSON.parse(readFileSync(sessionFilePath(env), 'utf8')));
86
140
  }
@@ -156,7 +210,7 @@ export function sessionTmpPath(path) {
156
210
  */
157
211
  export async function writeSession(session, env = process.env) {
158
212
  if (isHosted(env)) {
159
- throw new McpToolError('The direct transport is local-only: a hosted server never stores a war.app session.', {
213
+ throw new McpToolError('A hosted server never stores a war.app session: its session is the one mcp-host captured at sign-in.', {
160
214
  kind: 'unknown',
161
215
  });
162
216
  }