@g33ks/foundryvtt-mcp 2.0.0 → 2.2.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 (35) hide show
  1. package/README.md +21 -29
  2. package/dist/cli/init.js +5 -1
  3. package/dist/cli/snippets.js +16 -1
  4. package/dist/core.js +104 -14
  5. package/dist/diagnostics/client.js +36 -98
  6. package/dist/foundry/auth.js +4 -0
  7. package/dist/foundry/client.js +750 -157
  8. package/dist/foundry/event-log.js +2 -3
  9. package/dist/foundry/headless-gm-session.js +119 -2
  10. package/dist/foundry/journal-conflicts.js +141 -0
  11. package/dist/foundry/journal-integrity.js +20 -4
  12. package/dist/foundry/message-author.js +19 -0
  13. package/dist/foundry/module-bridge.js +153 -6
  14. package/dist/foundry/world-cache.js +206 -8
  15. package/dist/mcp-server.js +5 -3
  16. package/dist/shared/control.js +47 -6
  17. package/dist/shared/daemon.js +2 -4
  18. package/dist/shared/protocol.js +14 -10
  19. package/dist/tools/definitions.js +128 -31
  20. package/dist/tools/handlers/actor-mutations.js +13 -7
  21. package/dist/tools/handlers/actor-target.js +80 -0
  22. package/dist/tools/handlers/actors.js +25 -12
  23. package/dist/tools/handlers/chat.js +3 -1
  24. package/dist/tools/handlers/combat-mutations.js +3 -2
  25. package/dist/tools/handlers/combat.js +48 -17
  26. package/dist/tools/handlers/diagnostics.js +14 -2
  27. package/dist/tools/handlers/effects.js +23 -24
  28. package/dist/tools/handlers/item-mutations.js +23 -21
  29. package/dist/tools/handlers/module-bridge.js +131 -2
  30. package/dist/tools/handlers/token-mutations.js +151 -16
  31. package/dist/tools/handlers/utils.js +3 -2
  32. package/dist/tools/router.js +6 -23
  33. package/dist/tools/tool-dependencies.js +207 -0
  34. package/dist/utils/mcp-errors.js +47 -0
  35. package/package.json +5 -5
@@ -17,10 +17,11 @@ import { RefusedError } from '../utils/refusal.js';
17
17
  import { authenticateFoundry, NoActiveWorldError, sessionSocketOptions } from './auth.js';
18
18
  import { evaluateDiceFormula } from './dice-formula.js';
19
19
  import { summarizeDocumentBroadcast, WorldEventLog } from './event-log.js';
20
+ import { JournalConflictFile } from './journal-conflicts.js';
20
21
  import { JournalHistory } from './journal-history.js';
21
22
  import { conflictAuthor, JOURNAL_CONFLICT_SPEAKER, JournalWatch, journalConflictMessage, journalContribution, journalVersion, OVERWRITTEN_BY_CONNECTOR, RECENT_AUTOSAVE_MS, } from './journal-integrity.js';
22
23
  import { ACTIVE_EFFECT_MODES, OWNERSHIP_LEVELS, USER_ROLES, VISIBILITY_LEVELS } from './types.js';
23
- import { applyDocumentBroadcast, applyUserActivity, parseDocumentBatch, parseDocumentBroadcast, parseUserActivity, } from './world-cache.js';
24
+ import { applyDocumentBroadcast, applyUserActivity, mergePatch, parseDocumentBatch, parseDocumentBroadcast, parseUserActivity, } from './world-cache.js';
24
25
  /** Who overwrote a page when an editor autosave did: FoundryVTT does not say. */
25
26
  const EDITOR_AUTOSAVE_USER = 'editor-autosave (unknown user)';
26
27
  /** FoundryVTT document IDs are 16-character alphanumeric strings. */
