@g33ks/foundryvtt-mcp 0.0.0-stage → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +457 -2
  3. package/dist/character/manager.js +208 -0
  4. package/dist/cli/checks.js +307 -0
  5. package/dist/cli/config-file.js +120 -0
  6. package/dist/cli/init.js +414 -0
  7. package/dist/cli/prompt.js +117 -0
  8. package/dist/cli/snippets.js +64 -0
  9. package/dist/combat/manager.js +371 -0
  10. package/dist/config/env-layers.js +49 -0
  11. package/dist/config/index.js +298 -0
  12. package/dist/config/sources.js +201 -0
  13. package/dist/core.js +481 -0
  14. package/dist/diagnostics/client.js +291 -0
  15. package/dist/diagnostics/types.js +94 -0
  16. package/dist/foundry/auth.js +224 -0
  17. package/dist/foundry/browser-detect.js +170 -0
  18. package/dist/foundry/client.js +5874 -0
  19. package/dist/foundry/dice-formula.js +154 -0
  20. package/dist/foundry/event-log.js +298 -0
  21. package/dist/foundry/headless-gm-session.js +857 -0
  22. package/dist/foundry/journal-conflicts.js +141 -0
  23. package/dist/foundry/journal-history.js +90 -0
  24. package/dist/foundry/journal-integrity.js +322 -0
  25. package/dist/foundry/message-author.js +19 -0
  26. package/dist/foundry/module-bridge.js +441 -0
  27. package/dist/foundry/types.js +52 -0
  28. package/dist/foundry/world-cache.js +386 -0
  29. package/dist/index.js +107 -0
  30. package/dist/mcp-server.js +65 -0
  31. package/dist/server.js +159 -0
  32. package/dist/shared/build-order.js +134 -0
  33. package/dist/shared/config-hash.js +62 -0
  34. package/dist/shared/config-notice.js +55 -0
  35. package/dist/shared/control.js +291 -0
  36. package/dist/shared/daemon-link.js +135 -0
  37. package/dist/shared/daemon.js +311 -0
  38. package/dist/shared/ipc-client.js +200 -0
  39. package/dist/shared/ipc-server.js +316 -0
  40. package/dist/shared/paths.js +79 -0
  41. package/dist/shared/protocol.js +230 -0
  42. package/dist/shared/relay-config.js +65 -0
  43. package/dist/shared/relay.js +120 -0
  44. package/dist/shared/rotating-log.js +57 -0
  45. package/dist/shared/spawn.js +39 -0
  46. package/dist/shared/state-file.js +33 -0
  47. package/dist/shared/token.js +62 -0
  48. package/dist/shared/version.js +57 -0
  49. package/dist/tools/base.js +74 -0
  50. package/dist/tools/definitions.js +3109 -0
  51. package/dist/tools/handlers/actor-mutations.js +128 -0
  52. package/dist/tools/handlers/actors.js +114 -0
  53. package/dist/tools/handlers/chat-mutations.js +49 -0
  54. package/dist/tools/handlers/chat.js +38 -0
  55. package/dist/tools/handlers/combat-mutations.js +215 -0
  56. package/dist/tools/handlers/combat-order.js +94 -0
  57. package/dist/tools/handlers/combat.js +51 -0
  58. package/dist/tools/handlers/compendium.js +83 -0
  59. package/dist/tools/handlers/diagnostics.js +450 -0
  60. package/dist/tools/handlers/dice.js +54 -0
  61. package/dist/tools/handlers/effects.js +103 -0
  62. package/dist/tools/handlers/events.js +50 -0
  63. package/dist/tools/handlers/generation.js +258 -0
  64. package/dist/tools/handlers/item-mutations.js +132 -0
  65. package/dist/tools/handlers/items.js +53 -0
  66. package/dist/tools/handlers/journal-mutations.js +230 -0
  67. package/dist/tools/handlers/journals.js +80 -0
  68. package/dist/tools/handlers/module-bridge.js +421 -0
  69. package/dist/tools/handlers/placeable-mutations.js +272 -0
  70. package/dist/tools/handlers/resources.js +203 -0
  71. package/dist/tools/handlers/roll-tables.js +97 -0
  72. package/dist/tools/handlers/scene-mutations.js +159 -0
  73. package/dist/tools/handlers/scenes.js +355 -0
  74. package/dist/tools/handlers/settings.js +53 -0
  75. package/dist/tools/handlers/tile-mutations.js +56 -0
  76. package/dist/tools/handlers/token-mutations.js +356 -0
  77. package/dist/tools/handlers/users.js +59 -0
  78. package/dist/tools/handlers/utils.js +48 -0
  79. package/dist/tools/handlers/wall-mutations.js +98 -0
  80. package/dist/tools/handlers/world-documents.js +222 -0
  81. package/dist/tools/handlers/world.js +92 -0
  82. package/dist/tools/index.js +25 -0
  83. package/dist/tools/new-router.js +97 -0
  84. package/dist/tools/registry.js +79 -0
  85. package/dist/tools/resources.js +63 -0
  86. package/dist/tools/router.js +688 -0
  87. package/dist/tools/tool-dependencies.js +194 -0
  88. package/dist/tools/write-tools.js +97 -0
  89. package/dist/utils/cache-instance.js +30 -0
  90. package/dist/utils/cache.js +205 -0
  91. package/dist/utils/diagnostics.js +332 -0
  92. package/dist/utils/guards.js +17 -0
  93. package/dist/utils/image-size.js +160 -0
  94. package/dist/utils/log-args.js +47 -0
  95. package/dist/utils/logger.js +203 -0
  96. package/dist/utils/mcp-errors.js +47 -0
  97. package/dist/utils/refusal.js +30 -0
  98. package/dist/utils/sanitize.js +22 -0
  99. package/dist/utils/serial-queue.js +22 -0
  100. package/package.json +124 -4
