@g33ks/foundryvtt-mcp 0.0.0-stage → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +457 -2
  3. package/dist/character/manager.js +208 -0
  4. package/dist/cli/checks.js +307 -0
  5. package/dist/cli/config-file.js +120 -0
  6. package/dist/cli/init.js +414 -0
  7. package/dist/cli/prompt.js +117 -0
  8. package/dist/cli/snippets.js +64 -0
  9. package/dist/combat/manager.js +371 -0
  10. package/dist/config/env-layers.js +49 -0
  11. package/dist/config/index.js +298 -0
  12. package/dist/config/sources.js +201 -0
  13. package/dist/core.js +481 -0
  14. package/dist/diagnostics/client.js +291 -0
  15. package/dist/diagnostics/types.js +94 -0
  16. package/dist/foundry/auth.js +224 -0
  17. package/dist/foundry/browser-detect.js +170 -0
  18. package/dist/foundry/client.js +5874 -0
  19. package/dist/foundry/dice-formula.js +154 -0
  20. package/dist/foundry/event-log.js +298 -0
  21. package/dist/foundry/headless-gm-session.js +857 -0
  22. package/dist/foundry/journal-conflicts.js +141 -0
  23. package/dist/foundry/journal-history.js +90 -0
  24. package/dist/foundry/journal-integrity.js +322 -0
  25. package/dist/foundry/message-author.js +19 -0
  26. package/dist/foundry/module-bridge.js +441 -0
  27. package/dist/foundry/types.js +52 -0
  28. package/dist/foundry/world-cache.js +386 -0
  29. package/dist/index.js +107 -0
  30. package/dist/mcp-server.js +65 -0
  31. package/dist/server.js +159 -0
  32. package/dist/shared/build-order.js +134 -0
  33. package/dist/shared/config-hash.js +62 -0
  34. package/dist/shared/config-notice.js +55 -0
  35. package/dist/shared/control.js +291 -0
  36. package/dist/shared/daemon-link.js +135 -0
  37. package/dist/shared/daemon.js +311 -0
  38. package/dist/shared/ipc-client.js +200 -0
  39. package/dist/shared/ipc-server.js +316 -0
  40. package/dist/shared/paths.js +79 -0
  41. package/dist/shared/protocol.js +230 -0
  42. package/dist/shared/relay-config.js +65 -0
  43. package/dist/shared/relay.js +120 -0
  44. package/dist/shared/rotating-log.js +57 -0
  45. package/dist/shared/spawn.js +39 -0
  46. package/dist/shared/state-file.js +33 -0
  47. package/dist/shared/token.js +62 -0
  48. package/dist/shared/version.js +57 -0
  49. package/dist/tools/base.js +74 -0
  50. package/dist/tools/definitions.js +3109 -0
  51. package/dist/tools/handlers/actor-mutations.js +128 -0
  52. package/dist/tools/handlers/actors.js +114 -0
  53. package/dist/tools/handlers/chat-mutations.js +49 -0
  54. package/dist/tools/handlers/chat.js +38 -0
  55. package/dist/tools/handlers/combat-mutations.js +215 -0
  56. package/dist/tools/handlers/combat-order.js +94 -0
  57. package/dist/tools/handlers/combat.js +51 -0
  58. package/dist/tools/handlers/compendium.js +83 -0
  59. package/dist/tools/handlers/diagnostics.js +450 -0
  60. package/dist/tools/handlers/dice.js +54 -0
  61. package/dist/tools/handlers/effects.js +103 -0
  62. package/dist/tools/handlers/events.js +50 -0
  63. package/dist/tools/handlers/generation.js +258 -0
  64. package/dist/tools/handlers/item-mutations.js +132 -0
  65. package/dist/tools/handlers/items.js +53 -0
  66. package/dist/tools/handlers/journal-mutations.js +230 -0
  67. package/dist/tools/handlers/journals.js +80 -0
  68. package/dist/tools/handlers/module-bridge.js +421 -0
  69. package/dist/tools/handlers/placeable-mutations.js +272 -0
  70. package/dist/tools/handlers/resources.js +203 -0
  71. package/dist/tools/handlers/roll-tables.js +97 -0
  72. package/dist/tools/handlers/scene-mutations.js +159 -0
  73. package/dist/tools/handlers/scenes.js +355 -0
  74. package/dist/tools/handlers/settings.js +53 -0
  75. package/dist/tools/handlers/tile-mutations.js +56 -0
  76. package/dist/tools/handlers/token-mutations.js +356 -0
  77. package/dist/tools/handlers/users.js +59 -0
  78. package/dist/tools/handlers/utils.js +48 -0
  79. package/dist/tools/handlers/wall-mutations.js +98 -0
  80. package/dist/tools/handlers/world-documents.js +222 -0
  81. package/dist/tools/handlers/world.js +92 -0
  82. package/dist/tools/index.js +25 -0
  83. package/dist/tools/new-router.js +97 -0
  84. package/dist/tools/registry.js +79 -0
  85. package/dist/tools/resources.js +63 -0
  86. package/dist/tools/router.js +688 -0
  87. package/dist/tools/tool-dependencies.js +194 -0
  88. package/dist/tools/write-tools.js +97 -0
  89. package/dist/utils/cache-instance.js +30 -0
  90. package/dist/utils/cache.js +205 -0
  91. package/dist/utils/diagnostics.js +332 -0
  92. package/dist/utils/guards.js +17 -0
  93. package/dist/utils/image-size.js +160 -0
  94. package/dist/utils/log-args.js +47 -0
  95. package/dist/utils/logger.js +203 -0
  96. package/dist/utils/mcp-errors.js +47 -0
  97. package/dist/utils/refusal.js +30 -0
  98. package/dist/utils/sanitize.js +22 -0
  99. package/dist/utils/serial-queue.js +22 -0
  100. package/package.json +124 -4
