@g33ks/foundryvtt-mcp 2.0.0 → 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.
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import { isRecord } from '../utils/guards.js';
19
19
  import { stripHtml } from '../utils/sanitize.js';
20
+ import { messageAuthorId } from './message-author.js';
20
21
  /** Longest chat excerpt carried in a summary line, in characters. */
21
22
  const MAX_SUMMARY_TEXT = 200;
22
23
  /**
@@ -255,9 +256,7 @@ function renderSummary(broadcast, first, changed, ids, worldData) {
255
256
  if (type === 'ChatMessage' && action === 'create' && first) {
256
257
  const speaker = isRecord(first.speaker) ? first.speaker : undefined;
257
258
  const alias = speaker && typeof speaker.alias === 'string' ? speaker.alias : undefined;
258
- const author = alias ??
259
- userName(worldData, typeof first.user === 'string' ? first.user : broadcast.userId) ??
260
- 'Unknown';
259
+ const author = alias ?? userName(worldData, messageAuthorId(first) ?? broadcast.userId) ?? 'Unknown';
261
260
  const raw = typeof first.content === 'string' ? first.content : '';
262
261
  const text = truncate(stripHtml(raw));
263
262
  const flavor = typeof first.flavor === 'string' ? truncate(stripHtml(first.flavor)) : '';
@@ -155,6 +155,71 @@ export const HEADLESS_BROWSER_ARGS = [
155
155
  'BraveLocalhostAccessPermission',
156
156
  ].join(',')}`,
157
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
+ }
158
223
  /** Page binding behind `window.foundryMcpBridge`; see {@link BRIDGE_INIT_SCRIPT}. */
159
224
  const BRIDGE_BINDING = '__foundryMcpBridgeCall';
160
225
  /**
@@ -238,6 +303,10 @@ export class HeadlessGmSession {
238
303
  lastError = null;
239
304
  retryDelayMs = BASE_RETRY_MS;
240
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;
241
310
  watchdogTimer = null;
242
311
  bridgeDownTicks = 0;
243
312
  stopped = false;
@@ -262,12 +331,22 @@ export class HeadlessGmSession {
262
331
  const { sessionSource } = this.options;
263
332
  if (sessionSource) {
264
333
  // A context of its own: the shared cookie never mixes with anything else.
265
- this.context = await this.browser.newContext();
334
+ this.context = await this.browser.newContext({ viewport: HEADLESS_VIEWPORT });
266
335
  this.page = await this.context.newPage();
267
336
  }
268
337
  else {
269
- this.page = await this.browser.newPage();
338
+ this.page = await this.browser.newPage({ viewport: HEADLESS_VIEWPORT });
270
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
+ });
271
350
  if (this.options.bridgeCredentials) {
272
351
  // Before the first navigation, so the module finds it on its first `ready`.
273
352
  await this.exposeBridgeCredentials(this.page, this.options.bridgeCredentials);
@@ -348,6 +427,18 @@ export class HeadlessGmSession {
348
427
  isActive() {
349
428
  return this.active;
350
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
+ }
351
442
  /** `shared`: the page reuses the connector's session; `separate`: its own account. */