@@ -0,0 +1,441 @@
1
+ /**
2
+ * @fileoverview WebSocket relay to the companion Foundry module.
3
+ *
4
+ * FoundryVTT's own Socket.IO API (used by {@link FoundryClient}) only reaches
5
+ * the document/database layer — it has no route to the browser's canvas,
6
+ * PIXI, or `game.packs`. A handful of capabilities (scene screenshots, fog
7
+ * reveal, compendium import) only exist inside a real, rendered browser tab.
8
+ *
9
+ * This class is the server side of that bridge: it hosts a plain WebSocket
10
+ * server that the companion `foundry-module/` package (loaded into Foundry as
11
+ * a module, running in the GM's browser) dials into as a client. Commands are
12
+ * `{ id, type, params }`; responses are `{ id, result }` or `{ id, error }` —
13
+ * the same shape used by alexivenkov/foundry-api-bridge-module's
14
+ * `WebSocketClient.ts` (MIT), which this mirrors from the server side.
15
+ *
16
+ * Exactly one module connection is supported at a time (the GM's client); a
17
+ * new *authenticated* connection replaces the previous one.
18
+ *
19
+ * Authentication (protocol v1). The loopback listener is reachable by every
20
+ * local process and every page open in a local browser, so a connection is
21
+ * only trusted once it has proven it is the module running in the headless
22
+ * GM session ({@link HeadlessGmSession}), and the module only obeys once the
23
+ * server has proven it is this process:
24
+ *
25
+ * 1. Upgrade: the `Origin` header must be `FOUNDRY_URL`'s origin (HTTP 403
26
+ * otherwise), so a page from any other site cannot even open the socket.
27
+ * 2. Server → module `{type: "auth_challenge", protocol: 1, nonce: Ns}`.
28
+ * 3. Module → server `{type: "auth_response", protocol: 1, nonce: Nc, proof: Pc}`.
29
+ * 4. Server → module `{type: "auth_ok", proof: Ps}`.
30
+ *
31
+ * Both proofs are HMAC-SHA256 over the two nonces, keyed by a random secret
32
+ * generated per instance that never leaves this class: the module obtains
33
+ * `Nc`, `Pc` and the expected `Ps` from {@link ModuleBridge.prove}, which the
34
+ * headless session exposes to its page through a Playwright binding. Until
35
+ * step 3 checks out, a connection cannot replace the current module, receives
36
+ * no command, and nothing it sends is processed.
37
+ */
38
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
39
+ import { WebSocket, WebSocketServer } from 'ws';
40
+ import { isRecord } from '../utils/guards.js';
41
+ import { logger } from '../utils/logger.js';
42
+ /** Version of the authentication handshake spoken by this server. */
43
+ export const BRIDGE_PROTOCOL_VERSION = 1;
44
+ /** Close codes sent to a connection that fails authentication. */
45
+ export const BRIDGE_CLOSE_CODES = {
46
+ /** Wrong proof, unknown protocol version, or any other message before authenticating. */
47
+ unauthorized: 4401,
48
+ /** No `auth_response` within the authentication window. */
49
+ authTimeout: 4408,
50
+ /** A message larger than {@link MAX_PREAUTH_MESSAGE_BYTES} before authenticating. */
51
+ messageTooBig: 1009,
52
+ };
53
+ const NONCE_BYTES = 32;
54
+ /** Length of the base64 encoding of {@link NONCE_BYTES} bytes. */
55
+ const NONCE_BASE64_LENGTH = 44;
56
+ const AUTH_TIMEOUT_MS = 5000;
57
+ const MAX_PREAUTH_MESSAGE_BYTES = 4096;
58
+ const PROOF_LABEL = 'foundryvtt-mcp-bridge/v1';
59
+ /** Refusal warnings logged per window; the rest are counted and summarised. */
60
+ const REFUSAL_LOG_LIMIT = 10;
61
+ const REFUSAL_LOG_WINDOW_MS = 60_000;
62
+ function isBridgeMessage(value) {
63
+ return typeof value === 'object' && value !== null;
64
+ }
65
+ /** A canonical base64 encoding of exactly {@link NONCE_BYTES} bytes. */
66
+ function isNonce(value) {
67
+ if (typeof value !== 'string' || value.length !== NONCE_BASE64_LENGTH) {
68
+ return false;
69
+ }
70
+ const bytes = Buffer.from(value, 'base64');
71
+ return bytes.length === NONCE_BYTES && bytes.toString('base64') === value;
72
+ }
73
+ function rawDataBytes(data) {
74
+ if (Array.isArray(data)) {
75
+ return data.reduce((total, chunk) => total + chunk.length, 0);
76
+ }
77
+ return data instanceof ArrayBuffer ? data.byteLength : data.length;
78
+ }
79
+ function rawDataText(data) {
80
+ if (Array.isArray(data)) {
81
+ return Buffer.concat(data).toString();
82
+ }
83
+ return data instanceof ArrayBuffer ? Buffer.from(data).toString() : data.toString();
84
+ }
85
+ /**
86
+ * Logs connection refusals without letting a local process flood the log by
87
+ * reconnecting in a loop: at most {@link REFUSAL_LOG_LIMIT} per window, then
88
+ * one line with the count of the ones left out.
89
+ */
90
+ class RefusalLog {
91
+ windowStart = 0;
92
+ logged = 0;
93
+ suppressed = 0;
94
+ warn(message, meta) {
95
+ const now = Date.now();
96
+ if (now - this.windowStart >= REFUSAL_LOG_WINDOW_MS) {
97
+ if (this.suppressed > 0) {
98
+ logger.warn(`Module bridge: ${this.suppressed} more refused connection(s) not logged in the last minute`);
99
+ }
100
+ this.windowStart = now;
101
+ this.logged = 0;
102
+ this.suppressed = 0;
103
+ }
104
+ if (this.logged < REFUSAL_LOG_LIMIT) {
105
+ this.logged++;
106
+ logger.warn(message, meta);
107
+ }
108
+ else {
109
+ this.suppressed++;
110
+ }
111
+ }
112
+ }
113
+ export class ModuleBridge {
114
+ /** One listener per loopback address. */
115
+ servers = [];
116
+ /** The authenticated module connection; unauthenticated ones are never stored here. */
117
+ socket = null;
118
+ connectedSince = null;
119
+ pending = new Map();
120
+ /** Callers of {@link waitUntilConnected}, woken by the next authentication. */
121
+ connectionWaiters = new Set();
122
+ nextId = 1;
123
+ port;
124
+ expectedOrigin;
125
+ requestTimeoutMs;
126
+ authTimeoutMs;
127
+ /** HMAC key of the handshake. In memory only: never logged, persisted or returned. */
128
+ secret = randomBytes(32);
129
+ refusals = new RefusalLog();
130
+ /**
131
+ * Invoked for every unsolicited `{event, payload}` push from the module —
132
+ * canvas activity (targeting, pings) that never crosses FoundryVTT's own
133
+ * `modifyDocument` Socket.IO channel. `null` when nobody is listening.
134
+ */
135
+ onEvent = null;
136
+ constructor(port, options) {
137
+ this.port = port;
138
+ this.expectedOrigin = options.expectedOrigin;
139
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 15000;
140
+ this.authTimeoutMs = options.authTimeoutMs ?? AUTH_TIMEOUT_MS;
141
+ }
142
+ /**
143
+ * Starts the relay server and waits for it to be listening.
144
+ *
145
+ * Loopback only: the module dials `ws://localhost:<port>` from a browser
146
+ * on this machine, and the bridge drives a GM session, so it must not be
147
+ * reachable from the network. `localhost` may resolve to either family,
148
+ * hence one listener on 127.0.0.1 and one on ::1 (skipped when IPv6 is
149
+ * unavailable).
150
+ */
151
+ async start() {
152
+ await this.listenOn('127.0.0.1');
153
+ try {
154
+ await this.listenOn('::1');
155
+ }
156
+ catch (error) {
157
+ const code = error.code;
158
+ if (code !== 'EADDRNOTAVAIL' && code !== 'EAFNOSUPPORT') {
159
+ await this.stop();
160
+ throw error;
161
+ }
162
+ logger.debug(`Module bridge: IPv6 loopback unavailable (${code}); IPv4 only`);
163
+ }
164
+ logger.info(`Module bridge listening on ws://localhost:${this.port} (loopback only)`);
165
+ }
166
+ listenOn(host) {
167
+ return new Promise((resolve, reject) => {
168
+ const wss = new WebSocketServer({
169
+ host,
170
+ port: this.port,
171
+ verifyClient: (info, done) => {
172
+ if (info.origin === this.expectedOrigin) {
173
+ done(true);
174
+ return;
175
+ }
176
+ this.refusals.warn('Module bridge refused a connection: unexpected Origin', {
177
+ origin: info.origin ?? '(none)',
178
+ remoteAddress: info.req.socket.remoteAddress,
179
+ });
180
+ done(false, 403, 'Forbidden');
181
+ },
182
+ });
183
+ wss.once('listening', () => {
184
+ this.servers.push(wss);
185
+ resolve();
186
+ });
187
+ wss.once('error', (err) => {
188
+ wss.close();
189
+ reject(err);
190
+ });
191
+ wss.on('connection', (ws, req) => this.handleConnection(ws, req));
192
+ });
193
+ }
194
+ /**
195
+ * Challenges a fresh connection. It only becomes the module connection —
196
+ * replacing the previous one — once its `auth_response` checks out.
197
+ */
198
+ handleConnection(ws, req) {
199
+ const remoteAddress = req.socket.remoteAddress;
200
+ const serverNonce = randomBytes(NONCE_BYTES).toString('base64');
201
+ let authenticated = false;
202
+ let refused = false;
203
+ const refuse = (code, reason, detail) => {
204
+ refused = true;
205
+ clearTimeout(authTimer);
206
+ this.refusals.warn(`Module bridge refused a connection: ${detail}`, { remoteAddress });
207
+ ws.close(code, reason);
208
+ };
209
+ const authTimer = setTimeout(() => refuse(BRIDGE_CLOSE_CODES.authTimeout, 'authentication timeout', `client did not authenticate within ${this.authTimeoutMs} ms; likely an outdated ` +
210
+ 'foundryvtt-mcp-bridge module (< 0.5.0), redeploy it'), this.authTimeoutMs);
211
+ ws.on('message', (data) => {
212
+ if (authenticated) {
213
+ // A replaced module may still be sending until its socket closes.
214
+ if (this.socket === ws) {
215
+ this.handleMessage(rawDataText(data));
216
+ }
217
+ return;
218
+ }
219
+ if (refused) {
220
+ return;
221
+ }
222
+ if (rawDataBytes(data) > MAX_PREAUTH_MESSAGE_BYTES) {
223
+ refuse(BRIDGE_CLOSE_CODES.messageTooBig, 'message too big', `message over ${MAX_PREAUTH_MESSAGE_BYTES} bytes before authentication`);
224
+ return;
225
+ }
226
+ const verdict = this.checkAuthResponse(rawDataText(data), serverNonce);
227
+ if (!verdict.ok) {
228
+ refuse(BRIDGE_CLOSE_CODES.unauthorized, 'unauthorized', verdict.reason);
229
+ return;
230
+ }
231
+ authenticated = true;
232
+ clearTimeout(authTimer);
233
+ ws.send(JSON.stringify({ type: 'auth_ok', proof: verdict.serverProof }));
234
+ this.adopt(ws, remoteAddress);
235
+ });
236
+ ws.on('close', () => {
237
+ clearTimeout(authTimer);
238
+ if (this.socket === ws) {
239
+ logger.warn('Foundry module disconnected from bridge');
240
+ this.socket = null;
241
+ this.connectedSince = null;
242
+ }
243
+ });
244
+ ws.on('error', (err) => {
245
+ logger.error('Module bridge socket error', { error: err.message });
246
+ });
247
+ ws.send(JSON.stringify({
248
+ type: 'auth_challenge',
249
+ protocol: BRIDGE_PROTOCOL_VERSION,
250
+ nonce: serverNonce,
251
+ }));
252
+ }
253
+ /** Makes an authenticated connection the module connection. */
254
+ adopt(ws, remoteAddress) {
255
+ const previous = this.socket;
256
+ this.socket = ws;
257
+ this.connectedSince = new Date();
258
+ if (previous) {
259
+ // e.g. the headless page reloaded before its old socket closed.
260
+ previous.terminate();
261
+ logger.info('Foundry module re-authenticated; previous module connection replaced', {
262
+ remoteAddress,
263
+ });
264
+ }
265
+ else {
266
+ logger.info(`Foundry module connected and authenticated (protocol v${BRIDGE_PROTOCOL_VERSION})`, { remoteAddress });
267
+ }
268
+ this.wakeConnectionWaiters(true);
269
+ }
270
+ wakeConnectionWaiters(connected) {
271
+ for (const wake of [...this.connectionWaiters]) {
272
+ wake(connected);
273
+ }
274
+ }
275
+ /**
276
+ * Waits until an authenticated module is connected.
277
+ *
278
+ * @returns true once connected, false when `timeoutMs` ran out first or the bridge stopped
279
+ */
280
+ waitUntilConnected(timeoutMs) {
281
+ if (this.isConnected()) {
282
+ return Promise.resolve(true);
283
+ }
284
+ return new Promise((resolve) => {
285
+ const wake = (connected) => {
286
+ clearTimeout(timer);
287
+ this.connectionWaiters.delete(wake);
288
+ resolve(connected);
289
+ };
290
+ const timer = setTimeout(() => wake(false), timeoutMs);
291
+ this.connectionWaiters.add(wake);
292
+ });
293
+ }
294
+ checkAuthResponse(raw, serverNonce) {
295
+ let parsed;
296
+ try {
297
+ parsed = JSON.parse(raw);
298
+ }
299
+ catch {
300
+ return { ok: false, reason: 'non-JSON message before authentication' };
301
+ }
302
+ if (!isRecord(parsed) || parsed.type !== 'auth_response') {
303
+ return { ok: false, reason: 'message other than auth_response before authentication' };
304
+ }
305
+ if (parsed.protocol !== BRIDGE_PROTOCOL_VERSION) {
306
+ return {
307
+ ok: false,
308
+ reason: `unsupported bridge protocol ${JSON.stringify(parsed.protocol)} (expected ${BRIDGE_PROTOCOL_VERSION})`,
309
+ };
310
+ }
311
+ if (!isNonce(parsed.nonce) || typeof parsed.proof !== 'string') {
312
+ return { ok: false, reason: 'malformed auth_response' };
313
+ }
314
+ const expected = this.hmac('client', serverNonce, parsed.nonce);
315
+ const received = Buffer.from(parsed.proof, 'base64');
316
+ if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
317
+ return { ok: false, reason: 'wrong authentication proof' };
318
+ }
319
+ return {
320
+ ok: true,
321
+ serverProof: this.hmac('server', serverNonce, parsed.nonce).toString('base64'),
322
+ };
323
+ }
324
+ hmac(role, serverNonce, clientNonce) {
325
+ return createHmac('sha256', this.secret)
326
+ .update(`${PROOF_LABEL}|${role}|${serverNonce}|${clientNonce}`)
327
+ .digest();
328
+ }
329
+ /**
330
+ * Answers a server challenge on the module's behalf: picks the client
331
+ * nonce and computes both proofs. Called from the headless session's page
332
+ * binding, so `serverNonce` is untrusted input.
333
+ *
334
+ * @throws if `serverNonce` is not the base64 of {@link NONCE_BYTES} bytes
335
+ */
336
+ prove(serverNonce) {
337
+ if (!isNonce(serverNonce)) {
338
+ throw new Error('Invalid server nonce');
339
+ }
340
+ const nonce = randomBytes(NONCE_BYTES).toString('base64');
341
+ return {
342
+ nonce,
343
+ clientProof: this.hmac('client', serverNonce, nonce).toString('base64'),
344
+ serverProof: this.hmac('server', serverNonce, nonce).toString('base64'),
345
+ };
346
+ }
347
+ /** What the module needs to dial in: the protocol and this bridge's port. */
348
+ info() {
349
+ return { protocol: BRIDGE_PROTOCOL_VERSION, port: this.port };
350
+ }
351
+ async stop() {
352
+ for (const [, pending] of this.pending) {
353
+ clearTimeout(pending.timeout);
354
+ pending.reject(new Error('Module bridge shutting down'));
355
+ }
356
+ this.pending.clear();
357
+ this.wakeConnectionWaiters(false);
358
+ this.socket?.close();
359
+ this.socket = null;
360
+ this.connectedSince = null;
361
+ const servers = this.servers;
362
+ this.servers = [];
363
+ await Promise.all(servers.map((wss) => new Promise((resolve, reject) => {
364
+ // Unauthenticated connections are not tracked here; close them too.
365
+ for (const client of wss.clients) {
366
+ client.terminate();
367
+ }
368
+ wss.close((err) => (err ? reject(err) : resolve()));
369
+ })));
370
+ }
371
+ /** True once {@link start} has bound the port, until {@link stop}. */
372
+ isListening() {
373
+ return this.servers.length > 0;
374
+ }
375
+ /** True while an authenticated module is connected. */
376
+ isConnected() {
377
+ return this.socket?.readyState === WebSocket.OPEN;
378
+ }
379
+ /** When the current authenticated module connection was established, or `null`. */
380
+ moduleConnectedSince() {
381
+ return this.isConnected() ? this.connectedSince : null;
382
+ }
383
+ /**
384
+ * Sends a command to the connected module and awaits its response.
385
+ *
386
+ * @throws if no module is connected, or the module reports an error, or
387
+ * the request times out (the module hung, or the command type is unknown
388
+ * to it).
389
+ */
390
+ send(type, params = {}) {
391
+ if (!this.isConnected() || !this.socket) {
392
+ throw new Error('No authenticated Foundry module connected to the bridge. Install and enable the companion module (0.5.0 or later), confirm FOUNDRY_MODULE_BRIDGE_ENABLED=true, and check that the headless GM session is logged in.');
393
+ }
394
+ const id = String(this.nextId++);
395
+ const socket = this.socket;
396
+ return new Promise((resolve, reject) => {
397
+ const timeout = setTimeout(() => {
398
+ this.pending.delete(id);
399
+ reject(new Error(`Module command '${type}' timed out after ${this.requestTimeoutMs}ms`));
400
+ }, this.requestTimeoutMs);
401
+ this.pending.set(id, { resolve, reject, timeout });
402
+ socket.send(JSON.stringify({ id, type, params }));
403
+ });
404
+ }
405
+ handleMessage(raw) {
406
+ let parsed;
407
+ try {
408
+ parsed = JSON.parse(raw);
409
+ }
410
+ catch {
411
+ logger.warn('Module bridge received non-JSON message');
412
+ return;
413
+ }
414
+ if (!isBridgeMessage(parsed)) {
415
+ logger.warn('Module bridge received a message with no request id');
416
+ return;
417
+ }
418
+ if (typeof parsed.id !== 'string') {
419
+ if (typeof parsed.event === 'string') {
420
+ this.onEvent?.(parsed.event, isRecord(parsed.payload) ? parsed.payload : {});
421
+ return;
422
+ }
423
+ logger.warn('Module bridge received a message with no request id');
424
+ return;
425
+ }
426
+ const pending = this.pending.get(parsed.id);
427
+ if (!pending) {
428
+ // Late response to a request that already timed out, or an unsolicited message.
429
+ return;
430
+ }
431
+ this.pending.delete(parsed.id);
432
+ clearTimeout(pending.timeout);
433
+ if (parsed.error !== undefined) {
434
+ pending.reject(new Error(typeof parsed.error === 'string' ? parsed.error : 'Module error'));
435
+ }
436
+ else {
437
+ pending.resolve(parsed.result);
438
+ }
439
+ }
440
+ }
441
+ //# sourceMappingURL=module-bridge.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @fileoverview TypeScript type definitions for FoundryVTT data structures
3
+ *
4
+ * This module contains comprehensive type definitions for all FoundryVTT entities
5
+ * including actors, items, scenes, tokens, and other game objects. These types
6
+ * provide type safety and intellisense when working with FoundryVTT data.
7
+ *
8
+ * @version 0.1.0
9
+ * @author FoundryVTT MCP Team
10
+ * @see {@link https://foundryvtt.com/api/} FoundryVTT API Documentation
11
+ */
12
+ /** {@link DocumentVisibility} → the `ownership.default` level it maps to. */
13
+ export const VISIBILITY_LEVELS = {
14
+ 'gm-only': 0,
15
+ observer: 2,
16
+ owner: 3,
17
+ };
18
+ /**
19
+ * FoundryVTT's `CONST.DOCUMENT_OWNERSHIP_LEVELS` — who can read, observe, or
20
+ * edit a document.
21
+ */
22
+ export const OWNERSHIP_LEVELS = {
23
+ none: 0,
24
+ limited: 1,
25
+ observer: 2,
26
+ owner: 3,
27
+ };
28
+ /**
29
+ * FoundryVTT's `CONST.USER_ROLES` — user permission tiers.
30
+ */
31
+ export const USER_ROLES = {
32
+ none: 0,
33
+ player: 1,
34
+ trusted: 2,
35
+ assistant: 3,
36
+ gamemaster: 4,
37
+ };
38
+ /**
39
+ * FoundryVTT's `CONST.ACTIVE_EFFECT_MODES` — how an `ActiveEffect` change
40
+ * combines with the base value. Tools accept the string name, never the raw
41
+ * number: an LLM misremembering whether `override` is `2` or `5` would
42
+ * silently apply the wrong mechanic rather than fail loudly.
43
+ */
44
+ export const ACTIVE_EFFECT_MODES = {
45
+ custom: 0,
46
+ multiply: 1,
47
+ add: 2,
48
+ downgrade: 3,
49
+ upgrade: 4,
50
+ override: 5,
51
+ };
52
+ //# sourceMappingURL=types.js.map