@@ -211,6 +212,19 @@ const WorldDataSchema = z.object({
211
212
  export const REAUTH_BASE_RETRY_MS = 5000;
212
213
  /** Longest wait between two reauthentication attempts. */
213
214
  export const REAUTH_MAX_RETRY_MS = 120_000;
215
+ /**
216
+ * How long to wait for FoundryVTT's `world` payload. It is the whole world in
217
+ * one message: about 10 s for an imported adventure with ~850 actors, which
218
+ * the old 10-15 s limits cut off.
219
+ */
220
+ const WORLD_LOAD_TIMEOUT_MS = 60_000;
221
+ /**
222
+ * Most cache changes kept while a world reload runs, to replay onto the new
223
+ * snapshot. Past it the replay is abandoned and the cache stays stale.
224
+ */
225
+ export const WORLD_REPLAY_MAX_CHANGES = 10_000;
226
+ /** Why the cache is stale after a replay that overflowed. */
227
+ const REPLAY_OVERFLOW_REASON = `more than ${WORLD_REPLAY_MAX_CHANGES} changes arrived while the world data was loading`;
214
228
  /** States in which the current session is known to be unusable. */
215
229
  const SESSION_LOST_STATES = new Set([
216
230
  'reauthenticating',
@@ -228,6 +242,38 @@ const ROLE_LABELS = {
228
242
  function errorMessage(error) {
229
243
  return error instanceof Error ? error.message : String(error);
230
244
  }
245
+ /**
246
+ * During a socket outage, a failed reconnection attempt is logged at most
247
+ * once per this interval — or at once when its message changes.
248
+ */
249
+ export const RECONNECT_ERROR_LOG_INTERVAL_MS = 60_000;
250
+ /** Longest reconnection error text kept for the log. */
251
+ const CONNECT_ERROR_MAX_LENGTH = 300;
252
+ /**
253
+ * Hides a session cookie in a text bound for the log. The socket URL
254
+ * carries it in its query (`?session=…`), and the cookie header as
255
+ * `session=…`: a transport error that quotes either must not leak it.
256
+ */
257
+ export function redactSession(text) {
258
+ return text.replace(/session=[^&\s;,"')]+/gi, 'session=<redacted>');
259
+ }
260
+ /**
261
+ * One line for a socket.io `connect_error`: its message, plus the message of
262
+ * the underlying transport error when it has one (e.g. "websocket error
263
+ * (getaddrinfo ENOTFOUND …)"). Never the error object itself, which holds
264
+ * the WebSocket and its URL. Session cookies are masked.
265
+ */
266
+ export function describeConnectError(error) {
267
+ const message = errorMessage(error);
268
+ const description = isRecord(error) ? error.description : undefined;
269
+ const detail = typeof description === 'string'
270
+ ? description
271
+ : isRecord(description) && typeof description.message === 'string'
272
+ ? description.message
273
+ : undefined;
274
+ const text = detail && detail !== message ? `${message} (${detail})` : message;
275
+ return redactSession(text).slice(0, CONNECT_ERROR_MAX_LENGTH);
276
+ }
231
277
  /** Label of a FoundryVTT user role, e.g. `Assistant GM`. */
232
278
  export function roleLabel(role) {
233
279
  return ROLE_LABELS[role] ?? `role ${role}`;
@@ -269,6 +315,27 @@ export class FoundryClient {
269
315
  worldData = null;
270
316
  /** Set when the socket drops with a cache still loaded (laurigates/foundryvtt-mcp#217). */
271
317
  worldDataStale = false;
318
+ /** Since when, and why, the cache is stale ({@link markWorldDataStale}); `null` when fresh. */
319
+ worldDataStaleSince = null;
320
+ worldDataStaleReason = null;
321
+ /** The world reload running, shared by every caller of {@link refreshWorldData}. */
322
+ worldReload = null;
323
+ /** Rejects the running reload and clears its timer; set while one waits for its answer. */
324
+ cancelWorldReload = null;
325
+ /**
326
+ * Cache changes made while a snapshot loads (first load or reload),
327
+ * replayed onto it ({@link changeCache}); `null` when none loads.
328
+ */
329
+ worldReplay = null;
330
+ /** Journal entries autosaved while the socket could not be asked; re-read once it can. */
331
+ autosavedDuringLoad = new Set();
332
+ /**
333
+ * The socket transport's current outage: since when, how many
334
+ * reconnection attempts failed, and the last one logged. `null` while up.
335
+ */
336
+ outage = null;
337
+ /** Counts socket drops: a reload that saw one leaves the cache stale. */
338
+ socketDrops = 0;
272
339
  /**
273
340
  * Last observed outcome of a REST request: false once one failed to reach
274
341
  * FoundryVTT at all (laurigates/foundryvtt-mcp#217). Unused in Socket.IO mode.
@@ -304,7 +371,7 @@ export class FoundryClient {
304
371
  ...config,
305
372
  };
306
373
  this.eventLog = new WorldEventLog(config.eventBufferSize ?? 500);
307
- this.journalWatch = new JournalWatch();
374
+ this.journalWatch = new JournalWatch(Date.now, config.journalConflictsFile ? new JournalConflictFile(config.journalConflictsFile) : null);
308
375
  this.journalHistory = new JournalHistory(config.journalHistoryDir ?? pathJoin(defaultStateDir(), 'journal-history'));
309
376
  this.http = axios.create({
310
377
  baseURL: this.config.baseUrl,
@@ -396,16 +463,17 @@ export class FoundryClient {
396
463
  async establishSession(user, password) {
397
464
  const { session } = await authenticateFoundry(this.config.baseUrl, user, password);
398
465
  // Connect authenticated socket and load world data
399
- this.worldData = await this.connectAndLoadWorld(session);
400
- this.worldDataStale = false;
466
+ const { overflowed } = await this.connectAndLoadWorld(session);
467
+ this.markWorldDataStale(overflowed, REPLAY_OVERFLOW_REASON);
401
468
  this.session = session;
402
469
  this.awaitingSession = false;
403
470
  this.setConnectionState('connected', null);
404
471
  logger.info('Connected to FoundryVTT via Socket.IO', {
405
- actors: this.worldData.actors.length,
406
- scenes: this.worldData.scenes.length,
407
- items: this.worldData.items.length,
472
+ actors: this.worldData?.actors.length ?? 0,
473
+ scenes: this.worldData?.scenes.length ?? 0,
474
+ items: this.worldData?.items.length ?? 0,
408
475
  });
476
+ this.rereadJournalsAutosavedDuringLoad();
409
477
  for (const listener of this.sessionListeners) {
410
478
  try {
411
479
  listener(session);
@@ -504,8 +572,9 @@ export class FoundryClient {
504
572
  this.connectionState = state;
505
573
  this.connectionError = state === 'connected' ? null : error;
506
574
  if (state === 'connected') {
507
- if (previous !== 'connected' && this.loggedConnection !== null) {
508
- logger.info('FoundryVTT connection restored');
575
+ const summary = previous !== 'connected' ? this.takeOutageSummary() : '';
576
+ if (previous !== 'connected' && (this.loggedConnection !== null || summary)) {
577
+ logger.info(`FoundryVTT connection restored${summary}`);
509
578
  }
510
579
  this.loggedConnection = null;
511
580
  for (const wake of this.connectionWaiters) {
@@ -614,71 +683,111 @@ export class FoundryClient {
614
683
  return designated;
615
684
  }
616
685
  /**
617
- * Connects Socket.IO with an authenticated session and loads worldData.
686
+ * Connects Socket.IO with an authenticated session and loads worldData
687
+ * ({@link loadWorldSnapshot}, which installs it).
688
+ *
689
+ * The data listeners and the replay are set up with the socket, before
690
+ * the handshake: a broadcast that arrives after FoundryVTT names the user
691
+ * but before the world is asked for (even in the same packet as the
692
+ * `session` event), or while FoundryVTT builds and sends the snapshot, is
693
+ * kept and replayed onto it instead of being lost. The lifecycle listeners
694
+ * (`connect`, `disconnect`, `session`, `shutdown`) come only once the
695
+ * snapshot is in: before that, the handshake's own `session` handler
696
+ * decides, and a `session` event must not read as connected yet.
697
+ *
698
+ * @returns whether the replay overflowed (the cache is then stale)
618
699
  */
619
- connectAndLoadWorld(session) {
700
+ async connectAndLoadWorld(session) {
620
701
  // A previous socket must not outlive its replacement (see `detachSocket`).
621
702
  this.detachSocket();
703
+ const replay = { changes: [], overflowed: false };
704
+ this.worldReplay = replay;
705
+ const socket = io(this.config.baseUrl, sessionSocketOptions(session));
706
+ this.socket = socket;
707
+ this.attachDataListeners(socket);
708
+ const deadline = Date.now() + WORLD_LOAD_TIMEOUT_MS;
709
+ const timeoutMessage = `Timeout waiting for world data (${WORLD_LOAD_TIMEOUT_MS / 1000}s)`;
710
+ try {
711
+ await this.waitForSessionUser(socket, WORLD_LOAD_TIMEOUT_MS, timeoutMessage);
712
+ const { overflowed } = await this.loadWorldSnapshot(socket, {
713
+ timeoutMs: Math.max(deadline - Date.now(), 0),
714
+ timeoutMessage,
715
+ schemaWarning: 'WorldData failed schema validation — proceeding with raw data',
716
+ replay,
717
+ });
718
+ // Liveness (laurigates/foundryvtt-mcp#217): a socket that drops on its own must stop reading
719
+ // as connected, and one that socket.io reconnects must read as
720
+ // connected again. Both are removed in `disconnect()`.
721
+ socket.on('connect', this.onSocketConnect);
722
+ socket.on('disconnect', this.onSocketDisconnect);
723
+ // Authentication (01.11 zombie socket): FoundryVTT answers every
724
+ // (re)connection with `session`; one without a user means the
725
+ // server forgot the session (restart) or no world is running.
726
+ socket.on('session', this.onSessionEvent);
727
+ // The world was shut down: its sessions outlive it, its sockets
728
+ // do not (a socket is only bound to a user when it connects).
729
+ socket.on('shutdown', this.onWorldShutdown);
730
+ // Each failed reconnection attempt while the socket is down.
731
+ socket.on('connect_error', this.onReconnectError);
732
+ return { overflowed };
733
+ }
734
+ catch (error) {
735
+ if (this.worldReplay === replay) {
736
+ this.worldReplay = null;
737
+ }
738
+ this.detachDataListeners(socket);
739
+ socket.disconnect();
740
+ throw error;
741
+ }
742
+ }
743
+ /**
744
+ * Keeps the cache live from the moment the socket exists
745
+ * (laurigates/foundryvtt-mcp#205); see {@link changeCache} for the
746
+ * changes that arrive while a snapshot loads.
747
+ */
748
+ attachDataListeners(socket) {
749
+ socket.on('modifyDocument', this.onDocumentBroadcast);
750
+ // Batches and operations with server-side side effects arrive here
751
+ // instead, never on both channels.
752
+ socket.on('modifyDocumentBatch', this.onDocumentBatchBroadcast);
753
+ // Presence (laurigates/foundryvtt-mcp#218): `activeUsers` is not a document collection, so it
754
+ // only moves on this event.
755
+ socket.on('userActivity', this.onUserActivity);
756
+ // Collaborative-editor autosaves bypass `modifyDocument` entirely.
757
+ socket.on('pm.autosave', this.onEditorAutosave);
758
+ }
759
+ detachDataListeners(socket) {
760
+ socket.off('modifyDocument', this.onDocumentBroadcast);
761
+ socket.off('modifyDocumentBatch', this.onDocumentBatchBroadcast);
762
+ socket.off('userActivity', this.onUserActivity);
763
+ socket.off('pm.autosave', this.onEditorAutosave);
764
+ }
765
+ /** The handshake: FoundryVTT's first `session` event must name a user. */
766
+ waitForSessionUser(socket, timeoutMs, timeoutMessage) {
622
767
  return new Promise((resolve, reject) => {
623
- this.socket = io(this.config.baseUrl, sessionSocketOptions(session));
624
768
  const cleanup = () => {
625
- this.socket?.off('session', onSession);
626
- this.socket?.off('connect_error', onConnectError);
769
+ clearTimeout(timeout);
770
+ socket.off('session', onSession);
771
+ socket.off('connect_error', onConnectError);
627
772
  };
628
773
  const timeout = setTimeout(() => {
629
774
  cleanup();
630
- this.socket?.disconnect();
631
- reject(new Error('Timeout waiting for world data (15s)'));
632
- }, 15000);
775
+ reject(new Error(timeoutMessage));
776
+ }, timeoutMs);
633
777
  const onSession = (data) => {
778
+ cleanup();
634
779
  if (!data?.userId) {
635
- clearTimeout(timeout);
636
- cleanup();
637
- this.socket?.disconnect();
638
- return reject(new Error('Authentication failed — session event returned no userId'));
780
+ reject(new Error('Authentication failed — session event returned no userId'));
781
+ return;
639
782
  }
640
- this.socket?.emit('world', (worldData) => {
641
- clearTimeout(timeout);
642
- cleanup();
643
- const parsed = WorldDataSchema.safeParse(worldData);
644
- if (!parsed.success) {
645
- logger.warn('WorldData failed schema validation — proceeding with raw data', {
646
- issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
647
- });
648
- }
649
- // Keep the snapshot live from here on (laurigates/foundryvtt-mcp#205). Attached only after a
650
- // successful handshake so the reject paths have no listener to leak.
651
- this.socket?.on('modifyDocument', this.onDocumentBroadcast);
652
- // Batches and operations with server-side side effects arrive here
653
- // instead, never on both channels.
654
- this.socket?.on('modifyDocumentBatch', this.onDocumentBatchBroadcast);
655
- // Presence (laurigates/foundryvtt-mcp#218): `activeUsers` is not a document collection, so it
656
- // only moves on this event.
657
- this.socket?.on('userActivity', this.onUserActivity);
658
- // Collaborative-editor autosaves bypass `modifyDocument` entirely.
659
- this.socket?.on('pm.autosave', this.onEditorAutosave);
660
- // Liveness (laurigates/foundryvtt-mcp#217): a socket that drops on its own must stop reading
661
- // as connected, and one that socket.io reconnects must read as
662
- // connected again. Both are removed in `disconnect()`.
663
- this.socket?.on('connect', this.onSocketConnect);
664
- this.socket?.on('disconnect', this.onSocketDisconnect);
665
- // Authentication (01.11 zombie socket): FoundryVTT answers every
666
- // (re)connection with `session`; one without a user means the
667
- // server forgot the session (restart) or no world is running.
668
- this.socket?.on('session', this.onSessionEvent);
669
- // The world was shut down: its sessions outlive it, its sockets
670
- // do not (a socket is only bound to a user when it connects).
671
- this.socket?.on('shutdown', this.onWorldShutdown);
672
- resolve(worldData);
673
- });
783
+ resolve();
674
784
  };
675
785
  const onConnectError = (err) => {
676
- clearTimeout(timeout);
677
786
  cleanup();
678
- reject(new Error(`Socket.IO connection failed: ${err.message}`));
787
+ reject(new Error(`Socket.IO connection failed: ${describeConnectError(err)}`));
679
788
  };
680
- this.socket.on('session', onSession);
681
- this.socket.on('connect_error', onConnectError);
789
+ socket.on('session', onSession);
790
+ socket.on('connect_error', onConnectError);
682
791
  });
683
792
  }
684
793
  /**
@@ -689,7 +798,7 @@ export class FoundryClient {
689
798
  * leaves the cache untouched (and stale) rather than taking the connection down.
690
799
  */
691
800
  onDocumentBroadcast = (payload) => {
692
- if (!this.worldData) {
801
+ if (!this.hasCacheTarget()) {
693
802
  return;
694
803
  }
695
804
  const broadcast = parseDocumentBroadcast(payload);
@@ -706,7 +815,7 @@ export class FoundryClient {
706
815
  * Bound field rather than a method so the same reference reaches `socket.off()`.
707
816
  */
708
817
  onDocumentBatchBroadcast = (payload) => {
709
- if (!this.worldData) {
818
+ if (!this.hasCacheTarget()) {
710
819
  return;
711
820
  }
712
821
  for (const broadcast of parseDocumentBatch(payload) ?? []) {
@@ -715,14 +824,16 @@ export class FoundryClient {
715
824
  };
716
825
  /** Cache, event log and journal overwrite watch for one document broadcast. Never throws. */
717
826
  handleDocumentBroadcast(broadcast) {
718
- if (!this.worldData) {
827
+ if (!this.hasCacheTarget()) {
719
828
  return;
720
829
  }
721
830
  try {
722
- const applied = applyDocumentBroadcast(this.worldData, broadcast);
723
- logger.debug(applied
724
- ? `Applied ${broadcast.action} ${broadcast.type} broadcast to cached worldData`
725
- : `Ignored ${broadcast.action} ${broadcast.type} broadcast (not cached)`);
831
+ const applied = this.changeCache((worldData) => applyDocumentBroadcast(worldData, broadcast));
832
+ logger.debug(!this.worldData
833
+ ? `Kept ${broadcast.action} ${broadcast.type} broadcast for the world data being loaded`
834
+ : applied
835
+ ? `Applied ${broadcast.action} ${broadcast.type} broadcast to cached worldData`
836
+ : `Ignored ${broadcast.action} ${broadcast.type} broadcast (not cached)`);
726
837
  }
727
838
  catch (error) {
728
839
  logger.warn('Failed to apply document broadcast to cached worldData', {
@@ -731,6 +842,11 @@ export class FoundryClient {
731
842
  error: error instanceof Error ? error.message : String(error),
732
843
  });
733
844
  }
845
+ if (!this.worldData) {
846
+ // First load of the session: the event log and the overwrite watch
847
+ // start with the snapshot.
848
+ return;
849
+ }
734
850
  // Recorded regardless of cache outcome — an uncached type (e.g. Setting)
735
851
  // is still world activity a `watch_events` caller may be waiting on.
736
852
  // Isolated in its own try/catch: a summarizer bug must never take the
@@ -790,13 +906,32 @@ export class FoundryClient {
790
906
  content: html,
791
907
  source: { kind: 'autosave' },
792
908
  });
909
+ if (!this.canSendOnSocket()) {
910
+ // A reauthentication is loading the world on a new socket, or the
911
+ // session is not known yet: nothing may be asked now. Re-read once it
912
+ // can. (On a first load the request may go: its answer goes through
913
+ // changeCache, so it reaches the snapshot being loaded.)
914
+ this.autosavedDuringLoad.add(journalId);
915
+ return;
916
+ }
917
+ this.rereadAutosavedJournal(journalId);
918
+ };
919
+ rereadAutosavedJournal(journalId) {
793
920
  this.fetchJournalEntry(journalId).catch((error) => {
794
921
  logger.warn('Could not re-read a journal entry after an editor autosave', {
795
922
  journalId,
796
923
  error: error instanceof Error ? error.message : String(error),
797
924
  });
798
925
  });
799
- };
926
+ }
927
+ /** Re-reads the entries autosaved while the socket could not be asked. */
928
+ rereadJournalsAutosavedDuringLoad() {
929
+ const journalIds = [...this.autosavedDuringLoad];
930
+ this.autosavedDuringLoad.clear();
931
+ for (const journalId of journalIds) {
932
+ this.rereadAutosavedJournal(journalId);
933
+ }
934
+ }
800
935
  /** The connected user plus the connector's other sessions (headless GM). */
801
936
  connectorUserIds() {
802
937
  const ids = new Set();
@@ -924,7 +1059,7 @@ export class FoundryClient {
924
1059
  * Never throws: an unrecognized payload leaves presence as it was.
925
1060
  */
926
1061
  onUserActivity = (userId, activityData) => {
927
- if (!this.worldData) {
1062
+ if (!this.hasCacheTarget()) {
928
1063
  return;
929
1064
  }
930
1065
  const activity = parseUserActivity(userId, activityData);
@@ -932,9 +1067,9 @@ export class FoundryClient {
932
1067
  logger.debug('Ignored unrecognized userActivity payload');
933
1068
  return;
934
1069
  }
935
- if (applyUserActivity(this.worldData, activity)) {
1070
+ if (this.changeCache((worldData) => applyUserActivity(worldData, activity))) {
936
1071
  logger.debug(`User ${activity.userId} is now ${activity.active ? 'active' : 'inactive'} (userActivity)`);
937
- const name = this.worldData.users?.find((user) => user._id === activity.userId)?.name;
1072
+ const name = this.worldData?.users?.find((user) => user._id === activity.userId)?.name;
938
1073
  this.eventLog.append({
939
1074
  kind: 'presence',
940
1075
  type: '',
@@ -971,9 +1106,9 @@ export class FoundryClient {
971
1106
  * FoundryVTT's `session` event names a user ({@link onSessionEvent}): after
972
1107
  * a server restart the same reconnect yields an anonymous socket.
973
1108
  *
974
- * `worldDataStale` is deliberately *not* cleared: broadcasts emitted while
975
- * the socket was down were never delivered and are not replayed, so the
976
- * cache stays flagged until an explicit `refreshWorldData()`.
1109
+ * `worldDataStale` is *not* cleared here: broadcasts emitted while the
1110
+ * socket was down were never delivered and are not replayed. Once
1111
+ * FoundryVTT names the user, {@link onSessionEvent} reloads the world.
977
1112
  *
978
1113
  * Bound field rather than a method so the same reference reaches `socket.off()`.
979
1114
  */
@@ -985,9 +1120,10 @@ export class FoundryClient {
985
1120
  };
986
1121
  /**
987
1122
  * Handles the `session` event FoundryVTT sends on every (re)connection of
988
- * the socket. With a user, the reconnected socket is authenticated again;
989
- * without one (server restarted, world not running), it is anonymous and
990
- * the client authenticates anew.
1123
+ * the socket. With a user, the reconnected socket is authenticated again,
1124
+ * and a cache that went stale while it was down is reloaded in the
1125
+ * background; without one (server restarted, world not running), it is
1126
+ * anonymous and the client authenticates anew.
991
1127
  *
992
1128
  * Bound field rather than a method so the same reference reaches `socket.off()`.
993
1129
  */
@@ -1000,19 +1136,40 @@ export class FoundryClient {
1000
1136
  if (userId) {
1001
1137
  if (this.connectionState !== 'connected') {
1002
1138
  this.setConnectionState('connected', null);
1003
- logger.info('FoundryVTT socket reconnected — cached world data is still stale until refreshed');
1139
+ logger.info('FoundryVTT socket reconnected with the same session');
1004
1140
  }
1141
+ if (this.worldDataStale) {
1142
+ this.reloadAfterReconnection();
1143
+ }
1144
+ this.rereadJournalsAutosavedDuringLoad();
1005
1145
  return;
1006
1146
  }
1007
1147
  this.reauthenticate('FoundryVTT no longer recognises the session (server restart?)').catch(() => undefined);
1008
1148
  };
1009
1149
  /** Bound field rather than a method so the same reference reaches `socket.off()`. */
1010
1150
  onWorldShutdown = () => {
1011
- this.worldDataStale = this.worldData !== null;
1151
+ this.markWorldDataStale(this.worldData !== null, 'the world was shut down');
1012
1152
  this.reauthenticate('the world was shut down').catch(() => undefined);
1013
1153
  };
1154
+ /**
1155
+ * Reloads the world without blocking anyone (tools keep answering from the
1156
+ * stale cache meanwhile). A failure leaves the cache stale.
1157
+ */
1158
+ reloadAfterReconnection() {
1159
+ logger.info('Reloading the world data after the socket reconnected');
1160
+ this.refreshWorldData().catch((error) => {
1161
+ logger.warn('Could not reload the world data after the socket reconnected — the cache stays stale', { error: errorMessage(error) });
1162
+ if (this.worldDataStale) {
1163
+ this.markWorldDataStale(true, `the reload after the reconnection failed: ${errorMessage(error)}`);
1164
+ }
1165
+ });
1166
+ }
1014
1167
  onSocketDisconnect = (reason) => {
1015
- this.worldDataStale = this.worldData !== null;
1168
+ this.socketDrops += 1;
1169
+ this.outage ??= { since: Date.now(), failedAttempts: 0, loggedAt: 0, loggedMessage: null };
1170
+ // Socket.IO never answers a request sent before the drop.
1171
+ this.cancelWorldReload?.('the socket dropped while the world data was loading');
1172
+ this.markWorldDataStale(this.worldData !== null, 'the socket dropped');
1016
1173
  if (this.reauthInFlight || this.connectionState !== 'connected') {
1017
1174
  return;
1018
1175
  }
@@ -1021,6 +1178,42 @@ export class FoundryClient {
1021
1178
  reason: typeof reason === 'string' ? reason : undefined,
1022
1179
  });
1023
1180
  };
1181
+ /**
1182
+ * A reconnection attempt of socket.io failed (socket.io emits
1183
+ * `connect_error` for each one while the socket is down). The first
1184
+ * failure is logged, then one line per {@link RECONNECT_ERROR_LOG_INTERVAL_MS},
1185
+ * or at once when the error changes; the count goes into the line written
1186
+ * when the connection is back ({@link takeOutageSummary}).
1187
+ *
1188
+ * Bound field rather than a method so the same reference reaches `socket.off()`.
1189
+ */
1190
+ onReconnectError = (error) => {
1191
+ this.outage ??= { since: Date.now(), failedAttempts: 0, loggedAt: 0, loggedMessage: null };
1192
+ const outage = this.outage;
1193
+ outage.failedAttempts += 1;
1194
+ const message = describeConnectError(error);
1195
+ const now = Date.now();
1196
+ if (outage.loggedMessage === null ||
1197
+ message !== outage.loggedMessage ||
1198
+ now - outage.loggedAt >= RECONNECT_ERROR_LOG_INTERVAL_MS) {
1199
+ outage.loggedAt = now;
1200
+ outage.loggedMessage = message;
1201
+ logger.warn(`FoundryVTT socket reconnection failed (attempt ${outage.failedAttempts}): ${message}`);
1202
+ }
1203
+ };
1204
+ /**
1205
+ * Ends the outage record: e.g. " after 42 s and 9 failed reconnection
1206
+ * attempt(s)", or `''` when there was none.
1207
+ */
1208
+ takeOutageSummary() {
1209
+ const outage = this.outage;
1210
+ if (!outage) {
1211
+ return '';
1212
+ }
1213
+ this.outage = null;
1214
+ const seconds = Math.round((Date.now() - outage.since) / 1000);
1215
+ return ` after ${seconds} s and ${outage.failedAttempts} failed reconnection attempt(s)`;
1216
+ }
1024
1217
  /**
1025
1218
  * Closes the current socket and removes every persistent listener bound to
1026
1219
  * it. Used both by `disconnect()` and before a socket is replaced: a
@@ -1030,17 +1223,16 @@ export class FoundryClient {
1030
1223
  * client, so this is reachable in-repo).
1031
1224
  */
1032
1225
  detachSocket() {
1226
+ this.cancelWorldReload?.('the connection closed while the world data was loading');
1033
1227
  if (!this.socket) {
1034
1228
  return;
1035
1229
  }
1036
- this.socket.off('modifyDocument', this.onDocumentBroadcast);
1037
- this.socket.off('modifyDocumentBatch', this.onDocumentBatchBroadcast);
1038
- this.socket.off('userActivity', this.onUserActivity);
1039
- this.socket.off('pm.autosave', this.onEditorAutosave);
1230
+ this.detachDataListeners(this.socket);
1040
1231
  this.socket.off('connect', this.onSocketConnect);
1041
1232
  this.socket.off('disconnect', this.onSocketDisconnect);
1042
1233
  this.socket.off('session', this.onSessionEvent);
1043
1234
  this.socket.off('shutdown', this.onWorldShutdown);
1235
+ this.socket.off('connect_error', this.onReconnectError);
1044
1236
  this.socket.disconnect();
1045
1237
  this.socket = null;
1046
1238
  }
@@ -1050,7 +1242,7 @@ export class FoundryClient {
1050
1242
  this.reauthTimer = null;
1051
1243
  this.detachSocket();
1052
1244
  this.worldData = null;
1053
- this.worldDataStale = false;
1245
+ this.markWorldDataStale(false);
1054
1246
  this._isConnected = false;
1055
1247
  this.session = null;
1056
1248
  this.connectionState = 'disconnected';
@@ -1058,6 +1250,7 @@ export class FoundryClient {
1058
1250
  this.loggedConnection = null;
1059
1251
  this.awaitingSession = false;
1060
1252
  this.restLinkLive = true;
1253
+ this.outage = null;
1061
1254
  logger.info('FoundryVTT client disconnected');
1062
1255
  }
1063
1256
  /** True when `FOUNDRY_API_KEY` is set: the REST API module backs diagnostics. */
@@ -1105,6 +1298,33 @@ export class FoundryClient {
1105
1298
  isWorldDataStale() {
1106
1299
  return this.worldDataStale;
1107
1300
  }
1301
+ /** Since when and why the cache is stale, for `status`; `null` while it is live. */
1302
+ worldDataStaleness() {
1303
+ if (!this.worldDataStale) {
1304
+ return null;
1305
+ }
1306
+ return {
1307
+ since: this.worldDataStaleSince?.toISOString() ?? null,
1308
+ reason: this.worldDataStaleReason,
1309
+ };
1310
+ }
1311
+ /**
1312
+ * Marks the cache stale, or live again. A cache that stays stale keeps the
1313
+ * time it became so; its reason is the latest one.
1314
+ */
1315
+ markWorldDataStale(stale, reason) {
1316
+ if (!stale) {
1317
+ this.worldDataStale = false;
1318
+ this.worldDataStaleSince = null;
1319
+ this.worldDataStaleReason = null;
1320
+ return;
1321
+ }
1322
+ if (!this.worldDataStale || this.worldDataStaleSince === null) {
1323
+ this.worldDataStaleSince = new Date();
1324
+ }
1325
+ this.worldDataStale = true;
1326
+ this.worldDataStaleReason = reason ?? this.worldDataStaleReason;
1327
+ }
1108
1328
  /**
1109
1329
  * Whether `FOUNDRY_WRITE_ENABLED` is set, without attempting a write.
1110
1330
  * Lets a caller that batches several writes in one tool call (e.g.
@@ -1198,51 +1418,162 @@ export class FoundryClient {
1198
1418
  /**
1199
1419
  * Re-emits 'world' on the existing socket to refresh the cached snapshot.
1200
1420
  *
1201
- * Registers a one-shot 'world' listener and cleans it up on every exit
1202
- * path (success, error, timeout) via `socket.off()` so that repeated
1203
- * refreshes over a long-running session do not leak listener handles.
1421
+ * FoundryVTT answers the `world` request through the Socket.IO
1422
+ * acknowledgement callback, exactly as in {@link connectAndLoadWorld}; it
1423
+ * never sends a separate `world` event, so listening for one always timed
1424
+ * out. An ack that arrives after the timeout is ignored.
1425
+ *
1426
+ * One reload at a time: concurrent callers (`refresh_world_data`, the
1427
+ * journal read fallback, the reload after a reconnection) share it. Cache
1428
+ * changes made while it runs are replayed onto the new snapshot, which the
1429
+ * server may have built before them ({@link changeCache}). The cache stays
1430
+ * stale when that replay overflowed or the socket dropped meanwhile. A
1431
+ * drop, a replaced socket or `disconnect()` cancels the reload.
1204
1432
  */
1205
- async refreshWorldData() {
1206
- if (!this.socket?.connected) {
1433
+ refreshWorldData() {
1434
+ if (this.worldReload) {
1435
+ return this.worldReload;
1436
+ }
1437
+ const reload = this.reloadWorldData().finally(() => {
1438
+ this.worldReload = null;
1439
+ });
1440
+ this.worldReload = reload;
1441
+ return reload;
1442
+ }
1443
+ async reloadWorldData() {
1444
+ const socket = this.socket;
1445
+ if (!socket?.connected) {
1207
1446
  throw new Error('Not connected — cannot refresh world data');
1208
1447
  }
1209
1448
  this.assertAuthenticated();
1210
- this.worldData = await new Promise((resolve, reject) => {
1211
- const cleanup = () => {
1212
- this.socket?.off('world', onWorld);
1213
- };
1214
- const timeoutId = setTimeout(() => {
1215
- cleanup();
1216
- reject(new Error('Refresh timeout'));
1217
- }, this.config.timeout ?? 15000);
1218
- const onWorld = (data) => {
1219
- cleanup();
1220
- clearTimeout(timeoutId);
1221
- try {
1222
- const parsed = WorldDataSchema.safeParse(data);
1449
+ const drops = this.socketDrops;
1450
+ const { data, overflowed } = await this.loadWorldSnapshot(socket, {
1451
+ timeoutMs: WORLD_LOAD_TIMEOUT_MS,
1452
+ timeoutMessage: 'Refresh timeout',
1453
+ schemaWarning: 'WorldData refresh failed schema validation — proceeding with raw data',
1454
+ });
1455
+ if (overflowed) {
1456
+ this.markWorldDataStale(true, REPLAY_OVERFLOW_REASON);
1457
+ }
1458
+ else {
1459
+ this.markWorldDataStale(this.socketDrops !== drops, 'the socket dropped while the world data was reloading');
1460
+ }
1461
+ logger.info('World data refreshed', {
1462
+ actors: data.actors.length,
1463
+ items: data.items.length,
1464
+ });
1465
+ }
1466
+ /**
1467
+ * Asks FoundryVTT for the whole world on `socket`, replays onto it the
1468
+ * cache changes that arrived meanwhile ({@link changeCache}), and installs
1469
+ * it as the cache. Shared by the first load of a session and the reloads.
1470
+ * An answer after the timeout, a cancellation ({@link cancelWorldReload})
1471
+ * or a replaced socket is ignored.
1472
+ *
1473
+ * @returns the installed snapshot, and whether the replay overflowed
1474
+ */
1475
+ async loadWorldSnapshot(socket, options) {
1476
+ const replay = options.replay ?? { changes: [], overflowed: false };
1477
+ this.worldReplay = replay;
1478
+ try {
1479
+ const data = await new Promise((resolve, reject) => {
1480
+ let settled = false;
1481
+ const settle = () => {
1482
+ settled = true;
1483
+ clearTimeout(timeoutId);
1484
+ this.cancelWorldReload = null;
1485
+ };
1486
+ const timeoutId = setTimeout(() => {
1487
+ settle();
1488
+ reject(new Error(options.timeoutMessage));
1489
+ }, options.timeoutMs);
1490
+ this.cancelWorldReload = (reason) => {
1491
+ settle();
1492
+ reject(new Error(`World data refresh cancelled: ${reason}`));
1493
+ };
1494
+ socket.emit('world', (payload) => {
1495
+ if (settled) {
1496
+ return;
1497
+ }
1498
+ settle();
1499
+ const parsed = WorldDataSchema.safeParse(payload);
1223
1500
  if (!parsed.success) {
1224
- logger.warn('WorldData refresh failed schema validation — proceeding with raw data', {
1501
+ logger.warn(options.schemaWarning, {
1225
1502
  issues: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
1226
1503
  });
1227
1504
  }
1228
- resolve(data);
1505
+ resolve(payload);
1506
+ });
1507
+ });
1508
+ if (this.socket !== socket) {
1509
+ throw new Error('World data refresh cancelled: the connection was replaced');
1510
+ }
1511
+ for (const change of replay.changes) {
1512
+ try {
1513
+ change(data);
1229
1514
  }
1230
- catch (err) {
1231
- reject(err);
1515
+ catch (error) {
1516
+ logger.warn('Failed to replay a cache change onto the reloaded world data', {
1517
+ error: errorMessage(error),
1518
+ });
1232
1519
  }
1233
- };
1234
- this.socket?.once('world', onWorld);
1235
- this.socket?.emit('world');
1236
- });
1237
- this.worldDataStale = false;
1238
- logger.info('World data refreshed', {
1239
- actors: this.worldData.actors.length,
1240
- items: this.worldData.items.length,
1241
- });
1520
+ }
1521
+ this.worldData = data;
1522
+ if (replay.overflowed) {
1523
+ logger.warn(`More than ${WORLD_REPLAY_MAX_CHANGES} cache changes arrived while the world data was loading, too many to replay — the cache stays stale until the next refresh`);
1524
+ }
1525
+ else if (replay.changes.length > 0) {
1526
+ logger.debug(`Replayed ${replay.changes.length} cache change(s) onto the loaded world data`);
1527
+ }
1528
+ return { data, overflowed: replay.overflowed };
1529
+ }
1530
+ finally {
1531
+ if (this.worldReplay === replay) {
1532
+ this.worldReplay = null;
1533
+ }
1534
+ }
1535
+ }
1536
+ /**
1537
+ * Applies a change to the cached world. While a snapshot loads (the first
1538
+ * one of a session, or a reload), the change is also kept for it: changes
1539
+ * are idempotent upserts and removals applied in arrival order, so
1540
+ * replaying one the snapshot already holds is harmless. Before the first
1541
+ * snapshot there is no cache: the change is only kept. Past
1542
+ * {@link WORLD_REPLAY_MAX_CHANGES} the kept changes are dropped and the
1543
+ * load leaves the cache stale.
1544
+ *
1545
+ * @returns what `change` returned, or `undefined` without a cache
1546
+ */
1547
+ changeCache(change) {
1548
+ const result = this.worldData ? change(this.worldData) : undefined;
1549
+ const replay = this.worldReplay;
1550
+ if (replay && !replay.overflowed) {
1551
+ if (replay.changes.length >= WORLD_REPLAY_MAX_CHANGES) {
1552
+ replay.changes = [];
1553
+ replay.overflowed = true;
1554
+ }
1555
+ else {
1556
+ replay.changes.push(change);
1557
+ }
1558
+ }
1559
+ return result;
1560
+ }
1561
+ /** True while there is a cache, or a snapshot loading that a change must reach. */
1562
+ hasCacheTarget() {
1563
+ return this.worldData !== null || this.worldReplay !== null;
1242
1564
  }
1243
1565
  getWorldData() {
1244
1566
  return this.worldData;
1245
1567
  }
1568
+ /**
1569
+ * The version of a module installed in the world, from the cached world's
1570
+ * module list; `null` when the module or its version is not there.
1571
+ */
1572
+ installedModuleVersion(moduleId) {
1573
+ const modules = this.worldData?.modules;
1574
+ const entry = Array.isArray(modules) ? modules.find((m) => m.id === moduleId) : undefined;
1575
+ return typeof entry?.version === 'string' ? entry.version : null;
1576
+ }
1246
1577
  // ==========================================================================
1247
1578
  // Actor methods
1248
1579
  // ==========================================================================
@@ -1370,6 +1701,169 @@ export class FoundryClient {
1370
1701
  }
1371
1702
  return { success: true, updatedAttributes };
1372
1703
  }
1704
+ /**
1705
+ * The `system` data a token's actor actually has: the world actor's for a
1706
+ * linked token, or the base actor's merged with the token's own delta for an
1707
+ * unlinked one (each unlinked copy of a monster has its own HP).
1708
+ *
1709
+ * @returns undefined when the token or its actor isn't in the cache
1710
+ */
1711
+ getTokenActorSystem(tokenId, sceneId) {
1712
+ const found = this.findToken(tokenId, sceneId);
1713
+ if (!found) {
1714
+ return undefined;
1715
+ }
1716
+ const { token } = found;
1717
+ const actorId = typeof token.actorId === 'string' ? token.actorId : undefined;
1718
+ const base = actorId ? systemOf(this.getRawActor(actorId)) : undefined;
1719
+ if (token.actorLink === true) {
1720
+ return base;
1721
+ }
1722
+ const merged = base ? structuredClone(base) : {};
1723
+ const deltaSystem = isRecord(token.delta) ? token.delta.system : undefined;
1724
+ if (isRecord(deltaSystem)) {
1725
+ mergePatch(merged, structuredClone(deltaSystem));
1726
+ }
1727
+ return merged;
1728
+ }
1729
+ /**
1730
+ * A token and the actor it carries, checked.
1731
+ *
1732
+ * @param actorId - when given, must be the token's actor
1733
+ * @throws when the scene or the token isn't in the cache, the token has no
1734
+ * actor, or carries another actor
1735
+ */
1736
+ resolveTokenActor(tokenId, sceneId, actorId) {
1737
+ const found = this.findToken(tokenId, sceneId);
1738
+ if (!found) {
1739
+ if (sceneId && this.worldData && !this.worldData.scenes.some((s) => s._id === sceneId)) {
1740
+ throw new Error(`Scene not found: ${sceneId}`);
1741
+ }
1742
+ throw new Error(`Token not found: ${tokenId}${sceneId ? ` in scene ${sceneId}` : ''}`);
1743
+ }
1744
+ const tokenActorId = typeof found.token.actorId === 'string' && found.token.actorId
1745
+ ? found.token.actorId
1746
+ : undefined;
1747
+ if (!tokenActorId) {
1748
+ throw new Error(`Token ${tokenId} has no actor`);
1749
+ }
1750
+ if (actorId !== undefined && actorId !== tokenActorId) {
1751
+ throw new Error(`Token ${tokenId} carries actor ${tokenActorId}, not ${actorId}`);
1752
+ }
1753
+ return { ...found, actorId: tokenActorId, linked: found.token.actorLink === true };
1754
+ }
1755
+ /**
1756
+ * A token's actor's effects, as FoundryVTT shows them (see {@link mergeDeltaEntries}).
1757
+ *
1758
+ * @returns undefined when the token isn't in the cache
1759
+ */
1760
+ getTokenActorEffects(tokenId, sceneId) {
1761
+ const found = this.findToken(tokenId, sceneId);
1762
+ if (!found) {
1763
+ return undefined;
1764
+ }
1765
+ const base = this.tokenBaseActor(found.token)?.effects ?? [];
1766
+ return found.token.actorLink === true
1767
+ ? [...base]
1768
+ : mergeDeltaEntries(base, isRecord(found.token.delta) ? found.token.delta.effects : undefined);
1769
+ }
1770
+ /**
1771
+ * A token's actor's items, as FoundryVTT shows them (see {@link mergeDeltaEntries}).
1772
+ *
1773
+ * @returns undefined when the token isn't in the cache
1774
+ */
1775
+ getTokenActorItems(tokenId, sceneId) {
1776
+ const found = this.findToken(tokenId, sceneId);
1777
+ if (!found) {
1778
+ return undefined;
1779
+ }
1780
+ const base = this.tokenBaseActor(found.token)?.items ?? [];
1781
+ return found.token.actorLink === true
1782
+ ? [...base]
1783
+ : mergeDeltaEntries(base, isRecord(found.token.delta) ? found.token.delta.items : undefined);
1784
+ }
1785
+ /**
1786
+ * A token's actor, mapped like {@link getActor}: for an unlinked token, its
1787
+ * base actor with the system data of {@link getTokenActorSystem} (and the
1788
+ * delta's name, when it has one). Read from the cache.
1789
+ *
1790
+ * @throws when the token or its base actor isn't in the cache
1791
+ */
1792
+ getTokenActor(tokenId, sceneId) {
1793
+ const { token, actorId, linked } = this.resolveTokenActor(tokenId, sceneId);
1794
+ const base = this.getRawActor(actorId);
1795
+ if (!base) {
1796
+ throw new Error(`Actor not found: ${actorId}`);
1797
+ }
1798
+ if (linked) {
1799
+ return worldActorToFoundry(base);
1800
+ }
1801
+ const deltaName = isRecord(token.delta) ? token.delta.name : undefined;
1802
+ return worldActorToFoundry({
1803
+ ...base,
1804
+ ...(typeof deltaName === 'string' && deltaName ? { name: deltaName } : {}),
1805
+ system: this.getTokenActorSystem(tokenId, sceneId) ?? {},
1806
+ });
1807
+ }
1808
+ /** The world actor a token was made from, when it is cached. */
1809
+ tokenBaseActor(token) {
1810
+ return typeof token.actorId === 'string' ? this.getRawActor(token.actorId) : undefined;
1811
+ }
1812
+ /**
1813
+ * Patches attributes on one token's actor. WRITE — Socket.IO.
1814
+ *
1815
+ * A linked token shares its world actor, so this is {@link updateActorAttribute}.
1816
+ * An unlinked token's changes go to its ActorDelta, the way FoundryVTT's own
1817
+ * client sends them: an `ActorDelta` update parented to the token, with the
1818
+ * delta's id and `syntheticActorUpdate: true`. The base actor, and every other
1819
+ * token made from it, is untouched.
1820
+ */
1821
+ async updateTokenActorAttribute(sceneId, tokenId, patch) {
1822
+ this.assertWriteable();
1823
+ if (!FOUNDRY_ID_PATTERN.test(sceneId)) {
1824
+ throw new Error(`Invalid sceneId format: ${sceneId}`);
1825
+ }
1826
+ if (!FOUNDRY_ID_PATTERN.test(tokenId)) {
1827
+ throw new Error(`Invalid tokenId format: ${tokenId}`);
1828
+ }
1829
+ if (!isRecord(patch) || Object.keys(patch).length === 0) {
1830
+ throw new Error('patch is required and must contain at least one attribute path');
1831
+ }
1832
+ const found = this.findToken(tokenId, sceneId);
1833
+ if (!found) {
1834
+ throw new Error(`Token not found: ${tokenId} in scene ${sceneId}`);
1835
+ }
1836
+ const { token } = found;
1837
+ const actorId = typeof token.actorId === 'string' ? token.actorId : undefined;
1838
+ if (!actorId) {
1839
+ throw new Error(`Token ${tokenId} has no actor`);
1840
+ }
1841
+ if (token.actorLink === true) {
1842
+ return this.updateActorAttribute(actorId, patch);
1843
+ }
1844
+ const actor = await this.getActor(actorId);
1845
+ validateAttributePatch(patch, actor, this.getTokenActorSystem(tokenId, sceneId));
1846
+ const delta = token.delta;
1847
+ const deltaId = isRecord(delta) && typeof delta._id === 'string' ? delta._id : tokenId;
1848
+ const update = { _id: deltaId };
1849
+ for (const [path, value] of Object.entries(patch)) {
1850
+ update[`system.${path}`] = value;
1851
+ }
1852
+ await this.modifyDocument('ActorDelta', 'update', {
1853
+ updates: [update],
1854
+ parentUuid: `Scene.${sceneId}.Token.${tokenId}`,
1855
+ syntheticActorUpdate: true,
1856
+ diff: true,
1857
+ recursive: true,
1858
+ });
1859
+ const after = this.getTokenActorSystem(tokenId, sceneId);
1860
+ const updatedAttributes = {};
1861
+ for (const [path, value] of Object.entries(patch)) {
1862
+ const cached = after ? getDotPath(after, path) : undefined;
1863
+ updatedAttributes[path] = cached !== undefined ? cached : value;
1864
+ }
1865
+ return { success: true, updatedAttributes };
1866
+ }
1373
1867
  /**
1374
1868
  * Creates a new top-level Actor document in the world.
1375
1869
  *
@@ -1382,9 +1876,10 @@ export class FoundryClient {
1382
1876
  * @param type - game-system actor type (e.g. "character", "npc")
1383
1877
  * @param system - optional system-specific data merged into `actor.system`
1384
1878
  * @param folder - optional 16-char Folder document id to file the actor under
1879
+ * @param flags - optional module flags (`actor.flags`), keyed by module id
1385
1880
  * @returns the newly created actor document
1386
1881
  */
1387
- async createWorldActor(name, type, system, folder) {
1882
+ async createWorldActor(name, type, system, folder, flags) {
1388
1883
  this.assertWriteable();
1389
1884
  if (!name || typeof name !== 'string') {
1390
1885
  throw new Error('name is required and must be a string');
@@ -1395,6 +1890,9 @@ export class FoundryClient {
1395
1890
  if (folder !== undefined && !FOUNDRY_ID_PATTERN.test(folder)) {
1396
1891
  throw new Error(`Invalid folder format: ${folder}`);
1397
1892
  }
1893
+ if (flags !== undefined && (!isRecord(flags) || !Object.values(flags).every(isRecord))) {
1894
+ throw new Error('flags must be an object of per-module objects, e.g. {"my-module": {...}}');
1895
+ }
1398
1896
  const data = { name, type };
1399
1897
  if (system) {
1400
1898
  data.system = system;
@@ -1402,6 +1900,9 @@ export class FoundryClient {
1402
1900
  if (folder) {
1403
1901
  data.folder = folder;
1404
1902
  }
1903
+ if (flags) {
1904
+ data.flags = flags;
1905
+ }
1405
1906
  const result = await this.modifyDocument('Actor', 'create', { data: [data] });
1406
1907
  return result[0];
1407
1908
  }
@@ -1676,13 +2177,11 @@ export class FoundryClient {
1676
2177
  }
1677
2178
  const main = responses[responses.length - 1];
1678
2179
  const result = Array.isArray(main?.result) ? main.result : [];
1679
- if (this.worldData) {
1680
- // Side effects are not echoed back to this client either.
1681
- for (const sideEffect of responses.slice(0, -1)) {
1682
- const broadcast = parseDocumentBroadcast(sideEffect);
1683
- if (broadcast) {
1684
- applyDocumentBroadcast(this.worldData, broadcast);
1685
- }
2180
+ // Side effects are not echoed back to this client either.
2181
+ for (const sideEffect of responses.slice(0, -1)) {
2182
+ const broadcast = parseDocumentBroadcast(sideEffect);
2183
+ if (broadcast) {
2184
+ this.changeCache((worldData) => applyDocumentBroadcast(worldData, broadcast));
1686
2185
  }
1687
2186
  }
1688
2187
  // FoundryVTT does not echo a client's own writes back on the
@@ -1694,28 +2193,47 @@ export class FoundryClient {
1694
2193
  // unconditionally: it is idempotent by construction (upserts by _id,
1695
2194
  // tolerates an already-gone delete id), so if Foundry *does* also
1696
2195
  // broadcast this write back later, re-applying it is a no-op.
1697
- if (this.worldData) {
1698
- const parentUuid = operation.parentUuid;
1699
- applyDocumentBroadcast(this.worldData, {
1700
- type,
1701
- action,
1702
- result,
1703
- ...(typeof parentUuid === 'string' && parentUuid ? { parentUuid } : {}),
1704
- });
1705
- }
2196
+ const parentUuid = operation.parentUuid;
2197
+ const ownWrite = {
2198
+ type,
2199
+ action,
2200
+ result,
2201
+ ...(typeof parentUuid === 'string' && parentUuid ? { parentUuid } : {}),
2202
+ };
2203
+ this.changeCache((worldData) => applyDocumentBroadcast(worldData, ownWrite));
1706
2204
  return result;
1707
2205
  }
1708
2206
  // ==========================================================================
1709
2207
  // Item mutation methods (WRITE — Socket.IO modifyDocument)
1710
2208
  // ==========================================================================
2209
+ /**
2210
+ * The parent of an item write: `Actor.<actorId>`, or, for one token, that
2211
+ * token's actor - its ActorDelta when unlinked (see {@link toDeltaParentUuid}).
2212
+ *
2213
+ * @throws when the token isn't in the cache or carries another actor
2214
+ */
2215
+ itemParentUuid(actorId, token) {
2216
+ if (!token) {
2217
+ return `Actor.${actorId}`;
2218
+ }
2219
+ if (!FOUNDRY_ID_PATTERN.test(token.sceneId)) {
2220
+ throw new Error(`Invalid sceneId format: ${token.sceneId}`);
2221
+ }
2222
+ if (!FOUNDRY_ID_PATTERN.test(token.tokenId)) {
2223
+ throw new Error(`Invalid tokenId format: ${token.tokenId}`);
2224
+ }
2225
+ return this.toDeltaParentUuid(`Scene.${token.sceneId}.Token.${token.tokenId}.Actor.${actorId}`);
2226
+ }
1711
2227
  /**
1712
2228
  * Creates a new item on an actor via the `modifyDocument` socket protocol.
1713
2229
  *
1714
2230
  * @param actorId - 16-char alphanumeric actor document id
1715
2231
  * @param source - inline item document or compendium source
2232
+ * @param token - one token whose actor gets the item instead (only that
2233
+ * token, for an unlinked one)
1716
2234
  * @returns the newly created item document
1717
2235
  */
1718
- async createActorItem(actorId, source) {
2236
+ async createActorItem(actorId, source, token) {
1719
2237
  this.assertWriteable();
1720
2238
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
1721
2239
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -1723,7 +2241,7 @@ export class FoundryClient {
1723
2241
  const itemData = source.type === 'inline' ? source.item : {};
1724
2242
  const result = await this.modifyDocument('Item', 'create', {
1725
2243
  data: [itemData],
1726
- parentUuid: `Actor.${actorId}`,
2244
+ parentUuid: this.itemParentUuid(actorId, token),
1727
2245
  });
1728
2246
  return result[0];
1729
2247
  }
@@ -1737,9 +2255,14 @@ export class FoundryClient {
1737
2255
  * @param actorId - 16-char alphanumeric actor document id
1738
2256
  * @param itemId - 16-char alphanumeric item document id
1739
2257
  * @param patch - shallow/nested JSON merge patch applied to `item.system`
1740
- * @returns the updated item document
2258
+ * @param token - one token whose actor's item to change instead; for an
2259
+ * unlinked token, an item it inherits is copied into its delta by the
2260
+ * server, so the base actor and its other tokens keep theirs
2261
+ * @returns the server's answer (only the changed fields) with the item's
2262
+ * `name` and `type` read back from the cache, which the answer has already
2263
+ * updated
1741
2264
  */
1742
- async updateActorItem(actorId, itemId, patch) {
2265
+ async updateActorItem(actorId, itemId, patch, token) {
1743
2266
  this.assertWriteable();
1744
2267
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
1745
2268
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -1749,19 +2272,27 @@ export class FoundryClient {
1749
2272
  }
1750
2273
  const result = await this.modifyDocument('Item', 'update', {
1751
2274
  updates: [{ _id: itemId, system: patch }],
1752
- parentUuid: `Actor.${actorId}`,
2275
+ parentUuid: this.itemParentUuid(actorId, token),
1753
2276
  diff: true,
1754
2277
  recursive: true,
1755
2278
  });
1756
- return result[0];
2279
+ const cached = (token
2280
+ ? this.getTokenActorItems(token.tokenId, token.sceneId)
2281
+ : this.getRawActor(actorId)?.items)?.find((item) => item._id === itemId);
2282
+ return {
2283
+ ...result[0],
2284
+ ...(cached ? { name: cached.name, type: cached.type } : {}),
2285
+ };
1757
2286
  }
1758
2287
  /**
1759
2288
  * Deletes an item owned by an actor via the `modifyDocument` socket protocol.
1760
2289
  *
1761
2290
  * @param actorId - 16-char alphanumeric actor document id
1762
2291
  * @param itemId - 16-char alphanumeric item document id
2292
+ * @param token - one token whose actor loses the item instead; for an
2293
+ * unlinked token, the server tombstones an inherited item in its delta
1763
2294
  */
1764
- async deleteActorItem(actorId, itemId) {
2295
+ async deleteActorItem(actorId, itemId, token) {
1765
2296
  this.assertWriteable();
1766
2297
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
1767
2298
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -1771,7 +2302,7 @@ export class FoundryClient {
1771
2302
  }
1772
2303
  await this.modifyDocument('Item', 'delete', {
1773
2304
  ids: [itemId],
1774
- parentUuid: `Actor.${actorId}`,
2305
+ parentUuid: this.itemParentUuid(actorId, token),
1775
2306
  });
1776
2307
  }
1777
2308
  // ==========================================================================
@@ -1883,6 +2414,11 @@ export class FoundryClient {
1883
2414
  parentUuid: `Combat.${combatId}`,
1884
2415
  });
1885
2416
  }
2417
+ // Begin the encounter as Foundry's own "Begin Combat" does (Combat#startCombat);
2418
+ // a combat left at round 0 hasn't started, and turn advances are meaningless.
2419
+ await this.modifyDocument('Combat', 'update', {
2420
+ updates: [{ _id: combatId, round: 1, turn: 0 }],
2421
+ });
1886
2422
  return { combatId, combatantCount: combatants.length };
1887
2423
  }
1888
2424
  // ==========================================================================
@@ -2016,14 +2552,45 @@ export class FoundryClient {
2016
2552
  });
2017
2553
  return result[0];
2018
2554
  }
2555
+ /**
2556
+ * Rewrites an unlinked token's synthetic-actor UUID to its ActorDelta UUID.
2557
+ *
2558
+ * FoundryVTT keeps an unlinked token's own items and effects on the token's
2559
+ * ActorDelta, and its client sends embedded writes for a token actor with
2560
+ * `parentUuid: "Scene.<sid>.Token.<tid>.ActorDelta.<did>"`
2561
+ * (ClientDatabaseBackend#adjustActorDeltaRequest). v14 rejects the
2562
+ * `...Token.<tid>.Actor.<aid>` form outright. The delta's id defaults to the
2563
+ * token's id. A linked token shares its world actor, so it gets
2564
+ * `Actor.<aid>`. Any other UUID is returned unchanged.
2565
+ *
2566
+ * @throws when the token isn't in the cache or carries another actor
2567
+ */
2568
+ toDeltaParentUuid(parentActorUuid) {
2569
+ const match = /^Scene\.([a-zA-Z0-9]{16})\.Token\.([a-zA-Z0-9]{16})\.Actor\.([a-zA-Z0-9]{16})$/.exec(parentActorUuid);
2570
+ if (!match) {
2571
+ return parentActorUuid;
2572
+ }
2573
+ const [, sceneId = '', tokenId = '', actorId = ''] = match;
2574
+ const { token, linked } = this.resolveTokenActor(tokenId, sceneId, actorId);
2575
+ if (linked) {
2576
+ return `Actor.${actorId}`;
2577
+ }
2578
+ const delta = token.delta;
2579
+ const deltaId = isRecord(delta) && typeof delta._id === 'string' ? delta._id : tokenId;
2580
+ return `Scene.${sceneId}.Token.${tokenId}.ActorDelta.${deltaId}`;
2581
+ }
2019
2582
  /**
2020
2583
  * Creates a status-effect `ActiveEffect` on a token's actor (FR-019).
2021
2584
  *
2022
- * `ActiveEffect` is an embedded document of `Actor`, so the create is sent with
2023
- * the actor's parent UUID:
2024
- * - `Actor.<id>` for a world-linked actor (`actorLink: true`)
2025
- * - `Scene.<sid>.Token.<tid>.Actor.<aid>` for an unlinked token's synthetic
2026
- * actor (the per-token delta).
2585
+ * `parentActorUuid` takes one of two forms:
2586
+ * - `Actor.<id>` for a world actor
2587
+ * - `Scene.<sid>.Token.<tid>.Actor.<aid>` for a token's actor.
2588
+ *
2589
+ * The create is sent with the parent {@link toDeltaParentUuid} makes of it:
2590
+ * `Actor.<aid>` for a world actor or a linked token, and
2591
+ * `Scene.<sid>.Token.<tid>.ActorDelta.<did>` for an unlinked token (its
2592
+ * per-token delta). A token that isn't cached or carries another actor is
2593
+ * refused before anything is sent.
2027
2594
  *
2028
2595
  * The effect carries a `statuses` array, matching how FoundryVTT v11+ models
2029
2596
  * conditions (`Actor#toggleStatusEffect` toggles by this field).
@@ -2044,13 +2611,17 @@ export class FoundryClient {
2044
2611
  const effectData = {
2045
2612
  name: options.name ?? statusId,
2046
2613
  statuses: [statusId],
2614
+ // ACTIVE_EFFECT_SHOW_ICON.ALWAYS, as ActiveEffect.fromStatusEffect sets.
2615
+ // The default (CONDITIONAL) only draws the token icon for temporary
2616
+ // effects, and since v14 a status alone no longer makes one temporary.
2617
+ showIcon: 2,
2047
2618
  };
2048
2619
  if (options.img) {
2049
2620
  effectData.img = options.img;
2050
2621
  }
2051
2622
  const result = await this.modifyDocument('ActiveEffect', 'create', {
2052
2623
  data: [effectData],
2053
- parentUuid: parentActorUuid,
2624
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2054
2625
  });
2055
2626
  return result[0];
2056
2627
  }
@@ -2072,7 +2643,7 @@ export class FoundryClient {
2072
2643
  }
2073
2644
  await this.modifyDocument('ActiveEffect', 'delete', {
2074
2645
  ids: [effectId],
2075
- parentUuid: parentActorUuid,
2646
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2076
2647
  });
2077
2648
  }
2078
2649
  /**
@@ -2105,6 +2676,12 @@ export class FoundryClient {
2105
2676
  }
2106
2677
  if (effect.statuses) {
2107
2678
  effectData.statuses = effect.statuses;
2679
+ if (effect.statuses.length > 0) {
2680
+ // ACTIVE_EFFECT_SHOW_ICON.ALWAYS, as createActorStatusEffect sets: since
2681
+ // v14 a status alone no longer makes the effect temporary, so the
2682
+ // default (CONDITIONAL) would hide its token icon.
2683
+ effectData.showIcon = 2;
2684
+ }
2108
2685
  }
2109
2686
  if (effect.duration) {
2110
2687
  effectData.duration = effect.duration;
@@ -2115,7 +2692,7 @@ export class FoundryClient {
2115
2692
  }
2116
2693
  const result = await this.modifyDocument('ActiveEffect', 'create', {
2117
2694
  data: [effectData],
2118
- parentUuid: parentActorUuid,
2695
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2119
2696
  });
2120
2697
  return result[0];
2121
2698
  }
@@ -2161,7 +2738,7 @@ export class FoundryClient {
2161
2738
  }
2162
2739
  const result = await this.modifyDocument('ActiveEffect', 'update', {
2163
2740
  updates: [update],
2164
- parentUuid: parentActorUuid,
2741
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2165
2742
  });
2166
2743
  return result[0];
2167
2744
  }
@@ -2383,9 +2960,9 @@ export class FoundryClient {
2383
2960
  const raw = Array.isArray(response.result) ? response.result[0] : undefined;
2384
2961
  if (raw === undefined) {
2385
2962
  // Gone on the server: drop it from the cache too.
2386
- if (this.worldData) {
2387
- this.worldData.journal = this.worldData.journal.filter((j) => j._id !== journalId);
2388
- }
2963
+ this.changeCache((worldData) => {
2964
+ worldData.journal = worldData.journal.filter((j) => j._id !== journalId);
2965
+ });
2389
2966
  return undefined;
2390
2967
  }
2391
2968
  const parsed = FetchedJournalSchema.safeParse(raw);
@@ -2394,15 +2971,15 @@ export class FoundryClient {
2394
2971
  }
2395
2972
  // Validated above; the cast only bridges `exactOptionalPropertyTypes`.
2396
2973
  const journal = parsed.data;
2397
- if (this.worldData) {
2398
- const index = this.worldData.journal.findIndex((j) => j._id === journalId);
2974
+ this.changeCache((worldData) => {
2975
+ const index = worldData.journal.findIndex((j) => j._id === journalId);
2399
2976
  if (index === -1) {
2400
- this.worldData.journal.push(journal);
2977
+ worldData.journal.push(journal);
2401
2978
  }
2402
2979
  else {
2403
- this.worldData.journal[index] = journal;
2980
+ worldData.journal[index] = journal;
2404
2981
  }
2405
- }
2982
+ });
2406
2983
  return journal;
2407
2984
  }
2408
2985
  // ==========================================================================
@@ -5436,6 +6013,22 @@ function worldSceneToFoundry(s) {
5436
6013
  }
5437
6014
  return scene;
5438
6015
  }
6016
+ /**
6017
+ * An unlinked token's effects or items: the base actor's, each replaced by the
6018
+ * delta's entry with the same id, then the delta's own, without the entries
6019
+ * the delta tombstoned. Builds a new array and leaves the cache as it is.
6020
+ */
6021
+ function mergeDeltaEntries(base, delta) {
6022
+ const deltaEntries = Array.isArray(delta)
6023
+ ? delta.filter((entry) => isRecord(entry) && typeof entry._id === 'string')
6024
+ : [];
6025
+ const byId = new Map(deltaEntries.map((entry) => [entry._id, entry]));
6026
+ const baseIds = new Set(base.map((entry) => entry._id));
6027
+ return [
6028
+ ...base.map((entry) => byId.get(entry._id) ?? entry),
6029
+ ...deltaEntries.filter((entry) => !baseIds.has(entry._id)),
6030
+ ].filter((entry) => entry._tombstone !== true);
6031
+ }
5439
6032
  /**
5440
6033
  * Returns the `system` object of an actor-like document, accepting either the
5441
6034
  * raw REST/world document (`{ ..., system }`) or a cached {@link WorldActor}.