352
443
  mode() {
353
444
  return this.options.sessionSource ? 'shared' : 'separate';
@@ -379,6 +470,9 @@ export class HeadlessGmSession {
379
470
  if (state === 'waiting-for-session') {
380
471
  return `⏳ Waiting for the connector's session — ${mode}`;
381
472
  }
473
+ if (state === 'loading-game') {
474
+ return `⏳ Opening /game with the connector's session — ${mode}`;
475
+ }
382
476
  if (state === 'reauthenticating') {
383
477
  return `⏳ Reauthenticating — ${mode}${this.lastError ? ` (${this.lastError})` : ''}`;
384
478
  }
@@ -425,6 +519,7 @@ export class HeadlessGmSession {
425
519
  /** Shared mode: installs a new session cookie, then (re)loads `/game`. */
426
520
  useSession(session) {
427
521
  this.reauthRequested = false;
522
+ this.reauthFailed = false;
428
523
  clearTimeout(this.retryTimer ?? undefined);
429
524
  this.retryTimer = null;
430
525
  this.sessionQueued = true;
@@ -471,6 +566,10 @@ export class HeadlessGmSession {
471
566
  this.sharedState = 'reconnecting';
472
567
  this.lastError = 'loading /game';
473
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
+ }
474
573
  try {
475
574
  const gameUrl = new URL('/game', this.options.foundryUrl).toString();
476
575
  await this.page.goto(gameUrl, { waitUntil: 'domcontentloaded' });
@@ -531,6 +630,7 @@ export class HeadlessGmSession {
531
630
  }
532
631
  const wasLoggedIn = this.sharedState === 'logged-in';
533
632
  this.active = true;
633
+ this.activeSince = Date.now();
534
634
  this.sharedState = 'logged-in';
535
635
  this.lastError = null;
536
636
  this.retryDelayMs = BASE_RETRY_MS;
@@ -584,6 +684,7 @@ export class HeadlessGmSession {
584
684
  sessionSource.reauthenticate(`headless GM page: ${reason}`).catch((error) => {
585
685
  // The connector keeps retrying on its own; the page waits for its cookie.
586
686
  this.lastError = `${reason}; reauthentication failed: ${errorText(error)}`;
687
+ this.reauthFailed = true;
587
688
  });
588
689
  }
589
690
  /**
@@ -627,6 +728,7 @@ export class HeadlessGmSession {
627
728
  }
628
729
  clearTimeout(this.retryTimer ?? undefined);
629
730
  this.retryTimer = setTimeout(() => {
731
+ this.retryTimer = null;
630
732
  this.attemptLogin().catch((error) => {
631
733
  // attemptLogin itself never throws (see its own try/catch) — this is
632
734
  // a last-resort guard so a bug there can never kill the retry loop.
@@ -682,6 +784,7 @@ export class HeadlessGmSession {
682
784
  throw new Error('Join submitted but the session never reached /game — check the password and that the world is active');
683
785
  }
684
786
  this.active = true;
787
+ this.activeSince = Date.now();
685
788
  this.lastError = null;
686
789
  this.retryDelayMs = BASE_RETRY_MS;
687
790
  logger.info(`Headless GM session logged in as ${this.options.username}`);
@@ -719,6 +822,20 @@ export class HeadlessGmSession {
719
822
  this.bridgeDownTicks = 0;
720
823
  this.reloadForBridgeRecovery();
721
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
+ }
722
839
  /**
723
840
  * Forces a fresh page load: the Foundry session cookie survives a reload,
724
841
  * so this does not need to repeat the login form — it just re-executes
@@ -0,0 +1,141 @@
1
+ /**
2
+ * @fileoverview The list of detected journal overwrites, kept on disk so that
3
+ * `get_health_status` still lists them after the shared process restarts.
4
+ *
5
+ * `<state dir>/journal-conflicts.json`:
6
+ * `{ "version": 1, "conflicts": [{ at, journalId, pageId, journalName,
7
+ * pageName, reason, savedBy, historyPath }] }`, `at` as an ISO date. Ids,
8
+ * names, who saved and the path of the local copy: never page content (that
9
+ * stays in the copies under `journal-history/`). Written whole on every
10
+ * change, to a `.tmp` file renamed over the list, so a crash leaves the old
11
+ * list or the new one, never half of one.
12
+ */
13
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
14
+ import path from 'node:path';
15
+ import { z } from 'zod';
16
+ import { logger } from '../utils/logger.js';
17
+ const FILE_VERSION = 1;
18
+ const StoredConflictSchema = z.object({
19
+ at: z.string().refine((value) => !Number.isNaN(Date.parse(value))),
20
+ journalId: z.string(),
21
+ pageId: z.string(),
22
+ journalName: z.string(),
23
+ pageName: z.string(),
24
+ reason: z.string(),
25
+ savedBy: z.string().nullable(),
26
+ historyPath: z.string().nullable(),
27
+ });
28
+ const FileSchema = z.object({ version: z.literal(FILE_VERSION), conflicts: z.array(z.unknown()) });
29
+ const NODE_OPS = { writeFileSync, renameSync };
30
+ /** Windows: an antivirus or indexer briefly holding the file. */
31
+ const TRANSIENT_CODES = new Set(['EPERM', 'EBUSY']);
32
+ function errorCode(error) {
33
+ return typeof error === 'object' && error !== null && 'code' in error
34
+ ? String(error.code)
35
+ : undefined;
36
+ }
37
+ function errorText(error) {
38
+ return error instanceof Error ? error.message : String(error);
39
+ }
40
+ export class JournalConflictFile {
41
+ file;
42
+ ops;
43
+ constructor(file, ops = NODE_OPS) {
44
+ this.file = file;
45
+ this.ops = ops;
46
+ }
47
+ /**
48
+ * The conflicts kept in the file. A missing file is an empty list; an
49
+ * unreadable or invalid one is an empty list and one warning; an invalid
50
+ * entry is skipped. Pruning is the caller's.
51
+ */
52
+ load() {
53
+ let raw;
54
+ try {
55
+ raw = readFileSync(this.file, 'utf8');
56
+ }
57
+ catch (error) {
58
+ if (errorCode(error) !== 'ENOENT') {
59
+ logger.warn('Could not read the list of journal overwrites; starting with an empty one', {
60
+ file: this.file,
61
+ error: errorText(error),
62
+ });
63
+ }
64
+ return [];
65
+ }
66
+ let parsed;
67
+ try {
68
+ parsed = FileSchema.parse(JSON.parse(raw));
69
+ }
70
+ catch {
71
+ logger.warn('The list of journal overwrites is not valid; starting with an empty one', {
72
+ file: this.file,
73
+ });
74
+ return [];
75
+ }
76
+ const conflicts = [];
77
+ let skipped = 0;
78
+ for (const entry of parsed.conflicts) {
79
+ const stored = StoredConflictSchema.safeParse(entry);
80
+ if (!stored.success) {
81
+ skipped++;
82
+ continue;
83
+ }
84
+ conflicts.push({ ...stored.data, at: Date.parse(stored.data.at) });
85
+ }
86
+ if (skipped > 0) {
87
+ logger.warn(`Skipped ${skipped} invalid entr${skipped === 1 ? 'y' : 'ies'} of the list of journal overwrites`, {
88
+ file: this.file,
89
+ });
90
+ }
91
+ return conflicts;
92
+ }
93
+ /**
94
+ * Writes the whole list: a `.tmp` file, then a rename over the list, tried
95
+ * twice when Windows reports the file busy. A failure is one warning; the
96
+ * list in memory is unaffected.
97
+ *
98
+ * @returns whether the list was written
99
+ */
100
+ save(conflicts) {
101
+ const content = `${JSON.stringify({
102
+ version: FILE_VERSION,
103
+ conflicts: conflicts.map((conflict) => ({
104
+ at: new Date(conflict.at).toISOString(),
105
+ journalId: conflict.journalId,
106
+ pageId: conflict.pageId,
107
+ journalName: conflict.journalName,
108
+ pageName: conflict.pageName,
109
+ reason: conflict.reason,
110
+ savedBy: conflict.savedBy,
111
+ historyPath: conflict.historyPath,
112
+ })),
113
+ }, null, 2)}\n`;
114
+ const tmp = `${this.file}.tmp`;
115
+ for (let attempt = 1;; attempt++) {
116
+ try {
117
+ mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
118
+ this.ops.writeFileSync(tmp, content, { encoding: 'utf8', mode: 0o600 });
119
+ this.ops.renameSync(tmp, this.file);
120
+ return true;
121
+ }
122
+ catch (error) {
123
+ if (attempt === 1 && TRANSIENT_CODES.has(errorCode(error) ?? '')) {
124
+ continue;
125
+ }
126
+ try {
127
+ rmSync(tmp, { force: true });
128
+ }
129
+ catch {
130
+ // Left behind; the next save overwrites it.
131
+ }
132
+ logger.warn('Could not save the list of journal overwrites; it is kept in memory', {
133
+ file: this.file,
134
+ error: errorText(error),
135
+ });
136
+ return false;
137
+ }
138
+ }
139
+ }
140
+ }
141
+ //# sourceMappingURL=journal-conflicts.js.map
@@ -196,18 +196,28 @@ function pageKey(journalId, pageId) {
196
196
  return `${journalId}.${pageId}`;
197
197
  }
198
198
  /**
199
- * In-memory integrity state for journal pages: writes in flight, watched
200
- * writes, recent editor autosaves, pending warnings and recent conflicts.
199
+ * Integrity state for journal pages: writes in flight, watched writes, recent
200
+ * editor autosaves and pending warnings, in memory; the recent conflicts also
201
+ * in a file when one is given ({@link JournalConflictFile}), so they survive
202
+ * a restart.
201
203
  */
202
204
  export class JournalWatch {
203
205
  now;
206
+ conflictFile;
204
207
  watches = new Map();
205
208
  inflight = new Map();
206
209
  autosaves = new Map();
207
210
  warnings = [];
208
211
  conflicts = [];
209
- constructor(now = Date.now) {
212
+ constructor(now = Date.now, conflictFile = null) {
210
213
  this.now = now;
214
+ this.conflictFile = conflictFile;
215
+ if (conflictFile) {
216
+ this.conflicts = conflictFile.load();
217
+ if (this.pruneConflicts()) {
218
+ conflictFile.save(this.conflicts);
219
+ }
220
+ }
211
221
  }
212
222
  /** Starts collecting foreign changes to a page while a connector write is in flight. */
213
223
  beginWrite(journalId, pageId) {
@@ -284,10 +294,13 @@ export class JournalWatch {
284
294
  recordConflict(conflict) {
285
295
  this.conflicts.push(conflict);
286
296
  this.pruneConflicts();
297
+ this.conflictFile?.save(this.conflicts);
287
298
  }
288
299
  /** Conflicts detected within {@link CONFLICT_RETENTION_MS}, oldest first. */
289
300
  recentConflicts() {
290
- this.pruneConflicts();
301
+ if (this.pruneConflicts()) {
302
+ this.conflictFile?.save(this.conflicts);
303
+ }
291
304
  return [...this.conflicts];
292
305
  }
293
306
  pruneWatches() {
@@ -298,9 +311,12 @@ export class JournalWatch {
298
311
  }
299
312
  }
300
313
  }
314
+ /** @returns whether any conflict was dropped */
301
315
  pruneConflicts() {
302
316
  const cutoff = this.now() - CONFLICT_RETENTION_MS;
317
+ const before = this.conflicts.length;
303
318
  this.conflicts = this.conflicts.filter((conflict) => conflict.at > cutoff);
319
+ return this.conflicts.length !== before;
304
320
  }
305
321
  }
306
322
  //# sourceMappingURL=journal-integrity.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @fileoverview Who wrote a chat message.
3
+ *
4
+ * FoundryVTT stores the author of a chat message in `author` since v12
5
+ * (v14: common/documents/chat-message.mjs,
6
+ * `author: new fields.DocumentAuthorField(documents.BaseUser)`); `user` is
7
+ * its earlier name, kept for messages from older data (G33ks/foundryvtt-mcp#13).
8
+ */
9
+ /** The id of the user who wrote `message`: `author`, else `user`; `undefined` when neither is a string. */
10
+ export function messageAuthorId(message) {
11
+ if (typeof message.author === 'string' && message.author !== '') {
12
+ return message.author;
13
+ }
14
+ if (typeof message.user === 'string' && message.user !== '') {
15
+ return message.user;
16
+ }
17
+ return undefined;
18
+ }
19
+ //# sourceMappingURL=message-author.js.map
@@ -117,6 +117,8 @@ export class ModuleBridge {
117
117
  socket = null;
118
118
  connectedSince = null;
119
119
  pending = new Map();
120
+ /** Callers of {@link waitUntilConnected}, woken by the next authentication. */
121
+ connectionWaiters = new Set();
120
122
  nextId = 1;
121
123
  port;
122
124
  expectedOrigin;
@@ -263,6 +265,31 @@ export class ModuleBridge {
263
265
  else {
264
266
  logger.info(`Foundry module connected and authenticated (protocol v${BRIDGE_PROTOCOL_VERSION})`, { remoteAddress });
265
267
  }
268
+ this.wakeConnectionWaiters(true);
269
+ }
270
+ wakeConnectionWaiters(connected) {
271
+ for (const wake of [...this.connectionWaiters]) {
272
+ wake(connected);
273
+ }
274
+ }
275
+ /**
276
+ * Waits until an authenticated module is connected.
277
+ *
278
+ * @returns true once connected, false when `timeoutMs` ran out first or the bridge stopped
279
+ */
280
+ waitUntilConnected(timeoutMs) {
281
+ if (this.isConnected()) {
282
+ return Promise.resolve(true);
283
+ }
284
+ return new Promise((resolve) => {
285
+ const wake = (connected) => {
286
+ clearTimeout(timer);
287
+ this.connectionWaiters.delete(wake);
288
+ resolve(connected);
289
+ };
290
+ const timer = setTimeout(() => wake(false), timeoutMs);
291
+ this.connectionWaiters.add(wake);
292
+ });
266
293
  }
267
294
  checkAuthResponse(raw, serverNonce) {
268
295
  let parsed;
@@ -327,6 +354,7 @@ export class ModuleBridge {
327
354
  pending.reject(new Error('Module bridge shutting down'));
328
355
  }
329
356
  this.pending.clear();
357
+ this.wakeConnectionWaiters(false);
330
358
  this.socket?.close();
331
359
  this.socket = null;
332
360
  this.connectedSince = null;
@@ -14,6 +14,7 @@ import { packageVersion } from './shared/version.js';
14
14
  import { getAllTools } from './tools/definitions.js';
15
15
  import { getAllResources } from './tools/resources.js';
16
16
  import { logger } from './utils/logger.js';
17
+ import { withBareErrors } from './utils/mcp-errors.js';
17
18
  export function createMcpServer(backend) {
18
19
  // Answers `initialize` even with no usable configuration yet: tool calls
19
20
  // then say what is missing (see the relay and the all-in-one server).
@@ -41,14 +42,15 @@ export function createMcpServer(backend) {
41
42
  resources: getAllResources(),
42
43
  };
43
44
  });
44
- // Handle tool calls
45
+ // Handle tool calls. Errors leave with their bare message: the client adds
46
+ // the "MCP error <code>: " prefix itself (see withBareErrors).
45
47
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
46
48
  const { name, arguments: args } = request.params;
47
- return backend.callTool(name, args || {});
49
+ return withBareErrors(() => backend.callTool(name, args || {}));
48
50
  });
49
51
  // Handle resource reads
50
52
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
51
- return backend.readResource(request.params.uri);
53
+ return withBareErrors(() => backend.readResource(request.params.uri));
52
54
  });
53
55
  return server;
54
56
  }
@@ -71,6 +71,9 @@ export function formatStatus(status) {
71
71
  lines.push(` Write queue: ${status.writeQueue} pending`);
72
72
  }
73
73
  lines.push(` FoundryVTT: ${formatFoundryConnection(status)}`);
74
+ if (status.staleCache) {
75
+ lines.push(` World cache: ${formatStaleCache(status.staleCache)}`);
76
+ }
74
77
  if (status.account) {
75
78
  const role = status.account.role ? ` (${status.account.role})` : '';
76
79
  lines.push(` Account: ${status.account.name}${role}`);
@@ -81,10 +84,14 @@ export function formatStatus(status) {
81
84
  if (status.startupError) {
82
85
  lines.push(` Startup error: ${status.startupError}`);
83
86
  }
84
- const bridgeState = bridge?.state ?? 'disabled';
87
+ const connecting = isConnecting(status);
88
+ // Before the core is built, nothing reports the bridge: it is not started yet.
89
+ const bridgeState = bridge?.state ?? (connecting ? 'not-started' : 'disabled');
85
90
  const notStarted = status.foundryConnected
86
91
  ? 'not started yet'
87
- : 'not started (FoundryVTT connection failed)';
92
+ : connecting
93
+ ? 'not started yet (connecting to FoundryVTT)'
94
+ : 'not started (FoundryVTT connection failed)';
88
95
  lines.push(` Module bridge: ${formatBridge(bridge, bridgeState, notStarted)}`);
89
96
  if (bridgeState === 'listening' && bridge?.origin) {
90
97
  lines.push(` Bridge origin: ${bridge.origin}`);
@@ -157,10 +164,35 @@ export function formatTerminalConfig(settings = resolveSettings()) {
157
164
  }))),
158
165
  ];
159
166
  }
167
+ /** e.g. "stale since 2026-11-06T13:02:11.000Z — the socket dropped". */
168
+ function formatStaleCache(stale) {
169
+ const since = stale.since ? ` since ${stale.since}` : '';
170
+ const reason = stale.reason ? ` — ${stale.reason}` : '';
171
+ return `stale${since}${reason}`;
172
+ }
173
+ /**
174
+ * True while the shared process makes its first connection to FoundryVTT:
175
+ * not connected, no startup error, and either the core is not built yet (no
176
+ * connection nor bridge reported) or the link is still in its initial state
177
+ * (`disconnected` with no reason: every later disconnection carries one).
178
+ */
179
+ function isConnecting(status) {
180
+ if (status.foundryConnected || status.startupError) {
181
+ return false;
182
+ }
183
+ const connection = status.foundryConnection;
184
+ if (connection === undefined) {
185
+ return status.bridge === undefined && status.headlessGm === undefined;
186
+ }
187
+ return connection.state === 'disconnected' && connection.error === null;
188
+ }
160
189
  function formatFoundryConnection(status) {
161
190
  if (status.foundryConnected) {
162
191
  return 'connected';
163
192
  }
193
+ if (isConnecting(status)) {
194
+ return 'connecting…';
195
+ }
164
196
  const connection = status.foundryConnection;
165
197
  if (!connection || connection.state === 'disconnected') {
166
198
  return connection?.error ? `not connected — ${connection.error}` : 'not connected';
@@ -168,15 +200,15 @@ function formatFoundryConnection(status) {
168
200
  return `not connected (${connection.state}${connection.error ? ` — ${connection.error}` : ''})`;
169
201
  }
170
202
  function formatBridge(bridge, state, notStarted) {
203
+ if (state === 'not-started') {
204
+ return notStarted;
205
+ }
171
206
  if (!bridge || state === 'disabled') {
172
207
  return 'disabled';
173
208
  }
174
209
  if (state === 'failed') {
175
210
  return `failed to start — ${bridge.error ?? 'see the log'}`;
176
211
  }
177
- if (state === 'not-started') {
178
- return notStarted;
179
- }
180
212
  return (`listening on port ${bridge.port}, protocol v${bridge.protocol}, authenticated module connected: ` +
181
213
  yesNo(bridge.moduleConnected) +
182
214
  (bridge.moduleConnectedSince ? ` (since ${bridge.moduleConnectedSince})` : ''));
@@ -185,6 +217,10 @@ function formatHeadlessGm(headlessGm, bridgeState, notStarted) {
185
217
  if (headlessGm?.launchError) {
186
218
  return `browser launch failed — ${headlessGm.launchError}`;
187
219
  }
220
+ if (!headlessGm && bridgeState === 'not-started') {
221
+ // The core is not built yet (see isConnecting).
222
+ return notStarted;
223
+ }
188
224
  const state = headlessGm?.state ?? 'disabled';
189
225
  if (!headlessGm || state === 'disabled') {
190
226
  return 'disabled';
@@ -14,6 +14,7 @@ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
14
14
  import { configFromSettings, getConfig } from '../config/index.js';
15
15
  import { displayValue, KNOWN_SETTINGS, resolveSettings } from '../config/sources.js';
16
16
  import { logger } from '../utils/logger.js';
17
+ import { bareMessage } from '../utils/mcp-errors.js';
17
18
  import { isRefusal } from '../utils/refusal.js';
18
19
  import { compareBuilds } from './build-order.js';
19
20
  import { configDigests, configFingerprint } from './config-hash.js';
@@ -23,10 +24,7 @@ import { RotatingLog } from './rotating-log.js';
23
24
  import { removeStateFile, writeStateFile } from './state-file.js';
24
25
  import { loadOrCreateToken } from './token.js';
25
26
  import { buildVersion } from './version.js';
26
- /** McpError prefixes its message with "MCP error <code>: "; send the bare text. */
27
- function bareMessage(error) {
28
- return error.message.replace(/^MCP error -?\d+: /, '');
29
- }
27
+ /** Sends the bare text of an McpError: the relay rebuilds the McpError. */
30
28
  export function toIpcError(error) {
31
29
  if (error instanceof McpError) {
32
30
  return {
@@ -141,6 +141,11 @@ export const DaemonStatusSchema = z.object({
141
141
  error: z.string().nullable(),
142
142
  })
143
143
  .optional(),
144
+ // Absent from shared processes older than this field.
145
+ staleCache: z
146
+ .object({ since: z.string().nullable(), reason: z.string().nullable() })
147
+ .nullable()
148
+ .optional(),
144
149
  account: z
145
150
  .object({ name: z.string(), role: z.string().nullable(), warning: z.string().nullable() })
146
151
  .nullable()
@@ -171,16 +176,11 @@ export const DaemonStatusSchema = z.object({
171
176
  state: z.enum(['running', 'not-started', 'launch-failed', 'disabled']).optional(),
172
177
  mode: z.enum(['shared', 'separate']).nullable().optional(),
173
178
  modeText: z.string().nullable().optional(),
174
- sessionState: z
175
- .enum([
176
- 'waiting-for-session',
177
- 'logging-in',
178
- 'logged-in',
179
- 'reauthenticating',
180
- 'reconnecting',
181
- ])
182
- .nullable()
183
- .optional(),
179
+ // A HeadlessSessionState ('waiting-for-session', 'loading-game',
180
+ // 'logging-in', 'logged-in', 'reauthenticating', 'reconnecting'), read
181
+ // as a plain string so that a state added later does not make an older
182
+ // `status` command reject the whole answer.
183
+ sessionState: z.string().nullable().optional(),
184
184
  // Absent from shared processes older than browser detection.
185
185
  browser: z
186
186
  .object({