@@ -0,0 +1,857 @@
1
+ /**
2
+ * @fileoverview Automatic, invisible GM-tier browser session for the module bridge.
3
+ *
4
+ * {@link ModuleBridge} hosts a WebSocket server that `foundry-module/` (a
5
+ * companion Foundry module) dials into from inside a real, rendered browser
6
+ * tab — canvas screenshots, native dice rolls, and `FilePicker` uploads only
7
+ * exist inside an actual browser engine, not the headless `socket.io-client`
8
+ * connection {@link FoundryClient} uses.
9
+ *
10
+ * The module's own `Hooks.once('ready')` handler only calls `transport.connect()`
11
+ * when `game.user.isGM` — by design (a Player's canvas is fog-of-war-limited,
12
+ * and `game.togglePause()`/`FilePicker.upload()` are GM-gated by Foundry core
13
+ * itself, not just this module). That means *some* browser tab, logged in as
14
+ * a GM/Assistant-GM user, must stay open for the whole session — previously a
15
+ * manual, easy-to-forget setup step (and a common cause of "capture_scene
16
+ * says no module connected" confusion when the human plays as a Player and
17
+ * nobody is logged in as GM anywhere).
18
+ *
19
+ * This class removes that step: it drives a headless Chromium-based tab
20
+ * (via `playwright-core` — the browser given by an explicit executable path,
21
+ * else the first one installed among Chrome, Edge, Brave, Vivaldi, Chromium
22
+ * and Playwright's own Chromium, see `browser-detect.ts`) and keeps it on `/game`
23
+ * for as long as the server runs, in one of two modes:
24
+ *
25
+ * - **Shared** (default, one account): the page reuses {@link FoundryClient}'s
26
+ * own session cookie in a dedicated browser context and never fills the
27
+ * `/join` form. FoundryVTT keeps any number of sockets per session, so the
28
+ * two connections coexist. Only `FoundryClient` authenticates: when the
29
+ * cookie stops opening the game (server restart, world shutdown, 24-hour
30
+ * session expiry) the page asks it for a new session and waits for it.
31
+ * - **Separate account** (`FOUNDRY_HEADLESS_GM_USERNAME` naming another
32
+ * user): the page logs that account in through `/join` itself and logs in
33
+ * again if Foundry kicks it back there.
34
+ *
35
+ * A separate watchdog covers a narrower failure the Foundry-level login
36
+ * check above cannot see: the module's own WebSocket to {@link ModuleBridge}
37
+ * can drop (the module's client-side reconnect logic gives up permanently
38
+ * after 10 capped-backoff attempts) while the Foundry session itself stays
39
+ * perfectly logged in — the page never navigates anywhere, so nothing about
40
+ * the login state changes. `isBridgeConnected` in {@link HeadlessGmSessionOptions}
41
+ * lets the caller wire in `ModuleBridge.isConnected()`; if it stays false for
42
+ * a full grace window while the session is otherwise active, this class force-
43
+ * reloads the page, which re-executes the module's `ready` hook and gives it
44
+ * a fresh `transport.connect()` with its backoff counter reset.
45
+ *
46
+ * Best-effort throughout, matching {@link ModuleBridge}: a launch failure (no
47
+ * browser found) or a login failure (wrong credentials, world not active
48
+ * yet) never takes down the Socket.IO connection or the 100+ tools that don't
49
+ * need a browser at all — canvas-only tools just keep reporting "module not
50
+ * connected" until this resolves itself or the operator fixes the cause.
51
+ */
52
+ import { chromium } from 'playwright-core';
53
+ import { logger } from '../utils/logger.js';
54
+ import { browserNameFromPath, findBrowsers, noBrowserMessage, } from './browser-detect.js';
55
+ /**
56
+ * Detection with Playwright's own Chromium as the last candidate, for when
57
+ * `playwright install chromium` was run.
58
+ */
59
+ export function defaultBrowserSearch() {
60
+ let playwrightPath = null;
61
+ try {
62
+ playwrightPath = chromium.executablePath() || null;
63
+ }
64
+ catch {
65
+ // No Chromium build registered for this platform.
66
+ }
67
+ return findBrowsers({ playwrightPath });
68
+ }
69
+ function errorText(error) {
70
+ return error instanceof Error ? error.message : String(error);
71
+ }
72
+ /** First line of an error: Playwright appends a multi-line call log. */
73
+ function firstLine(text) {
74
+ return text.split('\n')[0]?.trim() ?? text;
75
+ }
76
+ /**
77
+ * Launches the headless browser: the explicit `executablePath` (no fallback),
78
+ * else the first browser found that starts. Every launch gets
79
+ * {@link HEADLESS_BROWSER_ARGS} and Playwright's throwaway profile.
80
+ *
81
+ * @throws with the real launch errors; install advice and the locations
82
+ * tried only when no browser was found at all
83
+ */
84
+ export async function launchHeadlessBrowser(options) {
85
+ const args = [...HEADLESS_BROWSER_ARGS];
86
+ const { executablePath } = options;
87
+ if (executablePath) {
88
+ try {
89
+ const browser = await chromium.launch({ headless: true, executablePath, args });
90
+ return {
91
+ browser,
92
+ choice: {
93
+ name: browserNameFromPath(executablePath),
94
+ path: executablePath,
95
+ origin: 'configured',
96
+ },
97
+ };
98
+ }
99
+ catch (error) {
100
+ throw new Error(`Could not launch the browser at FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH=${executablePath}: ` +
101
+ `${errorText(error)}. Check the path: it must point to the executable of a ` +
102
+ 'Chromium-based browser (Chrome, Edge, Brave, Chromium).');
103
+ }
104
+ }
105
+ const { found, tried } = (options.findBrowsers ?? defaultBrowserSearch)();
106
+ // Install advice only when nothing was found: a browser that is there
107
+ // but fails to start needs its real error, not a hint to install another.
108
+ if (found.length === 0) {
109
+ throw new Error(noBrowserMessage(tried));
110
+ }
111
+ const failures = [];
112
+ for (const candidate of found) {
113
+ try {
114
+ const browser = await chromium.launch({
115
+ headless: true,
116
+ executablePath: candidate.path,
117
+ args,
118
+ });
119
+ if (failures.length > 0) {
120
+ logger.warn(`Headless GM session: using ${candidate.name} — ${failures.join('; ')}`);
121
+ }
122
+ return { browser, choice: { ...candidate, origin: 'detected' } };
123
+ }
124
+ catch (error) {
125
+ failures.push(`${candidate.name} (${candidate.path}): ${firstLine(errorText(error))}`);
126
+ }
127
+ }
128
+ throw new Error(`Could not launch a browser for the headless GM session. Attempts: ${failures.join('; ')}`);
129
+ }
130
+ /**
131
+ * Chromium features that stop the companion module from reaching
132
+ * {@link ModuleBridge}. The page is served from `FOUNDRY_URL` (often a public
133
+ * origin) while the bridge listens on `ws://localhost`, and recent Chromium
134
+ * builds block public → local requests: Local Network Access (and its
135
+ * predecessor, Private Network Access) gates them behind a permission prompt,
136
+ * and Brave adds its own "localhost access" permission. A headless browser
137
+ * cannot show or accept a prompt, so the WebSocket just fails with no detail.
138
+ *
139
+ * `LocalNetworkAccessChecks` alone unblocks current builds (verified on
140
+ * Brave 156); the Private Network Access and Brave flags cover older Chromium
141
+ * releases and Brave variants. Unknown feature names are silently ignored, so
142
+ * listing them all is harmless on any given browser.
143
+ *
144
+ * Disabling these checks is acceptable here because this browser is
145
+ * throwaway: a fresh, empty profile per launch that only ever loads
146
+ * `FOUNDRY_URL`, never arbitrary sites — the user's own browser keeps its
147
+ * protections.
148
+ */
149
+ export const HEADLESS_BROWSER_ARGS = [
150
+ `--disable-features=${[
151
+ 'LocalNetworkAccessChecks',
152
+ 'BlockInsecurePrivateNetworkRequests',
153
+ 'PrivateNetworkAccessSendPreflights',
154
+ 'PrivateNetworkAccessRespectPreflightResults',
155
+ 'BraveLocalhostAccessPermission',
156
+ ].join(',')}`,
157
+ ];
158
+ /**
159
+ * Size of the headless GM page. Playwright's default, 1280x720, is below
160
+ * FoundryVTT's 1366x768 minimum: Foundry warns, and canvas work such as
161
+ * `capture_scene` misbehaves.
162
+ */
163
+ export const HEADLESS_VIEWPORT = { width: 1920, height: 1080 };
164
+ /** Where the companion module's scripts are served from. */
165
+ const BRIDGE_SCRIPT_PATH = '/modules/foundryvtt-mcp-bridge/';
166
+ /** The prefixes the companion module puts on its console lines. */
167
+ const BRIDGE_CONSOLE_PREFIXES = ['FoundryVTT MCP Bridge | ', 'foundryvtt-mcp-bridge | '];
168
+ const BRIDGE_CONSOLE_MAX_LENGTH = 500;
169
+ const BRIDGE_PAGE_ERROR_MAX_LENGTH = 200;
170
+ /** A stack frame (Chromium format) inside one of the module's scripts. */
171
+ const BRIDGE_STACK_FRAME = /^\s+at .*\/modules\/foundryvtt-mcp-bridge\//m;
172
+ function isBridgeScript(url) {
173
+ try {
174
+ return new URL(url).pathname.startsWith(BRIDGE_SCRIPT_PATH);
175
+ }
176
+ catch {
177
+ return false;
178
+ }
179
+ }
180
+ /**
181
+ * The part of a page console message worth copying to the log: a companion
182
+ * module line, printed by one of the module's own scripts, reduced to its
183
+ * first argument. Further arguments (a received command, an error) and
184
+ * every other script's lines stay out of the log, so no page, document or
185
+ * command content reaches it. `msg.text()` is never used: it renders every
186
+ * argument, including an object's own fields.
187
+ *
188
+ * @returns the line, cut to {@link BRIDGE_CONSOLE_MAX_LENGTH}, or `null`
189
+ */
190
+ export async function bridgeConsoleText(message) {
191
+ if (!isBridgeScript(message.location().url)) {
192
+ return null;
193
+ }
194
+ const first = message.args()[0];
195
+ if (!first) {
196
+ return null;
197
+ }
198
+ let value;
199
+ try {
200
+ value = await first.jsonValue();
201
+ }
202
+ catch {
203
+ // The page navigated away before the argument could be read.
204
+ return null;
205
+ }
206
+ if (typeof value !== 'string' || !BRIDGE_CONSOLE_PREFIXES.some((p) => value.startsWith(p))) {
207
+ return null;
208
+ }
209
+ return value.slice(0, BRIDGE_CONSOLE_MAX_LENGTH);
210
+ }
211
+ /**
212
+ * `name: message` of an uncaught page error thrown from the companion
213
+ * module's code (a stack frame in its scripts), without the stack.
214
+ *
215
+ * @returns the text, cut to {@link BRIDGE_PAGE_ERROR_MAX_LENGTH}, or `null`
216
+ */
217
+ export function bridgePageErrorText(error) {
218
+ if (!BRIDGE_STACK_FRAME.test(error.stack ?? '')) {
219
+ return null;
220
+ }
221
+ return `${error.name}: ${error.message}`.slice(0, BRIDGE_PAGE_ERROR_MAX_LENGTH);
222
+ }
223
+ /** Page binding behind `window.foundryMcpBridge`; see {@link BRIDGE_INIT_SCRIPT}. */
224
+ const BRIDGE_BINDING = '__foundryMcpBridgeCall';
225
+ /**
226
+ * Defines `window.foundryMcpBridge`, which the companion module looks for
227
+ * before dialling the bridge, on top of {@link BRIDGE_BINDING}. Runs before
228
+ * any page script on every navigation (join form, /game, reloads); the
229
+ * binding is looked up at call time, so the order in which Playwright
230
+ * installs the two never matters.
231
+ */
232
+ const BRIDGE_INIT_SCRIPT = `(() => {
233
+ const call = (method, arg) => globalThis.${BRIDGE_BINDING}(method, arg);
234
+ Object.defineProperty(globalThis, 'foundryMcpBridge', {
235
+ value: Object.freeze({
236
+ getInfo: () => call('getInfo'),
237
+ prove: (serverNonce) => call('prove', serverNonce),
238
+ }),
239
+ configurable: false,
240
+ enumerable: false,
241
+ writable: false,
242
+ });
243
+ })();`;
244
+ /**
245
+ * Shared mode: main-frame navigations the page may make are to `/game` only;
246
+ * see {@link HeadlessGmSession.guardNavigations}. Matches same-origin URLs
247
+ * whose path has no file extension (pages, not assets) other than `/game`,
248
+ * so only those few requests are intercepted.
249
+ */
250
+ function guardedNavigationPattern(origin) {
251
+ const escaped = origin.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
252
+ return new RegExp(`^${escaped}/(?!game(?:[/?#]|$))[^.?#]*(?:[?#].*)?$`);
253
+ }
254
+ /** Shared mode: how long a loaded `/game` may take to report `game.ready`. */
255
+ const GAME_READY_TIMEOUT_MS = 60000;
256
+ const JOIN_SELECTOR_TIMEOUT_MS = 20000;
257
+ const LOGIN_NAV_TIMEOUT_MS = 15000;
258
+ const BASE_RETRY_MS = 5000;
259
+ const MAX_RETRY_MS = 120000;
260
+ /** How often the bridge-connectivity watchdog polls `isBridgeConnected`. */
261
+ const WATCHDOG_INTERVAL_MS = 20000;
262
+ /** Consecutive down polls (≈60s) tolerated before forcing a page reload. */
263
+ const WATCHDOG_GRACE_TICKS = 3;
264
+ /** The origin of `url`, or `null` when it has none (`about:blank`, a malformed URL). */
265
+ function frameOrigin(url) {
266
+ try {
267
+ const origin = new URL(url).origin;
268
+ return origin === 'null' ? null : origin;
269
+ }
270
+ catch {
271
+ return null;
272
+ }
273
+ }
274
+ /** URL pathnames Foundry serves when nobody is logged in for this session. */
275
+ const LOGGED_OUT_PATHS = {
276
+ '/join': true,
277
+ '/setup': true,
278
+ '/license': true,
279
+ '/no-auth': true,
280
+ };
281
+ /**
282
+ * Drives an invisible, persistently-logged-in GM browser session so the
283
+ * companion module's bridge stays connected without any manual browser tab.
284
+ */
285
+ export class HeadlessGmSession {
286
+ options;
287
+ browser = null;
288
+ /** Shared mode: the dedicated context holding the shared cookie. */
289
+ context = null;
290
+ page = null;
291
+ active = false;
292
+ sharedState = 'waiting-for-session';
293
+ /** Shared mode: a new session was asked for and has not arrived yet. */
294
+ reauthRequested = false;
295
+ /** Shared mode: a new cookie waits its turn; a load still using the old one may fail. */
296
+ sessionQueued = false;
297
+ /** Shared mode: cookie updates and `/game` loads, one after the other. */
298
+ pageTask = Promise.resolve();
299
+ loadingGame = false;
300
+ /** Shared mode: loads of /game keep failing (one warning per outage). */
301
+ loadRetrying = false;
302
+ unsubscribeSession = null;
303
+ lastError = null;
304
+ retryDelayMs = BASE_RETRY_MS;
305
+ retryTimer = null;
306
+ /** When {@link active} last became true. */
307
+ activeSince = null;
308
+ /** Shared mode: the connector could not get a new session; it retries on its own. */
309
+ reauthFailed = false;
310
+ watchdogTimer = null;
311
+ bridgeDownTicks = 0;
312
+ stopped = false;
313
+ browserChoice = null;
314
+ constructor(options) {
315
+ this.options = options;
316
+ }
317
+ /**
318
+ * Launches the browser and returns once it is up. Login itself happens in
319
+ * the background (see {@link attemptLogin}): Foundry may not be reachable
320
+ * yet, and that must not block server startup or take other tools down.
321
+ *
322
+ * @throws if no browser could be launched at all — the explicit path
323
+ * failed, or no browser was found or none of those found would start.
324
+ * The message carries the real launch errors (install advice and the
325
+ * locations tried only when nothing was found); the caller logs it and keeps it for
326
+ * `status` and `get_health_status`.
327
+ */
328
+ async start() {
329
+ this.stopped = false;
330
+ this.browser = await this.launchBrowser();
331
+ const { sessionSource } = this.options;
332
+ if (sessionSource) {
333
+ // A context of its own: the shared cookie never mixes with anything else.
334
+ this.context = await this.browser.newContext({ viewport: HEADLESS_VIEWPORT });
335
+ this.page = await this.context.newPage();
336
+ }
337
+ else {
338
+ this.page = await this.browser.newPage({ viewport: HEADLESS_VIEWPORT });
339
+ }
340
+ // The companion module reports bridge failures only in the browser console.
341
+ this.page.on('console', (message) => {
342
+ void this.logBridgeConsole(message);
343
+ });
344
+ this.page.on('pageerror', (error) => {
345
+ const text = bridgePageErrorText(error);
346
+ if (text) {
347
+ logger.warn(`Headless GM page error (bridge): ${text}`);
348
+ }
349
+ });
350
+ if (this.options.bridgeCredentials) {
351
+ // Before the first navigation, so the module finds it on its first `ready`.
352
+ await this.exposeBridgeCredentials(this.page, this.options.bridgeCredentials);
353
+ }
354
+ this.page.on('framenavigated', (frame) => {
355
+ if (frame !== this.page?.mainFrame()) {
356
+ return;
357
+ }
358
+ const path = new URL(frame.url()).pathname;
359
+ if (sessionSource && path === '/game' && !this.loadingGame) {
360
+ // The page reloaded /game by itself (its client after a server
361
+ // restart, the bridge watchdog). With no world, FoundryVTT serves
362
+ // its "No Active Game" page there instead of redirecting: only
363
+ // `game.ready` tells.
364
+ this.active = false;
365
+ this.sharedState = 'reconnecting';
366
+ this.lastError = 'the page reloaded; waiting for the game';
367
+ this.enqueuePageTask(() => this.confirmGameReady());
368
+ return;
369
+ }
370
+ if (!LOGGED_OUT_PATHS[path]) {
371
+ return;
372
+ }
373
+ if (sessionSource) {
374
+ // Only a server redirect gets here (guardNavigations blocks the
375
+ // page's own navigations), and FoundryVTT redirects to /join only
376
+ // when the session is no longer valid.
377
+ this.onSessionRefused(`FoundryVTT redirected the page to ${path}`);
378
+ return;
379
+ }
380
+ if (this.active) {
381
+ logger.warn('Headless GM session logged out unexpectedly — re-logging in', {
382
+ url: frame.url(),
383
+ });
384
+ this.active = false;
385
+ this.scheduleLogin(0);
386
+ }
387
+ });
388
+ if (sessionSource) {
389
+ await this.guardNavigations(this.page);
390
+ this.unsubscribeSession = sessionSource.onSessionChanged((session) => {
391
+ this.useSession(session);
392
+ });
393
+ const session = sessionSource.currentSession();
394
+ if (session) {
395
+ this.useSession(session);
396
+ }
397
+ }
398
+ else {
399
+ this.sharedState = 'logging-in';
400
+ this.scheduleLogin(0);
401
+ }
402
+ if (this.options.isBridgeConnected) {
403
+ this.watchdogTimer = setInterval(() => this.checkBridgeHealth(), WATCHDOG_INTERVAL_MS);
404
+ }
405
+ }
406
+ async stop() {
407
+ this.stopped = true;
408
+ clearTimeout(this.retryTimer ?? undefined);
409
+ this.retryTimer = null;
410
+ clearInterval(this.watchdogTimer ?? undefined);
411
+ this.watchdogTimer = null;
412
+ this.unsubscribeSession?.();
413
+ this.unsubscribeSession = null;
414
+ this.active = false;
415
+ await this.page?.close().catch(() => undefined);
416
+ await this.context?.close().catch(() => undefined);
417
+ await this.browser?.close().catch(() => undefined);
418
+ this.page = null;
419
+ this.context = null;
420
+ this.browser = null;
421
+ }
422
+ /** True once {@link start} has launched the browser, until {@link stop}. */
423
+ isStarted() {
424
+ return this.browser !== null;
425
+ }
426
+ /** True once the session is logged in with a live GM-tier Foundry client. */
427
+ isActive() {
428
+ return this.active;
429
+ }
430
+ /** When the session became logged in (epoch ms), while it still is; `null` otherwise. */
431
+ loggedInSince() {
432
+ return this.active ? this.activeSince : null;
433
+ }
434
+ /**
435
+ * True while the session is failing: a failed attempt waits for its next
436
+ * try (login, or loading /game), or the connector could not provide a new
437
+ * session. The retries go on in the background, with growing delays.
438
+ */
439
+ isRetrying() {
440
+ return (this.retryTimer !== null && this.lastError !== null) || this.reauthFailed;
441
+ }
442
+ /** `shared`: the page reuses the connector's session; `separate`: its own account. */
443
+ mode() {
444
+ return this.options.sessionSource ? 'shared' : 'separate';
445
+ }
446
+ /** Account the page runs as. */
447
+ username() {
448
+ return this.options.username;
449
+ }
450
+ /** See {@link HeadlessSessionState}. */
451
+ sessionState() {
452
+ if (this.active) {
453
+ return 'logged-in';
454
+ }
455
+ return this.sharedState;
456
+ }
457
+ /** e.g. "sharing the connector's session (mcp-api)" or "separate account (mcp-gm)". */
458
+ modeText() {
459
+ return this.mode() === 'shared'
460
+ ? `sharing the connector's session (${this.options.username})`
461
+ : `separate account (${this.options.username})`;
462
+ }
463
+ /** Short human-readable status line for `get_health_status`. */
464
+ statusText() {
465
+ const mode = this.modeText();
466
+ if (this.active) {
467
+ return `✅ Logged in — ${mode}`;
468
+ }
469
+ const state = this.sessionState();
470
+ if (state === 'waiting-for-session') {
471
+ return `⏳ Waiting for the connector's session — ${mode}`;
472
+ }
473
+ if (state === 'loading-game') {
474
+ return `⏳ Opening /game with the connector's session — ${mode}`;
475
+ }
476
+ if (state === 'reauthenticating') {
477
+ return `⏳ Reauthenticating — ${mode}${this.lastError ? ` (${this.lastError})` : ''}`;
478
+ }
479
+ if (state === 'reconnecting') {
480
+ return `⏳ Reconnecting — ${mode}${this.lastError ? ` (${this.lastError})` : ''}`;
481
+ }
482
+ return this.lastError
483
+ ? `⏳ Not connected yet — ${mode} — ${this.lastError}`
484
+ : `⏳ Logging in — ${mode}`;
485
+ }
486
+ /**
487
+ * Shared mode: blocks every main-frame navigation away from `/game` —
488
+ * `game.logOut()` (the "Log Out" button, or the client reacting to its
489
+ * own role change) loads `/join`, and a GET /join logs the SHARED session
490
+ * out of the world (server sessions.mjs `logoutWorld`), which would leave
491
+ * the connector's socket anonymous at its next reconnection. The page
492
+ * reloads `/game` instead.
493
+ *
494
+ * A server redirect escapes this: Playwright calls a route handler only
495
+ * for the first URL of a redirect chain, so GET /game → 302 /join is not
496
+ * intercepted. That is harmless: FoundryVTT redirects /game to /join only
497
+ * when the session no longer names a user (server views/game.mjs), so the
498
+ * GET /join it causes has nothing left to log out, and the
499
+ * `framenavigated` handler asks for a new session.
500
+ */
501
+ async guardNavigations(page) {
502
+ const origin = new URL(this.options.foundryUrl).origin;
503
+ await page.route(guardedNavigationPattern(origin), async (route) => {
504
+ const request = route.request();
505
+ if (!request.isNavigationRequest() || request.frame() !== page.mainFrame()) {
506
+ await route.continue().catch(() => undefined);
507
+ return;
508
+ }
509
+ logger.warn('Headless GM session blocked a navigation away from /game — reloading /game', {
510
+ path: new URL(request.url()).pathname,
511
+ });
512
+ await route.abort('aborted').catch(() => undefined);
513
+ if (this.active && !this.loadingGame) {
514
+ this.active = false;
515
+ this.enqueuePageTask(() => this.loadGame());
516
+ }
517
+ });
518
+ }
519
+ /** Shared mode: installs a new session cookie, then (re)loads `/game`. */
520
+ useSession(session) {
521
+ this.reauthRequested = false;
522
+ this.reauthFailed = false;
523
+ clearTimeout(this.retryTimer ?? undefined);
524
+ this.retryTimer = null;
525
+ this.sessionQueued = true;
526
+ this.enqueuePageTask(async () => {
527
+ this.sessionQueued = false;
528
+ if (!this.context) {
529
+ return;
530
+ }
531
+ const url = new URL(this.options.foundryUrl);
532
+ await this.context.clearCookies();
533
+ await this.context.addCookies([
534
+ {
535
+ name: 'session',
536
+ value: session,
537
+ domain: url.hostname,
538
+ path: '/',
539
+ httpOnly: true,
540
+ secure: url.protocol === 'https:',
541
+ sameSite: 'Strict',
542
+ },
543
+ ]);
544
+ await this.loadGame();
545
+ });
546
+ }
547
+ enqueuePageTask(task) {
548
+ this.pageTask = this.pageTask.then(task).catch((error) => {
549
+ // loadGame() handles its own failures; this guards the chain itself.
550
+ logger.error('Headless GM session page task failed unexpectedly', error);
551
+ });
552
+ }
553
+ /**
554
+ * Shared mode: loads `/game` with the current cookie and waits for
555
+ * `game.ready`. FoundryVTT answers /game with its "No Active Game" page
556
+ * (HTTP 200, no `game`) when no world runs, hence the ready check.
557
+ */
558
+ async loadGame() {
559
+ if (this.stopped || !this.page) {
560
+ return;
561
+ }
562
+ this.loadingGame = true;
563
+ this.active = false;
564
+ if (this.sharedState === 'logged-in') {
565
+ // Not logged in until the game is ready again.
566
+ this.sharedState = 'reconnecting';
567
+ this.lastError = 'loading /game';
568
+ }
569
+ else if (this.sharedState === 'waiting-for-session') {
570
+ // The session is in hand: what remains is the game itself.
571
+ this.sharedState = 'loading-game';
572
+ }
573
+ try {
574
+ const gameUrl = new URL('/game', this.options.foundryUrl).toString();
575
+ await this.page.goto(gameUrl, { waitUntil: 'domcontentloaded' });
576
+ const path = new URL(this.page.url()).pathname;
577
+ if (path !== '/game') {
578
+ this.onSessionRefused(`FoundryVTT redirected the page to ${path}`);
579
+ return;
580
+ }
581
+ await this.awaitGameReady(true);
582
+ }
583
+ catch (error) {
584
+ // The page could not load at all (network down, server restarting):
585
+ // nothing says the cookie is bad, so keep it and try again.
586
+ this.retryLoadGame(firstLine(errorText(error)));
587
+ }
588
+ finally {
589
+ this.loadingGame = false;
590
+ }
591
+ }
592
+ /**
593
+ * Shared mode: after the page reloaded `/game` on its own, waits for
594
+ * the game again. Skipped when a load of ours started meanwhile.
595
+ */
596
+ async confirmGameReady() {
597
+ if (this.stopped || !this.page || this.active || this.loadingGame) {
598
+ return;
599
+ }
600
+ if (new URL(this.page.url()).pathname !== '/game') {
601
+ return;
602
+ }
603
+ this.loadingGame = true;
604
+ try {
605
+ await this.awaitGameReady(false);
606
+ }
607
+ finally {
608
+ this.loadingGame = false;
609
+ }
610
+ }
611
+ /**
612
+ * Shared mode: `game.ready` within the timeout, or a request for a new session.
613
+ *
614
+ * @param announce - log the login even when the page already counted as
615
+ * logged in (a load with a new cookie), not only after a loss
616
+ */
617
+ async awaitGameReady(announce) {
618
+ if (!this.page) {
619
+ return;
620
+ }
621
+ const ready = await this.page
622
+ .waitForFunction(() => globalThis.game?.ready === true, null, { timeout: GAME_READY_TIMEOUT_MS })
623
+ .then(() => true, () => false);
624
+ if (this.stopped) {
625
+ return;
626
+ }
627
+ if (!ready) {
628
+ this.onSessionRefused('the game never became ready (no active world?)');
629
+ return;
630
+ }
631
+ const wasLoggedIn = this.sharedState === 'logged-in';
632
+ this.active = true;
633
+ this.activeSince = Date.now();
634
+ this.sharedState = 'logged-in';
635
+ this.lastError = null;
636
+ this.retryDelayMs = BASE_RETRY_MS;
637
+ this.loadRetrying = false;
638
+ if (announce || !wasLoggedIn) {
639
+ logger.info(`Headless GM session logged in — ${this.modeText()}`);
640
+ }
641
+ }
642
+ /**
643
+ * Shared mode: `/game` could not be loaded. Tries again with the same
644
+ * cookie, waiting {@link BASE_RETRY_MS} and doubling up to
645
+ * {@link MAX_RETRY_MS}; one warning per outage, not per attempt.
646
+ */
647
+ retryLoadGame(reason) {
648
+ if (this.stopped) {
649
+ return;
650
+ }
651
+ if (!this.loadRetrying) {
652
+ this.loadRetrying = true;
653
+ logger.warn(`Headless GM session could not load /game (${reason}) — retrying with the same session`);
654
+ }
655
+ this.active = false;
656
+ this.sharedState = 'reconnecting';
657
+ this.lastError = reason;
658
+ clearTimeout(this.retryTimer ?? undefined);
659
+ const delay = this.retryDelayMs;
660
+ this.retryDelayMs = Math.min(this.retryDelayMs * 2, MAX_RETRY_MS);
661
+ this.retryTimer = setTimeout(() => {
662
+ this.retryTimer = null;
663
+ this.enqueuePageTask(() => this.loadGame());
664
+ }, delay);
665
+ }
666
+ /**
667
+ * Shared mode: the cookie no longer opens the game. Asks the connector for
668
+ * a new session — once, however many events report it, until one arrives.
669
+ */
670
+ onSessionRefused(reason) {
671
+ const { sessionSource } = this.options;
672
+ if (!sessionSource || this.stopped) {
673
+ return;
674
+ }
675
+ this.active = false;
676
+ this.sharedState = 'reauthenticating';
677
+ this.lastError = reason;
678
+ // A newer cookie is about to be tried: this refusal was the old one's.
679
+ if (this.reauthRequested || this.sessionQueued) {
680
+ return;
681
+ }
682
+ this.reauthRequested = true;
683
+ logger.warn(`Headless GM session: ${reason} — asking the connector for a new session`);
684
+ sessionSource.reauthenticate(`headless GM page: ${reason}`).catch((error) => {
685
+ // The connector keeps retrying on its own; the page waits for its cookie.
686
+ this.lastError = `${reason}; reauthentication failed: ${errorText(error)}`;
687
+ this.reauthFailed = true;
688
+ });
689
+ }
690
+ /**
691
+ * Gives the page `window.foundryMcpBridge`. The binding and the init
692
+ * script are page-wide and survive navigations and reloads, so this runs
693
+ * once per page. Only frames served from `FOUNDRY_URL`'s origin get an
694
+ * answer: an embedded third-party iframe sees the object, but its calls
695
+ * are refused.
696
+ */
697
+ async exposeBridgeCredentials(page, credentials) {
698
+ const foundryOrigin = new URL(this.options.foundryUrl).origin;
699
+ await page.exposeBinding(BRIDGE_BINDING, (source, method, arg) => {
700
+ if (frameOrigin(source.frame.url()) !== foundryOrigin) {
701
+ logger.warn('Headless GM session refused a foundryMcpBridge call from another origin', {
702
+ url: source.frame.url(),
703
+ });
704
+ throw new Error('foundryMcpBridge is only available to the Foundry page');
705
+ }
706
+ if (method === 'getInfo') {
707
+ return credentials.info();
708
+ }
709
+ if (method === 'prove') {
710
+ return credentials.prove(arg);
711
+ }
712
+ throw new Error('Unknown foundryMcpBridge call');
713
+ });
714
+ await page.addInitScript({ content: BRIDGE_INIT_SCRIPT });
715
+ }
716
+ /** The browser this session launched; `null` until {@link start} launches one. */
717
+ browserInfo() {
718
+ return this.browserChoice;
719
+ }
720
+ async launchBrowser() {
721
+ const { browser, choice } = await launchHeadlessBrowser(this.options);
722
+ this.browserChoice = choice;
723
+ return browser;
724
+ }
725
+ scheduleLogin(delayMs) {
726
+ if (this.stopped) {
727
+ return;
728
+ }
729
+ clearTimeout(this.retryTimer ?? undefined);
730
+ this.retryTimer = setTimeout(() => {
731
+ this.retryTimer = null;
732
+ this.attemptLogin().catch((error) => {
733
+ // attemptLogin itself never throws (see its own try/catch) — this is
734
+ // a last-resort guard so a bug there can never kill the retry loop.
735
+ logger.error('Headless GM session login attempt threw unexpectedly', error);
736
+ });
737
+ }, delayMs);
738
+ }
739
+ async attemptLogin() {
740
+ if (this.stopped || !this.page) {
741
+ return;
742
+ }
743
+ try {
744
+ const joinUrl = new URL('/join', this.options.foundryUrl).toString();
745
+ await this.page.goto(joinUrl, { waitUntil: 'domcontentloaded' });
746
+ // FoundryVTT v14 renamed the join form's user list from `userid` (v13)
747
+ // to `userId` (camelCase), so match either.
748
+ const userSelectSelector = 'select[name="userId"], select[name="userid"]';
749
+ await this.page.waitForSelector(userSelectSelector, {
750
+ timeout: JOIN_SELECTOR_TIMEOUT_MS,
751
+ });
752
+ const selected = await this.page.evaluate(({ username, selector }) => {
753
+ const select = document.querySelector(selector);
754
+ if (!select) {
755
+ return false;
756
+ }
757
+ const option = Array.from(select.options).find((o) => o.text.trim().toLowerCase() === username.trim().toLowerCase());
758
+ if (!option) {
759
+ return false;
760
+ }
761
+ select.value = option.value;
762
+ select.dispatchEvent(new Event('change', { bubbles: true }));
763
+ return true;
764
+ }, { username: this.options.username, selector: userSelectSelector });
765
+ if (!selected) {
766
+ throw new Error(`No user named "${this.options.username}" is registered in this world's join list`);
767
+ }
768
+ // FoundryVTT v14's join form has two password fields: the player
769
+ // `password` and the world's `adminPassword`. Target the player field by
770
+ // name and never touch `adminPassword`; fall back to the first password
771
+ // input only for forms without a named `password` field.
772
+ const passwordInput = (await this.page.$('input[name="password"]')) ??
773
+ (await this.page.$('input[type="password"]'));
774
+ if (passwordInput) {
775
+ await passwordInput.fill(this.options.password ?? '');
776
+ }
777
+ await Promise.all([
778
+ this.page
779
+ .waitForURL((url) => url.pathname === '/game', { timeout: LOGIN_NAV_TIMEOUT_MS })
780
+ .catch(() => undefined),
781
+ this.page.click('button[name="join"]'),
782
+ ]);
783
+ if (!this.page.url() || new URL(this.page.url()).pathname !== '/game') {
784
+ throw new Error('Join submitted but the session never reached /game — check the password and that the world is active');
785
+ }
786
+ this.active = true;
787
+ this.activeSince = Date.now();
788
+ this.lastError = null;
789
+ this.retryDelayMs = BASE_RETRY_MS;
790
+ logger.info(`Headless GM session logged in as ${this.options.username}`);
791
+ }
792
+ catch (error) {
793
+ this.active = false;
794
+ this.lastError = error instanceof Error ? error.message : String(error);
795
+ logger.warn(`Headless GM session login failed — retrying in ${Math.round(this.retryDelayMs / 1000)}s`, { error: this.lastError });
796
+ const delay = this.retryDelayMs;
797
+ this.retryDelayMs = Math.min(this.retryDelayMs * 2, MAX_RETRY_MS);
798
+ this.scheduleLogin(delay);
799
+ }
800
+ }
801
+ /**
802
+ * Polled by the watchdog interval. A single down poll is normal — the
803
+ * module's own client-side reconnect logic should recover most drops on
804
+ * its own within a few seconds — so this only acts once the down count
805
+ * reaches {@link WATCHDOG_GRACE_TICKS}, at which point that logic has
806
+ * plausibly given up (it caps out after 10 attempts) and a page reload
807
+ * gives it a completely fresh start.
808
+ */
809
+ checkBridgeHealth() {
810
+ if (this.stopped || !this.active || !this.options.isBridgeConnected) {
811
+ this.bridgeDownTicks = 0;
812
+ return;
813
+ }
814
+ if (this.options.isBridgeConnected()) {
815
+ this.bridgeDownTicks = 0;
816
+ return;
817
+ }
818
+ this.bridgeDownTicks++;
819
+ if (this.bridgeDownTicks < WATCHDOG_GRACE_TICKS) {
820
+ return;
821
+ }
822
+ this.bridgeDownTicks = 0;
823
+ this.reloadForBridgeRecovery();
824
+ }
825
+ /** Copies a companion module console line to the log ({@link bridgeConsoleText}). Never throws. */
826
+ async logBridgeConsole(message) {
827
+ const text = await bridgeConsoleText(message);
828
+ if (!text) {
829
+ return;
830
+ }
831
+ const type = message.type();
832
+ if (type === 'warning' || type === 'error') {
833
+ logger.warn(`Headless GM page [bridge console.${type === 'warning' ? 'warn' : type}]: ${text}`);
834
+ }
835
+ else {
836
+ logger.info(`Headless GM page [bridge console.${type}]: ${text}`);
837
+ }
838
+ }
839
+ /**
840
+ * Forces a fresh page load: the Foundry session cookie survives a reload,
841
+ * so this does not need to repeat the login form — it just re-executes
842
+ * every module's `init`/`ready` hooks, giving the companion module a new
843
+ * `transport.connect()` attempt with its reconnect backoff reset to zero.
844
+ * Never throws: a failed reload just leaves the next watchdog tick to try
845
+ * again.
846
+ */
847
+ reloadForBridgeRecovery() {
848
+ if (!this.page) {
849
+ return;
850
+ }
851
+ logger.warn('Module bridge has been disconnected while the headless GM session stayed logged in — reloading the page to recover');
852
+ this.page.reload({ waitUntil: 'domcontentloaded' }).catch((error) => {
853
+ logger.error('Headless GM session bridge-recovery reload failed', error);
854
+ });
855
+ }
856
+ }
857
+ //# sourceMappingURL=headless-gm-session.js.map