@g33ks/foundryvtt-mcp 2.1.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.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
6
  [![Node.js](https://img.shields.io/badge/Node.js-22%2B-green.svg)](https://nodejs.org/)
7
7
  [![TypeScript](https://img.shields.io/badge/TypeScript-6-blue.svg)](https://www.typescriptlang.org/)
8
- [![Tools](https://img.shields.io/badge/MCP%20Tools-114-purple.svg)](https://modelcontextprotocol.io/)
8
+ [![Tools](https://img.shields.io/badge/MCP%20Tools-115-purple.svg)](https://modelcontextprotocol.io/)
9
9
 
10
10
  A comprehensive, production-grade [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server for **Foundry Virtual Tabletop (FoundryVTT)**.
11
11
 
@@ -28,13 +28,13 @@ Your AI assistant starts a small relay program for this server. Every relay, fro
28
28
  - **Live world cache**: on connect, the server loads the world over Socket.IO and keeps it in memory; every `modifyDocument` broadcast — from the AI's own writes or from any user in Foundry — updates it, so reads are instant and stay current. `refresh_world_data` forces a full reload.
29
29
  - **Socket.IO connection**: authenticates as `FOUNDRY_USERNAME` (Assistant GM role recommended) and performs every write over Foundry's core `modifyDocument` protocol — only when `FOUNDRY_WRITE_ENABLED=true`. It is the only side that logs in: when Foundry forgets its session (server restart, world shut down) it logs in again by itself, retrying every 5 s at first and at most every 2 min, and tool calls made meanwhile wait up to 15 s before being refused with the reason.
30
30
  - **Invisible GM session**: started when `FOUNDRY_MODULE_BRIDGE_ENABLED=true`. The shared process drives a background browser through `playwright-core`: the first one found among Chrome, Edge, Brave, Vivaldi, a system Chromium and Playwright's own Chromium (`npx playwright install chromium`), or the Chromium-based browser set in `FOUNDRY_HEADLESS_GM_EXECUTABLE_PATH`. The page shares the Socket.IO connection's session — one account, one login — and never fills the `/join` form: Foundry keeps several connections per session, so neither ejects the other. The page stays on `/game` (a navigation elsewhere, such as **Log Out**, is blocked and the page reloads `/game`, because leaving would log the shared session out). A watchdog reloads the page if the module stays disconnected for about a minute. Advanced: `FOUNDRY_HEADLESS_GM_USERNAME` / `FOUNDRY_HEADLESS_GM_PASSWORD` naming another account give the page its own login instead. A human can meanwhile play as a normal **Player** in their own browser.
31
- - **Companion module** (`foundryvtt-mcp-bridge`, 0.5.0 or later): runs only in that GM session and serves the bridge tools — `capture_scene` (canvas screenshot with a grid overlay), `roll_and_post` (native `Roll` chat cards), `get_document_schema`, `search_compendium_content` and compendium imports, `upload_asset` (FilePicker), `set_pause`, `ping_canvas`, `set_target` / `get_targets`. Without it these tools report unavailable; everything else keeps working. The bridge listens on loopback only and authenticates the module — see [Module Bridge Security](#module-bridge-security).
31
+ - **Companion module** (`foundryvtt-mcp-bridge`, 0.5.0 or later): runs only in that GM session and serves the bridge tools — `capture_scene` (canvas screenshot with a grid overlay), `roll_and_post` (native `Roll` chat cards), `get_document_schema`, `search_compendium_content` and compendium imports, `upload_asset` (FilePicker), `set_pause`, `ping_canvas`, `set_target` / `get_targets`, and since 0.6.0 `get_actor_stats` (an actor's prepared data) and the game system's own path for `apply_status_effect`. Without it these tools report unavailable (`apply_status_effect` keeps its socket path); everything else keeps working. From 0.6.0 the module announces its version and commands when it connects, and the server sends it no command it does not announce; an older module is sent only the commands every 0.5 module serves. The bridge listens on loopback only and authenticates the module — see [Module Bridge Security](#module-bridge-security).
32
32
  - **Optional REST API module**: with `FOUNDRY_API_KEY` set, the server also connects to the Foundry Local REST API module over HTTP. It backs the diagnostics tools (`get_health_status`, `get_system_health`, `get_recent_logs`, `search_logs`, `diagnose_errors`) and `search_compendium`, and some reads use it instead of the cache (actor and item search, actor details, scene and world info, `roll_dice`). Socket.IO stays the main connection and carries every write.
33
33
  - **Shared process** (default): MCP clients may start several server instances — Claude Desktop starts several at launch — so each instance is only a lightweight relay, and the FoundryVTT connection, the bridge and the GM session live once, in a background process every relay shares. See [Shared Process Mode](#shared-process-mode); `FOUNDRY_MCP_SHARED=false` runs everything in one process instead.
34
34
 
35
35
  ---
36
36
 
37
- ## 🌟 Key Highlights & Capabilities (114 Tools)
37
+ ## 🌟 Key Highlights & Capabilities (115 Tools)
38
38
 
39
39
  - 👁️ **Real-Time Event Stream & Activity Log (`watch_events`)**: Zero-polling event awareness via Socket.IO `modifyDocument` and companion bridge pushes. An AI DM agent can long-poll on a cursor-addressed stream (`cursor`, `waitMs`, `excludeSelf`, `types`, `sceneId`) to react instantly when players chat, move tokens, advance combat, toggle doors, or select targets.
40
40
  - 🎲 **Game Mechanics & Interactive Chat**: Roll dice with standard or complex drop/keep notation (`4d6kh3`, `1d20r1`). Roll and post interactive, clickable chat cards directly to the Foundry chat log via the companion bridge (`roll_and_post`).
@@ -52,7 +52,7 @@ Your AI assistant starts a small relay program for this server. Every relay, fro
52
52
  - 🧙 **Token & Actor Control**:
53
53
  - **A\* Pathfinding Movement**: tokens navigate around walls and automatically open closed doors along their path (`move_token_pathfind`).
54
54
  - **Token Vision & Lighting**: configure sight ranges, vision modes, dim/bright emitted light, and vision detection angles (`update_token_vision`).
55
- - **Generalized ActiveEffects**: create, update, delete, and inspect mechanical buffs/debuffs with attribute changes (`key`, `mode`, `value`, `priority`) and durations (`rounds`, `seconds`, `turns`) on top-level or synthetic unlinked token actors (`create_actor_effect`, `update_actor_effect`, `delete_actor_effect`, `list_actor_effects`).
55
+ - **Generalized ActiveEffects**: create, update, delete, and inspect mechanical buffs/debuffs with attribute changes (`key`, `mode`, `value`, `priority`) and durations (`rounds`, `seconds`, `turns`) on world actors or on one token (an unlinked token changes alone, not its base actor) (`create_actor_effect`, `update_actor_effect`, `delete_actor_effect`, `list_actor_effects`).
56
56
  - **Status Conditions**: apply/remove system-agnostic status conditions (`apply_status_effect`).
57
57
  - **Compendium Actor & Item Import**: import entire NPC/monster documents from compendium packs with automatic per-item error recovery (`import_compendium_actor`), or import specific items into actor inventories (`create_actor_item`).
58
58
  - **System Attribute Mutations**: patch actor system data (HP, temporary HP, currency, resources, spell slots) using JSON merge patches (`update_actor_attributes`).
@@ -258,7 +258,8 @@ The bridge drives a GM session, and its loopback port is reachable by every loca
258
258
 
259
259
  - **Origin**: the WebSocket upgrade is refused (HTTP 403) unless its `Origin` header is the origin of `FOUNDRY_URL` — a page from another site cannot open the socket.
260
260
  - **Mutual handshake (protocol v1)**: the server sends a random challenge; the module answers with an HMAC-SHA256 proof, and the server answers with its own proof, which the module checks before obeying. Both are keyed by a random secret the shared process generates at startup and keeps in memory only — never written to disk, logged or returned by a tool. The headless GM session exposes a `window.foundryMcpBridge` function to its page (a Playwright binding) that computes the proofs, so the secret never enters the page or the WebSocket. It disappears with the shared process.
261
- - **Until authenticated**, a connection receives no command, nothing it sends is processed, and it cannot displace the connected module. It is closed with `4401` (wrong proof, unknown protocol, any other message), `4408` (no answer within 5 s — typically a module older than 0.5.0, logged as such) or `1009` (a message over 4 KiB). Refusals are logged as warnings (rate-limited); `status` and `get_health_status` show whether an authenticated module is connected.
261
+ - **Until authenticated**, a connection receives no command, nothing it sends is processed, and it cannot displace the connected module. It is closed with `4401` (wrong proof, unknown protocol, any other message), `4408` (no answer within 5 s — typically a module older than 0.5.0, logged as such) or `1009` (a message over 4 KiB). Refusals are logged as warnings (rate-limited); `status` and `get_health_status` show whether an authenticated module is connected, and its version: the one it announced (0.6.0 or later), otherwise the version installed in the world followed by `(not announced)`.
262
+ - **Module announcement (0.6.0 or later)**: the module's answer to the challenge also lists its version and the commands it serves. The proofs do not cover this list: it only decides which commands the server tries to send, and an absent or malformed one never fails the authentication.
262
263
  - **No manual GM tab**: a GM tab opened by hand has no `window.foundryMcpBridge`, so the module logs `no foundryvtt-mcp credentials in this browser, bridge disabled` to the browser console and stays silent. `FOUNDRY_HEADLESS_GM_ENABLED=false` therefore disables the bridge in practice.
263
264
  - **Check it**: with the connector running and the module connected, `npm run check:bridge-security`, from a clone, tries four forged connections and confirms each is refused while the module stays connected.
264
265
 
@@ -325,7 +326,7 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
325
326
 
326
327
  ---
327
328
 
328
- ## 🛠️ Tool Catalog (114 Tools)
329
+ ## 🛠️ Tool Catalog (115 Tools)
329
330
 
330
331
  ### 1. Real-Time Event Awareness
331
332
  - `watch_events` — long-poll a cursor-addressed activity log (`cursor`, `waitMs`, `limit`, `kinds`, `types`, `actions`, `sceneId`, `excludeSelf`) capturing document broadcasts and canvas activity without polling.
@@ -354,23 +355,25 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
354
355
  - `move_tokens` — batch move multiple tokens simultaneously.
355
356
  - `set_target` / `get_targets` — set and inspect token targeting reticles across connected users.
356
357
  - `update_token_vision` — configure vision ranges, vision modes, dim/bright emitted lights, and angles.
357
- - `apply_status_effect` — toggle simple status conditions (`prone`, `stunned`, `blinded`, `invisible`, etc.).
358
+ - `apply_status_effect` — toggle status conditions (`prone`, `stunned`, `blinded`, `invisible`, etc.). With the companion module 0.6.0 or later connected (it waits up to 10 s for one still connecting), it goes through the game system's own status effects, so the system recognises the condition, and effects an earlier version wrote for the status are reported, then removed with `active=false`. A game system that asks for a value when a status is created gets it from `createOptions`, under the option name the system documents; without it the call fails at once and nothing is created. `createOptions` are refused when that path is not available. Otherwise it writes an effect carrying the status over the socket (token icon always shown), which a game system that defines its own statuses with fixed effect ids may not recognise. The answer names the path used.
358
359
 
359
360
  ### 4. Actors & Inventory
360
361
  - `create_world_actor` / `create_full_actor` / `delete_world_actor` — create and delete actor documents.
361
362
  - `import_compendium_actor` — import entire NPCs/monsters from compendium packs with embedded items and automatic error recovery.
362
363
  - `search_actors` — query actors by name and type with cursor pagination support.
363
- - `get_actor_details` — retrieve actor system data, statistics, attributes, and health.
364
- - `update_actor_attributes` — patch nested system data using dot paths (`attributes.hp.value`, `currency.gp`).
365
- - `get_actor_inventory` — list owned items with full system properties.
364
+ - `get_actor_details` — retrieve actor system data, statistics, attributes, and health; with `sceneId` + `tokenId`, those of one token (an unlinked token has its own).
365
+ - `update_actor_attributes` — patch nested system data using dot paths (`attributes.hp.value`, `currency.gp`), on a world actor or one token. Write stored fields only: a field the game system computes is saved but has no effect in play.
366
+ - `get_actor_inventory` — list owned items with full system properties, of a world actor or one token.
367
+ - `get_actor_stats` — an actor's prepared system data as JSON, including the values the game system computes and does not store, of a world actor or one token; `paths` narrows it, `maxBytes` bounds it (companion module 0.6.0 or later).
366
368
  - `search_items` — search world item documents by name, optionally filtered by type (world items, not owned items).
367
369
  - `create_actor_item` — create inline items OR import directly from compendium packs (`source: { type: 'compendium', compendiumId, itemId }`).
368
370
  - `update_actor_item` — apply JSON merge patches to owned items.
369
371
  - `delete_actor_item` — delete specific items from actor inventories.
370
- - `create_actor_effect` / `update_actor_effect` / `delete_actor_effect` / `list_actor_effects` — general-purpose ActiveEffects with mechanical changes (`key`, `mode`, `value`, `priority`) and durations on top-level or synthetic unlinked token actors.
372
+ - The three item tools also take `sceneId` + `tokenId`: on an unlinked token, only that token changes.
373
+ - `create_actor_effect` / `update_actor_effect` / `delete_actor_effect` / `list_actor_effects` — general-purpose ActiveEffects with mechanical changes (`key`, `mode`, `value`, `priority`) and durations, on a world actor or one token (on an unlinked token, only that token changes).
371
374
 
372
375
  ### 5. Combat Encounters
373
- - `start_combat` — create encounters and seed combatants from scene tokens.
376
+ - `start_combat` — create encounters and seed combatants from scene tokens; the encounter begins at round 1.
374
377
  - `get_combat_state` — retrieve combatant turn order, HP, AC, and round number.
375
378
  - `set_initiative` — set combatant initiative values and re-order turns.
376
379
  - `next_turn` — advance the turn tracker (handles round increments and skips defeated combatants).
@@ -400,7 +403,7 @@ Add to `~/.omp/agent/mcp.json` (or `~/.omp/mcp.json`):
400
403
  - `roll_dice` — local mathematical dice formula evaluation.
401
404
  - `roll_and_post` — evaluates formulas via Foundry's native engine and posts interactive chat cards.
402
405
  - `lookup_rule` — search world journals and system compendium packs for rules with snippet previews.
403
- - `get_document_schema` — introspect game system DataModel schemas for actor and item types.
406
+ - `get_document_schema` — introspect game system DataModel schemas for actor and item types, with computed (`persisted: false`) fields and number bounds; for a type declared only by template.json, its default values with inferred types (module 0.6.0 or later).
404
407
  - `search_compendium` — search compendium packs by name and metadata, across all enabled packs or one pack (requires the REST API module; returns no results without it).
405
408
  - `search_compendium_content` — deep search inside compendium pack documents and journal pages.
406
409
  - `send_chat_message` / `get_chat_messages` — post and read messages from the Foundry chat log.
package/dist/core.js CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import path from 'node:path';
10
10
  import { ErrorCode, McpError, } from '@modelcontextprotocol/sdk/types.js';
11
+ import { BRIDGE_MODULE_ID } from './cli/checks.js';
11
12
  import { config, configSettings } from './config/index.js';
12
13
  import { summarizeSources } from './config/sources.js';
13
14
  import { DiagnosticsClient } from './diagnostics/client.js';
@@ -17,7 +18,7 @@ import { HeadlessGmSession } from './foundry/headless-gm-session.js';
17
18
  import { BRIDGE_PROTOCOL_VERSION, ModuleBridge } from './foundry/module-bridge.js';
18
19
  import { defaultStateDir } from './shared/paths.js';
19
20
  import { routeResourceRequest, routeToolRequest } from './tools/index.js';
20
- import { needsBridge, resourceDependency, toolDependency, waitsForSocket, } from './tools/tool-dependencies.js';
21
+ import { needsBridge, prefersBridge, resourceDependency, toolDependency, waitsForSocket, } from './tools/tool-dependencies.js';
21
22
  import { isWriteTool } from './tools/write-tools.js';
22
23
  import { DiagnosticSystem } from './utils/diagnostics.js';
23
24
  import { redactToolArgs } from './utils/log-args.js';
@@ -146,6 +147,7 @@ export class FoundryCore {
146
147
  this.moduleBridge = config.moduleBridge.enabled
147
148
  ? new ModuleBridge(config.moduleBridge.port, {
148
149
  expectedOrigin: new URL(config.foundry.url).origin,
150
+ installedModuleVersion: () => this.foundryClient.installedModuleVersion(BRIDGE_MODULE_ID),
149
151
  })
150
152
  : null;
151
153
  if (this.moduleBridge) {
@@ -307,6 +309,9 @@ export class FoundryCore {
307
309
  if (needsBridge(name, args)) {
308
310
  await this.waitForModule();
309
311
  }
312
+ else if (prefersBridge(name) && this.foundryClient.isWriteEnabled()) {
313
+ await this.waitForModuleIfComing();
314
+ }
310
315
  return (await routeToolRequest(name, args, this.foundryClient, this.diagnosticsClient, this.diagnosticSystem, this.moduleBridge, this.headlessGmSession, this.healthRuntime()));
311
316
  }
312
317
  catch (error) {
@@ -381,6 +386,22 @@ export class FoundryCore {
381
386
  }
382
387
  throw refuse(`still waiting for it after ${BRIDGE_CONNECT_WAIT_MS / 1000} s — ${session.statusText()}. Try again in a moment.`);
383
388
  }
389
+ /**
390
+ * For a tool that only prefers the module ({@link prefersBridge}): the same
391
+ * wait as {@link waitForModule}, but a module that cannot come, or does not
392
+ * come in time, leaves the call to go ahead on its socket path.
393
+ */
394
+ async waitForModuleIfComing() {
395
+ try {
396
+ await this.waitForModule();
397
+ }
398
+ catch (error) {
399
+ if (!isRefusal(error)) {
400
+ throw error;
401
+ }
402
+ logger.debug('Going ahead without the companion module', { reason: refusalReason(error) });
403
+ }
404
+ }
384
405
  /** Logs {@link gamemasterAccountWarning} after each authentication. */
385
406
  warnIfGamemaster() {
386
407
  const warning = gamemasterAccountWarning(this.sharedAccount, this.foundryClient.accountInfo());
@@ -462,6 +483,9 @@ export class FoundryCore {
462
483
  protocol: BRIDGE_PROTOCOL_VERSION,
463
484
  origin: new URL(config.foundry.url).origin,
464
485
  moduleConnectedSince: this.moduleBridge?.moduleConnectedSince()?.toISOString() ?? null,
486
+ moduleVersion: this.moduleBridge?.moduleAnnouncement().version ?? null,
487
+ moduleInstalledVersion: this.foundryClient.installedModuleVersion(BRIDGE_MODULE_ID),
488
+ moduleCommands: this.moduleBridge?.moduleAnnouncement().commands ?? null,
465
489
  },
466
490
  headlessGm: {
467
491
  enabled: headlessGmState !== 'disabled',
@@ -21,7 +21,7 @@ import { JournalConflictFile } from './journal-conflicts.js';
21
21
  import { JournalHistory } from './journal-history.js';
22
22
  import { conflictAuthor, JOURNAL_CONFLICT_SPEAKER, JournalWatch, journalConflictMessage, journalContribution, journalVersion, OVERWRITTEN_BY_CONNECTOR, RECENT_AUTOSAVE_MS, } from './journal-integrity.js';
23
23
  import { ACTIVE_EFFECT_MODES, OWNERSHIP_LEVELS, USER_ROLES, VISIBILITY_LEVELS } from './types.js';
24
- import { applyDocumentBroadcast, applyUserActivity, parseDocumentBatch, parseDocumentBroadcast, parseUserActivity, } from './world-cache.js';
24
+ import { applyDocumentBroadcast, applyUserActivity, mergePatch, parseDocumentBatch, parseDocumentBroadcast, parseUserActivity, } from './world-cache.js';
25
25
  /** Who overwrote a page when an editor autosave did: FoundryVTT does not say. */
26
26
  const EDITOR_AUTOSAVE_USER = 'editor-autosave (unknown user)';
27
27
  /** FoundryVTT document IDs are 16-character alphanumeric strings. */
@@ -1565,6 +1565,15 @@ export class FoundryClient {
1565
1565
  getWorldData() {
1566
1566
  return this.worldData;
1567
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
+ }
1568
1577
  // ==========================================================================
1569
1578
  // Actor methods
1570
1579
  // ==========================================================================
@@ -1692,6 +1701,169 @@ export class FoundryClient {
1692
1701
  }
1693
1702
  return { success: true, updatedAttributes };
1694
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
+ }
1695
1867
  /**
1696
1868
  * Creates a new top-level Actor document in the world.
1697
1869
  *
@@ -1704,9 +1876,10 @@ export class FoundryClient {
1704
1876
  * @param type - game-system actor type (e.g. "character", "npc")
1705
1877
  * @param system - optional system-specific data merged into `actor.system`
1706
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
1707
1880
  * @returns the newly created actor document
1708
1881
  */
1709
- async createWorldActor(name, type, system, folder) {
1882
+ async createWorldActor(name, type, system, folder, flags) {
1710
1883
  this.assertWriteable();
1711
1884
  if (!name || typeof name !== 'string') {
1712
1885
  throw new Error('name is required and must be a string');
@@ -1717,6 +1890,9 @@ export class FoundryClient {
1717
1890
  if (folder !== undefined && !FOUNDRY_ID_PATTERN.test(folder)) {
1718
1891
  throw new Error(`Invalid folder format: ${folder}`);
1719
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
+ }
1720
1896
  const data = { name, type };
1721
1897
  if (system) {
1722
1898
  data.system = system;
@@ -1724,6 +1900,9 @@ export class FoundryClient {
1724
1900
  if (folder) {
1725
1901
  data.folder = folder;
1726
1902
  }
1903
+ if (flags) {
1904
+ data.flags = flags;
1905
+ }
1727
1906
  const result = await this.modifyDocument('Actor', 'create', { data: [data] });
1728
1907
  return result[0];
1729
1908
  }
@@ -2027,14 +2206,34 @@ export class FoundryClient {
2027
2206
  // ==========================================================================
2028
2207
  // Item mutation methods (WRITE — Socket.IO modifyDocument)
2029
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
+ }
2030
2227
  /**
2031
2228
  * Creates a new item on an actor via the `modifyDocument` socket protocol.
2032
2229
  *
2033
2230
  * @param actorId - 16-char alphanumeric actor document id
2034
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)
2035
2234
  * @returns the newly created item document
2036
2235
  */
2037
- async createActorItem(actorId, source) {
2236
+ async createActorItem(actorId, source, token) {
2038
2237
  this.assertWriteable();
2039
2238
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
2040
2239
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -2042,7 +2241,7 @@ export class FoundryClient {
2042
2241
  const itemData = source.type === 'inline' ? source.item : {};
2043
2242
  const result = await this.modifyDocument('Item', 'create', {
2044
2243
  data: [itemData],
2045
- parentUuid: `Actor.${actorId}`,
2244
+ parentUuid: this.itemParentUuid(actorId, token),
2046
2245
  });
2047
2246
  return result[0];
2048
2247
  }
@@ -2056,9 +2255,14 @@ export class FoundryClient {
2056
2255
  * @param actorId - 16-char alphanumeric actor document id
2057
2256
  * @param itemId - 16-char alphanumeric item document id
2058
2257
  * @param patch - shallow/nested JSON merge patch applied to `item.system`
2059
- * @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
2060
2264
  */
2061
- async updateActorItem(actorId, itemId, patch) {
2265
+ async updateActorItem(actorId, itemId, patch, token) {
2062
2266
  this.assertWriteable();
2063
2267
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
2064
2268
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -2068,19 +2272,27 @@ export class FoundryClient {
2068
2272
  }
2069
2273
  const result = await this.modifyDocument('Item', 'update', {
2070
2274
  updates: [{ _id: itemId, system: patch }],
2071
- parentUuid: `Actor.${actorId}`,
2275
+ parentUuid: this.itemParentUuid(actorId, token),
2072
2276
  diff: true,
2073
2277
  recursive: true,
2074
2278
  });
2075
- 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
+ };
2076
2286
  }
2077
2287
  /**
2078
2288
  * Deletes an item owned by an actor via the `modifyDocument` socket protocol.
2079
2289
  *
2080
2290
  * @param actorId - 16-char alphanumeric actor document id
2081
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
2082
2294
  */
2083
- async deleteActorItem(actorId, itemId) {
2295
+ async deleteActorItem(actorId, itemId, token) {
2084
2296
  this.assertWriteable();
2085
2297
  if (!FOUNDRY_ID_PATTERN.test(actorId)) {
2086
2298
  throw new Error(`Invalid actorId format: ${actorId}`);
@@ -2090,7 +2302,7 @@ export class FoundryClient {
2090
2302
  }
2091
2303
  await this.modifyDocument('Item', 'delete', {
2092
2304
  ids: [itemId],
2093
- parentUuid: `Actor.${actorId}`,
2305
+ parentUuid: this.itemParentUuid(actorId, token),
2094
2306
  });
2095
2307
  }
2096
2308
  // ==========================================================================
@@ -2202,6 +2414,11 @@ export class FoundryClient {
2202
2414
  parentUuid: `Combat.${combatId}`,
2203
2415
  });
2204
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
+ });
2205
2422
  return { combatId, combatantCount: combatants.length };
2206
2423
  }
2207
2424
  // ==========================================================================
@@ -2335,14 +2552,45 @@ export class FoundryClient {
2335
2552
  });
2336
2553
  return result[0];
2337
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
+ }
2338
2582
  /**
2339
2583
  * Creates a status-effect `ActiveEffect` on a token's actor (FR-019).
2340
2584
  *
2341
- * `ActiveEffect` is an embedded document of `Actor`, so the create is sent with
2342
- * the actor's parent UUID:
2343
- * - `Actor.<id>` for a world-linked actor (`actorLink: true`)
2344
- * - `Scene.<sid>.Token.<tid>.Actor.<aid>` for an unlinked token's synthetic
2345
- * 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.
2346
2594
  *
2347
2595
  * The effect carries a `statuses` array, matching how FoundryVTT v11+ models
2348
2596
  * conditions (`Actor#toggleStatusEffect` toggles by this field).
@@ -2363,13 +2611,17 @@ export class FoundryClient {
2363
2611
  const effectData = {
2364
2612
  name: options.name ?? statusId,
2365
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,
2366
2618
  };
2367
2619
  if (options.img) {
2368
2620
  effectData.img = options.img;
2369
2621
  }
2370
2622
  const result = await this.modifyDocument('ActiveEffect', 'create', {
2371
2623
  data: [effectData],
2372
- parentUuid: parentActorUuid,
2624
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2373
2625
  });
2374
2626
  return result[0];
2375
2627
  }
@@ -2391,7 +2643,7 @@ export class FoundryClient {
2391
2643
  }
2392
2644
  await this.modifyDocument('ActiveEffect', 'delete', {
2393
2645
  ids: [effectId],
2394
- parentUuid: parentActorUuid,
2646
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2395
2647
  });
2396
2648
  }
2397
2649
  /**
@@ -2424,6 +2676,12 @@ export class FoundryClient {
2424
2676
  }
2425
2677
  if (effect.statuses) {
2426
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
+ }
2427
2685
  }
2428
2686
  if (effect.duration) {
2429
2687
  effectData.duration = effect.duration;
@@ -2434,7 +2692,7 @@ export class FoundryClient {
2434
2692
  }
2435
2693
  const result = await this.modifyDocument('ActiveEffect', 'create', {
2436
2694
  data: [effectData],
2437
- parentUuid: parentActorUuid,
2695
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2438
2696
  });
2439
2697
  return result[0];
2440
2698
  }
@@ -2480,7 +2738,7 @@ export class FoundryClient {
2480
2738
  }
2481
2739
  const result = await this.modifyDocument('ActiveEffect', 'update', {
2482
2740
  updates: [update],
2483
- parentUuid: parentActorUuid,
2741
+ parentUuid: this.toDeltaParentUuid(parentActorUuid),
2484
2742
  });
2485
2743
  return result[0];
2486
2744
  }
@@ -5755,6 +6013,22 @@ function worldSceneToFoundry(s) {
5755
6013
  }
5756
6014
  return scene;
5757
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
+ }
5758
6032
  /**
5759
6033
  * Returns the `system` object of an actor-like document, accepting either the
5760
6034
  * raw REST/world document (`{ ..., system }`) or a cached {@link WorldActor}.