@chrischall/warapp-mcp 0.2.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.
package/dist/bundle.js CHANGED
@@ -50509,7 +50509,7 @@ var require_parse3 = __commonJS({
50509
50509
  var { maxNameValuePairSize, maxAttributeValueSize } = require_constants5();
50510
50510
  var { isCTLExcludingHtab } = require_util6();
50511
50511
  var assert2 = __require("node:assert");
50512
- function parseSetCookie(header) {
50512
+ function parseSetCookie2(header) {
50513
50513
  if (isCTLExcludingHtab(header)) {
50514
50514
  return null;
50515
50515
  }
@@ -50632,7 +50632,7 @@ var require_parse3 = __commonJS({
50632
50632
  }
50633
50633
  }
50634
50634
  module.exports = {
50635
- parseSetCookie,
50635
+ parseSetCookie: parseSetCookie2,
50636
50636
  parseUnparsedAttributes
50637
50637
  };
50638
50638
  }
@@ -50642,7 +50642,7 @@ var require_parse3 = __commonJS({
50642
50642
  var require_cookies = __commonJS({
50643
50643
  "node_modules/undici/lib/web/cookies/index.js"(exports, module) {
50644
50644
  "use strict";
50645
- var { parseSetCookie } = require_parse3();
50645
+ var { parseSetCookie: parseSetCookie2 } = require_parse3();
50646
50646
  var { stringify } = require_util6();
50647
50647
  var { webidl } = require_webidl();
50648
50648
  var { Headers: Headers3 } = require_headers();
@@ -50681,11 +50681,11 @@ var require_cookies = __commonJS({
50681
50681
  if (!cookies) {
50682
50682
  return [];
50683
50683
  }
50684
- return cookies.map((pair2) => parseSetCookie(pair2));
50684
+ return cookies.map((pair2) => parseSetCookie2(pair2));
50685
50685
  }
50686
50686
  function parseCookie(cookie) {
50687
50687
  cookie = webidl.converters.DOMString(cookie);
50688
- return parseSetCookie(cookie);
50688
+ return parseSetCookie2(cookie);
50689
50689
  }
50690
50690
  function setCookie(headers, cookie) {
50691
50691
  webidl.argumentLengthCheck(arguments, 2, "setCookie");
@@ -69811,8 +69811,8 @@ function truncateErrorMessage(text, max = DEFAULT_ERROR_MESSAGE_MAX, opts = {})
69811
69811
  const str = text === null || text === void 0 ? "" : String(text);
69812
69812
  const cap = Math.max(ERROR_REDACTION_INPUT_MAX, max);
69813
69813
  const capped = str.length > cap ? str.slice(0, cap) : str;
69814
- const scrubbed = opts.values !== void 0 ? redactValues(capped, opts.values, opts.placeholder !== void 0 ? { placeholder: opts.placeholder } : {}) : capped;
69815
- const redacted = redactSecrets(scrubbed);
69814
+ const scrubbed2 = opts.values !== void 0 ? redactValues(capped, opts.values, opts.placeholder !== void 0 ? { placeholder: opts.placeholder } : {}) : capped;
69815
+ const redacted = redactSecrets(scrubbed2);
69816
69816
  if (redacted.length <= max)
69817
69817
  return redacted;
69818
69818
  return `${redacted.slice(0, max)}\u2026 [truncated]`;
@@ -91148,9 +91148,9 @@ function detectEdgeBlock(input2) {
91148
91148
  const body = input2.body?.slice(0, EDGE_BLOCK_SCAN_MAX);
91149
91149
  if (!body)
91150
91150
  return null;
91151
- const refusal2 = input2.status === void 0 || input2.status >= 400 && input2.status < 500;
91151
+ const refusal3 = input2.status === void 0 || input2.status >= 400 && input2.status < 500;
91152
91152
  for (const marker of EDGE_BLOCK_MARKERS) {
91153
- if ((marker.anyStatus || refusal2) && marker.test(body))
91153
+ if ((marker.anyStatus || refusal3) && marker.test(body))
91154
91154
  return { vendor: marker.vendor };
91155
91155
  }
91156
91156
  return null;
@@ -120915,7 +120915,7 @@ async function startHost(opts) {
120915
120915
  }
120916
120916
  if (frame.type === "hello-rejected" && identified === "extension") {
120917
120917
  if (frame.mcpId === opts.ownMcpId) {
120918
- const refusal2 = new FetchproxyHelloRejectedError({
120918
+ const refusal3 = new FetchproxyHelloRejectedError({
120919
120919
  mcpId: frame.mcpId,
120920
120920
  reason: frame.reason,
120921
120921
  platform: extensionHello?.platform ?? null
@@ -120923,8 +120923,8 @@ async function startHost(opts) {
120923
120923
  if (ownRetryableRefusal)
120924
120924
  resetSessionPromise();
120925
120925
  const settlesPending = !ownSessionSettled;
120926
- rejectOwnSession(refusal2);
120927
- if (refusal2.retryable && settlesPending)
120926
+ rejectOwnSession(refusal3);
120927
+ if (refusal3.retryable && settlesPending)
120928
120928
  ownRetryableRefusal = true;
120929
120929
  } else {
120930
120930
  const slot = peers.get(frame.mcpId);
@@ -121315,7 +121315,7 @@ async function startPeer(opts) {
121315
121315
  return;
121316
121316
  }
121317
121317
  if (frame.type === "hello-rejected" && frame.mcpId === opts.mcpId) {
121318
- const refusal2 = new FetchproxyHelloRejectedError({
121318
+ const refusal3 = new FetchproxyHelloRejectedError({
121319
121319
  mcpId: frame.mcpId,
121320
121320
  reason: frame.reason,
121321
121321
  platform: extensionHello?.platform ?? null
@@ -121323,8 +121323,8 @@ async function startPeer(opts) {
121323
121323
  if (retryableRefusal)
121324
121324
  resetSessionPromise();
121325
121325
  const settlesPending = !sessionPromiseSettled;
121326
- rejectFirstReady(refusal2);
121327
- if (refusal2.retryable && settlesPending)
121326
+ rejectFirstReady(refusal3);
121327
+ if (refusal3.retryable && settlesPending)
121328
121328
  retryableRefusal = true;
121329
121329
  }
121330
121330
  if (frame.type === "pair-pending" && frame.mcpId === opts.mcpId) {
@@ -124776,7 +124776,7 @@ async function captureBearerHeader(opts) {
124776
124776
  }
124777
124777
 
124778
124778
  // src/version.ts
124779
- var VERSION2 = "0.2.0";
124779
+ var VERSION2 = "0.3.0";
124780
124780
 
124781
124781
  // src/transport-bridge.ts
124782
124782
  var SERVER_NAME = "warapp-mcp";
@@ -124799,6 +124799,165 @@ function createWarappBridge(opts = {}) {
124799
124799
  return createLazyTransport(() => createBridgeTransport(opts));
124800
124800
  }
124801
124801
 
124802
+ // src/direct/session.ts
124803
+ import { execFile } from "node:child_process";
124804
+ import { randomBytes as randomBytes7 } from "node:crypto";
124805
+ import { readFileSync as readFileSync2 } from "node:fs";
124806
+ import { chmod as chmod4, mkdir as mkdir7, open as open2, readFile as readFile8, rename as rename7, rm as rm4, stat as stat4 } from "node:fs/promises";
124807
+ import { dirname, join as join11, resolve } from "node:path";
124808
+ import { promisify } from "node:util";
124809
+ var SESSION_HOST = "war.app";
124810
+ var HOST_TOKEN_ENV = "WARAPP_AUTH_TOKEN";
124811
+ var HOST_CAPTURED_AT = "captured by the host";
124812
+ var HOST_TOKEN_SHAPE = /^[\x21-\x7e]{16,4096}$/;
124813
+ var HOST_TOKEN_FORBIDDEN = /[;,"\\]/;
124814
+ function hostTokenValue(env) {
124815
+ const raw = readEnvVar(HOST_TOKEN_ENV, { env });
124816
+ if (raw === void 0) return void 0;
124817
+ return raw.trim().replace(/^AuthToken=/, "");
124818
+ }
124819
+ function hostedTokenState(env = process.env) {
124820
+ if (!isHosted(env)) return "none";
124821
+ const v = hostTokenValue(env);
124822
+ if (v === void 0) return "none";
124823
+ return isPlausibleAuthToken(v) ? "ok" : "malformed";
124824
+ }
124825
+ function isPlausibleAuthToken(v) {
124826
+ return HOST_TOKEN_SHAPE.test(v) && !HOST_TOKEN_FORBIDDEN.test(v);
124827
+ }
124828
+ function hostedSession(env = process.env) {
124829
+ if (hostedTokenState(env) !== "ok") return null;
124830
+ return { authToken: hostTokenValue(env), capturedAt: HOST_CAPTURED_AT, host: SESSION_HOST, origin: "host" };
124831
+ }
124832
+ var isRec6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
124833
+ function sessionFilePath(env = process.env) {
124834
+ return readEnvVar("WARAPP_SESSION_FILE", { env }) ?? join11(dataDir(env), "session.json");
124835
+ }
124836
+ function parseSession(raw) {
124837
+ if (!isRec6(raw)) return null;
124838
+ const { authToken, capturedAt, host } = raw;
124839
+ if (typeof authToken !== "string" || authToken.length === 0) return null;
124840
+ if (typeof capturedAt !== "string" || capturedAt.length === 0) return null;
124841
+ if (host !== SESSION_HOST) return null;
124842
+ return { authToken, capturedAt, host };
124843
+ }
124844
+ async function readSession(env = process.env) {
124845
+ if (isHosted(env)) return hostedSession(env);
124846
+ try {
124847
+ return parseSession(JSON.parse(await readFile8(sessionFilePath(env), "utf8")));
124848
+ } catch {
124849
+ return null;
124850
+ }
124851
+ }
124852
+ function readSessionSync(env = process.env) {
124853
+ if (isHosted(env)) return hostedSession(env);
124854
+ try {
124855
+ return parseSession(JSON.parse(readFileSync2(sessionFilePath(env), "utf8")));
124856
+ } catch {
124857
+ return null;
124858
+ }
124859
+ }
124860
+ function sessionDirVerdict(st, myUid) {
124861
+ if (myUid === void 0) return "ok";
124862
+ if (st.uid === myUid) return (st.mode & 63) !== 0 ? "tighten" : "ok";
124863
+ if (st.uid !== 0) return "refuse";
124864
+ return (st.mode & 18) !== 0 ? "refuse" : "ok";
124865
+ }
124866
+ var run = promisify(execFile);
124867
+ var MACOS_ACLS = process.platform === "darwin";
124868
+ function lsShowsAcl(stdout) {
124869
+ return stdout.split("\n").slice(1).some((line) => /^\s*\d+: /.test(line));
124870
+ }
124871
+ async function hasAcl(path) {
124872
+ const { stdout } = await run("/bin/ls", ["-led", path]);
124873
+ return lsShowsAcl(stdout);
124874
+ }
124875
+ async function stripAcl(path, what) {
124876
+ await run("/bin/chmod", ["-N", path]);
124877
+ if (await hasAcl(path)) {
124878
+ throw new McpToolError(`Refusing to store the war.app session: could not remove the access control list on ${what}.`, {
124879
+ hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory only you can read, with no ACL (`ls -le`)."
124880
+ });
124881
+ }
124882
+ }
124883
+ function sessionTmpPath(path) {
124884
+ return `${path}.${randomBytes7(16).toString("hex")}.tmp`;
124885
+ }
124886
+ async function writeSession(session, env = process.env) {
124887
+ if (isHosted(env)) {
124888
+ throw new McpToolError(
124889
+ "A hosted server never stores a war.app session: its session is the one mcp-host captured at sign-in.",
124890
+ {
124891
+ kind: "unknown"
124892
+ }
124893
+ );
124894
+ }
124895
+ const path = resolve(sessionFilePath(env));
124896
+ const dir = dirname(path);
124897
+ await mkdir7(dir, { recursive: true, mode: 448 });
124898
+ const st = await stat4(dir);
124899
+ const myUid = process.getuid?.();
124900
+ const verdict = sessionDirVerdict(st, myUid);
124901
+ if (verdict === "refuse") {
124902
+ throw new McpToolError(`Refusing to store the war.app session in ${dir}: it is not yours, and others could reach files in it.`, {
124903
+ hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can write to."
124904
+ });
124905
+ }
124906
+ if (verdict === "tighten") await chmod4(dir, 448);
124907
+ if (MACOS_ACLS) {
124908
+ if (st.uid === myUid) await stripAcl(dir, dir);
124909
+ else if (await hasAcl(dir)) {
124910
+ throw new McpToolError(`Refusing to store the war.app session in ${dir}: it carries an access control list and is not yours.`, {
124911
+ hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can read."
124912
+ });
124913
+ }
124914
+ }
124915
+ const tmp = sessionTmpPath(path);
124916
+ const file2 = await open2(tmp, "wx", 384);
124917
+ try {
124918
+ try {
124919
+ await file2.chmod(384);
124920
+ if (MACOS_ACLS) await stripAcl(tmp, "the session file");
124921
+ await file2.writeFile(JSON.stringify(session));
124922
+ } finally {
124923
+ await file2.close();
124924
+ }
124925
+ await rename7(tmp, path);
124926
+ } catch (e) {
124927
+ await rm4(tmp, { force: true }).catch(() => {
124928
+ });
124929
+ throw e;
124930
+ }
124931
+ }
124932
+ var SCRUBBED = "[warapp-session]";
124933
+ function scrubToken(s, token) {
124934
+ if (!token) return s;
124935
+ return scrubSecrets(s, [token, stripBearer(token)], SCRUBBED);
124936
+ }
124937
+ function errorStrings(err, depth = 0) {
124938
+ if (depth > 4 || typeof err !== "object" || err === null) return typeof err === "string" ? [err] : [];
124939
+ const e = err;
124940
+ const own2 = [e.message, e.hint, e.stack].filter((v) => typeof v === "string");
124941
+ return [...own2, ...errorStrings(e.cause, depth + 1)];
124942
+ }
124943
+ function errorCarriesToken(err, tokens) {
124944
+ const strings = errorStrings(err);
124945
+ return tokens.some((t) => !!t && strings.some((s) => scrubToken(s, t) !== s));
124946
+ }
124947
+ function scrubError(err, tokens) {
124948
+ if (!errorCarriesToken(err, tokens)) return err;
124949
+ const ordered = tokens.filter((t) => !!t).sort((a, b) => b.length - a.length);
124950
+ const scrub = (s) => ordered.reduce((acc, t) => scrubToken(acc, t), s);
124951
+ const e = typeof err === "object" && err !== null ? err : {};
124952
+ const message = scrub(typeof e.message === "string" ? e.message : String(err));
124953
+ const kind = err instanceof McpToolError && err.kind ? err.kind : "transport";
124954
+ return new McpToolError(message, {
124955
+ kind,
124956
+ ...typeof e.status === "number" ? { status: e.status } : {},
124957
+ ...typeof e.hint === "string" ? { hint: scrub(e.hint) } : {}
124958
+ });
124959
+ }
124960
+
124802
124961
  // src/tools/live-context.ts
124803
124962
  function parseInviteTokenText(html) {
124804
124963
  const m = /Your invite token is\s*(\d{5,20})/.exec(html);
@@ -124952,6 +125111,7 @@ function createLiveContext(opts) {
124952
125111
  fetchPage: fetchText,
124953
125112
  dataDir: dir,
124954
125113
  hosted: isHosted(opts.env ?? process.env),
125114
+ hostSignIn: hostedSession(opts.env ?? process.env) !== null,
124955
125115
  client: opts.client,
124956
125116
  rpc,
124957
125117
  decoderReport: () => lastBundle?.report?.(),
@@ -125034,6 +125194,424 @@ async function loadPicks(ctx, gameId, inGamePlayerId) {
125034
125194
  return readTerritoryPicks(env.body);
125035
125195
  }
125036
125196
 
125197
+ // node_modules/@chrischall/mcp-utils/dist/netguard/index.js
125198
+ var import_undici = __toESM(require_undici(), 1);
125199
+ import { lookup as dnsLookup } from "node:dns/promises";
125200
+ import { isIP as isIP2 } from "node:net";
125201
+ var systemResolver = async (hostname3) => (await dnsLookup(hostname3, { all: true, verbatim: true })).map((a) => a.address);
125202
+ function refuseHost(hostname3) {
125203
+ return new UrlNotAllowedError(`Refusing to connect to ${hostname3}: it is, or resolves to, a private, loopback, link-local or reserved address.`, "host");
125204
+ }
125205
+ function createPublicOnlyDispatcher(opts = {}) {
125206
+ const resolve2 = opts.resolve ?? systemResolver;
125207
+ const allowed = opts.isAllowedAddress ?? isPublicAddress;
125208
+ const lookup = (hostname3, options, callback2) => {
125209
+ resolve2(hostname3).then((addresses) => {
125210
+ if (addresses.length === 0 || !addresses.every(allowed)) {
125211
+ callback2(refuseHost(hostname3), "", 0);
125212
+ return;
125213
+ }
125214
+ const entries2 = addresses.map((address) => ({ address, family: isIP2(address) }));
125215
+ if (options.all) {
125216
+ callback2(null, entries2);
125217
+ return;
125218
+ }
125219
+ const wanted = options.family === 4 || options.family === 6 ? options.family : 0;
125220
+ const pick5 = entries2.find((e) => wanted === 0 || e.family === wanted) ?? entries2[0];
125221
+ callback2(null, pick5.address, pick5.family);
125222
+ }, (err) => callback2(err, "", 0));
125223
+ };
125224
+ const inner = (0, import_undici.buildConnector)({ ...opts.connect, lookup });
125225
+ const connect = (options, callback2) => {
125226
+ const host = options.hostname.replace(/^\[|\]$/g, "");
125227
+ if (isIP2(host) !== 0 && !allowed(host)) {
125228
+ callback2(refuseHost(options.hostname), null);
125229
+ return;
125230
+ }
125231
+ inner(options, callback2);
125232
+ };
125233
+ return new import_undici.Agent({ ...opts.agent, connect });
125234
+ }
125235
+ var REDIRECT_STATUSES2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
125236
+ var CROSS_ORIGIN_DROPPED = ["authorization", "cookie", "proxy-authorization"];
125237
+ function findUrlRefusal(err) {
125238
+ let e = err;
125239
+ for (let i2 = 0; i2 < 8 && e; i2 += 1) {
125240
+ if (e instanceof UrlNotAllowedError)
125241
+ return e;
125242
+ e = e.cause;
125243
+ }
125244
+ return void 0;
125245
+ }
125246
+ async function fetchPublic(url4, opts = {}) {
125247
+ const { maxRedirects = 10, timeoutMs, maxBytes, signal: callerSignal, dispatcher: given2, requireHttps, allowHosts, stopBefore, resolve: resolve2, isAllowedAddress, headers: initHeaders, method: initMethod, body: initBody, ...init } = opts;
125248
+ if (!Number.isInteger(maxRedirects) || maxRedirects < 0) {
125249
+ throw new TypeError("fetchPublic: maxRedirects must be a non-negative integer.");
125250
+ }
125251
+ const check2 = (target) => assertAllowedUrl(target, {
125252
+ allowHosts: allowHosts ?? [/(?:)/],
125253
+ ...requireHttps !== void 0 ? { requireHttps } : {}
125254
+ });
125255
+ let current2 = check2(url4);
125256
+ const origin = current2.origin;
125257
+ if (stopBefore?.(current2))
125258
+ return { stopped: true, url: current2.href, hops: 0 };
125259
+ const timeout = timeoutMs !== void 0 ? AbortSignal.timeout(timeoutMs) : void 0;
125260
+ const signals = [callerSignal, timeout].filter((s) => s !== void 0);
125261
+ const signal = signals.length > 0 ? AbortSignal.any(signals) : void 0;
125262
+ const owned = given2 === void 0 ? createPublicOnlyDispatcher({
125263
+ ...resolve2 ? { resolve: resolve2 } : {},
125264
+ ...isAllowedAddress ? { isAllowedAddress } : {}
125265
+ }) : void 0;
125266
+ const dispatcher = given2 ?? owned;
125267
+ let method = (initMethod ?? "GET").toUpperCase();
125268
+ let body = initBody;
125269
+ const headers = new import_undici.Headers(initHeaders);
125270
+ const fail = (err) => {
125271
+ if (callerSignal?.aborted)
125272
+ throw callerSignal.reason;
125273
+ if (timeout?.aborted)
125274
+ throw new RequestTimeoutError(current2.host, timeoutMs);
125275
+ const refused = findUrlRefusal(err);
125276
+ if (refused)
125277
+ throw refused;
125278
+ if (err instanceof McpToolError)
125279
+ throw err;
125280
+ throw new McpToolError(`Could not reach ${current2.host}.`, {
125281
+ kind: "transport",
125282
+ hint: "Check the link is reachable from the server.",
125283
+ cause: err
125284
+ });
125285
+ };
125286
+ try {
125287
+ for (let hops = 0; ; ) {
125288
+ let res;
125289
+ try {
125290
+ res = await (0, import_undici.fetch)(current2, {
125291
+ ...init,
125292
+ method,
125293
+ headers,
125294
+ ...body !== void 0 && body !== null ? { body } : {},
125295
+ redirect: "manual",
125296
+ dispatcher,
125297
+ ...signal ? { signal } : {}
125298
+ });
125299
+ } catch (err) {
125300
+ return fail(err);
125301
+ }
125302
+ const location = REDIRECT_STATUSES2.has(res.status) ? res.headers.get("location") : null;
125303
+ if (location === null) {
125304
+ let bytes;
125305
+ try {
125306
+ bytes = await readBytesCapped(res, maxBytes, current2.host, (p) => p);
125307
+ } catch (err) {
125308
+ return fail(err);
125309
+ }
125310
+ return { stopped: false, url: current2.href, hops, status: res.status, headers: res.headers, body: bytes };
125311
+ }
125312
+ await res.body?.cancel().catch(() => {
125313
+ });
125314
+ if (hops >= maxRedirects) {
125315
+ throw new RedirectRefusedError(`Refusing to follow more than ${maxRedirects} redirects (last from ${current2.host}).`);
125316
+ }
125317
+ let next;
125318
+ try {
125319
+ next = new URL(location, current2);
125320
+ } catch {
125321
+ throw new UrlNotAllowedError("The redirect target is not a valid URL.", "invalid");
125322
+ }
125323
+ next = check2(next);
125324
+ hops += 1;
125325
+ if (res.status === 303 || (res.status === 301 || res.status === 302) && method === "POST") {
125326
+ if (method !== "HEAD")
125327
+ method = "GET";
125328
+ body = void 0;
125329
+ for (const h of ["content-type", "content-length", "content-encoding", "content-language", "content-location"]) {
125330
+ headers.delete(h);
125331
+ }
125332
+ }
125333
+ if (next.origin !== origin)
125334
+ for (const h of CROSS_ORIGIN_DROPPED)
125335
+ headers.delete(h);
125336
+ current2 = next;
125337
+ if (stopBefore?.(current2))
125338
+ return { stopped: true, url: current2.href, hops };
125339
+ }
125340
+ } finally {
125341
+ if (owned)
125342
+ await owned.destroy().catch(() => {
125343
+ });
125344
+ }
125345
+ }
125346
+
125347
+ // src/direct/transport.ts
125348
+ var TRANSPORT_ENV = "WARAPP_TRANSPORT";
125349
+ var MAX_DIRECT_BODY_BYTES = 16 * 1024 * 1024;
125350
+ var DIRECT_TIMEOUT_MS = 3e4;
125351
+ var HOST_SIGN_IN_ADVICE = 'Use "Sign in" on this war.app connection, or reconnect it (mcp-host signs in to war.app again and captures a new session). Meanwhile, a war.app tab signed in and paired with the browser bridge works, since calls fall back to it.';
125352
+ var SessionNotLinkedError = class extends McpToolError {
125353
+ name = "SessionNotLinkedError";
125354
+ constructor(opts = {}) {
125355
+ super(
125356
+ opts.hostSignIn ? `This connection has no war.app session. ${HOST_SIGN_IN_ADVICE}` : "No war.app session is linked for the direct transport. Run warapp_link_session to capture one.",
125357
+ { kind: "no_credential" }
125358
+ );
125359
+ }
125360
+ };
125361
+ var SessionExpiredError = class extends McpToolError {
125362
+ name = "SessionExpiredError";
125363
+ /** When the expired session was captured (non-secret), so a relink can be told apart. */
125364
+ capturedAt;
125365
+ /** The session was the one mcp-host captured: the remedy is its Sign in, not warapp_link_session. */
125366
+ hostSignIn;
125367
+ constructor(opts = {}) {
125368
+ const remedy = opts.hostSignIn ? HOST_SIGN_IN_ADVICE : "Run warapp_link_session to relink.";
125369
+ super(
125370
+ (opts.hostSignIn ? "The war.app session this connection signed in with is no longer signed in. " : "The linked war.app session is no longer signed in. ") + (opts.notResent ? `The request had already reached war.app, so it was not re-sent over the browser bridge (a write must never be sent twice); later calls use the bridge. Retry, or: ${remedy}` : remedy),
125371
+ { kind: "session_expired" }
125372
+ );
125373
+ this.capturedAt = opts.capturedAt;
125374
+ this.hostSignIn = opts.hostSignIn ?? false;
125375
+ }
125376
+ };
125377
+ var decoder = new TextDecoder();
125378
+ var isSafeToReplay = (method) => /^(?:GET|HEAD)$/i.test(method);
125379
+ var SESSION_ORIGIN = `https://${SESSION_HOST}`;
125380
+ var MAX_DIRECT_GET_REDIRECTS = 5;
125381
+ var UNFOLLOWED_REDIRECT_STATUS = 302;
125382
+ function directFetchOptions(method) {
125383
+ const base = { requireHttps: true, allowHosts: [SESSION_HOST] };
125384
+ if (isSafeToReplay(method)) {
125385
+ return { ...base, maxRedirects: MAX_DIRECT_GET_REDIRECTS, stopBefore: (url4) => url4.origin !== SESSION_ORIGIN };
125386
+ }
125387
+ let first = true;
125388
+ return {
125389
+ ...base,
125390
+ maxRedirects: 1,
125391
+ stopBefore: () => {
125392
+ if (first) {
125393
+ first = false;
125394
+ return false;
125395
+ }
125396
+ return true;
125397
+ }
125398
+ };
125399
+ }
125400
+ function toDirectResult(res) {
125401
+ if ("stopped" in res && res.stopped) return { status: UNFOLLOWED_REDIRECT_STATUS, body: "", url: res.url };
125402
+ const done = res;
125403
+ const out = { status: done.status, body: decoder.decode(done.body), url: done.url };
125404
+ if (done.headers) {
125405
+ const headers = {};
125406
+ done.headers.forEach((v, k) => {
125407
+ headers[k.toLowerCase()] = v;
125408
+ });
125409
+ out.headers = headers;
125410
+ }
125411
+ return out;
125412
+ }
125413
+ var fetchViaPublic = async (url4, init) => {
125414
+ const res = await fetchPublic(url4, {
125415
+ ...directFetchOptions(init.method),
125416
+ method: init.method,
125417
+ headers: init.headers,
125418
+ maxBytes: MAX_DIRECT_BODY_BYTES,
125419
+ timeoutMs: DIRECT_TIMEOUT_MS,
125420
+ ...init.body !== void 0 ? { body: init.body } : {},
125421
+ ...init.signal ? { signal: init.signal } : {}
125422
+ });
125423
+ return toDirectResult(res);
125424
+ };
125425
+ function warappUrl(path) {
125426
+ const raw = /^https?:\/\//i.test(path) ? path : `https://${SESSION_HOST}${path.startsWith("/") ? "" : "/"}${path}`;
125427
+ let u;
125428
+ try {
125429
+ u = new URL(raw);
125430
+ } catch {
125431
+ throw new McpToolError(`The direct transport could not parse the request path.`, { kind: "unknown" });
125432
+ }
125433
+ if (u.hostname !== SESSION_HOST || u.port !== "" || u.username !== "" || u.password !== "") {
125434
+ throw new McpToolError(`The direct transport only talks to ${SESSION_HOST}.`, { kind: "unknown" });
125435
+ }
125436
+ if (u.protocol !== "https:") {
125437
+ throw new McpToolError("The direct transport requires https.", { kind: "unknown" });
125438
+ }
125439
+ return u.href;
125440
+ }
125441
+ var SIGNIN_PATH = /\/(?:sign-?in|log-?in)\b/i;
125442
+ var INPUT_TAG = /<input(?=[\s/>])/gi;
125443
+ var TAG_ATTR = /\s*(?:(>)|([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>`=]+)))?|\/)/y;
125444
+ var NOT_MARKUP = /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title)\b[^>]*(?:>|$)[\s\S]*?(?:<\/\1\s*>|$)/gi;
125445
+ function hasPasswordInput(raw) {
125446
+ const body = raw.replace(NOT_MARKUP, " ");
125447
+ INPUT_TAG.lastIndex = 0;
125448
+ for (let m = INPUT_TAG.exec(body); m; m = INPUT_TAG.exec(body)) {
125449
+ TAG_ATTR.lastIndex = INPUT_TAG.lastIndex;
125450
+ for (let a = TAG_ATTR.exec(body); a && !a[1]; a = TAG_ATTR.exec(body)) {
125451
+ const name = a[2]?.toLowerCase();
125452
+ const value = (a[3] ?? a[4] ?? a[5] ?? "").trim().toLowerCase();
125453
+ if ((name === "type" || name === "name") && value === "password") return true;
125454
+ }
125455
+ }
125456
+ return false;
125457
+ }
125458
+ function looksLikeHexFrame(body) {
125459
+ const t = body.trim();
125460
+ return t.length > 0 && t.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(t);
125461
+ }
125462
+ function looksSignedOut(requestedUrl, res) {
125463
+ let finalPath = "";
125464
+ try {
125465
+ finalPath = new URL(res.url).pathname;
125466
+ } catch {
125467
+ finalPath = "";
125468
+ }
125469
+ if (SIGNIN_PATH.test(finalPath)) return true;
125470
+ if (res.status === 401 || res.status === 403) return true;
125471
+ if (res.status !== 200) return false;
125472
+ if (hasPasswordInput(res.body)) return true;
125473
+ let reqPath = "";
125474
+ try {
125475
+ reqPath = new URL(requestedUrl).pathname;
125476
+ } catch {
125477
+ reqPath = "";
125478
+ }
125479
+ if (/\/services\b/i.test(reqPath) && !looksLikeHexFrame(res.body)) return true;
125480
+ return false;
125481
+ }
125482
+ var DirectBridge = class {
125483
+ constructor(store, fetchImpl = fetchViaPublic, hostSignIn = false) {
125484
+ this.store = store;
125485
+ this.fetchImpl = fetchImpl;
125486
+ this.hostSignIn = hostSignIn;
125487
+ }
125488
+ store;
125489
+ fetchImpl;
125490
+ hostSignIn;
125491
+ async fetch(init, signal) {
125492
+ const sess = await this.store.read();
125493
+ if (!sess) throw new SessionNotLinkedError(this.hostSignIn ? { hostSignIn: true } : {});
125494
+ const token = sess.authToken;
125495
+ const url4 = warappUrl(init.path);
125496
+ const headers = { ...init.headers ?? {}, cookie: `AuthToken=${token}` };
125497
+ let res;
125498
+ try {
125499
+ res = await this.fetchImpl(url4, {
125500
+ method: init.method,
125501
+ headers,
125502
+ ...init.body !== void 0 ? { body: init.body } : {},
125503
+ ...signal ? { signal } : {}
125504
+ });
125505
+ } catch (err) {
125506
+ throw scrubError(err, [token]);
125507
+ }
125508
+ const answered = res.status === 200 && looksLikeHexFrame(res.body);
125509
+ if (!answered && (res.status !== 200 || res.headers?.["cf-mitigated"])) {
125510
+ const edge = detectEdgeBlock({ body: res.body, ...res.headers ? { headers: res.headers } : {}, status: res.status });
125511
+ if (edge) {
125512
+ throw new EdgeBlockedError(res.status, edge.vendor, {
125513
+ service: SESSION_HOST,
125514
+ method: init.method,
125515
+ path: new URL(url4).pathname
125516
+ });
125517
+ }
125518
+ }
125519
+ if (looksSignedOut(url4, res)) {
125520
+ throw new SessionExpiredError({ capturedAt: sess.capturedAt, hostSignIn: this.hostSignIn || sess.origin === "host" });
125521
+ }
125522
+ return { status: res.status, body: res.body, url: res.url };
125523
+ }
125524
+ };
125525
+ var RELINK_CHECK_MS = 5e3;
125526
+ function createDirectFirstBridge(opts) {
125527
+ const env = opts.env ?? process.env;
125528
+ const hosted = isHosted(env);
125529
+ const hostSession = hosted ? hostedSession(env) : null;
125530
+ const pinned = hosted && !hostSession;
125531
+ const mode = pinned ? "fetchproxy" : opts.mode ?? readTransportMode(TRANSPORT_ENV, opts.env ? { env: opts.env } : {});
125532
+ const store = hosted ? { read: async () => hostSession } : opts.store;
125533
+ const hostSignIn = hostSession !== null;
125534
+ const direct = new DirectBridge(store, opts.directFetch, hostSignIn);
125535
+ const log = opts.log ?? ((m) => console.error(m));
125536
+ const now = opts.now ?? Date.now;
125537
+ let wall = null;
125538
+ let stale = false;
125539
+ let lastRelinkCheck = Number.NEGATIVE_INFINITY;
125540
+ const onFallback = ({ error: error62 }) => {
125541
+ const next = error62 instanceof SessionExpiredError ? { kind: "session", capturedAt: error62.capturedAt ?? null } : error62 instanceof SessionNotLinkedError ? { kind: "session", capturedAt: null } : { kind: "edge" };
125542
+ wall = next;
125543
+ const why = error62 instanceof SessionExpiredError ? "the linked war.app session is signed out" : error62 instanceof SessionNotLinkedError ? "no war.app session is linked" : "the site edge refused the direct request";
125544
+ log(
125545
+ `[warapp-mcp] Direct transport unavailable (${why}) \u2014 switching to the ContextMint Bridge browser bridge. Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` + (next.kind !== "session" ? "." : hostSignIn ? `. ${HOST_SIGN_IN_ADVICE}` : hosted ? "." : "; run warapp_link_session to return to the direct transport.")
125546
+ );
125547
+ };
125548
+ const build2 = () => createDirectFirstTransport({
125549
+ direct,
125550
+ bridge: opts.makeBridge,
125551
+ mode,
125552
+ serverName: "warapp-mcp",
125553
+ hostLabel: SESSION_HOST,
125554
+ shouldFallBack: (err) => err instanceof SessionExpiredError || err instanceof SessionNotLinkedError || err instanceof EdgeBlockedError,
125555
+ bridgeHealth: (b) => b.transport(),
125556
+ onFallback
125557
+ });
125558
+ let legs = build2();
125559
+ const liftSessionWall = () => {
125560
+ if (wall?.kind !== "session") return;
125561
+ wall = null;
125562
+ legs = build2();
125563
+ };
125564
+ const relinkedSinceWall = async () => {
125565
+ if (wall?.kind !== "session") return false;
125566
+ const t = now();
125567
+ if (t - lastRelinkCheck < RELINK_CHECK_MS) return false;
125568
+ lastRelinkCheck = t;
125569
+ const sess = await store.read();
125570
+ return sess !== null && sess.capturedAt !== wall.capturedAt;
125571
+ };
125572
+ const runOne = async (init) => {
125573
+ if (mode === "auto" && await relinkedSinceWall()) {
125574
+ liftSessionWall();
125575
+ stale = false;
125576
+ }
125577
+ let reached;
125578
+ return legs.run(async (leg, ctx) => {
125579
+ if (leg === direct) {
125580
+ try {
125581
+ const res = await direct.fetch(init, ctx.signal);
125582
+ if (res.status === 200) stale = false;
125583
+ return res;
125584
+ } catch (err) {
125585
+ if (err instanceof SessionExpiredError) {
125586
+ stale = true;
125587
+ if (!isSafeToReplay(init.method)) reached = err;
125588
+ }
125589
+ throw err;
125590
+ }
125591
+ }
125592
+ if (reached) {
125593
+ throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true, hostSignIn: reached.hostSignIn });
125594
+ }
125595
+ return leg.ready().then((t) => t.fetch(init));
125596
+ });
125597
+ };
125598
+ return {
125599
+ ready: async () => ({ fetch: (init) => runOne(init) }),
125600
+ status: () => legs.status(),
125601
+ bridgeTransport: () => legs.bridgeTransport(),
125602
+ stats: () => legs.stats(),
125603
+ sessionStale: () => stale,
125604
+ sessionLinked: () => {
125605
+ stale = false;
125606
+ if (mode === "auto") liftSessionWall();
125607
+ },
125608
+ identityState: async () => {
125609
+ const sess = await store.read();
125610
+ return JSON.stringify([legs.status().transport, stale, sess?.capturedAt ?? null]);
125611
+ }
125612
+ };
125613
+ }
125614
+
125037
125615
  // src/tools/resolve.ts
125038
125616
  function pick3(items, input2, what) {
125039
125617
  const raw = String(input2).trim();
@@ -125077,7 +125655,9 @@ function resolvePlayer(players, input2) {
125077
125655
  function refuse(message, hint) {
125078
125656
  throw new McpToolError(message, { kind: "unknown", hint });
125079
125657
  }
125080
- function signedInHint(hosted) {
125658
+ function signedInHint(view) {
125659
+ const { hosted, hostSignIn } = typeof view === "object" ? view : { hosted: view, hostSignIn: false };
125660
+ if (hosted && hostSignIn) return `${HOST_SIGN_IN_ADVICE} Then retry.`;
125081
125661
  return hosted ? "Make sure a war.app tab signed in to your account is open and paired (reload or focus it if it is frozen), then retry." : "Make sure a war.app tab signed in to your account is open and paired (reload or focus it if it is frozen), or link a session with warapp_link_session, then retry.";
125082
125662
  }
125083
125663
  function accountUnknown(hosted, consequence = "nothing was sent") {
@@ -125088,7 +125668,7 @@ function accountUnknown(hosted, consequence = "nothing was sent") {
125088
125668
  }
125089
125669
  async function requireMe(ctx, opts = {}) {
125090
125670
  const token = await ctx.myInviteToken({ fresh: opts.fresh ?? true });
125091
- if (token === void 0) throw accountUnknown(ctx.hosted, opts.consequence);
125671
+ if (token === void 0) throw accountUnknown(ctx, opts.consequence);
125092
125672
  return token;
125093
125673
  }
125094
125674
  function mySeat(game, token) {
@@ -125747,7 +126327,7 @@ function chatViewMarks(lines, meInGame, channels) {
125747
126327
  out.channels = CHAT_CHANNELS.filter((c) => has[c]);
125748
126328
  return out.channels.length ? out : void 0;
125749
126329
  }
125750
- var isRec6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
126330
+ var isRec7 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
125751
126331
  var pick4 = (r, keys) => {
125752
126332
  for (const k of keys) if (r[k] !== void 0 && r[k] !== null) return r[k];
125753
126333
  return void 0;
@@ -125761,11 +126341,11 @@ var CHANNEL_KEYS = ["channel", "Channel", "teamID", "teamId", "team", "Team"];
125761
126341
  var RECIPIENT_KEYS = ["recipientID", "recipientId", "recipient", "toPlayerID", "toPlayerId", "privateTo", "to"];
125762
126342
  function feedChatLines(raw) {
125763
126343
  let list3 = raw;
125764
- if (isRec6(list3)) list3 = pick4(list3, LIST_KEYS);
126344
+ if (isRec7(list3)) list3 = pick4(list3, LIST_KEYS);
125765
126345
  if (!Array.isArray(list3)) return void 0;
125766
126346
  const out = [];
125767
126347
  for (const item of list3) {
125768
- if (!isRec6(item)) return void 0;
126348
+ if (!isRec7(item)) return void 0;
125769
126349
  const text = pick4(item, TEXT_KEYS);
125770
126350
  if (typeof text !== "string") return void 0;
125771
126351
  const from = pick4(item, SENDER_KEYS);
@@ -125819,9 +126399,9 @@ function fillFromFeed(web, feed) {
125819
126399
 
125820
126400
  // src/chat-cursor.ts
125821
126401
  import { randomUUID as randomUUID2 } from "node:crypto";
125822
- import { mkdir as mkdir7, readFile as readFile8, rename as rename7, rm as rm4, writeFile as writeFile7 } from "node:fs/promises";
125823
- import { join as join11 } from "node:path";
125824
- var chatCursorPath = (dir, gameId) => join11(dir, "chat", `${gameId}.json`);
126402
+ import { mkdir as mkdir8, readFile as readFile9, rename as rename8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
126403
+ import { join as join12 } from "node:path";
126404
+ var chatCursorPath = (dir, gameId) => join12(dir, "chat", `${gameId}.json`);
125825
126405
  var byChannel = (lines, channel) => lines.map((l, i2) => [l, i2]).filter(([l]) => l.channel === channel);
125826
126406
  function markNew(lines, cursor) {
125827
126407
  const out = lines.map((l) => !l.mine);
@@ -125870,10 +126450,10 @@ function unreadCounts(lines, fresh) {
125870
126450
  const unknown4 = n("unknown");
125871
126451
  return { public: n("public"), team: n("team"), private: n("private"), ...unknown4 ? { unknown: unknown4 } : {} };
125872
126452
  }
125873
- var isRec7 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
126453
+ var isRec8 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
125874
126454
  var count = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
125875
126455
  function channelOf(v) {
125876
- if (!isRec7(v) || !count(v.seen)) return void 0;
126456
+ if (!isRec8(v) || !count(v.seen)) return void 0;
125877
126457
  const c = { seen: v.seen };
125878
126458
  if (typeof v.lastTimeMs === "number" && Number.isFinite(v.lastTimeMs)) {
125879
126459
  c.lastTimeMs = v.lastTimeMs;
@@ -125883,8 +126463,8 @@ function channelOf(v) {
125883
126463
  }
125884
126464
  async function readChatCursor(dir, gameId, playerId) {
125885
126465
  try {
125886
- const c = JSON.parse(await readFile8(chatCursorPath(dir, gameId), "utf8"));
125887
- if (!isRec7(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec7(c.channels)) return void 0;
126466
+ const c = JSON.parse(await readFile9(chatCursorPath(dir, gameId), "utf8"));
126467
+ if (!isRec8(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec8(c.channels)) return void 0;
125888
126468
  const channels = {};
125889
126469
  for (const ch of CHAT_CHANNELS) {
125890
126470
  const v = channelOf(c.channels[ch]);
@@ -125899,13 +126479,13 @@ async function readChatCursor(dir, gameId, playerId) {
125899
126479
  async function writeChatCursor(dir, cursor) {
125900
126480
  try {
125901
126481
  const path = chatCursorPath(dir, cursor.gameId);
125902
- await mkdir7(join11(dir, "chat"), { recursive: true, mode: 448 });
126482
+ await mkdir8(join12(dir, "chat"), { recursive: true, mode: 448 });
125903
126483
  const tmp = `${path}.${process.pid}.${randomUUID2()}.tmp`;
125904
126484
  try {
125905
126485
  await writeFile7(tmp, JSON.stringify(cursor), { mode: 384 });
125906
- await rename7(tmp, path);
126486
+ await rename8(tmp, path);
125907
126487
  } catch (e) {
125908
- await rm4(tmp, { force: true }).catch(() => void 0);
126488
+ await rm5(tmp, { force: true }).catch(() => void 0);
125909
126489
  throw e;
125910
126490
  }
125911
126491
  return true;
@@ -126918,21 +127498,21 @@ function commitmentWarnings(input2) {
126918
127498
 
126919
127499
  // src/relations-store.ts
126920
127500
  import { randomUUID as randomUUID3 } from "node:crypto";
126921
- import { mkdir as mkdir8, readFile as readFile9, rename as rename8, writeFile as writeFile8 } from "node:fs/promises";
126922
- import { join as join12 } from "node:path";
126923
- var isRec8 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
127501
+ import { mkdir as mkdir9, readFile as readFile10, rename as rename9, writeFile as writeFile8 } from "node:fs/promises";
127502
+ import { join as join13 } from "node:path";
127503
+ var isRec9 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
126924
127504
  var isInt4 = (v) => typeof v === "number" && Number.isInteger(v);
126925
127505
  var ints = (v) => Array.isArray(v) && v.every(isInt4) ? [...v] : void 0;
126926
127506
  var MAX_AGREEMENTS = 50;
126927
127507
  var MAX_USAGE_TURNS = 200;
126928
127508
  var MAX_COMMITMENTS = 200;
126929
- var relationsDir = (dir) => join12(dir, "relations");
126930
- var relationsPath = (dir, gameId, playerId) => join12(relationsDir(dir), `${gameId}-${playerId}.json`);
127509
+ var relationsDir = (dir) => join13(dir, "relations");
127510
+ var relationsPath = (dir, gameId, playerId) => join13(relationsDir(dir), `${gameId}-${playerId}.json`);
126931
127511
  var AGREEMENT_ID = /^a(\d{1,9})$/;
126932
127512
  var idNumber = (id) => Number(AGREEMENT_ID.exec(id)?.[1] ?? 0);
126933
127513
  function scopeOf(v) {
126934
127514
  if (v === "all") return "all";
126935
- if (!isRec8(v)) return void 0;
127515
+ if (!isRec9(v)) return void 0;
126936
127516
  const t = ints(v.territories);
126937
127517
  if (t) return { territories: t };
126938
127518
  const b = ints(v.bonuses);
@@ -126940,7 +127520,7 @@ function scopeOf(v) {
126940
127520
  }
126941
127521
  var isStatus = (v) => typeof v === "string" && AGREEMENT_STATUSES.includes(v);
126942
127522
  function termsOf(v) {
126943
- if (!isRec8(v)) return void 0;
127523
+ if (!isRec9(v)) return void 0;
126944
127524
  const scope = scopeOf(v.scope);
126945
127525
  if (!scope || !isInt4(v.noticeTurns) || v.noticeTurns < 0 || v.noticeTurns > MAX_NOTICE_TURNS) return void 0;
126946
127526
  const t = { scope, noticeTurns: v.noticeTurns };
@@ -126951,11 +127531,11 @@ function termsOf(v) {
126951
127531
  return t;
126952
127532
  }
126953
127533
  function agreementOf(v) {
126954
- if (!isRec8(v) || typeof v.id !== "string" || !AGREEMENT_ID.test(v.id) || !isInt4(v.with) || v.kind !== "truce" || !isStatus(v.status) || !isInt4(v.createdTurn))
127534
+ if (!isRec9(v) || typeof v.id !== "string" || !AGREEMENT_ID.test(v.id) || !isInt4(v.with) || v.kind !== "truce" || !isStatus(v.status) || !isInt4(v.createdTurn))
126955
127535
  return void 0;
126956
127536
  const terms = termsOf(v.terms);
126957
127537
  if (!terms || !Array.isArray(v.history)) return void 0;
126958
- const history = v.history.filter((h) => isRec8(h) && isInt4(h.turn) && isStatus(h.status));
127538
+ const history = v.history.filter((h) => isRec9(h) && isInt4(h.turn) && isStatus(h.status));
126959
127539
  const a = { id: v.id, with: v.with, kind: "truce", status: v.status, createdTurn: v.createdTurn, terms, history };
126960
127540
  if (isInt4(v.agreedTurn)) a.agreedTurn = v.agreedTurn;
126961
127541
  if (isInt4(v.noticeTurn)) a.noticeTurn = v.noticeTurn;
@@ -126966,7 +127546,7 @@ function agreementOf(v) {
126966
127546
  }
126967
127547
  var COMMITMENT_ID = /^c(\d{1,9})$/;
126968
127548
  function commitmentOf(v) {
126969
- if (!isRec8(v) || typeof v.id !== "string" || !COMMITMENT_ID.test(v.id) || !isInt4(v.sentTurn)) return void 0;
127549
+ if (!isRec9(v) || typeof v.id !== "string" || !COMMITMENT_ID.test(v.id) || !isInt4(v.sentTurn)) return void 0;
126970
127550
  if (typeof v.kind !== "string" || !COMMITMENT_KINDS.includes(v.kind)) return void 0;
126971
127551
  const base = { id: v.id, sentTurn: v.sentTurn };
126972
127552
  switch (v.kind) {
@@ -126996,12 +127576,12 @@ function nextCommitmentId(ledger) {
126996
127576
  return `c${n + 1}`;
126997
127577
  }
126998
127578
  function usageOf(v) {
126999
- if (!isRec8(v)) return {};
127579
+ if (!isRec9(v)) return {};
127000
127580
  const out = {};
127001
127581
  for (const [k, list3] of Object.entries(v)) {
127002
127582
  if (!/^\d+$/.test(k) || !Array.isArray(list3)) continue;
127003
127583
  const num3 = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
127004
- out[k] = list3.filter((u) => isRec8(u) && typeof u.agreementId === "string").map((u) => ({
127584
+ out[k] = list3.filter((u) => isRec9(u) && typeof u.agreementId === "string").map((u) => ({
127005
127585
  agreementId: u.agreementId,
127006
127586
  armiesFreed: num3(u.armiesFreed),
127007
127587
  lossIfBroken: num3(u.lossIfBroken),
@@ -127013,8 +127593,8 @@ function usageOf(v) {
127013
127593
  var emptyLedger = (gameId, playerId) => ({ gameId, playerId, agreements: [], usage: {} });
127014
127594
  async function readLedger(dir, gameId, playerId) {
127015
127595
  try {
127016
- const c = JSON.parse(await readFile9(relationsPath(dir, gameId, playerId), "utf8"));
127017
- if (!isRec8(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements)) return void 0;
127596
+ const c = JSON.parse(await readFile10(relationsPath(dir, gameId, playerId), "utf8"));
127597
+ if (!isRec9(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements)) return void 0;
127018
127598
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== void 0);
127019
127599
  return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
127020
127600
  } catch {
@@ -127024,13 +127604,13 @@ async function readLedger(dir, gameId, playerId) {
127024
127604
  async function readLedgerForWrite(dir, gameId, playerId) {
127025
127605
  let text;
127026
127606
  try {
127027
- text = await readFile9(relationsPath(dir, gameId, playerId), "utf8");
127607
+ text = await readFile10(relationsPath(dir, gameId, playerId), "utf8");
127028
127608
  } catch (e) {
127029
127609
  return e.code === "ENOENT" ? null : "unreadable";
127030
127610
  }
127031
127611
  try {
127032
127612
  const c = JSON.parse(text);
127033
- if (!isRec8(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements)) return "unreadable";
127613
+ if (!isRec9(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements)) return "unreadable";
127034
127614
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== void 0);
127035
127615
  return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments) };
127036
127616
  } catch {
@@ -127052,10 +127632,10 @@ function boundLedger(ledger) {
127052
127632
  async function writeLedger(dir, ledger) {
127053
127633
  try {
127054
127634
  const path = relationsPath(dir, ledger.gameId, ledger.playerId);
127055
- await mkdir8(relationsDir(dir), { recursive: true, mode: 448 });
127635
+ await mkdir9(relationsDir(dir), { recursive: true, mode: 448 });
127056
127636
  const tmp = `${path}.${process.pid}.${randomUUID3()}.tmp`;
127057
127637
  await writeFile8(tmp, JSON.stringify(boundLedger(ledger)), { mode: 384 });
127058
- await rename8(tmp, path);
127638
+ await rename9(tmp, path);
127059
127639
  return true;
127060
127640
  } catch {
127061
127641
  return false;
@@ -127183,15 +127763,15 @@ function playerRecord(tallies, entries2 = []) {
127183
127763
  }
127184
127764
 
127185
127765
  // src/player-record-store.ts
127186
- import { createHmac as createHmac3, randomBytes as randomBytes7, randomUUID as randomUUID4 } from "node:crypto";
127187
- import { link as link2, mkdir as mkdir9, readFile as readFile10, rename as rename9, unlink as unlink7, writeFile as writeFile9 } from "node:fs/promises";
127188
- import { join as join13 } from "node:path";
127189
- var isRec9 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
127766
+ import { createHmac as createHmac3, randomBytes as randomBytes8, randomUUID as randomUUID4 } from "node:crypto";
127767
+ import { link as link2, mkdir as mkdir10, readFile as readFile11, rename as rename10, unlink as unlink7, writeFile as writeFile9 } from "node:fs/promises";
127768
+ import { join as join14 } from "node:path";
127769
+ var isRec10 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
127190
127770
  var SALT = /^[0-9a-f]{32}$/;
127191
127771
  var HASH = /^[0-9a-f]{32}$/;
127192
127772
  var OUTCOMES = /* @__PURE__ */ new Set(["open", "not-agreed", "kept", "ended-with-notice", "broken-by-them", "broken-by-me"]);
127193
- var playerRecordPath = (dir) => join13(relationsDir(dir), "players.json");
127194
- var playerRecordSaltPath = (dir) => join13(relationsDir(dir), "players.salt");
127773
+ var playerRecordPath = (dir) => join14(relationsDir(dir), "players.json");
127774
+ var playerRecordSaltPath = (dir) => join14(relationsDir(dir), "players.salt");
127195
127775
  function playerRecordEnabled(env = process.env) {
127196
127776
  const v = readEnvVar("WARAPP_PLAYER_RECORD", { env });
127197
127777
  return v === void 0 || !/^(off|0|false|no)$/i.test(v.trim());
@@ -127199,7 +127779,7 @@ function playerRecordEnabled(env = process.env) {
127199
127779
  async function readSalt(dir) {
127200
127780
  let text;
127201
127781
  try {
127202
- text = await readFile10(playerRecordSaltPath(dir), "utf8");
127782
+ text = await readFile11(playerRecordSaltPath(dir), "utf8");
127203
127783
  } catch (e) {
127204
127784
  return e.code === "ENOENT" ? "missing" : "malformed";
127205
127785
  }
@@ -127215,9 +127795,9 @@ async function playerSaltForWrite(dir) {
127215
127795
  if (typeof s === "object") return s.salt;
127216
127796
  if (s === "malformed") return void 0;
127217
127797
  const path = playerRecordSaltPath(dir);
127218
- await mkdir9(relationsDir(dir), { recursive: true, mode: 448 });
127798
+ await mkdir10(relationsDir(dir), { recursive: true, mode: 448 });
127219
127799
  const tmp = `${path}.${process.pid}.${randomUUID4()}.tmp`;
127220
- await writeFile9(tmp, randomBytes7(16).toString("hex"), { mode: 384 });
127800
+ await writeFile9(tmp, randomBytes8(16).toString("hex"), { mode: 384 });
127221
127801
  try {
127222
127802
  await link2(tmp, path);
127223
127803
  } catch (e) {
@@ -127237,19 +127817,19 @@ var legacyEntryKey = (salt, gameId, agreementId) => hmac(salt, `agreement:${game
127237
127817
  var count2 = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
127238
127818
  var intOrNull = (v) => v === null || typeof v === "number" && Number.isInteger(v);
127239
127819
  function talliesFrom(v) {
127240
- if (!isRec9(v) || !COUNT_KEYS.every((k) => count2(v[k]))) return void 0;
127820
+ if (!isRec10(v) || !COUNT_KEYS.every((k) => count2(v[k]))) return void 0;
127241
127821
  const out = { ...ZERO_COUNTS };
127242
127822
  for (const k of COUNT_KEYS) out[k] = v[k];
127243
127823
  return out;
127244
127824
  }
127245
127825
  function entryOf2(v) {
127246
- if (!isRec9(v) || typeof v.key !== "string" || !HASH.test(v.key) || !OUTCOMES.has(v.outcome) || typeof v.updated !== "number")
127826
+ if (!isRec10(v) || typeof v.key !== "string" || !HASH.test(v.key) || !OUTCOMES.has(v.outcome) || typeof v.updated !== "number")
127247
127827
  return void 0;
127248
- if (!isRec9(v.format) || !isRec9(v.terms) || !intOrNull(v.agreedTurn) || !intOrNull(v.endedTurn)) return void 0;
127828
+ if (!isRec10(v.format) || !isRec10(v.terms) || !intOrNull(v.agreedTurn) || !intOrNull(v.endedTurn)) return void 0;
127249
127829
  return v;
127250
127830
  }
127251
127831
  function playerOf(v) {
127252
- if (!isRec9(v)) return void 0;
127832
+ if (!isRec10(v)) return void 0;
127253
127833
  const entries2 = Array.isArray(v.entries) ? v.entries.map(entryOf2).filter((e) => e !== void 0) : [];
127254
127834
  const tallies = talliesFrom(v.tallies) ?? talliesFrom(v.counts) ?? (entries2.length ? talliesOf(entries2) : void 0);
127255
127835
  if (!tallies) return void 0;
@@ -127259,7 +127839,7 @@ function playerOf(v) {
127259
127839
  async function readFileRecord(dir) {
127260
127840
  let text;
127261
127841
  try {
127262
- text = await readFile10(playerRecordPath(dir), "utf8");
127842
+ text = await readFile11(playerRecordPath(dir), "utf8");
127263
127843
  } catch (e) {
127264
127844
  return e.code === "ENOENT" ? { version: 3, players: {} } : "unreadable";
127265
127845
  }
@@ -127269,7 +127849,7 @@ async function readFileRecord(dir) {
127269
127849
  } catch {
127270
127850
  return "unreadable";
127271
127851
  }
127272
- if (!isRec9(c) || !isRec9(c.players)) return "unreadable";
127852
+ if (!isRec10(c) || !isRec10(c.players)) return "unreadable";
127273
127853
  const players = {};
127274
127854
  for (const [k, v] of Object.entries(c.players)) {
127275
127855
  const p = HASH.test(k) ? playerOf(v) : void 0;
@@ -127281,10 +127861,10 @@ async function writeFileRecord(dir, file2) {
127281
127861
  const keys = Object.keys(file2.players).sort((a, b) => file2.players[b].updated - file2.players[a].updated || (a < b ? -1 : 1)).slice(0, MAX_RECORD_PLAYERS).sort();
127282
127862
  const bounded = { version: 3, players: Object.fromEntries(keys.map((k) => [k, file2.players[k]])) };
127283
127863
  const path = playerRecordPath(dir);
127284
- await mkdir9(relationsDir(dir), { recursive: true, mode: 448 });
127864
+ await mkdir10(relationsDir(dir), { recursive: true, mode: 448 });
127285
127865
  const tmp = `${path}.${process.pid}.${randomUUID4()}.tmp`;
127286
127866
  await writeFile9(tmp, JSON.stringify(bounded), { mode: 384 });
127287
- await rename9(tmp, path);
127867
+ await rename10(tmp, path);
127288
127868
  }
127289
127869
  async function readPlayerRecord(dir, playerId, env) {
127290
127870
  if (!playerRecordEnabled(env)) return "off";
@@ -127329,14 +127909,14 @@ async function updatePlayerRecord(dir, playerId, update, env, now = Date.now())
127329
127909
  }
127330
127910
 
127331
127911
  // src/replay.ts
127332
- import { readdir as readdir6, readFile as readFile11, stat as stat4, unlink as unlink8 } from "node:fs/promises";
127333
- import { join as join14 } from "node:path";
127912
+ import { readdir as readdir6, readFile as readFile12, stat as stat5, unlink as unlink8 } from "node:fs/promises";
127913
+ import { join as join15 } from "node:path";
127334
127914
  var MAX_GAME_RECORDS = 200;
127335
127915
  var VERSION3 = 1;
127336
127916
  var GAME_FILE = /^\d+\.json$/;
127337
- var isRec10 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
127338
- var gamesDir = (dir) => join14(dir, "games");
127339
- var gameRecordPath = (dir, gameId) => join14(gamesDir(dir), `${gameId}.json`);
127917
+ var isRec11 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
127918
+ var gamesDir = (dir) => join15(dir, "games");
127919
+ var gameRecordPath = (dir, gameId) => join15(gamesDir(dir), `${gameId}.json`);
127340
127920
  var ENUM_SETTINGS = /* @__PURE__ */ new Set(["Pace", "Fog", "MoveOrder", "RoundingMode", "InstantSurrender", "AutomaticTerritoryDistribution"]);
127341
127921
  var DROPPED_SETTINGS = /* @__PURE__ */ new Set(["PersonalMessage", "Mods", "OverriddenBonuses"]);
127342
127922
  var CARD_ENUM_KEYS = /* @__PURE__ */ new Set(["Mode"]);
@@ -127354,7 +127934,7 @@ function cleanValue(v, depth, enumOk, names2, enumKeys = NO_KEYS) {
127354
127934
  }
127355
127935
  if (depth > MAX_DEPTH2) return void 0;
127356
127936
  if (Array.isArray(v)) return v.map((x) => cleanValue(x, depth + 1, false, names2)).filter((x) => x !== void 0);
127357
- if (isRec10(v)) {
127937
+ if (isRec11(v)) {
127358
127938
  const out = {};
127359
127939
  for (const [k, x] of Object.entries(v)) {
127360
127940
  if (!ENUM.test(k) && !NUMERIC.test(k)) continue;
@@ -127392,8 +127972,8 @@ async function pruneGames(dir, keep) {
127392
127972
  for (const name of await readdir6(folder)) {
127393
127973
  if (!GAME_FILE.test(name) || name === `${keep}.json`) continue;
127394
127974
  try {
127395
- const at2 = (await stat4(join14(folder, name))).mtimeMs;
127396
- if (at2 < cutoff) await unlink8(join14(folder, name));
127975
+ const at2 = (await stat5(join15(folder, name))).mtimeMs;
127976
+ if (at2 < cutoff) await unlink8(join15(folder, name));
127397
127977
  else files.push({ name, at: at2 });
127398
127978
  } catch {
127399
127979
  }
@@ -127401,7 +127981,7 @@ async function pruneGames(dir, keep) {
127401
127981
  const excess = files.length + 1 - MAX_GAME_RECORDS;
127402
127982
  if (excess <= 0) return;
127403
127983
  files.sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
127404
- for (const f of files.slice(0, excess)) await unlink8(join14(folder, f.name)).catch(() => {
127984
+ for (const f of files.slice(0, excess)) await unlink8(join15(folder, f.name)).catch(() => {
127405
127985
  });
127406
127986
  }
127407
127987
  function nameFreeSettings(game) {
@@ -127441,13 +128021,13 @@ async function writeGameRecord(dir, game) {
127441
128021
  }
127442
128022
 
127443
128023
  // src/pick-list.ts
127444
- import { mkdir as mkdir10, readdir as readdir7, readFile as readFile12, rename as rename10, stat as stat5, unlink as unlink9, writeFile as writeFile10 } from "node:fs/promises";
127445
- import { join as join15 } from "node:path";
127446
- var pickListPath = (dir, gameId) => join15(dir, "picks", `${gameId}.json`);
128024
+ import { mkdir as mkdir11, readdir as readdir7, readFile as readFile13, rename as rename11, stat as stat6, unlink as unlink9, writeFile as writeFile10 } from "node:fs/promises";
128025
+ import { join as join16 } from "node:path";
128026
+ var pickListPath = (dir, gameId) => join16(dir, "picks", `${gameId}.json`);
127447
128027
  var PICK_LIST_MAX_AGE_MS = 60 * 864e5;
127448
128028
  var PICK_FILE = /^\d+\.json$/;
127449
128029
  var pruned2 = /* @__PURE__ */ new Set();
127450
- var isRec11 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
128030
+ var isRec12 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
127451
128031
  var isId = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
127452
128032
  var isIds = (v) => Array.isArray(v) && v.every(isId);
127453
128033
  var isArmies = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
@@ -127459,7 +128039,7 @@ function neutralsOf(v) {
127459
128039
  }
127460
128040
  function awardOf(v) {
127461
128041
  if (v === null) return null;
127462
- if (!isRec11(v) || !isIds(v.granted) || !isIds(v.unlisted) || !isIds(v.opponentStarts)) return void 0;
128042
+ if (!isRec12(v) || !isIds(v.granted) || !isIds(v.unlisted) || !isIds(v.opponentStarts)) return void 0;
127463
128043
  if (typeof v.allStartsKnown !== "boolean") return void 0;
127464
128044
  if (v.role !== null && v.role !== "first" && v.role !== "second") return void 0;
127465
128045
  if (v.opponentFirstAward !== null && !isId(v.opponentFirstAward)) return void 0;
@@ -127476,8 +128056,8 @@ function awardOf(v) {
127476
128056
  }
127477
128057
  async function readPickRecord(dir, gameId, playerId) {
127478
128058
  try {
127479
- const c = JSON.parse(await readFile12(pickListPath(dir, gameId), "utf8"));
127480
- if (!isRec11(c) || c.gameId !== gameId || c.playerId !== playerId) return void 0;
128059
+ const c = JSON.parse(await readFile13(pickListPath(dir, gameId), "utf8"));
128060
+ if (!isRec12(c) || c.gameId !== gameId || c.playerId !== playerId) return void 0;
127481
128061
  const list3 = isIds(c.list) && c.list.length ? c.list : void 0;
127482
128062
  const pickable = isIds(c.pickable) && c.pickable.length ? c.pickable : void 0;
127483
128063
  const neutrals = neutralsOf(c.neutrals);
@@ -127496,16 +128076,16 @@ async function readPickRecord(dir, gameId, playerId) {
127496
128076
  }
127497
128077
  }
127498
128078
  async function prunePickLists(dir) {
127499
- const picks = join15(dir, "picks");
128079
+ const picks = join16(dir, "picks");
127500
128080
  if (pruned2.has(picks)) return;
127501
128081
  pruned2.add(picks);
127502
128082
  const cutoff = Date.now() - PICK_LIST_MAX_AGE_MS;
127503
128083
  try {
127504
128084
  for (const name of await readdir7(picks)) {
127505
128085
  if (!PICK_FILE.test(name)) continue;
127506
- const file2 = join15(picks, name);
128086
+ const file2 = join16(picks, name);
127507
128087
  try {
127508
- if ((await stat5(file2)).mtimeMs < cutoff) await unlink9(file2);
128088
+ if ((await stat6(file2)).mtimeMs < cutoff) await unlink9(file2);
127509
128089
  } catch {
127510
128090
  }
127511
128091
  }
@@ -127515,10 +128095,10 @@ async function prunePickLists(dir) {
127515
128095
  async function writeRecord2(dir, record4) {
127516
128096
  try {
127517
128097
  const path = pickListPath(dir, record4.gameId);
127518
- await mkdir10(join15(dir, "picks"), { recursive: true, mode: 448 });
128098
+ await mkdir11(join16(dir, "picks"), { recursive: true, mode: 448 });
127519
128099
  const tmp = `${path}.${process.pid}.tmp`;
127520
128100
  await writeFile10(tmp, JSON.stringify(record4), { mode: 384 });
127521
- await rename10(tmp, path);
128101
+ await rename11(tmp, path);
127522
128102
  await prunePickLists(dir);
127523
128103
  return true;
127524
128104
  } catch {
@@ -127570,8 +128150,8 @@ function pickingNeutrals(board) {
127570
128150
  }
127571
128151
 
127572
128152
  // src/tools/team-source.ts
127573
- import { readdir as readdir12, readFile as readFile19, stat as stat11, unlink as unlink14 } from "node:fs/promises";
127574
- import { join as join22 } from "node:path";
128153
+ import { readdir as readdir12, readFile as readFile20, stat as stat12, unlink as unlink14 } from "node:fs/promises";
128154
+ import { join as join23 } from "node:path";
127575
128155
 
127576
128156
  // src/my-games.ts
127577
128157
  var MY_GAMES_RETURN = "warlight.shared.MyGamesReturn";
@@ -128407,15 +128987,15 @@ function addCalibration(a, b, scale = 1) {
128407
128987
  }
128408
128988
 
128409
128989
  // src/lessons-store.ts
128410
- import { readdir as readdir8, readFile as readFile13, stat as stat6, unlink as unlink10 } from "node:fs/promises";
128411
- import { join as join16 } from "node:path";
128990
+ import { readdir as readdir8, readFile as readFile14, stat as stat7, unlink as unlink10 } from "node:fs/promises";
128991
+ import { join as join17 } from "node:path";
128412
128992
  var MAX_MAP_ENTRIES = 50;
128413
128993
  var MAX_MAP_RECORDS = 200;
128414
128994
  var MAX_LESSON_ENTRIES = 500;
128415
- var mapRecordDir = (dir) => join16(dir, "maps-record");
128416
- var mapRecordPath = (dir, mapId) => join16(mapRecordDir(dir), `${mapId}.json`);
128417
- var lessonsPath = (dir) => join16(dir, "lessons.json");
128418
- var isRec12 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
128995
+ var mapRecordDir = (dir) => join17(dir, "maps-record");
128996
+ var mapRecordPath = (dir, mapId) => join17(mapRecordDir(dir), `${mapId}.json`);
128997
+ var lessonsPath = (dir) => join17(dir, "lessons.json");
128998
+ var isRec13 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
128419
128999
  var isInt6 = (v) => typeof v === "number" && Number.isInteger(v);
128420
129000
  var num = (v) => typeof v === "number" && Number.isFinite(v);
128421
129001
  var ints2 = (v) => Array.isArray(v) && v.every(isInt6);
@@ -128428,34 +129008,34 @@ var CAUSES = ["commander", "last-territories", "unknown", "surrendered", "booted
128428
129008
  async function readStore(path) {
128429
129009
  let text;
128430
129010
  try {
128431
- text = await readFile13(path, "utf8");
129011
+ text = await readFile14(path, "utf8");
128432
129012
  } catch (e) {
128433
129013
  return e.code === "ENOENT" ? "missing" : "unreadable";
128434
129014
  }
128435
129015
  try {
128436
129016
  const v = JSON.parse(text);
128437
- return isRec12(v) ? v : "unreadable";
129017
+ return isRec13(v) ? v : "unreadable";
128438
129018
  } catch {
128439
129019
  return "unreadable";
128440
129020
  }
128441
129021
  }
128442
- var countsOf = (v) => isRec12(v) && Object.values(v).every(isInt6) ? Object.fromEntries(Object.entries(v)) : void 0;
129022
+ var countsOf = (v) => isRec13(v) && Object.values(v).every(isInt6) ? Object.fromEntries(Object.entries(v)) : void 0;
128443
129023
  var bumpCount = (c, k, by) => {
128444
129024
  const n = (c[k] ?? 0) + by;
128445
129025
  if (n) c[k] = n;
128446
129026
  else delete c[k];
128447
129027
  };
128448
- var regionOf = (v) => isRec12(v) && ints2(v.territories) && ints2(v.bonuses) ? { territories: v.territories, bonuses: v.bonuses } : void 0;
129028
+ var regionOf = (v) => isRec13(v) && ints2(v.territories) && ints2(v.bonuses) ? { territories: v.territories, bonuses: v.bonuses } : void 0;
128449
129029
  function mapEntryOf(v) {
128450
- if (!isRec12(v) || typeof v.key !== "string" || !HASH2.test(v.key) || !isFormat(v.format) || !isInt6(v.seats) || !isResult(v.result) || !intOrNull2(v.turns)) return void 0;
129030
+ if (!isRec13(v) || typeof v.key !== "string" || !HASH2.test(v.key) || !isFormat(v.format) || !isInt6(v.seats) || !isResult(v.result) || !intOrNull2(v.turns)) return void 0;
128451
129031
  const m = v.me;
128452
129032
  const mine2 = regionOf(m);
128453
- if (!mine2 || !isRec12(m) || !Array.isArray(m.income) || !m.income.every(intOrNull2) || !intOrNull2(m.income4) || !intOrNull2(m.income8)) return void 0;
129033
+ if (!mine2 || !isRec13(m) || !Array.isArray(m.income) || !m.income.every(intOrNull2) || !intOrNull2(m.income4) || !intOrNull2(m.income8)) return void 0;
128454
129034
  if (!Array.isArray(v.winners)) return void 0;
128455
129035
  const winners = [];
128456
129036
  for (const w of v.winners) {
128457
129037
  const r = regionOf(w);
128458
- if (!r || !isRec12(w) || !intOrNull2(w.income4) || !intOrNull2(w.income8)) return void 0;
129038
+ if (!r || !isRec13(w) || !intOrNull2(w.income4) || !intOrNull2(w.income8)) return void 0;
128459
129039
  winners.push({ ...r, income4: w.income4, income8: w.income8 });
128460
129040
  }
128461
129041
  return {
@@ -128506,9 +129086,9 @@ async function pruneMapRecords(dir, keep, protect) {
128506
129086
  const files = [];
128507
129087
  for (const name of await readdir8(folder)) {
128508
129088
  if (!/^\d+\.json$/.test(name)) continue;
128509
- const path = join16(folder, name);
129089
+ const path = join17(folder, name);
128510
129090
  try {
128511
- files.push({ path, at: (await stat6(path)).mtimeMs });
129091
+ files.push({ path, at: (await stat7(path)).mtimeMs });
128512
129092
  } catch {
128513
129093
  }
128514
129094
  }
@@ -128559,11 +129139,11 @@ function mapRecordStarts(rec) {
128559
129139
  };
128560
129140
  }
128561
129141
  function statsOf(v) {
128562
- if (!isRec12(v) || !isInt6(v.n) || !num(v.sum) || !num(v.sq) || !num(v.logSum) || !isInt6(v.under) || !isInt6(v.over)) return void 0;
129142
+ if (!isRec13(v) || !isInt6(v.n) || !num(v.sum) || !num(v.sq) || !num(v.logSum) || !isInt6(v.under) || !isInt6(v.over)) return void 0;
128563
129143
  return { n: v.n, sum: v.sum, sq: v.sq, logSum: v.logSum, under: v.under, over: v.over };
128564
129144
  }
128565
129145
  function calibrationOf(v) {
128566
- if (!isRec12(v)) return void 0;
129146
+ if (!isRec13(v)) return void 0;
128567
129147
  const out = {};
128568
129148
  for (const [k, s] of Object.entries(v)) {
128569
129149
  if (!COVERAGE_BUCKETS.includes(k)) return void 0;
@@ -128575,23 +129155,23 @@ function calibrationOf(v) {
128575
129155
  }
128576
129156
  function lossOf(v) {
128577
129157
  if (v === null) return null;
128578
- if (!isRec12(v) || !CAUSES.includes(v.cause) || !intOrNull2(v.turn)) return void 0;
129158
+ if (!isRec13(v) || !CAUSES.includes(v.cause) || !intOrNull2(v.turn)) return void 0;
128579
129159
  return { cause: v.cause, turn: v.turn };
128580
129160
  }
128581
129161
  function lessonEntryOf(v) {
128582
- if (!isRec12(v) || typeof v.key !== "string" || !HASH2.test(v.key) || !isFormat(v.format) || !isInt6(v.seats) || !isResult(v.result) || !intOrNull2(v.flatAfterTurn)) return void 0;
129162
+ if (!isRec13(v) || typeof v.key !== "string" || !HASH2.test(v.key) || !isFormat(v.format) || !isInt6(v.seats) || !isResult(v.result) || !intOrNull2(v.flatAfterTurn)) return void 0;
128583
129163
  const loss = lossOf(v.howLost);
128584
129164
  const calibration = calibrationOf(v.calibration);
128585
129165
  if (loss === void 0 || !calibration) return void 0;
128586
129166
  return { key: v.key, format: v.format, seats: v.seats, result: v.result, flatAfterTurn: v.flatAfterTurn, howLost: loss, calibration };
128587
129167
  }
128588
129168
  function totalsOf(v) {
128589
- if (!isRec12(v) || !isInt6(v.games)) return void 0;
129169
+ if (!isRec13(v) || !isInt6(v.games)) return void 0;
128590
129170
  const outcomes = countsOf(v.outcomes);
128591
129171
  const lost = countsOf(v.howLost);
128592
129172
  const calibration = calibrationOf(v.calibration);
128593
129173
  const f = v.flat;
128594
- if (!outcomes || !lost || !calibration || !isRec12(f) || !isInt6(f.n) || !num(f.sum)) return void 0;
129174
+ if (!outcomes || !lost || !calibration || !isRec13(f) || !isInt6(f.n) || !num(f.sum)) return void 0;
128595
129175
  return { games: v.games, outcomes, howLost: lost, flat: { n: f.n, sum: f.sum }, calibration };
128596
129176
  }
128597
129177
  async function readLessons(dir) {
@@ -128599,7 +129179,7 @@ async function readLessons(dir) {
128599
129179
  const v = await readStore(lessonsPath(dir));
128600
129180
  if (v === "unreadable") return v;
128601
129181
  if (v === "missing") return { version: 1, byFormat: {}, entries: [] };
128602
- if (v.version !== 1 || !isRec12(v.byFormat)) return "unreadable";
129182
+ if (v.version !== 1 || !isRec13(v.byFormat)) return "unreadable";
128603
129183
  const byFormat = {};
128604
129184
  for (const [k, t] of Object.entries(v.byFormat)) {
128605
129185
  const totals = totalsOf(t);
@@ -128676,8 +129256,8 @@ function lessonsSummary(file2) {
128676
129256
  }
128677
129257
 
128678
129258
  // src/profile-store.ts
128679
- import { mkdir as mkdir11, readdir as readdir9, readFile as readFile14, rename as rename11, stat as stat7, unlink as unlink11, writeFile as writeFile11 } from "node:fs/promises";
128680
- import { join as join17 } from "node:path";
129259
+ import { mkdir as mkdir12, readdir as readdir9, readFile as readFile15, rename as rename12, stat as stat8, unlink as unlink11, writeFile as writeFile11 } from "node:fs/promises";
129260
+ import { join as join18 } from "node:path";
128681
129261
  import { randomUUID as randomUUID5 } from "node:crypto";
128682
129262
  var PROFILE_ENV = "WARAPP_PLAYER_PROFILE";
128683
129263
  var MAX_PROFILE_GAME_FILES = 200;
@@ -128689,18 +129269,18 @@ function profileState(env, dataDir2) {
128689
129269
  if (!profileEnabled(env)) return "off";
128690
129270
  return dataDir2 ? "kept" : "not-kept";
128691
129271
  }
128692
- var profileGamesDir = (dir) => join17(dir, "profiles", "games");
128693
- var profileGamePath = (dir, gameId, playerId) => join17(profileGamesDir(dir), `${gameId}-${playerId}.json`);
128694
- var isRec13 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
129272
+ var profileGamesDir = (dir) => join18(dir, "profiles", "games");
129273
+ var profileGamePath = (dir, gameId, playerId) => join18(profileGamesDir(dir), `${gameId}-${playerId}.json`);
129274
+ var isRec14 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
128695
129275
  var isInt7 = (v) => typeof v === "number" && Number.isInteger(v);
128696
129276
  var ids = (v) => Array.isArray(v) && v.every(isInt7) ? [...v] : void 0;
128697
129277
  function primitivesOf(v) {
128698
- if (!isRec13(v) || typeof v.contact !== "boolean" || typeof v.iAttacked !== "boolean") return void 0;
129278
+ if (!isRec14(v) || typeof v.contact !== "boolean" || typeof v.iAttacked !== "boolean") return void 0;
128699
129279
  if (v.attackedMe !== null && typeof v.attackedMe !== "boolean") return void 0;
128700
129280
  const r = v.reinforce;
128701
- if (!isRec13(r) || !isInt7(r.n) || !isInt7(r.e) || !isInt7(r.extra)) return void 0;
129281
+ if (!isRec14(r) || !isInt7(r.n) || !isInt7(r.e) || !isInt7(r.extra)) return void 0;
128702
129282
  const s = v.stack;
128703
- if (s !== null && !(isRec13(s) && isInt7(s.top) && isInt7(s.total))) return void 0;
129283
+ if (s !== null && !(isRec14(s) && isInt7(s.top) && isInt7(s.total))) return void 0;
128704
129284
  const took = v.tookFromMe === null ? null : ids(v.tookFromMe);
128705
129285
  const lost = ids(v.lostToMe);
128706
129286
  if (took === void 0 || !lost) return void 0;
@@ -128714,14 +129294,14 @@ function primitivesOf(v) {
128714
129294
  lostToMe: lost
128715
129295
  };
128716
129296
  }
128717
- var seatsOf = (v) => isRec13(v) && PROFILE_FORMATS.includes(v.format) && isInt7(v.players) && ids(v.ai) && ids(v.turnedAI) ? { format: v.format, players: v.players, ai: ids(v.ai), turnedAI: ids(v.turnedAI) } : void 0;
129297
+ var seatsOf = (v) => isRec14(v) && PROFILE_FORMATS.includes(v.format) && isInt7(v.players) && ids(v.ai) && ids(v.turnedAI) ? { format: v.format, players: v.players, ai: ids(v.ai), turnedAI: ids(v.turnedAI) } : void 0;
128718
129298
  async function readGameFile(dir, gameId, playerId) {
128719
129299
  try {
128720
- const f = JSON.parse(await readFile14(profileGamePath(dir, gameId, playerId), "utf8"));
128721
- if (!isRec13(f) || f.version !== 1 || f.gameId !== gameId || f.playerId !== playerId || !isRec13(f.turns)) return { turns: {} };
129300
+ const f = JSON.parse(await readFile15(profileGamePath(dir, gameId, playerId), "utf8"));
129301
+ if (!isRec14(f) || f.version !== 1 || f.gameId !== gameId || f.playerId !== playerId || !isRec14(f.turns)) return { turns: {} };
128722
129302
  const out = {};
128723
129303
  for (const [t, byOpponent] of Object.entries(f.turns)) {
128724
- if (!/^\d+$/.test(t) || !isRec13(byOpponent)) continue;
129304
+ if (!/^\d+$/.test(t) || !isRec14(byOpponent)) continue;
128725
129305
  const kept = {};
128726
129306
  for (const [o, p] of Object.entries(byOpponent)) {
128727
129307
  const v = /^\d+$/.test(o) ? primitivesOf(p) : void 0;
@@ -128785,9 +129365,9 @@ async function prune(dir, env) {
128785
129365
  for (const name of await readdir9(folder)) {
128786
129366
  const m = /^(\d+)-(\d+)\.json$/.exec(name);
128787
129367
  if (!m) continue;
128788
- const path = join17(folder, name);
129368
+ const path = join18(folder, name);
128789
129369
  try {
128790
- files.push({ path, mtime: (await stat7(path)).mtimeMs, gameId: Number(m[1]), playerId: Number(m[2]) });
129370
+ files.push({ path, mtime: (await stat8(path)).mtimeMs, gameId: Number(m[1]), playerId: Number(m[2]) });
128791
129371
  } catch {
128792
129372
  }
128793
129373
  }
@@ -128847,26 +129427,26 @@ async function recordBehaviour(dir, input2, env = process.env) {
128847
129427
  }
128848
129428
  }
128849
129429
  async function writeGameFile(path, body) {
128850
- await mkdir11(join17(path, ".."), { recursive: true, mode: 448 });
129430
+ await mkdir12(join18(path, ".."), { recursive: true, mode: 448 });
128851
129431
  const tmp = `${path}.${process.pid}.${randomUUID5()}.tmp`;
128852
129432
  await writeFile11(tmp, JSON.stringify(body), { mode: 384 });
128853
- await rename11(tmp, path);
129433
+ await rename12(tmp, path);
128854
129434
  }
128855
129435
  var MAX_PROFILE_ENTRIES = 30;
128856
129436
  var MAX_PROFILE_PLAYERS = 1e3;
128857
129437
  var MAX_POPULATION_ENTRIES = 500;
128858
- var profilePlayersPath = (dir) => join17(dir, "profiles", "players.json");
128859
- var profilePopulationPath = (dir) => join17(dir, "profiles", "population.json");
128860
- var storeLock = (dir) => join17(dir, "profiles", ".store");
129438
+ var profilePlayersPath = (dir) => join18(dir, "profiles", "players.json");
129439
+ var profilePopulationPath = (dir) => join18(dir, "profiles", "population.json");
129440
+ var storeLock = (dir) => join18(dir, "profiles", ".store");
128861
129441
  var ENDINGS = ["Won", "SurrenderAccepted", "Booted", "Eliminated", "EndedByVote"];
128862
129442
  function endingOf(state) {
128863
129443
  return ENDINGS.includes(state ?? "") ? state : "unknown";
128864
129444
  }
128865
129445
  var HASH3 = /^[0-9a-f]{32}$/;
128866
129446
  var num2 = (v) => typeof v === "number" && Number.isFinite(v);
128867
- var rateOf = (v) => isRec13(v) && num2(v.e) && num2(v.n) ? { e: v.e, n: v.n } : void 0;
129447
+ var rateOf = (v) => isRec14(v) && num2(v.e) && num2(v.n) ? { e: v.e, n: v.n } : void 0;
128868
129448
  function habitsFrom(v) {
128869
- if (!isRec13(v)) return void 0;
129449
+ if (!isRec14(v)) return void 0;
128870
129450
  const r = rateOf(v.reinforce);
128871
129451
  const a = rateOf(v.attack);
128872
129452
  const f = rateOf(v.firstStrike);
@@ -128875,12 +129455,12 @@ function habitsFrom(v) {
128875
129455
  const x = v.reinforceExtra;
128876
129456
  const s = v.stacking;
128877
129457
  if (!r || !a || !f || !rt || !rk || !num2(v.turns)) return void 0;
128878
- if (!isRec13(x) || !num2(x.n) || !num2(x.sum) || !isRec13(s) || !num2(s.n) || !num2(s.sum) || !num2(s.sq)) return void 0;
129458
+ if (!isRec14(x) || !num2(x.n) || !num2(x.sum) || !isRec14(s) || !num2(s.n) || !num2(s.sum) || !num2(s.sq)) return void 0;
128879
129459
  return { reinforce: r, reinforceExtra: { n: x.n, sum: x.sum }, attack: a, firstStrike: f, stacking: { n: s.n, sum: s.sum, sq: s.sq }, retaliate: rt, retake: rk, turns: v.turns };
128880
129460
  }
128881
129461
  function totalsFrom(v) {
128882
129462
  const out = {};
128883
- if (!isRec13(v)) return out;
129463
+ if (!isRec14(v)) return out;
128884
129464
  for (const f of PROFILE_FORMATS) {
128885
129465
  const h = habitsFrom(v[f]);
128886
129466
  if (h) out[f] = h;
@@ -128889,7 +129469,7 @@ function totalsFrom(v) {
128889
129469
  }
128890
129470
  var isFormat2 = (v) => PROFILE_FORMATS.includes(v);
128891
129471
  function entryFrom(v) {
128892
- if (!isRec13(v) || typeof v.key !== "string" || !HASH3.test(v.key) || !isFormat2(v.format) || !isInt7(v.players) || !isInt7(v.turnsSeen)) return void 0;
129472
+ if (!isRec14(v) || typeof v.key !== "string" || !HASH3.test(v.key) || !isFormat2(v.format) || !isInt7(v.players) || !isInt7(v.turnsSeen)) return void 0;
128893
129473
  if (v.source !== "live" && v.source !== "history" || !num2(v.weight)) return void 0;
128894
129474
  const habits = habitsFrom(v.habits);
128895
129475
  if (!habits) return void 0;
@@ -128899,13 +129479,13 @@ function entryFrom(v) {
128899
129479
  async function readStore2(path) {
128900
129480
  let text;
128901
129481
  try {
128902
- text = await readFile14(path, "utf8");
129482
+ text = await readFile15(path, "utf8");
128903
129483
  } catch (e) {
128904
129484
  return e.code === "ENOENT" ? "missing" : "unreadable";
128905
129485
  }
128906
129486
  try {
128907
129487
  const v = JSON.parse(text);
128908
- return isRec13(v) ? v : "unreadable";
129488
+ return isRec14(v) ? v : "unreadable";
128909
129489
  } catch {
128910
129490
  return "unreadable";
128911
129491
  }
@@ -128914,10 +129494,10 @@ async function readPlayers(dir) {
128914
129494
  const v = await readStore2(profilePlayersPath(dir));
128915
129495
  if (v === "unreadable") return v;
128916
129496
  if (v === "missing") return { version: 1, seq: 0, players: {} };
128917
- if (v.version !== 1 || !isRec13(v.players)) return "unreadable";
129497
+ if (v.version !== 1 || !isRec14(v.players)) return "unreadable";
128918
129498
  const players = {};
128919
129499
  for (const [k, p] of Object.entries(v.players)) {
128920
- if (!HASH3.test(k) || !isRec13(p) || !isInt7(p.seq) || !isInt7(p.games) || !Array.isArray(p.entries)) continue;
129500
+ if (!HASH3.test(k) || !isRec14(p) || !isInt7(p.seq) || !isInt7(p.games) || !Array.isArray(p.entries)) continue;
128921
129501
  players[k] = { seq: p.seq, games: p.games, totals: totalsFrom(p.totals), entries: p.entries.map(entryFrom).filter((e) => e !== void 0) };
128922
129502
  }
128923
129503
  return { version: 1, seq: isInt7(v.seq) ? v.seq : 0, players };
@@ -128929,7 +129509,7 @@ async function readPopulation(dir) {
128929
129509
  if (v.version !== 1) return "unreadable";
128930
129510
  const entries2 = [];
128931
129511
  for (const e of Array.isArray(v.entries) ? v.entries : []) {
128932
- if (!isRec13(e) || typeof e.key !== "string" || !HASH3.test(e.key) || !isFormat2(e.format)) continue;
129512
+ if (!isRec14(e) || typeof e.key !== "string" || !HASH3.test(e.key) || !isFormat2(e.format)) continue;
128933
129513
  if (e.source !== "live" && e.source !== "history") continue;
128934
129514
  const humans = habitsFrom(e.humans);
128935
129515
  const ai = habitsFrom(e.ai);
@@ -128938,10 +129518,10 @@ async function readPopulation(dir) {
128938
129518
  return { version: 1, games: isInt7(v.games) ? v.games : 0, totals: totalsFrom(v.totals), ai: habitsFrom(v.ai) ?? emptyHabits(), entries: entries2 };
128939
129519
  }
128940
129520
  async function writeStore(path, body) {
128941
- await mkdir11(join17(path, ".."), { recursive: true, mode: 448 });
129521
+ await mkdir12(join18(path, ".."), { recursive: true, mode: 448 });
128942
129522
  const tmp = `${path}.${process.pid}.${randomUUID5()}.tmp`;
128943
129523
  await writeFile11(tmp, JSON.stringify(body), { mode: 384 });
128944
- await rename11(tmp, path);
129524
+ await rename12(tmp, path);
128945
129525
  }
128946
129526
  var sumOf = (list3) => list3.reduce((a, h) => addHabits(a, h), emptyHabits());
128947
129527
  var sumTotals = (t) => sumOf(PROFILE_FORMATS.flatMap((f) => t[f] ? [t[f]] : []));
@@ -129022,7 +129602,7 @@ async function readProfileHistory(dir, ids2, game, env = process.env) {
129022
129602
  if (players === "unreadable" || population === "unreadable") return "unreadable";
129023
129603
  const pools = { byFormat: population.totals, all: sumTotals(population.totals), ai: population.ai, games: population.games };
129024
129604
  const out = { players: /* @__PURE__ */ new Map(), pools };
129025
- const saltText = await readFile14(playerRecordSaltPath(dir), "utf8").catch((e) => e.code === "ENOENT" ? null : "");
129605
+ const saltText = await readFile15(playerRecordSaltPath(dir), "utf8").catch((e) => e.code === "ENOENT" ? null : "");
129026
129606
  if (saltText === null) return out;
129027
129607
  const salt = await playerRecordSalt(dir);
129028
129608
  if (!salt) return "unreadable";
@@ -129108,7 +129688,7 @@ async function foldFinishedGame(dir, game, env = process.env) {
129108
129688
  async function markHistoryFolded(dir, gameId, playerId) {
129109
129689
  const path = profileGamePath(dir, gameId, playerId);
129110
129690
  try {
129111
- await stat7(path);
129691
+ await stat8(path);
129112
129692
  } catch {
129113
129693
  return;
129114
129694
  }
@@ -129120,7 +129700,7 @@ async function markHistoryFolded(dir, gameId, playerId) {
129120
129700
  }
129121
129701
  async function profileFileState(dir, gameId, playerId) {
129122
129702
  try {
129123
- await stat7(profileGamePath(dir, gameId, playerId));
129703
+ await stat8(profileGamePath(dir, gameId, playerId));
129124
129704
  } catch (e) {
129125
129705
  return e.code === "ENOENT" ? "none" : "kept";
129126
129706
  }
@@ -129139,7 +129719,7 @@ async function profileGameFolded(dir, me, gameId) {
129139
129719
  try {
129140
129720
  const population = await readPopulation(dir);
129141
129721
  if (population === "unreadable") return true;
129142
- const saltText = await readFile14(playerRecordSaltPath(dir), "utf8").catch((e) => e.code === "ENOENT" ? null : "");
129722
+ const saltText = await readFile15(playerRecordSaltPath(dir), "utf8").catch((e) => e.code === "ENOENT" ? null : "");
129143
129723
  if (saltText === null) return false;
129144
129724
  const salt = await playerRecordSalt(dir);
129145
129725
  if (!salt) return true;
@@ -129151,34 +129731,34 @@ async function profileGameFolded(dir, me, gameId) {
129151
129731
  }
129152
129732
 
129153
129733
  // src/finished-store.ts
129154
- import { readdir as readdir10, readFile as readFile15, stat as stat8, unlink as unlink12, utimes as utimes2 } from "node:fs/promises";
129155
- import { join as join18 } from "node:path";
129734
+ import { readdir as readdir10, readFile as readFile16, stat as stat9, unlink as unlink12, utimes as utimes2 } from "node:fs/promises";
129735
+ import { join as join19 } from "node:path";
129156
129736
  var MAX_FINISHED_RECORDS = 500;
129157
129737
  var MAX_PROCESSED_KEYS = 5e3;
129158
129738
  var MAX_RECORD_BOARDS_HEAD = 30;
129159
129739
  var MAX_RECORD_BOARDS_TAIL = 30;
129160
129740
  var VERSION4 = 1;
129161
129741
  var FILE = /^[0-9a-f]{32}\.json$/;
129162
- var finishedDir = (dir) => join18(dir, "finished");
129163
- var finishedPath = (dir, salt, me, gameId) => join18(finishedDir(dir), `${finishedGameKey(salt, me, gameId)}.json`);
129164
- var processedPath = (dir) => join18(finishedDir(dir), "processed.json");
129742
+ var finishedDir = (dir) => join19(dir, "finished");
129743
+ var finishedPath = (dir, salt, me, gameId) => join19(finishedDir(dir), `${finishedGameKey(salt, me, gameId)}.json`);
129744
+ var processedPath = (dir) => join19(finishedDir(dir), "processed.json");
129165
129745
  var KEY = /^[0-9a-f]{32}$/;
129166
129746
  var OWNER_NEUTRAL2 = -1;
129167
129747
  var OWNER_AVAILABLE = -2;
129168
129748
  var OWNER_UNKNOWN = -3;
129169
129749
  var FOG_WORD = /^[A-Za-z0-9]{1,20}$/;
129170
- var isRec14 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
129750
+ var isRec15 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
129171
129751
  var STATUSES = /* @__PURE__ */ new Set(["captured", "history-unreadable", "read-failed"]);
129172
129752
  async function readFinishedState(path) {
129173
129753
  let text;
129174
129754
  try {
129175
- text = await readFile15(path, "utf8");
129755
+ text = await readFile16(path, "utf8");
129176
129756
  } catch (e) {
129177
129757
  return e.code === "ENOENT" ? "missing" : "unreadable";
129178
129758
  }
129179
129759
  try {
129180
129760
  const v = JSON.parse(text);
129181
- if (!isRec14(v) || v.version !== VERSION4 || typeof v.status !== "string" || !STATUSES.has(v.status)) return "unreadable";
129761
+ if (!isRec15(v) || v.version !== VERSION4 || typeof v.status !== "string" || !STATUSES.has(v.status)) return "unreadable";
129182
129762
  return { status: v.status };
129183
129763
  } catch {
129184
129764
  return "unreadable";
@@ -129199,13 +129779,13 @@ async function readProcessed(dir) {
129199
129779
  async function readProcessedKeys(dir) {
129200
129780
  let text;
129201
129781
  try {
129202
- text = await readFile15(processedPath(dir), "utf8");
129782
+ text = await readFile16(processedPath(dir), "utf8");
129203
129783
  } catch (e) {
129204
129784
  return e.code === "ENOENT" ? [] : "unreadable";
129205
129785
  }
129206
129786
  try {
129207
129787
  const v = JSON.parse(text);
129208
- if (!isRec14(v) || v.version !== VERSION4 || !Array.isArray(v.keys) || !v.keys.every((k) => typeof k === "string" && KEY.test(k))) return "unreadable";
129788
+ if (!isRec15(v) || v.version !== VERSION4 || !Array.isArray(v.keys) || !v.keys.every((k) => typeof k === "string" && KEY.test(k))) return "unreadable";
129209
129789
  return v.keys;
129210
129790
  } catch {
129211
129791
  return "unreadable";
@@ -129231,9 +129811,9 @@ async function pruneFinished(dir, keep, protect) {
129231
129811
  const files = [];
129232
129812
  for (const name of await readdir10(folder)) {
129233
129813
  if (!FILE.test(name)) continue;
129234
- const path = join18(folder, name);
129814
+ const path = join19(folder, name);
129235
129815
  try {
129236
- files.push({ path, at: (await stat8(path)).mtimeMs });
129816
+ files.push({ path, at: (await stat9(path)).mtimeMs });
129237
129817
  } catch {
129238
129818
  }
129239
129819
  }
@@ -129328,12 +129908,12 @@ function storeBoards(boards, ids2, key) {
129328
129908
  }
129329
129909
 
129330
129910
  // src/outlook-log.ts
129331
- import { mkdir as mkdir12, readFile as readFile16, rename as rename12, writeFile as writeFile12 } from "node:fs/promises";
129911
+ import { mkdir as mkdir13, readFile as readFile17, rename as rename13, writeFile as writeFile12 } from "node:fs/promises";
129332
129912
  import { randomUUID as randomUUID6 } from "node:crypto";
129333
- import { join as join19 } from "node:path";
129334
- var isRec15 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
129913
+ import { join as join20 } from "node:path";
129914
+ var isRec16 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
129335
129915
  var OUTLOOK_LOG_TURNS = 500;
129336
- var outlookLogPath = (dir, gameId) => join19(dir, "outlook", `${gameId}.json`);
129916
+ var outlookLogPath = (dir, gameId) => join20(dir, "outlook", `${gameId}.json`);
129337
129917
  var logged = (e) => ({
129338
129918
  incomes: e.incomes ? { ...e.incomes, ...e.incomes.players ? { players: [...e.incomes.players] } : {} } : null,
129339
129919
  opponents: e.opponents.map(({ playerId, income, source, coverage, thin }) => ({ playerId, income, source, coverage, thin })),
@@ -129341,8 +129921,8 @@ var logged = (e) => ({
129341
129921
  });
129342
129922
  async function readOutlookLog(dir, gameId, playerId) {
129343
129923
  try {
129344
- const c = JSON.parse(await readFile16(outlookLogPath(dir, gameId), "utf8"));
129345
- if (!isRec15(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec15(c.turns)) return void 0;
129924
+ const c = JSON.parse(await readFile17(outlookLogPath(dir, gameId), "utf8"));
129925
+ if (!isRec16(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec16(c.turns)) return void 0;
129346
129926
  return c;
129347
129927
  } catch {
129348
129928
  return void 0;
@@ -129350,10 +129930,10 @@ async function readOutlookLog(dir, gameId, playerId) {
129350
129930
  }
129351
129931
  async function write(dir, log) {
129352
129932
  const path = outlookLogPath(dir, log.gameId);
129353
- await mkdir12(join19(dir, "outlook"), { recursive: true, mode: 448 });
129933
+ await mkdir13(join20(dir, "outlook"), { recursive: true, mode: 448 });
129354
129934
  const tmp = `${path}.${process.pid}.${randomUUID6()}.tmp`;
129355
129935
  await writeFile12(tmp, JSON.stringify(log), { mode: 384 });
129356
- await rename12(tmp, path);
129936
+ await rename13(tmp, path);
129357
129937
  }
129358
129938
  async function recordOutlook(dir, gameId, playerId, outlook) {
129359
129939
  try {
@@ -129419,8 +129999,8 @@ async function recordResult(dir, gameId, playerId, result) {
129419
129999
  }
129420
130000
  async function readOutlookPlayer(dir, gameId) {
129421
130001
  try {
129422
- const c = JSON.parse(await readFile16(outlookLogPath(dir, gameId), "utf8"));
129423
- return isRec15(c) && c.gameId === gameId && typeof c.playerId === "number" ? c.playerId : void 0;
130002
+ const c = JSON.parse(await readFile17(outlookLogPath(dir, gameId), "utf8"));
130003
+ return isRec16(c) && c.gameId === gameId && typeof c.playerId === "number" ? c.playerId : void 0;
129424
130004
  } catch {
129425
130005
  return void 0;
129426
130006
  }
@@ -129440,8 +130020,8 @@ async function recordLoss(dir, gameId, playerId, loss) {
129440
130020
  async function recordFinalResult(dir, game) {
129441
130021
  if (game.state !== "Finished") return false;
129442
130022
  try {
129443
- const c = JSON.parse(await readFile16(outlookLogPath(dir, game.id), "utf8"));
129444
- if (!isRec15(c) || typeof c.playerId !== "number") return false;
130023
+ const c = JSON.parse(await readFile17(outlookLogPath(dir, game.id), "utf8"));
130024
+ if (!isRec16(c) || typeof c.playerId !== "number") return false;
129445
130025
  const playerId = c.playerId;
129446
130026
  const state = game.players.find((p) => p.id === playerId)?.state;
129447
130027
  return state === void 0 ? false : await recordResult(dir, game.id, playerId, state);
@@ -129451,7 +130031,7 @@ async function recordFinalResult(dir, game) {
129451
130031
  }
129452
130032
 
129453
130033
  // src/tools/profile-hook.ts
129454
- import { stat as stat9, utimes as utimes3 } from "node:fs/promises";
130034
+ import { stat as stat10, utimes as utimes3 } from "node:fs/promises";
129455
130035
  function observeSettings(game) {
129456
130036
  const s = game.settings;
129457
130037
  return {
@@ -129545,7 +130125,7 @@ async function foldFinished(dataDir2, env, game) {
129545
130125
  );
129546
130126
  if (!kept) return nothing("no-turns");
129547
130127
  const path = profileGamePath(dataDir2, game.id, me);
129548
- const boardTime = await stat9(boardCachePath(dataDir2, game.id)).then((s) => s.mtime).catch(() => void 0);
130128
+ const boardTime = await stat10(boardCachePath(dataDir2, game.id)).then((s) => s.mtime).catch(() => void 0);
129549
130129
  if (!await foldFinishedGame(dataDir2, resolved, env)) return nothing("failed");
129550
130130
  if (boardTime) await utimes3(path, boardTime, boardTime).catch(() => void 0);
129551
130131
  return { status: "folded", source: "backfill", opponents: await foldedOpponents(dataDir2, env, resolved, me) };
@@ -129802,9 +130382,9 @@ function firstMoverOnTurn(input2) {
129802
130382
  }
129803
130383
 
129804
130384
  // src/move-order.ts
129805
- import { mkdir as mkdir13, readdir as readdir11, readFile as readFile17, rename as rename13, stat as stat10, unlink as unlink13, writeFile as writeFile13 } from "node:fs/promises";
129806
- import { join as join20 } from "node:path";
129807
- var firstMoverPath = (dir, gameId) => join20(dir, "move-order", `${gameId}.json`);
130385
+ import { mkdir as mkdir14, readdir as readdir11, readFile as readFile18, rename as rename14, stat as stat11, unlink as unlink13, writeFile as writeFile13 } from "node:fs/promises";
130386
+ import { join as join21 } from "node:path";
130387
+ var firstMoverPath = (dir, gameId) => join21(dir, "move-order", `${gameId}.json`);
129808
130388
  var FIRST_MOVER_MAX_AGE_MS = 60 * 864e5;
129809
130389
  var FILE2 = /^\d+\.json$/;
129810
130390
  var pruned3 = /* @__PURE__ */ new Set();
@@ -129850,7 +130430,7 @@ function verifiedFirstMover(resolved) {
129850
130430
  var same = (a, b) => b !== void 0 && a.turn === b.turn && a.firstMover === b.firstMover && a.source === b.source;
129851
130431
  async function readFirstMover(dir, gameId, playerId) {
129852
130432
  try {
129853
- const c = JSON.parse(await readFile17(firstMoverPath(dir, gameId), "utf8"));
130433
+ const c = JSON.parse(await readFile18(firstMoverPath(dir, gameId), "utf8"));
129854
130434
  if (typeof c !== "object" || c === null || Array.isArray(c)) return void 0;
129855
130435
  const r = c;
129856
130436
  if (r.gameId !== gameId || r.playerId !== playerId) return void 0;
@@ -129861,16 +130441,16 @@ async function readFirstMover(dir, gameId, playerId) {
129861
130441
  }
129862
130442
  }
129863
130443
  async function prune2(dir) {
129864
- const base = join20(dir, "move-order");
130444
+ const base = join21(dir, "move-order");
129865
130445
  if (pruned3.has(base)) return;
129866
130446
  pruned3.add(base);
129867
130447
  const cutoff = Date.now() - FIRST_MOVER_MAX_AGE_MS;
129868
130448
  try {
129869
130449
  for (const name of await readdir11(base)) {
129870
130450
  if (!FILE2.test(name)) continue;
129871
- const file2 = join20(base, name);
130451
+ const file2 = join21(base, name);
129872
130452
  try {
129873
- if ((await stat10(file2)).mtimeMs < cutoff) await unlink13(file2);
130453
+ if ((await stat11(file2)).mtimeMs < cutoff) await unlink13(file2);
129874
130454
  } catch {
129875
130455
  }
129876
130456
  }
@@ -129881,10 +130461,10 @@ async function writeFirstMover(dir, gameId, playerId, seen2) {
129881
130461
  if (!isTurn(seen2.turn) || !isMover(seen2.firstMover) || !isSource(seen2.source)) return false;
129882
130462
  try {
129883
130463
  const path = firstMoverPath(dir, gameId);
129884
- await mkdir13(join20(dir, "move-order"), { recursive: true, mode: 448 });
130464
+ await mkdir14(join21(dir, "move-order"), { recursive: true, mode: 448 });
129885
130465
  const tmp = `${path}.${process.pid}.tmp`;
129886
130466
  await writeFile13(tmp, JSON.stringify({ gameId, playerId, turn: seen2.turn, firstMover: seen2.firstMover, source: seen2.source }), { mode: 384 });
129887
- await rename13(tmp, path);
130467
+ await rename14(tmp, path);
129888
130468
  await prune2(dir);
129889
130469
  return true;
129890
130470
  } catch {
@@ -130723,7 +131303,7 @@ function registerTeamTool(server, ctx) {
130723
131303
  async ({ game_id }) => {
130724
131304
  const gameId = parseGameId(game_id);
130725
131305
  const identity = await ctx.myIdentity().catch(() => void 0);
130726
- if (!identity) throw accountUnknown(ctx.hosted, "your team cannot be read");
131306
+ if (!identity) throw accountUnknown(ctx, "your team cannot be read");
130727
131307
  const read = await ctx.client.getGame(gameId, { settings: true, chat: true });
130728
131308
  const { game, source } = await resolveTeams(ctx, read);
130729
131309
  const me = game.players.find((p) => p.id === identity.token);
@@ -132494,44 +133074,44 @@ function guessOrdersOf(orders, guess) {
132494
133074
  }
132495
133075
 
132496
133076
  // src/guess-salt.ts
132497
- import { randomBytes as randomBytes8 } from "node:crypto";
132498
- import { mkdir as mkdir14, readFile as readFile18, rename as rename14, writeFile as writeFile14 } from "node:fs/promises";
132499
- import { join as join21 } from "node:path";
133077
+ import { randomBytes as randomBytes9 } from "node:crypto";
133078
+ import { mkdir as mkdir15, readFile as readFile19, rename as rename15, writeFile as writeFile14 } from "node:fs/promises";
133079
+ import { join as join22 } from "node:path";
132500
133080
  var SALT2 = /^[0-9a-f]{32}$/;
132501
133081
  var processSalt;
132502
133082
  var cached2 = /* @__PURE__ */ new Map();
132503
- var guessSaltPath = (dir) => join21(dir, "guess-salt");
133083
+ var guessSaltPath = (dir) => join22(dir, "guess-salt");
132504
133084
  async function peekGuessSalt(dir) {
132505
133085
  if (!dir) return processSalt;
132506
133086
  const hit = cached2.get(dir);
132507
133087
  if (hit) return hit;
132508
133088
  try {
132509
- const text = (await readFile18(guessSaltPath(dir), "utf8")).trim();
133089
+ const text = (await readFile19(guessSaltPath(dir), "utf8")).trim();
132510
133090
  if (SALT2.test(text)) return text;
132511
133091
  } catch {
132512
133092
  }
132513
133093
  return processSalt;
132514
133094
  }
132515
133095
  async function guessSalt(dir) {
132516
- const fallback = () => processSalt ??= randomBytes8(16).toString("hex");
133096
+ const fallback = () => processSalt ??= randomBytes9(16).toString("hex");
132517
133097
  if (!dir) return fallback();
132518
133098
  const hit = cached2.get(dir);
132519
133099
  if (hit) return hit;
132520
133100
  const path = guessSaltPath(dir);
132521
133101
  try {
132522
- const text = (await readFile18(path, "utf8")).trim();
133102
+ const text = (await readFile19(path, "utf8")).trim();
132523
133103
  if (SALT2.test(text)) {
132524
133104
  cached2.set(dir, text);
132525
133105
  return text;
132526
133106
  }
132527
133107
  } catch {
132528
133108
  }
132529
- const salt = randomBytes8(16).toString("hex");
133109
+ const salt = randomBytes9(16).toString("hex");
132530
133110
  try {
132531
- await mkdir14(dir, { recursive: true, mode: 448 });
133111
+ await mkdir15(dir, { recursive: true, mode: 448 });
132532
133112
  const tmp = `${path}.${process.pid}.tmp`;
132533
133113
  await writeFile14(tmp, salt, { mode: 384 });
132534
- await rename14(tmp, path);
133114
+ await rename15(tmp, path);
132535
133115
  cached2.set(dir, salt);
132536
133116
  return salt;
132537
133117
  } catch {
@@ -138464,7 +139044,7 @@ async function listMyGames(read, windows = MY_GAMES_WINDOWS) {
138464
139044
  async function myInGameId(ctx) {
138465
139045
  const me = await ctx.myInGameId();
138466
139046
  if (me === void 0) {
138467
- throw accountUnknown(ctx.hosted, "its games cannot be listed");
139047
+ throw accountUnknown(ctx, "its games cannot be listed");
138468
139048
  }
138469
139049
  return me;
138470
139050
  }
@@ -138556,14 +139136,14 @@ function registerMyGamesTool(server, ctx, deps = {}) {
138556
139136
  var MAX_TEAM_RECORDS = 200;
138557
139137
  var TEAM_RECORD_VERSION = 2;
138558
139138
  var TEAM_FILE = /^\d+\.json$/;
138559
- var teamsDir = (dir) => join22(dir, "teams");
138560
- var teamRecordPath = (dir, gameId) => join22(teamsDir(dir), `${gameId}.json`);
138561
- var isRec16 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
139139
+ var teamsDir = (dir) => join23(dir, "teams");
139140
+ var teamRecordPath = (dir, gameId) => join23(teamsDir(dir), `${gameId}.json`);
139141
+ var isRec17 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
138562
139142
  var isInt10 = (v) => typeof v === "number" && Number.isInteger(v);
138563
139143
  async function readTeamFile(dir, gameId) {
138564
139144
  try {
138565
- const r = JSON.parse(await readFile19(teamRecordPath(dir, gameId), "utf8"));
138566
- if (!isRec16(r) || r.version !== TEAM_RECORD_VERSION || r.gameId !== gameId) return void 0;
139145
+ const r = JSON.parse(await readFile20(teamRecordPath(dir, gameId), "utf8"));
139146
+ if (!isRec17(r) || r.version !== TEAM_RECORD_VERSION || r.gameId !== gameId) return void 0;
138567
139147
  if (!("teams" in r)) return isInt10(r.incompleteTurn) ? { incompleteTurn: r.incompleteTurn } : void 0;
138568
139148
  if (!Array.isArray(r.teams)) return void 0;
138569
139149
  const out = /* @__PURE__ */ new Map();
@@ -138586,14 +139166,14 @@ async function pruneTeams(dir, keep) {
138586
139166
  for (const name of await readdir12(folder)) {
138587
139167
  if (!TEAM_FILE.test(name) || name === `${keep}.json`) continue;
138588
139168
  try {
138589
- files.push({ name, at: (await stat11(join22(folder, name))).mtimeMs });
139169
+ files.push({ name, at: (await stat12(join23(folder, name))).mtimeMs });
138590
139170
  } catch {
138591
139171
  }
138592
139172
  }
138593
139173
  const excess = files.length + 1 - MAX_TEAM_RECORDS;
138594
139174
  if (excess <= 0) return;
138595
139175
  files.sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
138596
- for (const f of files.slice(0, excess)) await unlink14(join22(folder, f.name)).catch(() => {
139176
+ for (const f of files.slice(0, excess)) await unlink14(join23(folder, f.name)).catch(() => {
138597
139177
  });
138598
139178
  }
138599
139179
  async function writeRecord3(dir, gameId, body) {
@@ -140185,7 +140765,7 @@ function registerMarkChatReadTool(server, ctx) {
140185
140765
  async plan({ game_id, channel }) {
140186
140766
  const game = await ctx.client.getGame(game_id, { chat: true, map: false });
140187
140767
  const me = await ctx.myIdentity({ fresh: true }).catch(() => void 0);
140188
- if (!me) throw accountUnknown(ctx.hosted);
140768
+ if (!me) throw accountUnknown(ctx);
140189
140769
  const read = await readChat(ctx, game, me);
140190
140770
  if (!read || read.source === "gamefeed") {
140191
140771
  refuse(
@@ -140999,146 +141579,13 @@ function registerGameTool(server, client, dir, env, identity) {
140999
141579
  );
141000
141580
  }
141001
141581
 
141002
- // src/direct/session.ts
141003
- import { execFile } from "node:child_process";
141004
- import { randomBytes as randomBytes9 } from "node:crypto";
141005
- import { readFileSync as readFileSync2 } from "node:fs";
141006
- import { chmod as chmod4, mkdir as mkdir15, open as open2, readFile as readFile20, rename as rename15, rm as rm5, stat as stat12 } from "node:fs/promises";
141007
- import { dirname, join as join23, resolve } from "node:path";
141008
- import { promisify } from "node:util";
141009
- var SESSION_HOST = "war.app";
141010
- var isRec17 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
141011
- function sessionFilePath(env = process.env) {
141012
- return readEnvVar("WARAPP_SESSION_FILE", { env }) ?? join23(dataDir(env), "session.json");
141013
- }
141014
- function parseSession(raw) {
141015
- if (!isRec17(raw)) return null;
141016
- const { authToken, capturedAt, host } = raw;
141017
- if (typeof authToken !== "string" || authToken.length === 0) return null;
141018
- if (typeof capturedAt !== "string" || capturedAt.length === 0) return null;
141019
- if (host !== SESSION_HOST) return null;
141020
- return { authToken, capturedAt, host };
141021
- }
141022
- async function readSession(env = process.env) {
141023
- if (isHosted(env)) return null;
141024
- try {
141025
- return parseSession(JSON.parse(await readFile20(sessionFilePath(env), "utf8")));
141026
- } catch {
141027
- return null;
141028
- }
141029
- }
141030
- function readSessionSync(env = process.env) {
141031
- if (isHosted(env)) return null;
141032
- try {
141033
- return parseSession(JSON.parse(readFileSync2(sessionFilePath(env), "utf8")));
141034
- } catch {
141035
- return null;
141036
- }
141037
- }
141038
- function sessionDirVerdict(st, myUid) {
141039
- if (myUid === void 0) return "ok";
141040
- if (st.uid === myUid) return (st.mode & 63) !== 0 ? "tighten" : "ok";
141041
- if (st.uid !== 0) return "refuse";
141042
- return (st.mode & 18) !== 0 ? "refuse" : "ok";
141043
- }
141044
- var run = promisify(execFile);
141045
- var MACOS_ACLS = process.platform === "darwin";
141046
- function lsShowsAcl(stdout) {
141047
- return stdout.split("\n").slice(1).some((line) => /^\s*\d+: /.test(line));
141048
- }
141049
- async function hasAcl(path) {
141050
- const { stdout } = await run("/bin/ls", ["-led", path]);
141051
- return lsShowsAcl(stdout);
141052
- }
141053
- async function stripAcl(path, what) {
141054
- await run("/bin/chmod", ["-N", path]);
141055
- if (await hasAcl(path)) {
141056
- throw new McpToolError(`Refusing to store the war.app session: could not remove the access control list on ${what}.`, {
141057
- hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory only you can read, with no ACL (`ls -le`)."
141058
- });
141059
- }
141060
- }
141061
- function sessionTmpPath(path) {
141062
- return `${path}.${randomBytes9(16).toString("hex")}.tmp`;
141063
- }
141064
- async function writeSession(session, env = process.env) {
141065
- if (isHosted(env)) {
141066
- throw new McpToolError("The direct transport is local-only: a hosted server never stores a war.app session.", {
141067
- kind: "unknown"
141068
- });
141069
- }
141070
- const path = resolve(sessionFilePath(env));
141071
- const dir = dirname(path);
141072
- await mkdir15(dir, { recursive: true, mode: 448 });
141073
- const st = await stat12(dir);
141074
- const myUid = process.getuid?.();
141075
- const verdict = sessionDirVerdict(st, myUid);
141076
- if (verdict === "refuse") {
141077
- throw new McpToolError(`Refusing to store the war.app session in ${dir}: it is not yours, and others could reach files in it.`, {
141078
- hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can write to."
141079
- });
141080
- }
141081
- if (verdict === "tighten") await chmod4(dir, 448);
141082
- if (MACOS_ACLS) {
141083
- if (st.uid === myUid) await stripAcl(dir, dir);
141084
- else if (await hasAcl(dir)) {
141085
- throw new McpToolError(`Refusing to store the war.app session in ${dir}: it carries an access control list and is not yours.`, {
141086
- hint: "Point WARAPP_SESSION_FILE (or MCP_DATA_DIR) at a directory of your own that only you can read."
141087
- });
141088
- }
141089
- }
141090
- const tmp = sessionTmpPath(path);
141091
- const file2 = await open2(tmp, "wx", 384);
141092
- try {
141093
- try {
141094
- await file2.chmod(384);
141095
- if (MACOS_ACLS) await stripAcl(tmp, "the session file");
141096
- await file2.writeFile(JSON.stringify(session));
141097
- } finally {
141098
- await file2.close();
141099
- }
141100
- await rename15(tmp, path);
141101
- } catch (e) {
141102
- await rm5(tmp, { force: true }).catch(() => {
141103
- });
141104
- throw e;
141105
- }
141106
- }
141107
- var SCRUBBED = "[warapp-session]";
141108
- function scrubToken(s, token) {
141109
- if (!token) return s;
141110
- return scrubSecrets(s, [token, stripBearer(token)], SCRUBBED);
141111
- }
141112
- function errorStrings(err, depth = 0) {
141113
- if (depth > 4 || typeof err !== "object" || err === null) return typeof err === "string" ? [err] : [];
141114
- const e = err;
141115
- const own2 = [e.message, e.hint, e.stack].filter((v) => typeof v === "string");
141116
- return [...own2, ...errorStrings(e.cause, depth + 1)];
141117
- }
141118
- function errorCarriesToken(err, tokens) {
141119
- const strings = errorStrings(err);
141120
- return tokens.some((t) => !!t && strings.some((s) => scrubToken(s, t) !== s));
141121
- }
141122
- function scrubError(err, tokens) {
141123
- if (!errorCarriesToken(err, tokens)) return err;
141124
- const ordered = tokens.filter((t) => !!t).sort((a, b) => b.length - a.length);
141125
- const scrub = (s) => ordered.reduce((acc, t) => scrubToken(acc, t), s);
141126
- const e = typeof err === "object" && err !== null ? err : {};
141127
- const message = scrub(typeof e.message === "string" ? e.message : String(err));
141128
- const kind = err instanceof McpToolError && err.kind ? err.kind : "transport";
141129
- return new McpToolError(message, {
141130
- kind,
141131
- ...typeof e.status === "number" ? { status: e.status } : {},
141132
- ...typeof e.hint === "string" ? { hint: scrub(e.hint) } : {}
141133
- });
141134
- }
141135
-
141136
141582
  // src/tools/healthcheck.ts
141137
141583
  var PROBE_PATH = `/API/GameFeed?GameID=${PROBE_GAME_ID}&GetMap=false`;
141138
141584
  var BRIDGE_PROBE_PATH = "/";
141139
141585
  function sessionSummary(env, now) {
141140
141586
  const s = readSessionSync(env);
141141
141587
  if (!s) return { linked: false };
141588
+ if (s.origin === "host") return { linked: true, linkedBy: "host" };
141142
141589
  const ageSeconds = Math.max(0, Math.round((now() - Date.parse(s.capturedAt)) / 1e3));
141143
141590
  return { linked: true, capturedAt: s.capturedAt, ageSeconds };
141144
141591
  }
@@ -141713,7 +142160,7 @@ function captureWarappCookie(opts) {
141713
142160
  }
141714
142161
  async function linkSession(opts = {}) {
141715
142162
  if (isHosted(opts.env ?? process.env)) {
141716
- throw new McpToolError("The direct transport is local-only: a hosted server never links a war.app session.", {
142163
+ throw new McpToolError("Linking a war.app session is local-only: a hosted server reaches war.app directly only from the session captured at sign-in, and never links one.", {
141717
142164
  kind: "unknown"
141718
142165
  });
141719
142166
  }
@@ -141732,7 +142179,10 @@ async function linkSession(opts = {}) {
141732
142179
 
141733
142180
  // src/tools/session.ts
141734
142181
  var HINT_NOT_LINKED = "No war.app session is linked. Run warapp_link_session to use the direct (no-browser) transport; the browser bridge is used until then.";
141735
- var NOTE_HOSTED = "This server is hosted: the direct (no-browser) transport is local-only, so war.app calls go through the browser bridge and your signed-in war.app tab.";
142182
+ var NOTE_HOSTED = "This server is hosted: it reaches war.app directly only from the session captured at sign-in, and this connection has none, so war.app calls go through the browser bridge and your signed-in war.app tab. " + HOST_SIGN_IN_ADVICE;
142183
+ var NOTE_HOSTED_DIRECT = "This server is hosted and signed in to war.app by mcp-host: war.app calls go directly to war.app with the session captured at sign-in, and fall back to the browser bridge only when that session stops working.";
142184
+ var NOTE_HOSTED_MALFORMED = `This server is hosted, and the war.app session mcp-host passed it is not usable, so war.app calls go through the browser bridge and your signed-in war.app tab. ${HOST_SIGN_IN_ADVICE}`;
142185
+ var HINT_HOST_EXPIRED = `The war.app session this connection signed in with is signed out. ${HOST_SIGN_IN_ADVICE}`;
141736
142186
  var HINT_EXPIRED = "The linked war.app session is signed out (war.app answered a direct call signed-out this run). Run warapp_link_session to relink.";
141737
142187
  function noBrowserNote(hosted) {
141738
142188
  return hosted ? "" : " Works without a browser once a session is linked (warapp_link_session).";
@@ -141742,6 +142192,7 @@ function registerSessionTools(server, deps) {
141742
142192
  const link3 = deps.link ?? ((opts) => linkSession({ ...deps.env ? { env: deps.env } : {}, ...opts }));
141743
142193
  const now = deps.now ?? Date.now;
141744
142194
  const hosted = deps.hosted ?? isHosted(deps.env ?? process.env);
142195
+ const hostToken = hosted ? deps.hostToken ?? hostedTokenState(deps.env ?? process.env) : "none";
141745
142196
  const decoderView = () => {
141746
142197
  if (!deps.decoder) return {};
141747
142198
  const d = deps.decoder();
@@ -141764,13 +142215,30 @@ function registerSessionTools(server, deps) {
141764
142215
  {
141765
142216
  title: "war.app direct-transport session status",
141766
142217
  description: untrustedDescription(
141767
- hosted ? "Report which transport serves war.app calls on this hosted server (always the browser bridge: the direct, no-browser transport is local-only) and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Read-only." : "Report whether a signed-in war.app session is linked for the direct (no-browser) transport, when it was captured and how old it is, which transport is currently active (direct, or the browser bridge), and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Never shows the session cookie. Read-only; use warapp_link_session to link or relink."
142218
+ hosted && hostToken === "ok" ? "Report which transport serves war.app calls on this hosted server (direct to war.app with the session mcp-host captured at sign-in, or the browser bridge after that session stops working) and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Never shows the session cookie. Read-only." : hosted ? "Report which transport serves war.app calls on this hosted server (the browser bridge: hosted, the direct, no-browser transport runs only from the session captured at sign-in, and this connection has none) and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Read-only." : "Report whether a signed-in war.app session is linked for the direct (no-browser) transport, when it was captured and how old it is, which transport is currently active (direct, or the browser bridge), and which transport the turn-notification push socket rides (websocket or xhr-polling) once it has run, and, once a live board has been read, which client bundle decodes boards (a cached stand-in or not) and which of its reader helpers were verified. Never shows the session cookie. Read-only; use warapp_link_session to link or relink."
141768
142219
  ),
141769
142220
  _meta: lookupMeta(["war.app session", "is war.app linked", "direct transport status"]),
141770
142221
  annotations: readAnnotations("war.app session status"),
141771
142222
  inputSchema: external_exports.object({})
141772
142223
  },
141773
142224
  async () => {
142225
+ if (hosted && hostToken === "ok") {
142226
+ const pt2 = deps.pushTransport?.();
142227
+ const base = {
142228
+ hosted: true,
142229
+ linked: true,
142230
+ linkedBy: "host",
142231
+ activeTransport: deps.transport.activeLeg(),
142232
+ ...pt2 ? { pushTransport: pt2 } : {},
142233
+ ...decoderView(),
142234
+ hostedNote: NOTE_HOSTED_DIRECT
142235
+ };
142236
+ return respond(
142237
+ void 0,
142238
+ ["compact"],
142239
+ () => deps.transport.sessionStale() ? { ...base, sessionExpired: true, hint: HINT_HOST_EXPIRED } : base
142240
+ );
142241
+ }
141774
142242
  if (hosted) {
141775
142243
  const pt2 = deps.pushTransport?.();
141776
142244
  return respond(void 0, ["compact"], () => ({
@@ -141779,7 +142247,7 @@ function registerSessionTools(server, deps) {
141779
142247
  activeTransport: "fetchproxy",
141780
142248
  ...pt2 ? { pushTransport: pt2 } : {},
141781
142249
  ...decoderView(),
141782
- hostedNote: NOTE_HOSTED
142250
+ hostedNote: hostToken === "malformed" ? NOTE_HOSTED_MALFORMED : NOTE_HOSTED
141783
142251
  }));
141784
142252
  }
141785
142253
  const session = await read();
@@ -141853,7 +142321,7 @@ async function openGamesPage(ctx) {
141853
142321
  } catch (e) {
141854
142322
  throw new McpToolError(`Could not read war.app's open games page: ${e instanceof Error ? e.message : String(e)}`, {
141855
142323
  kind: "unknown",
141856
- hint: (ctx.hosted ? "Make sure" : "Link a session with warapp_link_session to read it without a browser, or make sure") + " a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.",
142324
+ hint: ctx.hosted && ctx.hostSignIn ? `${HOST_SIGN_IN_ADVICE} Then retry.` : (ctx.hosted ? "Make sure" : "Link a session with warapp_link_session to read it without a browser, or make sure") + " a signed-in war.app tab is open and paired (reload or focus it if it is frozen), then retry.",
141857
142325
  cause: e
141858
142326
  });
141859
142327
  }
@@ -142090,7 +142558,7 @@ function registerJoinGameTool(server, ctx) {
142090
142558
  async plan({ game_id, allow_team, team: askedTeam, accept_entry_fee, color: requested }) {
142091
142559
  const gameId = parseGameId(game_id);
142092
142560
  const [html, me] = await Promise.all([openGamesPage(ctx), ctx.myIdentity({ fresh: true })]);
142093
- if (me === void 0) throw accountUnknown(ctx.hosted);
142561
+ if (me === void 0) throw accountUnknown(ctx);
142094
142562
  const { token, inGameId: myId } = me;
142095
142563
  const bundle = await ctx.bundle();
142096
142564
  const parsed = parseOpenGamesPage(html, bundle);
@@ -144779,7 +145247,7 @@ function registerTeamBriefTool(server, ctx) {
144779
145247
  async ({ game_id }) => {
144780
145248
  const gameId = parseGameId(game_id);
144781
145249
  const identity = await ctx.myIdentity().catch(() => void 0);
144782
- if (!identity) throw accountUnknown(ctx.hosted, "your team brief cannot be read");
145250
+ if (!identity) throw accountUnknown(ctx, "your team brief cannot be read");
144783
145251
  const feed = await ctx.client.getGame(gameId, { settings: true });
144784
145252
  if (feed.state !== PLAYING4 && feed.state !== DISTRIBUTING5) {
144785
145253
  throw new McpToolError(`Game ${feed.id} is not being picked or played (game state: ${feed.state}), so there is nothing to brief.`, {
@@ -145367,408 +145835,6 @@ function parsePacket(raw) {
145367
145835
  }
145368
145836
  }
145369
145837
 
145370
- // node_modules/@chrischall/mcp-utils/dist/netguard/index.js
145371
- var import_undici = __toESM(require_undici(), 1);
145372
- import { lookup as dnsLookup } from "node:dns/promises";
145373
- import { isIP as isIP2 } from "node:net";
145374
- var systemResolver = async (hostname3) => (await dnsLookup(hostname3, { all: true, verbatim: true })).map((a) => a.address);
145375
- function refuseHost(hostname3) {
145376
- return new UrlNotAllowedError(`Refusing to connect to ${hostname3}: it is, or resolves to, a private, loopback, link-local or reserved address.`, "host");
145377
- }
145378
- function createPublicOnlyDispatcher(opts = {}) {
145379
- const resolve2 = opts.resolve ?? systemResolver;
145380
- const allowed = opts.isAllowedAddress ?? isPublicAddress;
145381
- const lookup = (hostname3, options, callback2) => {
145382
- resolve2(hostname3).then((addresses) => {
145383
- if (addresses.length === 0 || !addresses.every(allowed)) {
145384
- callback2(refuseHost(hostname3), "", 0);
145385
- return;
145386
- }
145387
- const entries2 = addresses.map((address) => ({ address, family: isIP2(address) }));
145388
- if (options.all) {
145389
- callback2(null, entries2);
145390
- return;
145391
- }
145392
- const wanted = options.family === 4 || options.family === 6 ? options.family : 0;
145393
- const pick5 = entries2.find((e) => wanted === 0 || e.family === wanted) ?? entries2[0];
145394
- callback2(null, pick5.address, pick5.family);
145395
- }, (err) => callback2(err, "", 0));
145396
- };
145397
- const inner = (0, import_undici.buildConnector)({ ...opts.connect, lookup });
145398
- const connect = (options, callback2) => {
145399
- const host = options.hostname.replace(/^\[|\]$/g, "");
145400
- if (isIP2(host) !== 0 && !allowed(host)) {
145401
- callback2(refuseHost(options.hostname), null);
145402
- return;
145403
- }
145404
- inner(options, callback2);
145405
- };
145406
- return new import_undici.Agent({ ...opts.agent, connect });
145407
- }
145408
- var REDIRECT_STATUSES2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
145409
- var CROSS_ORIGIN_DROPPED = ["authorization", "cookie", "proxy-authorization"];
145410
- function findUrlRefusal(err) {
145411
- let e = err;
145412
- for (let i2 = 0; i2 < 8 && e; i2 += 1) {
145413
- if (e instanceof UrlNotAllowedError)
145414
- return e;
145415
- e = e.cause;
145416
- }
145417
- return void 0;
145418
- }
145419
- async function fetchPublic(url4, opts = {}) {
145420
- const { maxRedirects = 10, timeoutMs, maxBytes, signal: callerSignal, dispatcher: given2, requireHttps, allowHosts, stopBefore, resolve: resolve2, isAllowedAddress, headers: initHeaders, method: initMethod, body: initBody, ...init } = opts;
145421
- if (!Number.isInteger(maxRedirects) || maxRedirects < 0) {
145422
- throw new TypeError("fetchPublic: maxRedirects must be a non-negative integer.");
145423
- }
145424
- const check2 = (target) => assertAllowedUrl(target, {
145425
- allowHosts: allowHosts ?? [/(?:)/],
145426
- ...requireHttps !== void 0 ? { requireHttps } : {}
145427
- });
145428
- let current2 = check2(url4);
145429
- const origin = current2.origin;
145430
- if (stopBefore?.(current2))
145431
- return { stopped: true, url: current2.href, hops: 0 };
145432
- const timeout = timeoutMs !== void 0 ? AbortSignal.timeout(timeoutMs) : void 0;
145433
- const signals = [callerSignal, timeout].filter((s) => s !== void 0);
145434
- const signal = signals.length > 0 ? AbortSignal.any(signals) : void 0;
145435
- const owned = given2 === void 0 ? createPublicOnlyDispatcher({
145436
- ...resolve2 ? { resolve: resolve2 } : {},
145437
- ...isAllowedAddress ? { isAllowedAddress } : {}
145438
- }) : void 0;
145439
- const dispatcher = given2 ?? owned;
145440
- let method = (initMethod ?? "GET").toUpperCase();
145441
- let body = initBody;
145442
- const headers = new import_undici.Headers(initHeaders);
145443
- const fail = (err) => {
145444
- if (callerSignal?.aborted)
145445
- throw callerSignal.reason;
145446
- if (timeout?.aborted)
145447
- throw new RequestTimeoutError(current2.host, timeoutMs);
145448
- const refused = findUrlRefusal(err);
145449
- if (refused)
145450
- throw refused;
145451
- if (err instanceof McpToolError)
145452
- throw err;
145453
- throw new McpToolError(`Could not reach ${current2.host}.`, {
145454
- kind: "transport",
145455
- hint: "Check the link is reachable from the server.",
145456
- cause: err
145457
- });
145458
- };
145459
- try {
145460
- for (let hops = 0; ; ) {
145461
- let res;
145462
- try {
145463
- res = await (0, import_undici.fetch)(current2, {
145464
- ...init,
145465
- method,
145466
- headers,
145467
- ...body !== void 0 && body !== null ? { body } : {},
145468
- redirect: "manual",
145469
- dispatcher,
145470
- ...signal ? { signal } : {}
145471
- });
145472
- } catch (err) {
145473
- return fail(err);
145474
- }
145475
- const location = REDIRECT_STATUSES2.has(res.status) ? res.headers.get("location") : null;
145476
- if (location === null) {
145477
- let bytes;
145478
- try {
145479
- bytes = await readBytesCapped(res, maxBytes, current2.host, (p) => p);
145480
- } catch (err) {
145481
- return fail(err);
145482
- }
145483
- return { stopped: false, url: current2.href, hops, status: res.status, headers: res.headers, body: bytes };
145484
- }
145485
- await res.body?.cancel().catch(() => {
145486
- });
145487
- if (hops >= maxRedirects) {
145488
- throw new RedirectRefusedError(`Refusing to follow more than ${maxRedirects} redirects (last from ${current2.host}).`);
145489
- }
145490
- let next;
145491
- try {
145492
- next = new URL(location, current2);
145493
- } catch {
145494
- throw new UrlNotAllowedError("The redirect target is not a valid URL.", "invalid");
145495
- }
145496
- next = check2(next);
145497
- hops += 1;
145498
- if (res.status === 303 || (res.status === 301 || res.status === 302) && method === "POST") {
145499
- if (method !== "HEAD")
145500
- method = "GET";
145501
- body = void 0;
145502
- for (const h of ["content-type", "content-length", "content-encoding", "content-language", "content-location"]) {
145503
- headers.delete(h);
145504
- }
145505
- }
145506
- if (next.origin !== origin)
145507
- for (const h of CROSS_ORIGIN_DROPPED)
145508
- headers.delete(h);
145509
- current2 = next;
145510
- if (stopBefore?.(current2))
145511
- return { stopped: true, url: current2.href, hops };
145512
- }
145513
- } finally {
145514
- if (owned)
145515
- await owned.destroy().catch(() => {
145516
- });
145517
- }
145518
- }
145519
-
145520
- // src/direct/transport.ts
145521
- var TRANSPORT_ENV = "WARAPP_TRANSPORT";
145522
- var MAX_DIRECT_BODY_BYTES = 16 * 1024 * 1024;
145523
- var DIRECT_TIMEOUT_MS = 3e4;
145524
- var SessionNotLinkedError = class extends McpToolError {
145525
- name = "SessionNotLinkedError";
145526
- constructor() {
145527
- super("No war.app session is linked for the direct transport. Run warapp_link_session to capture one.", {
145528
- kind: "no_credential"
145529
- });
145530
- }
145531
- };
145532
- var SessionExpiredError = class extends McpToolError {
145533
- name = "SessionExpiredError";
145534
- /** When the expired session was captured (non-secret), so a relink can be told apart. */
145535
- capturedAt;
145536
- constructor(opts = {}) {
145537
- super(
145538
- "The linked war.app session is no longer signed in. " + (opts.notResent ? "The request had already reached war.app, so it was not re-sent over the browser bridge (a write must never be sent twice); later calls use the bridge. Retry, or run warapp_link_session to relink." : "Run warapp_link_session to relink."),
145539
- { kind: "session_expired" }
145540
- );
145541
- this.capturedAt = opts.capturedAt;
145542
- }
145543
- };
145544
- var decoder = new TextDecoder();
145545
- var isSafeToReplay = (method) => /^(?:GET|HEAD)$/i.test(method);
145546
- var SESSION_ORIGIN = `https://${SESSION_HOST}`;
145547
- var MAX_DIRECT_GET_REDIRECTS = 5;
145548
- var UNFOLLOWED_REDIRECT_STATUS = 302;
145549
- function directFetchOptions(method) {
145550
- const base = { requireHttps: true, allowHosts: [SESSION_HOST] };
145551
- if (isSafeToReplay(method)) {
145552
- return { ...base, maxRedirects: MAX_DIRECT_GET_REDIRECTS, stopBefore: (url4) => url4.origin !== SESSION_ORIGIN };
145553
- }
145554
- let first = true;
145555
- return {
145556
- ...base,
145557
- maxRedirects: 1,
145558
- stopBefore: () => {
145559
- if (first) {
145560
- first = false;
145561
- return false;
145562
- }
145563
- return true;
145564
- }
145565
- };
145566
- }
145567
- function toDirectResult(res) {
145568
- if ("stopped" in res && res.stopped) return { status: UNFOLLOWED_REDIRECT_STATUS, body: "", url: res.url };
145569
- const done = res;
145570
- const out = { status: done.status, body: decoder.decode(done.body), url: done.url };
145571
- if (done.headers) {
145572
- const headers = {};
145573
- done.headers.forEach((v, k) => {
145574
- headers[k.toLowerCase()] = v;
145575
- });
145576
- out.headers = headers;
145577
- }
145578
- return out;
145579
- }
145580
- var fetchViaPublic = async (url4, init) => {
145581
- const res = await fetchPublic(url4, {
145582
- ...directFetchOptions(init.method),
145583
- method: init.method,
145584
- headers: init.headers,
145585
- maxBytes: MAX_DIRECT_BODY_BYTES,
145586
- timeoutMs: DIRECT_TIMEOUT_MS,
145587
- ...init.body !== void 0 ? { body: init.body } : {},
145588
- ...init.signal ? { signal: init.signal } : {}
145589
- });
145590
- return toDirectResult(res);
145591
- };
145592
- function warappUrl(path) {
145593
- const raw = /^https?:\/\//i.test(path) ? path : `https://${SESSION_HOST}${path.startsWith("/") ? "" : "/"}${path}`;
145594
- let u;
145595
- try {
145596
- u = new URL(raw);
145597
- } catch {
145598
- throw new McpToolError(`The direct transport could not parse the request path.`, { kind: "unknown" });
145599
- }
145600
- if (u.hostname !== SESSION_HOST || u.port !== "" || u.username !== "" || u.password !== "") {
145601
- throw new McpToolError(`The direct transport only talks to ${SESSION_HOST}.`, { kind: "unknown" });
145602
- }
145603
- if (u.protocol !== "https:") {
145604
- throw new McpToolError("The direct transport requires https.", { kind: "unknown" });
145605
- }
145606
- return u.href;
145607
- }
145608
- var SIGNIN_PATH = /\/(?:sign-?in|log-?in)\b/i;
145609
- var INPUT_TAG = /<input(?=[\s/>])/gi;
145610
- var TAG_ATTR = /\s*(?:(>)|([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>`=]+)))?|\/)/y;
145611
- var NOT_MARKUP = /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title)\b[^>]*(?:>|$)[\s\S]*?(?:<\/\1\s*>|$)/gi;
145612
- function hasPasswordInput(raw) {
145613
- const body = raw.replace(NOT_MARKUP, " ");
145614
- INPUT_TAG.lastIndex = 0;
145615
- for (let m = INPUT_TAG.exec(body); m; m = INPUT_TAG.exec(body)) {
145616
- TAG_ATTR.lastIndex = INPUT_TAG.lastIndex;
145617
- for (let a = TAG_ATTR.exec(body); a && !a[1]; a = TAG_ATTR.exec(body)) {
145618
- const name = a[2]?.toLowerCase();
145619
- const value = (a[3] ?? a[4] ?? a[5] ?? "").trim().toLowerCase();
145620
- if ((name === "type" || name === "name") && value === "password") return true;
145621
- }
145622
- }
145623
- return false;
145624
- }
145625
- function looksLikeHexFrame(body) {
145626
- const t = body.trim();
145627
- return t.length > 0 && t.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(t);
145628
- }
145629
- function looksSignedOut(requestedUrl, res) {
145630
- let finalPath = "";
145631
- try {
145632
- finalPath = new URL(res.url).pathname;
145633
- } catch {
145634
- finalPath = "";
145635
- }
145636
- if (SIGNIN_PATH.test(finalPath)) return true;
145637
- if (res.status === 401 || res.status === 403) return true;
145638
- if (res.status !== 200) return false;
145639
- if (hasPasswordInput(res.body)) return true;
145640
- let reqPath = "";
145641
- try {
145642
- reqPath = new URL(requestedUrl).pathname;
145643
- } catch {
145644
- reqPath = "";
145645
- }
145646
- if (/\/services\b/i.test(reqPath) && !looksLikeHexFrame(res.body)) return true;
145647
- return false;
145648
- }
145649
- var DirectBridge = class {
145650
- constructor(store, fetchImpl = fetchViaPublic) {
145651
- this.store = store;
145652
- this.fetchImpl = fetchImpl;
145653
- }
145654
- store;
145655
- fetchImpl;
145656
- async fetch(init, signal) {
145657
- const sess = await this.store.read();
145658
- if (!sess) throw new SessionNotLinkedError();
145659
- const token = sess.authToken;
145660
- const url4 = warappUrl(init.path);
145661
- const headers = { ...init.headers ?? {}, cookie: `AuthToken=${token}` };
145662
- let res;
145663
- try {
145664
- res = await this.fetchImpl(url4, {
145665
- method: init.method,
145666
- headers,
145667
- ...init.body !== void 0 ? { body: init.body } : {},
145668
- ...signal ? { signal } : {}
145669
- });
145670
- } catch (err) {
145671
- throw scrubError(err, [token]);
145672
- }
145673
- const answered = res.status === 200 && looksLikeHexFrame(res.body);
145674
- if (!answered && (res.status !== 200 || res.headers?.["cf-mitigated"])) {
145675
- const edge = detectEdgeBlock({ body: res.body, ...res.headers ? { headers: res.headers } : {}, status: res.status });
145676
- if (edge) {
145677
- throw new EdgeBlockedError(res.status, edge.vendor, {
145678
- service: SESSION_HOST,
145679
- method: init.method,
145680
- path: new URL(url4).pathname
145681
- });
145682
- }
145683
- }
145684
- if (looksSignedOut(url4, res)) throw new SessionExpiredError({ capturedAt: sess.capturedAt });
145685
- return { status: res.status, body: res.body, url: res.url };
145686
- }
145687
- };
145688
- var RELINK_CHECK_MS = 5e3;
145689
- function createDirectFirstBridge(opts) {
145690
- const hosted = isHosted(opts.env ?? process.env);
145691
- const mode = hosted ? "fetchproxy" : opts.mode ?? readTransportMode(TRANSPORT_ENV, opts.env ? { env: opts.env } : {});
145692
- const store = hosted ? { read: async () => null } : opts.store;
145693
- const direct = new DirectBridge(store, opts.directFetch);
145694
- const log = opts.log ?? ((m) => console.error(m));
145695
- const now = opts.now ?? Date.now;
145696
- let wall = null;
145697
- let stale = false;
145698
- let lastRelinkCheck = Number.NEGATIVE_INFINITY;
145699
- const onFallback = ({ error: error62 }) => {
145700
- const next = error62 instanceof SessionExpiredError ? { kind: "session", capturedAt: error62.capturedAt ?? null } : error62 instanceof SessionNotLinkedError ? { kind: "session", capturedAt: null } : { kind: "edge" };
145701
- wall = next;
145702
- const why = error62 instanceof SessionExpiredError ? "the linked war.app session is signed out" : error62 instanceof SessionNotLinkedError ? "no war.app session is linked" : "the site edge refused the direct request";
145703
- log(
145704
- `[warapp-mcp] Direct transport unavailable (${why}) \u2014 switching to the ContextMint Bridge browser bridge. Keep a ${SESSION_HOST} tab open and approve the pairing prompt in the extension if one appears` + (next.kind === "session" && !hosted ? "; run warapp_link_session to return to the direct transport." : ".")
145705
- );
145706
- };
145707
- const build2 = () => createDirectFirstTransport({
145708
- direct,
145709
- bridge: opts.makeBridge,
145710
- mode,
145711
- serverName: "warapp-mcp",
145712
- hostLabel: SESSION_HOST,
145713
- shouldFallBack: (err) => err instanceof SessionExpiredError || err instanceof SessionNotLinkedError || err instanceof EdgeBlockedError,
145714
- bridgeHealth: (b) => b.transport(),
145715
- onFallback
145716
- });
145717
- let legs = build2();
145718
- const liftSessionWall = () => {
145719
- if (wall?.kind !== "session") return;
145720
- wall = null;
145721
- legs = build2();
145722
- };
145723
- const relinkedSinceWall = async () => {
145724
- if (wall?.kind !== "session") return false;
145725
- const t = now();
145726
- if (t - lastRelinkCheck < RELINK_CHECK_MS) return false;
145727
- lastRelinkCheck = t;
145728
- const sess = await store.read();
145729
- return sess !== null && sess.capturedAt !== wall.capturedAt;
145730
- };
145731
- const runOne = async (init) => {
145732
- if (mode === "auto" && await relinkedSinceWall()) {
145733
- liftSessionWall();
145734
- stale = false;
145735
- }
145736
- let reached;
145737
- return legs.run(async (leg, ctx) => {
145738
- if (leg === direct) {
145739
- try {
145740
- const res = await direct.fetch(init, ctx.signal);
145741
- if (res.status === 200) stale = false;
145742
- return res;
145743
- } catch (err) {
145744
- if (err instanceof SessionExpiredError) {
145745
- stale = true;
145746
- if (!isSafeToReplay(init.method)) reached = err;
145747
- }
145748
- throw err;
145749
- }
145750
- }
145751
- if (reached) throw new SessionExpiredError({ capturedAt: reached.capturedAt, notResent: true });
145752
- return leg.ready().then((t) => t.fetch(init));
145753
- });
145754
- };
145755
- return {
145756
- ready: async () => ({ fetch: (init) => runOne(init) }),
145757
- status: () => legs.status(),
145758
- bridgeTransport: () => legs.bridgeTransport(),
145759
- stats: () => legs.stats(),
145760
- sessionStale: () => stale,
145761
- sessionLinked: () => {
145762
- stale = false;
145763
- if (mode === "auto") liftSessionWall();
145764
- },
145765
- identityState: async () => {
145766
- const sess = await store.read();
145767
- return JSON.stringify([legs.status().transport, stale, sess?.capturedAt ?? null]);
145768
- }
145769
- };
145770
- }
145771
-
145772
145838
  // src/push/websocket.ts
145773
145839
  var defaultWebSocketFactory = (url4, init) => {
145774
145840
  const Ctor = globalThis.WebSocket;
@@ -146517,6 +146583,247 @@ function pushListenerFor(key, opts) {
146517
146583
  return l;
146518
146584
  }
146519
146585
 
146586
+ // src/direct/sign-in.ts
146587
+ var import_undici2 = __toESM(require_undici(), 1);
146588
+ var ORIGIN = `https://${SESSION_HOST}`;
146589
+ var SIGN_IN_URL = `${ORIGIN}/LogIn`;
146590
+ var AUTH_COOKIE2 = "AuthToken";
146591
+ var MAX_REDIRECTS = 3;
146592
+ var MIN_SCRUBBED_COOKIE = 6;
146593
+ var SIGN_IN_TIMEOUT_MS = 3e4;
146594
+ var SIGN_IN_MAX_BODY_BYTES = 2 * 1024 * 1024;
146595
+ function createSignInFetch(opts = {}) {
146596
+ const maxBytes = opts.maxBytes ?? SIGN_IN_MAX_BODY_BYTES;
146597
+ return async (url4, init) => {
146598
+ const owned = opts.dispatcher ? void 0 : createPublicOnlyDispatcher();
146599
+ try {
146600
+ const res = await (0, import_undici2.fetch)(url4, {
146601
+ method: init.method,
146602
+ headers: init.headers,
146603
+ ...init.body !== void 0 ? { body: init.body } : {},
146604
+ redirect: "manual",
146605
+ dispatcher: opts.dispatcher ?? owned,
146606
+ signal: init.signal
146607
+ });
146608
+ const headers = {};
146609
+ res.headers.forEach((v, k) => {
146610
+ if (k.toLowerCase() !== "set-cookie") headers[k.toLowerCase()] = v;
146611
+ });
146612
+ const setCookies = res.headers.getSetCookie();
146613
+ const body = await readCapped2(res.body, maxBytes);
146614
+ return { status: res.status, headers, setCookies, body };
146615
+ } finally {
146616
+ await owned?.close().catch(() => {
146617
+ });
146618
+ }
146619
+ };
146620
+ }
146621
+ async function readCapped2(body, maxBytes) {
146622
+ if (!body) return "";
146623
+ const chunks = [];
146624
+ let total = 0;
146625
+ for await (const chunk2 of body) {
146626
+ total += chunk2.byteLength;
146627
+ if (total > maxBytes) {
146628
+ throw new McpToolError(`war.app's sign-in answered with more than ${maxBytes} bytes.`, { kind: "too_large" });
146629
+ }
146630
+ chunks.push(chunk2);
146631
+ }
146632
+ return Buffer.concat(chunks).toString("utf8");
146633
+ }
146634
+ function parseSetCookie(header, now = Date.now()) {
146635
+ const [pair2 = "", ...attrs] = header.split(";");
146636
+ const eq = pair2.indexOf("=");
146637
+ if (eq <= 0) return null;
146638
+ const name = pair2.slice(0, eq).trim();
146639
+ if (!name) return null;
146640
+ let value = pair2.slice(eq + 1).trim();
146641
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) value = value.slice(1, -1);
146642
+ for (const attr of attrs) {
146643
+ const i2 = attr.indexOf("=");
146644
+ const key = (i2 < 0 ? attr : attr.slice(0, i2)).trim().toLowerCase();
146645
+ const v = i2 < 0 ? "" : attr.slice(i2 + 1).trim();
146646
+ if (key === "max-age" && /^-?\d+$/.test(v) && Number(v) <= 0) value = null;
146647
+ if (key === "expires") {
146648
+ const t = Date.parse(v);
146649
+ if (!Number.isNaN(t) && t <= now) value = null;
146650
+ }
146651
+ }
146652
+ if (value === "") value = null;
146653
+ return { name, value };
146654
+ }
146655
+ function onWarapp(url4) {
146656
+ return url4.origin === ORIGIN && url4.username === "" && url4.password === "";
146657
+ }
146658
+ var REDIRECTS = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
146659
+ var CHALLENGE_MARKUP = /g-recaptcha|grecaptcha|recaptcha\/api|h-captcha|hcaptcha\.com|cf-turnstile|challenges\.cloudflare\.com/i;
146660
+ var NOT_RETRIED = "It was not retried, because war.app may count failed sign-ins.";
146661
+ function refusal2(kind, message, hint) {
146662
+ return new McpToolError(message, { kind, ...hint ? { hint } : {} });
146663
+ }
146664
+ function challenge(what) {
146665
+ return refusal2(
146666
+ "edge_blocked",
146667
+ `war.app answered the sign-in with ${what}, which this connector cannot answer. ${NOT_RETRIED}`,
146668
+ "Wait a while and use Sign in on the connection again. Until then the connection still works through the war.app tab (the browser bridge); if it keeps happening, report it."
146669
+ );
146670
+ }
146671
+ function challengeIn(res) {
146672
+ const edge = detectEdgeBlock({ body: res.body, headers: res.headers, status: res.status });
146673
+ if (edge) return challenge(`a ${edge.vendor} bot check`);
146674
+ if (res.status === 429) return challenge('"too many requests" (HTTP 429)');
146675
+ if (CHALLENGE_MARKUP.test(res.body)) return challenge("a captcha");
146676
+ if (res.status === 403) return challenge("a refusal (HTTP 403)");
146677
+ return null;
146678
+ }
146679
+ async function signIn(creds, opts = {}) {
146680
+ const jar = /* @__PURE__ */ new Map();
146681
+ const secrets = () => [
146682
+ { value: creds.email, anyCase: true },
146683
+ creds.password,
146684
+ ...[...jar.values()].filter((v) => v.length >= MIN_SCRUBBED_COOKIE)
146685
+ ];
146686
+ try {
146687
+ return await exchange(creds, jar, opts);
146688
+ } catch (err) {
146689
+ throw scrubbed(err, secrets());
146690
+ }
146691
+ }
146692
+ async function exchange(creds, jar, opts) {
146693
+ if (!creds.email.trim() || !creds.password) {
146694
+ throw refusal2("no_credential", "Signing in to war.app needs both the email and the password; nothing was sent.");
146695
+ }
146696
+ const fetchHop = opts.fetch ?? createSignInFetch();
146697
+ const timeoutMs = opts.timeoutMs ?? SIGN_IN_TIMEOUT_MS;
146698
+ const timeout = AbortSignal.timeout(timeoutMs);
146699
+ const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
146700
+ let posted = false;
146701
+ const hop = async (url4, method, body) => {
146702
+ const headers = { accept: "text/html,application/xhtml+xml" };
146703
+ if (jar.size > 0) headers.cookie = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
146704
+ if (method === "POST") {
146705
+ headers["content-type"] = "application/x-www-form-urlencoded";
146706
+ headers.origin = ORIGIN;
146707
+ headers.referer = SIGN_IN_URL;
146708
+ }
146709
+ let res;
146710
+ try {
146711
+ res = await fetchHop(url4.href, { method, headers, ...body !== void 0 ? { body } : {}, signal });
146712
+ } catch (err) {
146713
+ if (opts.signal?.aborted) throw opts.signal.reason;
146714
+ const after = posted ? " The sign-in may or may not have reached war.app; it was not retried." : " Nothing was sent to war.app.";
146715
+ if (timeout.aborted) {
146716
+ throw refusal2("timeout", `war.app did not answer the sign-in within ${Math.round(timeoutMs / 1e3)} s.${after}`);
146717
+ }
146718
+ if (err instanceof McpToolError && err.kind === "too_large") throw err;
146719
+ throw refusal2("transport", `Could not reach war.app to sign in.${after}`);
146720
+ }
146721
+ for (const header of res.setCookies) {
146722
+ const c = parseSetCookie(header);
146723
+ if (!c) continue;
146724
+ if (c.value === null) jar.delete(c.name);
146725
+ else jar.set(c.name, c.value);
146726
+ }
146727
+ return res;
146728
+ };
146729
+ const follow = async (from, first) => {
146730
+ let url4 = from;
146731
+ let res = first;
146732
+ for (let n = 0; ; n++) {
146733
+ if (posted && jar.has(AUTH_COOKIE2)) return { url: url4, res };
146734
+ const location = REDIRECTS.has(res.status) ? res.headers.location : void 0;
146735
+ if (!location) return { url: url4, res };
146736
+ let next;
146737
+ try {
146738
+ next = new URL(location, url4);
146739
+ } catch {
146740
+ throw refusal2("unknown", `war.app redirected the sign-in to an address that does not parse. ${NOT_RETRIED}`);
146741
+ }
146742
+ if (!onWarapp(next)) {
146743
+ throw refusal2("unknown", `war.app redirected the sign-in away from ${ORIGIN}; it was not followed. ${NOT_RETRIED}`);
146744
+ }
146745
+ if (n >= MAX_REDIRECTS) {
146746
+ throw refusal2("unknown", `war.app redirected the sign-in more than ${MAX_REDIRECTS} times. ${NOT_RETRIED}`);
146747
+ }
146748
+ url4 = next;
146749
+ res = await hop(url4, "GET");
146750
+ }
146751
+ };
146752
+ const page2 = await follow(new URL(SIGN_IN_URL), await hop(new URL(SIGN_IN_URL), "GET"));
146753
+ const pageCheck = challengeIn(page2.res);
146754
+ if (pageCheck) throw pageCheck;
146755
+ if (page2.res.status !== 200 || !hasPasswordInput(page2.res.body)) {
146756
+ throw refusal2(
146757
+ "http",
146758
+ `war.app's sign-in page did not show its form (HTTP ${page2.res.status}); no password was sent.`,
146759
+ "war.app may be down or have changed its sign-in page. Try Sign in again later."
146760
+ );
146761
+ }
146762
+ jar.delete(AUTH_COOKIE2);
146763
+ const form = new URLSearchParams({ Email: creds.email.trim(), Password: creds.password, KeepSignedIn: "on" });
146764
+ posted = true;
146765
+ const postUrl = new URL(SIGN_IN_URL);
146766
+ const done = await follow(postUrl, await hop(postUrl, "POST", form.toString()));
146767
+ const token = jar.get(AUTH_COOKIE2);
146768
+ if (token) {
146769
+ if (isPlausibleAuthToken(token)) return { authToken: token };
146770
+ throw refusal2(
146771
+ "unknown",
146772
+ "war.app signed in, but its session cookie is not in a shape this connector can use; it was not kept.",
146773
+ "war.app may have changed its session cookie. Report this; nothing was retried."
146774
+ );
146775
+ }
146776
+ const check2 = challengeIn(done.res);
146777
+ if (check2) throw check2;
146778
+ if (hasPasswordInput(done.res.body)) {
146779
+ throw refusal2(
146780
+ "credential_rejected",
146781
+ `war.app refused the sign-in: the email or password is not right (its sign-in form came back). ${NOT_RETRIED}`,
146782
+ "Check the war.app password (and the email on this connection), then use Sign in on the connection again."
146783
+ );
146784
+ }
146785
+ throw refusal2(
146786
+ done.res.status >= 400 ? "http" : "unknown",
146787
+ `war.app answered the sign-in (HTTP ${done.res.status}) without setting a session. ${NOT_RETRIED}`,
146788
+ "war.app may have changed how it signs in. Try Sign in again later."
146789
+ );
146790
+ }
146791
+ function scrubbed(err, secrets) {
146792
+ const e = err;
146793
+ const scrub = (s) => scrubSecrets(s, secrets);
146794
+ const message = scrub(typeof e?.message === "string" ? e.message : String(err));
146795
+ const kind = err instanceof McpToolError && err.kind ? err.kind : "unknown";
146796
+ return new McpToolError(message, { kind, ...typeof e?.hint === "string" ? { hint: scrub(e.hint) } : {} });
146797
+ }
146798
+
146799
+ // src/tools/sign-in.ts
146800
+ function registerSignInTool(server, deps = {}) {
146801
+ const run2 = deps.signIn ?? signIn;
146802
+ server.registerTool(
146803
+ "warapp_sign_in",
146804
+ {
146805
+ title: "Sign in to war.app (host sign-in flow)",
146806
+ description: "For the host's sign-in flow only, not for chat use: signs in to war.app once with the account's email and password and returns the session cookie war.app sets, as `authToken`, which the host keeps as this connection's own secret so later calls reach war.app without a browser. The password is used for this one sign-in and never stored. A refusal (wrong email or password, a captcha or bot check, a network failure) is an error that says which, and is never retried, because war.app may count failed sign-ins.",
146807
+ _meta: mintMeta("other", ["sign in to war.app"]),
146808
+ annotations: toolAnnotations({
146809
+ title: "Sign in to war.app",
146810
+ readOnly: false,
146811
+ destructive: false,
146812
+ idempotent: false,
146813
+ openWorld: true
146814
+ }),
146815
+ inputSchema: external_exports.object({
146816
+ email: external_exports.string().min(1).max(320).describe("The war.app account's email."),
146817
+ password: external_exports.string().min(1).max(1024).describe("The war.app account's password, used once and never stored.")
146818
+ })
146819
+ },
146820
+ async ({ email: email4, password }, ctx) => {
146821
+ const { authToken } = await run2({ email: email4, password }, { signal: ctx.mcpReq.signal });
146822
+ return { content: [{ type: "text", text: JSON.stringify({ authToken }) }] };
146823
+ }
146824
+ );
146825
+ }
146826
+
146520
146827
  // src/tools/index.ts
146521
146828
  function registerAllTools(server, deps = {}) {
146522
146829
  const client = new WarappClient({ ...deps, dataDir: () => dataDir(deps.env) });
@@ -146596,6 +146903,7 @@ function registerAllTools(server, deps = {}) {
146596
146903
  ...env ? { env } : {}
146597
146904
  });
146598
146905
  registerPushTools(server, live, push, deps.env ? { env: deps.env } : {});
146906
+ if (hosted) registerSignInTool(server, deps.signIn ? { signIn: deps.signIn } : {});
146599
146907
  }
146600
146908
 
146601
146909
  // src/index.ts