@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,332 @@
1
+ /**
2
+ * @fileoverview Diagnostic utilities for enhanced user experience
3
+ *
4
+ * Provides smart error analysis, problem detection, and actionable suggestions
5
+ * to help users troubleshoot and resolve common issues.
6
+ */
7
+ import { config } from '../config/index.js';
8
+ import { ApiStatusResponseSchema } from '../diagnostics/types.js';
9
+ import { logger } from './logger.js';
10
+ const REPO_URL = 'https://github.com/G33ks/foundryvtt-mcp';
11
+ /**
12
+ * Enhanced diagnostic system for FoundryVTT MCP integration
13
+ */
14
+ export class DiagnosticSystem {
15
+ foundryClient;
16
+ constructor(foundryClient) {
17
+ this.foundryClient = foundryClient;
18
+ }
19
+ /**
20
+ * Diagnose why a specific feature isn't working
21
+ */
22
+ async diagnoseFeatureProblem(feature) {
23
+ logger.debug(`Diagnosing problem with feature: ${feature}`);
24
+ try {
25
+ // Test basic connectivity
26
+ const isConnected = await this.foundryClient.testConnection();
27
+ if (!isConnected) {
28
+ return this.createConnectivityDiagnostic();
29
+ }
30
+ // Test REST API availability
31
+ const hasRestApi = await this.testRestApiAvailability();
32
+ if (!hasRestApi && this.requiresRestApi(feature)) {
33
+ return this.createRestApiDiagnostic(feature);
34
+ }
35
+ // Test authentication
36
+ const authResult = await this.testAuthentication();
37
+ if (!authResult.valid) {
38
+ return this.createAuthenticationDiagnostic(authResult);
39
+ }
40
+ // Feature-specific diagnostics
41
+ return await this.createFeatureSpecificDiagnostic(feature);
42
+ }
43
+ catch (error) {
44
+ logger.error('Error during diagnosis:', error);
45
+ return this.createGenericErrorDiagnostic(error);
46
+ }
47
+ }
48
+ /**
49
+ * Perform comprehensive health check
50
+ */
51
+ async performHealthCheck() {
52
+ logger.info('Performing system health check');
53
+ const report = {
54
+ connectivity: { status: 'offline', emoji: '❌', details: 'Not tested' },
55
+ authentication: { method: 'none', status: 'untested', emoji: '❓' },
56
+ features: {
57
+ diceRolling: false,
58
+ actorSearch: false,
59
+ itemSearch: false,
60
+ sceneData: false,
61
+ diagnostics: false,
62
+ },
63
+ restApiAvailable: false,
64
+ websocketAvailable: false,
65
+ };
66
+ try {
67
+ // Test connectivity
68
+ const isConnected = await this.foundryClient.testConnection();
69
+ if (isConnected) {
70
+ report.connectivity = {
71
+ status: 'connected',
72
+ emoji: '✅',
73
+ details: `Connected to ${config.foundry.url}`,
74
+ };
75
+ }
76
+ else {
77
+ report.connectivity = {
78
+ status: 'offline',
79
+ emoji: '❌',
80
+ details: `Cannot reach ${config.foundry.url}`,
81
+ };
82
+ return report; // Early return if not connected
83
+ }
84
+ // Test REST API
85
+ report.restApiAvailable = await this.testRestApiAvailability();
86
+ // Test authentication
87
+ const authResult = await this.testAuthentication();
88
+ report.authentication = {
89
+ method: config.foundry.apiKey ? 'api-key' : 'credentials',
90
+ status: authResult.valid ? 'valid' : 'invalid',
91
+ emoji: authResult.valid ? '✅' : '❌',
92
+ };
93
+ // Test individual features
94
+ report.features.diceRolling = await this.testDiceRolling();
95
+ report.features.actorSearch = await this.testActorSearch();
96
+ report.features.itemSearch = await this.testItemSearch();
97
+ report.features.sceneData = await this.testSceneData();
98
+ report.features.diagnostics = report.restApiAvailable;
99
+ // Update connectivity status based on feature availability
100
+ if (report.restApiAvailable) {
101
+ report.connectivity.status = 'connected';
102
+ }
103
+ else if (report.features.diceRolling) {
104
+ report.connectivity.status = 'limited';
105
+ report.connectivity.emoji = '⚠️';
106
+ report.connectivity.details += ' (Limited functionality - REST API not available)';
107
+ }
108
+ }
109
+ catch (error) {
110
+ logger.error('Health check failed:', error);
111
+ report.connectivity = {
112
+ status: 'offline',
113
+ emoji: '❌',
114
+ details: `Health check failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
115
+ };
116
+ }
117
+ return report;
118
+ }
119
+ /**
120
+ * Format health report for user display
121
+ */
122
+ formatHealthReport(report) {
123
+ let output = '🏥 **FoundryVTT MCP Health Check**\n\n';
124
+ output += `**Connection**: ${report.connectivity.status.toUpperCase()} ${report.connectivity.emoji}\n`;
125
+ output += ` ${report.connectivity.details}\n\n`;
126
+ output += `**Authentication**: ${report.authentication.method.toUpperCase()} ${report.authentication.emoji}\n`;
127
+ if (report.authentication.status === 'invalid') {
128
+ output += ` ⚠️ Authentication failed - check your credentials\n`;
129
+ }
130
+ output += '\n';
131
+ output += `**Available Features**:\n`;
132
+ output += ` • Dice Rolling: ${report.features.diceRolling ? '✅ Working' : '❌ Failed'}\n`;
133
+ output += ` • Actor Search: ${report.features.actorSearch ? '✅ Full access' : '⚠️ Limited/None'}\n`;
134
+ output += ` • Item Search: ${report.features.itemSearch ? '✅ Full access' : '⚠️ Limited/None'}\n`;
135
+ output += ` • Scene Data: ${report.features.sceneData ? '✅ Real data' : '⚠️ Mock data only'}\n`;
136
+ output += ` • System Diagnostics: ${report.features.diagnostics ? '✅ Available' : '❌ Unavailable'}\n\n`;
137
+ if (!report.restApiAvailable) {
138
+ output += '💡 **Unlock Full Features**:\n';
139
+ output += ' → Install the "Foundry Local REST API" module in FoundryVTT\n';
140
+ output += ' → Enable the module and configure API key\n';
141
+ output += ` → See setup guide: ${REPO_URL}/blob/main/docs/guides/configuration.md#optional-diagnostics-tools\n\n`;
142
+ }
143
+ if (report.connectivity.status === 'offline') {
144
+ output += '🔧 **Troubleshooting Steps**:\n';
145
+ output += ' 1. Ensure FoundryVTT is running and accessible\n';
146
+ output +=
147
+ ' 2. Check FOUNDRY_URL in the configuration file (`foundryvtt-mcp status` shows it)\n';
148
+ output += ' 3. Verify network connectivity\n';
149
+ output += ' 4. Check the configuration with: `foundryvtt-mcp init --check`\n';
150
+ }
151
+ return output;
152
+ }
153
+ /**
154
+ * Create diagnostic for connectivity issues
155
+ */
156
+ createConnectivityDiagnostic() {
157
+ return {
158
+ explanation: 'Unable to connect to FoundryVTT server.',
159
+ suggestions: "• **Check if FoundryVTT is running** - Start FoundryVTT and ensure it's accessible\n" +
160
+ `• **Verify server URL** - Check that \`${config.foundry.url}\` is correct\n` +
161
+ '• **Test connectivity** - Run `foundryvtt-mcp init --check` for a step-by-step check\n' +
162
+ '• **Check firewall** - Ensure no firewall is blocking the connection',
163
+ severity: 'critical',
164
+ canContinue: false,
165
+ documentationUrl: `${REPO_URL}/blob/main/TROUBLESHOOTING.md#connection-issues`,
166
+ };
167
+ }
168
+ /**
169
+ * Create diagnostic for REST API issues
170
+ */
171
+ createRestApiDiagnostic(feature) {
172
+ return {
173
+ explanation: `${feature.charAt(0).toUpperCase() + feature.slice(1)} search requires the REST API module for full functionality.`,
174
+ suggestions: '• **Install REST API module** - Get it from the FoundryVTT module browser\n' +
175
+ "• **Enable the module** - Activate it in your world's module settings\n" +
176
+ '• **Configure API key** - Generate and copy the API key from module settings\n' +
177
+ '• **Set the key** - Set FOUNDRY_API_KEY in the configuration file\n' +
178
+ '• **Restart the connector** - Run `foundryvtt-mcp stop`; the next call uses the new configuration',
179
+ severity: 'warning',
180
+ canContinue: true,
181
+ documentationUrl: `${REPO_URL}/blob/main/docs/guides/configuration.md#optional-diagnostics-tools`,
182
+ };
183
+ }
184
+ /**
185
+ * Create diagnostic for authentication issues
186
+ */
187
+ createAuthenticationDiagnostic(_authResult) {
188
+ const isApiKey = !!config.foundry.apiKey;
189
+ return {
190
+ explanation: `Authentication failed using ${isApiKey ? 'API key' : 'username/password'}.`,
191
+ suggestions: isApiKey
192
+ ? "• **Check API key** - Verify the key is correct and hasn't expired\n" +
193
+ '• **Regenerate key** - Generate a new API key in FoundryVTT module settings\n' +
194
+ '• **Module status** - Ensure the REST API module is enabled and running\n' +
195
+ '• **Restart FoundryVTT** - Sometimes a restart resolves authentication issues'
196
+ : '• **Check credentials** - Verify username and password are correct\n' +
197
+ '• **User permissions** - Ensure the user has required permissions\n' +
198
+ '• **Case sensitivity** - Check for typos in username (case-sensitive)\n' +
199
+ '• **User status** - Make sure the user account is active',
200
+ severity: 'error',
201
+ canContinue: false,
202
+ documentationUrl: `${REPO_URL}/blob/main/TROUBLESHOOTING.md#authentication-issues`,
203
+ };
204
+ }
205
+ /**
206
+ * Create feature-specific diagnostic
207
+ */
208
+ async createFeatureSpecificDiagnostic(feature) {
209
+ return {
210
+ explanation: `Connected with full access, but no ${feature} data found.`,
211
+ suggestions: `• **Check data exists** - Verify that ${feature} exist in your FoundryVTT world\n` +
212
+ '• **User permissions** - Ensure you have permission to view this data\n' +
213
+ '• **Module conflicts** - Check if other modules might be interfering\n' +
214
+ `• **Direct test** - Try accessing ${feature} directly in FoundryVTT`,
215
+ severity: 'info',
216
+ canContinue: true,
217
+ documentationUrl: `${REPO_URL}/blob/main/TROUBLESHOOTING.md#empty-search-results`,
218
+ };
219
+ }
220
+ /**
221
+ * Create generic error diagnostic
222
+ */
223
+ createGenericErrorDiagnostic(_error) {
224
+ return {
225
+ explanation: 'An unexpected error occurred during diagnosis.',
226
+ suggestions: '• **Check logs** - Review server logs for detailed error information\n' +
227
+ '• **Restart services** - Try restarting both FoundryVTT and the MCP server\n' +
228
+ '• **Update software** - Ensure all components are up to date\n' +
229
+ '• **Report issue** - If problem persists, report it on GitHub',
230
+ severity: 'error',
231
+ canContinue: false,
232
+ documentationUrl: `${REPO_URL}/issues`,
233
+ };
234
+ }
235
+ /**
236
+ * Test if feature requires REST API
237
+ */
238
+ requiresRestApi(feature) {
239
+ return ['actors', 'items', 'diagnostics'].includes(feature);
240
+ }
241
+ /**
242
+ * Test REST API availability
243
+ */
244
+ async testRestApiAvailability() {
245
+ try {
246
+ const response = await this.foundryClient.get('/api/status');
247
+ return (response?.data !== null &&
248
+ response?.data !== undefined &&
249
+ ApiStatusResponseSchema.parse(response.data).status === 'ok');
250
+ }
251
+ catch (error) {
252
+ logger.debug('REST API not available:', error);
253
+ return false;
254
+ }
255
+ }
256
+ /**
257
+ * Test authentication
258
+ */
259
+ async testAuthentication() {
260
+ try {
261
+ if (config.foundry.apiKey) {
262
+ // Test API key authentication
263
+ const response = await this.foundryClient.get('/api/world');
264
+ return { valid: !!response };
265
+ }
266
+ else {
267
+ // Test credential authentication (via WebSocket)
268
+ await this.foundryClient.connect();
269
+ return { valid: this.foundryClient.isConnected() };
270
+ }
271
+ }
272
+ catch (error) {
273
+ return {
274
+ valid: false,
275
+ error: error instanceof Error ? error.message : 'Unknown authentication error',
276
+ };
277
+ }
278
+ }
279
+ /**
280
+ * Test dice rolling functionality
281
+ */
282
+ async testDiceRolling() {
283
+ try {
284
+ const result = await this.foundryClient.rollDice('1d20', 'Health check test');
285
+ return typeof result.total === 'number';
286
+ }
287
+ catch (error) {
288
+ logger.debug('Dice rolling test failed:', error);
289
+ return false;
290
+ }
291
+ }
292
+ /**
293
+ * Test actor search functionality
294
+ */
295
+ async testActorSearch() {
296
+ try {
297
+ const result = await this.foundryClient.searchActors({ limit: 1 });
298
+ return Array.isArray(result.actors);
299
+ }
300
+ catch (error) {
301
+ logger.debug('Actor search test failed:', error);
302
+ return false;
303
+ }
304
+ }
305
+ /**
306
+ * Test item search functionality
307
+ */
308
+ async testItemSearch() {
309
+ try {
310
+ const result = await this.foundryClient.searchItems({ limit: 1 });
311
+ return Array.isArray(result.items);
312
+ }
313
+ catch (error) {
314
+ logger.debug('Item search test failed:', error);
315
+ return false;
316
+ }
317
+ }
318
+ /**
319
+ * Test scene data functionality
320
+ */
321
+ async testSceneData() {
322
+ try {
323
+ const result = await this.foundryClient.getCurrentScene();
324
+ return !!result && typeof result.name === 'string';
325
+ }
326
+ catch (error) {
327
+ logger.debug('Scene data test failed:', error);
328
+ return false;
329
+ }
330
+ }
331
+ }
332
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @fileoverview Canonical runtime type guards shared across the server.
3
+ */
4
+ /**
5
+ * Narrows an unknown value to a plain keyed object.
6
+ *
7
+ * Arrays are excluded: every caller here uses this before reading named fields
8
+ * off a FoundryVTT document payload, and an array would satisfy `typeof ===
9
+ * 'object'` while having none of them.
10
+ *
11
+ * This proves only that the value is an object — its fields stay `unknown` and
12
+ * must each be checked (or parsed with Zod at the boundary) before use.
13
+ */
14
+ export function isRecord(value) {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
16
+ }
17
+ //# sourceMappingURL=guards.js.map
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @fileoverview Minimal, dependency-free image dimension reader.
3
+ *
4
+ * Scene backgrounds and tile textures are plain files on FoundryVTT's local
5
+ * `Data` directory (PNG/JPEG/WebP in practice for the asset packs this
6
+ * server's scene/tile tools work with). Reading true pixel dimensions from
7
+ * disk means `create_scene`/`create_tile` never have to ask the caller to
8
+ * guess a width/height — the number one source of misaligned grids and
9
+ * off-canvas tiles when doing this by hand.
10
+ *
11
+ * Each format is detected by magic bytes and parsed from its own minimal
12
+ * header structure — no image decoding, just the size fields every format
13
+ * stores near the front of the file.
14
+ */
15
+ import { closeSync, openSync, readSync } from 'node:fs';
16
+ /** True if `buf` starts with the 8-byte PNG signature. */
17
+ function isPng(buf) {
18
+ return (buf.length >= 24 &&
19
+ buf[0] === 0x89 &&
20
+ buf[1] === 0x50 &&
21
+ buf[2] === 0x4e &&
22
+ buf[3] === 0x47 &&
23
+ buf[4] === 0x0d &&
24
+ buf[5] === 0x0a &&
25
+ buf[6] === 0x1a &&
26
+ buf[7] === 0x0a);
27
+ }
28
+ /** PNG: width/height are a fixed 8 bytes into the mandatory IHDR chunk (offset 16). */
29
+ function pngSize(buf) {
30
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
31
+ }
32
+ /** True if `buf` starts with the JPEG SOI marker (0xFFD8). */
33
+ function isJpeg(buf) {
34
+ return buf.length >= 4 && buf[0] === 0xff && buf[1] === 0xd8;
35
+ }
36
+ /**
37
+ * JPEG: no fixed offset — width/height live in whichever Start-Of-Frame
38
+ * marker (0xC0-0xCF, excluding the DHT/JPG/DAC markers 0xC4/0xC8/0xCC) the
39
+ * file actually uses, reached by walking the marker segment chain from the
40
+ * SOI. Each segment after the marker byte pair carries a 2-byte big-endian
41
+ * length (including itself); SOF segments store height then width 3 bytes
42
+ * into their payload.
43
+ */
44
+ function jpegSize(buf) {
45
+ let offset = 2; // past the 0xFFD8 SOI marker
46
+ while (offset + 4 <= buf.length) {
47
+ if (buf[offset] !== 0xff) {
48
+ // Not aligned on a marker — bail rather than mis-scan garbage.
49
+ return null;
50
+ }
51
+ const marker = buf[offset + 1];
52
+ // Standalone markers with no length/payload.
53
+ if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) {
54
+ offset += 2;
55
+ continue;
56
+ }
57
+ const segmentLength = buf.readUInt16BE(offset + 2);
58
+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
59
+ if (isSof) {
60
+ if (offset + 9 > buf.length) {
61
+ return null;
62
+ }
63
+ const height = buf.readUInt16BE(offset + 5);
64
+ const width = buf.readUInt16BE(offset + 7);
65
+ return { width, height };
66
+ }
67
+ offset += 2 + segmentLength;
68
+ }
69
+ return null;
70
+ }
71
+ /** True if `buf` starts with a RIFF....WEBP container header. */
72
+ function isWebp(buf) {
73
+ return (buf.length >= 30 &&
74
+ buf.toString('ascii', 0, 4) === 'RIFF' &&
75
+ buf.toString('ascii', 8, 12) === 'WEBP');
76
+ }
77
+ /**
78
+ * WebP: dimensions are encoded differently per sub-format (VP8, VP8L, VP8X)
79
+ * following the 12-byte RIFF/WEBP header. Only the three sub-formats
80
+ * FoundryVTT/browsers actually produce are handled.
81
+ */
82
+ function webpSize(buf) {
83
+ const fourCc = buf.toString('ascii', 12, 16);
84
+ if (fourCc === 'VP8X') {
85
+ // Extended format: 24-bit little-endian canvas width/height minus one, at offset 24/27.
86
+ const width = buf[24] | (buf[25] << 8) | (buf[26] << 16);
87
+ const height = buf[27] | (buf[28] << 8) | (buf[29] << 16);
88
+ return { width: width + 1, height: height + 1 };
89
+ }
90
+ if (fourCc === 'VP8 ' && buf.length >= 30) {
91
+ // Lossy: 14-bit width/height (top 2 bits are an unrelated scale flag) at offset 26/28.
92
+ const width = buf.readUInt16LE(26) & 0x3fff;
93
+ const height = buf.readUInt16LE(28) & 0x3fff;
94
+ return { width, height };
95
+ }
96
+ if (fourCc === 'VP8L' && buf.length >= 25) {
97
+ // Lossless: a packed 32-bit little-endian field at offset 21 holds
98
+ // 14-bit (width-1) then 14-bit (height-1).
99
+ const bits = buf[21] |
100
+ (buf[22] << 8) |
101
+ (buf[23] << 16) |
102
+ (buf[24] << 24);
103
+ const width = (bits & 0x3fff) + 1;
104
+ const height = ((bits >> 14) & 0x3fff) + 1;
105
+ return { width, height };
106
+ }
107
+ return null;
108
+ }
109
+ /**
110
+ * Bytes read from the front of each file. All three formats' dimension
111
+ * fields live well inside this window for any file this server actually
112
+ * handles (PNG: fixed 24-byte offset; WebP: fixed ~30-byte offset; JPEG:
113
+ * markers before the first Start-Of-Frame — typically one EXIF/JFIF
114
+ * segment, each capped at 65533 bytes by the format itself). Reading a
115
+ * bounded prefix instead of the whole file keeps `list_scene_assets`
116
+ * cheap even over a folder of multi-megabyte battlemap JPEGs.
117
+ */
118
+ const HEADER_READ_BYTES = 262144;
119
+ /**
120
+ * Reads an image's true pixel dimensions from its header, without decoding
121
+ * pixel data. Supports PNG, JPEG, and WebP — the formats FoundryVTT's own
122
+ * asset pipeline and typical battlemap packs use. Reads only a bounded
123
+ * prefix of the file ({@link HEADER_READ_BYTES}), not the full contents.
124
+ *
125
+ * @param absolutePath - filesystem path to the image file
126
+ * @returns dimensions, or null if the file is missing, unreadable, not one
127
+ * of the supported formats, or the dimension fields fall outside the
128
+ * read window (pathological — not expected for real map/prop art)
129
+ */
130
+ export function getImageSize(absolutePath) {
131
+ let fd;
132
+ try {
133
+ fd = openSync(absolutePath, 'r');
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ try {
139
+ const buf = Buffer.alloc(HEADER_READ_BYTES);
140
+ const bytesRead = readSync(fd, buf, 0, HEADER_READ_BYTES, 0);
141
+ const header = buf.subarray(0, bytesRead);
142
+ if (isPng(header)) {
143
+ return pngSize(header);
144
+ }
145
+ if (isJpeg(header)) {
146
+ return jpegSize(header);
147
+ }
148
+ if (isWebp(header)) {
149
+ return webpSize(header);
150
+ }
151
+ return null;
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ finally {
157
+ closeSync(fd);
158
+ }
159
+ }
160
+ //# sourceMappingURL=image-size.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @fileoverview Tool arguments as they may appear in a log line.
3
+ *
4
+ * `daemon.log` records every tool call. Journal pages, chat messages, macro
5
+ * code and the like are the user's campaign text and have no business in a
6
+ * log, so content-bearing arguments are replaced by their length. Ids, names
7
+ * and other short parameters stay as they are, since they are what makes a
8
+ * log line useful.
9
+ */
10
+ /** Argument names whose string values are always content. */
11
+ const CONTENT_KEYS = new Set([
12
+ 'content',
13
+ 'text',
14
+ 'html',
15
+ 'description',
16
+ 'flavor',
17
+ 'command',
18
+ ]);
19
+ /** Any other string longer than this is treated as content too (pasted text, base64, …). */
20
+ const MAX_PLAIN_STRING = 200;
21
+ function placeholder(value) {
22
+ return `<${value.length} chars>`;
23
+ }
24
+ function redact(value, key) {
25
+ if (typeof value === 'string') {
26
+ if ((key !== null && CONTENT_KEYS.has(key)) || value.length > MAX_PLAIN_STRING) {
27
+ return placeholder(value);
28
+ }
29
+ return value;
30
+ }
31
+ if (Array.isArray(value)) {
32
+ // Array items inherit the array's key: `content: ["…"]` is still content.
33
+ return value.map((item) => redact(item, key));
34
+ }
35
+ if (value !== null && typeof value === 'object') {
36
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redact(v, k)]));
37
+ }
38
+ return value;
39
+ }
40
+ /**
41
+ * A copy of `args` safe to log: content-bearing strings (at any depth, e.g.
42
+ * `pages[].content`) become `"<312 chars>"`. Never mutates `args`.
43
+ */
44
+ export function redactToolArgs(args) {
45
+ return redact(args, null);
46
+ }
47
+ //# sourceMappingURL=log-args.js.map