@g33ks/foundryvtt-mcp 0.0.0-stage → 2.0.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/LICENSE +22 -0
- package/README.md +468 -2
- package/dist/character/manager.js +208 -0
- package/dist/cli/checks.js +307 -0
- package/dist/cli/config-file.js +120 -0
- package/dist/cli/init.js +410 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +49 -0
- package/dist/combat/manager.js +371 -0
- package/dist/config/env-layers.js +49 -0
- package/dist/config/index.js +298 -0
- package/dist/config/sources.js +201 -0
- package/dist/core.js +415 -0
- package/dist/diagnostics/client.js +353 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +220 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5555 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +299 -0
- package/dist/foundry/headless-gm-session.js +740 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +306 -0
- package/dist/foundry/module-bridge.js +413 -0
- package/dist/foundry/types.js +52 -0
- package/dist/foundry/world-cache.js +386 -0
- package/dist/index.js +107 -0
- package/dist/mcp-server.js +63 -0
- package/dist/server.js +159 -0
- package/dist/shared/build-order.js +134 -0
- package/dist/shared/config-hash.js +62 -0
- package/dist/shared/config-notice.js +55 -0
- package/dist/shared/control.js +255 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +313 -0
- package/dist/shared/ipc-client.js +200 -0
- package/dist/shared/ipc-server.js +316 -0
- package/dist/shared/paths.js +79 -0
- package/dist/shared/protocol.js +230 -0
- package/dist/shared/relay-config.js +65 -0
- package/dist/shared/relay.js +120 -0
- package/dist/shared/rotating-log.js +57 -0
- package/dist/shared/spawn.js +39 -0
- package/dist/shared/state-file.js +33 -0
- package/dist/shared/token.js +62 -0
- package/dist/shared/version.js +57 -0
- package/dist/tools/base.js +74 -0
- package/dist/tools/definitions.js +3109 -0
- package/dist/tools/handlers/actor-mutations.js +128 -0
- package/dist/tools/handlers/actors.js +114 -0
- package/dist/tools/handlers/chat-mutations.js +49 -0
- package/dist/tools/handlers/chat.js +36 -0
- package/dist/tools/handlers/combat-mutations.js +215 -0
- package/dist/tools/handlers/combat-order.js +94 -0
- package/dist/tools/handlers/combat.js +51 -0
- package/dist/tools/handlers/compendium.js +83 -0
- package/dist/tools/handlers/diagnostics.js +438 -0
- package/dist/tools/handlers/dice.js +54 -0
- package/dist/tools/handlers/effects.js +103 -0
- package/dist/tools/handlers/events.js +50 -0
- package/dist/tools/handlers/generation.js +258 -0
- package/dist/tools/handlers/item-mutations.js +132 -0
- package/dist/tools/handlers/items.js +53 -0
- package/dist/tools/handlers/journal-mutations.js +230 -0
- package/dist/tools/handlers/journals.js +80 -0
- package/dist/tools/handlers/module-bridge.js +421 -0
- package/dist/tools/handlers/placeable-mutations.js +272 -0
- package/dist/tools/handlers/resources.js +203 -0
- package/dist/tools/handlers/roll-tables.js +97 -0
- package/dist/tools/handlers/scene-mutations.js +159 -0
- package/dist/tools/handlers/scenes.js +355 -0
- package/dist/tools/handlers/settings.js +53 -0
- package/dist/tools/handlers/tile-mutations.js +56 -0
- package/dist/tools/handlers/token-mutations.js +356 -0
- package/dist/tools/handlers/users.js +59 -0
- package/dist/tools/handlers/utils.js +47 -0
- package/dist/tools/handlers/wall-mutations.js +98 -0
- package/dist/tools/handlers/world-documents.js +222 -0
- package/dist/tools/handlers/world.js +92 -0
- package/dist/tools/index.js +25 -0
- package/dist/tools/new-router.js +97 -0
- package/dist/tools/registry.js +79 -0
- package/dist/tools/resources.js +63 -0
- package/dist/tools/router.js +688 -0
- package/dist/tools/write-tools.js +97 -0
- package/dist/utils/cache-instance.js +30 -0
- package/dist/utils/cache.js +205 -0
- package/dist/utils/diagnostics.js +332 -0
- package/dist/utils/guards.js +17 -0
- package/dist/utils/image-size.js +160 -0
- package/dist/utils/log-args.js +47 -0
- package/dist/utils/logger.js +203 -0
- package/dist/utils/refusal.js +30 -0
- package/dist/utils/sanitize.js +22 -0
- package/dist/utils/serial-queue.js +22 -0
- package/package.json +124 -4
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { logger } from '../utils/logger.js';
|
|
3
|
+
export class CharacterManager extends EventEmitter {
|
|
4
|
+
foundryClient;
|
|
5
|
+
advancementHistory = [];
|
|
6
|
+
equipmentHistory = [];
|
|
7
|
+
resourceTracking = new Map();
|
|
8
|
+
constructor(foundryClient) {
|
|
9
|
+
super();
|
|
10
|
+
this.foundryClient = foundryClient;
|
|
11
|
+
}
|
|
12
|
+
// Character Advancement
|
|
13
|
+
async levelUpCharacter(actorId, options = {}) {
|
|
14
|
+
logger.info(`Starting level up process for actor ${actorId}`);
|
|
15
|
+
const actor = await this.foundryClient.getActor(actorId);
|
|
16
|
+
const currentLevel = actor.level || 1;
|
|
17
|
+
const newLevel = currentLevel + 1;
|
|
18
|
+
// Calculate HP gain
|
|
19
|
+
const hitPointsGained = this.calculateHitPointGain(actor, options.hitPointMethod || 'average');
|
|
20
|
+
// Process ability score improvements (every 4 levels in D&D 5e)
|
|
21
|
+
const abilityImprovements = options.abilityScoreImprovements || [];
|
|
22
|
+
if (newLevel % 4 === 0 && abilityImprovements.length === 0) {
|
|
23
|
+
// Suggest ability score improvements
|
|
24
|
+
abilityImprovements.push(...this.suggestAbilityImprovements(actor));
|
|
25
|
+
}
|
|
26
|
+
// Determine new spells and features based on class and level
|
|
27
|
+
const newSpells = options.newSpells || this.determineNewSpells(actor, newLevel);
|
|
28
|
+
const newFeatures = options.newFeatures || this.determineNewFeatures(actor, newLevel);
|
|
29
|
+
const newSkills = options.newSkills || this.determineNewSkills(actor, newLevel);
|
|
30
|
+
const advancement = {
|
|
31
|
+
actorId,
|
|
32
|
+
fromLevel: currentLevel,
|
|
33
|
+
toLevel: newLevel,
|
|
34
|
+
hitPointsGained,
|
|
35
|
+
abilityScoreImprovements: abilityImprovements,
|
|
36
|
+
newSpellsLearned: newSpells,
|
|
37
|
+
newFeatures,
|
|
38
|
+
skillProficiencies: newSkills,
|
|
39
|
+
timestamp: new Date(),
|
|
40
|
+
};
|
|
41
|
+
this.advancementHistory.push(advancement);
|
|
42
|
+
this.emit('character_level_up', advancement);
|
|
43
|
+
logger.info(`${actor.name} leveled up from ${currentLevel} to ${newLevel}`);
|
|
44
|
+
return advancement;
|
|
45
|
+
}
|
|
46
|
+
async calculateExperienceRequired(currentLevel, targetLevel) {
|
|
47
|
+
// D&D 5e experience table
|
|
48
|
+
const xpTable = [
|
|
49
|
+
0, 300, 900, 2700, 6500, 14000, 23000, 34000, 48000, 64000, 85000, 100000, 120000, 140000,
|
|
50
|
+
165000, 195000, 225000, 265000, 305000, 355000,
|
|
51
|
+
];
|
|
52
|
+
const currentXP = xpTable[Math.min(currentLevel - 1, xpTable.length - 1)] || 0;
|
|
53
|
+
const target = targetLevel || currentLevel + 1;
|
|
54
|
+
const requiredXP = xpTable[Math.min(target - 1, xpTable.length - 1)] || xpTable[xpTable.length - 1];
|
|
55
|
+
const nextLevelXP = xpTable[Math.min(currentLevel, xpTable.length - 1)] || xpTable[xpTable.length - 1];
|
|
56
|
+
return {
|
|
57
|
+
current: currentXP,
|
|
58
|
+
required: requiredXP || 0,
|
|
59
|
+
remaining: (requiredXP || 0) - currentXP,
|
|
60
|
+
nextMilestone: nextLevelXP || 0,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
// Equipment Management
|
|
64
|
+
async addItemToCharacter(actorId, itemData) {
|
|
65
|
+
logger.info(`Adding ${itemData.name} to actor ${actorId}`);
|
|
66
|
+
const transaction = {
|
|
67
|
+
actorId,
|
|
68
|
+
action: 'add',
|
|
69
|
+
itemId: this.generateItemId(),
|
|
70
|
+
itemName: itemData.name,
|
|
71
|
+
quantity: itemData.quantity || 1,
|
|
72
|
+
timestamp: new Date(),
|
|
73
|
+
};
|
|
74
|
+
this.equipmentHistory.push(transaction);
|
|
75
|
+
this.emit('equipment_changed', transaction);
|
|
76
|
+
return transaction;
|
|
77
|
+
}
|
|
78
|
+
async equipItem(actorId, itemId) {
|
|
79
|
+
const transaction = {
|
|
80
|
+
actorId,
|
|
81
|
+
action: 'equip',
|
|
82
|
+
itemId,
|
|
83
|
+
itemName: 'Unknown Item', // Would be retrieved from actual item data
|
|
84
|
+
timestamp: new Date(),
|
|
85
|
+
};
|
|
86
|
+
this.equipmentHistory.push(transaction);
|
|
87
|
+
this.emit('equipment_changed', transaction);
|
|
88
|
+
logger.info(`Equipped item ${itemId} on actor ${actorId}`);
|
|
89
|
+
return transaction;
|
|
90
|
+
}
|
|
91
|
+
async transferItem(fromActorId, toActorId, itemId, quantity) {
|
|
92
|
+
const transaction = {
|
|
93
|
+
actorId: fromActorId,
|
|
94
|
+
action: 'transfer',
|
|
95
|
+
itemId,
|
|
96
|
+
itemName: 'Unknown Item',
|
|
97
|
+
quantity: quantity || 1,
|
|
98
|
+
targetActorId: toActorId,
|
|
99
|
+
timestamp: new Date(),
|
|
100
|
+
};
|
|
101
|
+
this.equipmentHistory.push(transaction);
|
|
102
|
+
this.emit('equipment_changed', transaction);
|
|
103
|
+
logger.info(`Transferred item ${itemId} from ${fromActorId} to ${toActorId}`);
|
|
104
|
+
return transaction;
|
|
105
|
+
}
|
|
106
|
+
// Resource Management
|
|
107
|
+
async trackResource(actorId, resourceName, config) {
|
|
108
|
+
const resource = {
|
|
109
|
+
actorId,
|
|
110
|
+
resource: resourceName,
|
|
111
|
+
maxValue: config.maxValue,
|
|
112
|
+
currentValue: config.currentValue ?? config.maxValue,
|
|
113
|
+
resetType: config.resetType,
|
|
114
|
+
lastReset: new Date(),
|
|
115
|
+
};
|
|
116
|
+
if (!this.resourceTracking.has(actorId)) {
|
|
117
|
+
this.resourceTracking.set(actorId, []);
|
|
118
|
+
}
|
|
119
|
+
const resources = this.resourceTracking.get(actorId);
|
|
120
|
+
if (!resources) {
|
|
121
|
+
throw new Error(`Resources not found for actor ${actorId}`);
|
|
122
|
+
}
|
|
123
|
+
const existingIndex = resources.findIndex((r) => r.resource === resourceName);
|
|
124
|
+
if (existingIndex >= 0) {
|
|
125
|
+
resources[existingIndex] = resource;
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
resources.push(resource);
|
|
129
|
+
}
|
|
130
|
+
this.emit('resource_tracked', resource);
|
|
131
|
+
return resource;
|
|
132
|
+
}
|
|
133
|
+
async useResource(actorId, resourceName, amount = 1) {
|
|
134
|
+
const resources = this.resourceTracking.get(actorId);
|
|
135
|
+
if (!resources) {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
const resource = resources.find((r) => r.resource === resourceName);
|
|
139
|
+
if (!resource) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
if (resource.currentValue >= amount) {
|
|
143
|
+
resource.currentValue -= amount;
|
|
144
|
+
this.emit('resource_used', { resource, amountUsed: amount });
|
|
145
|
+
logger.info(`${actorId} used ${amount} ${resourceName} (${resource.currentValue}/${resource.maxValue} remaining)`);
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
logger.warn(`${actorId} attempted to use ${amount} ${resourceName} but only has ${resource.currentValue}`);
|
|
149
|
+
}
|
|
150
|
+
return resource;
|
|
151
|
+
}
|
|
152
|
+
async restoreResources(actorId, restType) {
|
|
153
|
+
const resources = this.resourceTracking.get(actorId) || [];
|
|
154
|
+
const restoredResources = [];
|
|
155
|
+
// Process resource restoration
|
|
156
|
+
for (const resource of resources) {
|
|
157
|
+
if ((restType === 'short_rest' && resource.resetType === 'short_rest') ||
|
|
158
|
+
(restType === 'long_rest' &&
|
|
159
|
+
(resource.resetType === 'long_rest' || resource.resetType === 'short_rest'))) {
|
|
160
|
+
resource.currentValue = resource.maxValue;
|
|
161
|
+
resource.lastReset = new Date();
|
|
162
|
+
restoredResources.push(resource);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (restoredResources.length > 0) {
|
|
166
|
+
this.emit('resources_restored', { actorId, restType, resources: restoredResources });
|
|
167
|
+
logger.info(`Restored ${restoredResources.length} resources for ${actorId} after ${restType} rest`);
|
|
168
|
+
}
|
|
169
|
+
return restoredResources;
|
|
170
|
+
}
|
|
171
|
+
// Helper methods for the character advancement system
|
|
172
|
+
calculateHitPointGain(_actor, method) {
|
|
173
|
+
const hitDie = 8; // Default d8, would be determined by class
|
|
174
|
+
switch (method) {
|
|
175
|
+
case 'roll':
|
|
176
|
+
return Math.floor(Math.random() * hitDie) + 1;
|
|
177
|
+
case 'average':
|
|
178
|
+
return Math.floor(hitDie / 2) + 1;
|
|
179
|
+
case 'max':
|
|
180
|
+
return hitDie;
|
|
181
|
+
default:
|
|
182
|
+
return Math.floor(hitDie / 2) + 1;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
suggestAbilityImprovements(_actor) {
|
|
186
|
+
// Simple suggestion logic - would be more sophisticated in practice
|
|
187
|
+
return [
|
|
188
|
+
{ ability: 'strength', increase: 1 },
|
|
189
|
+
{ ability: 'constitution', increase: 1 },
|
|
190
|
+
];
|
|
191
|
+
}
|
|
192
|
+
determineNewSpells(_actor, _level) {
|
|
193
|
+
// Would integrate with spell system
|
|
194
|
+
return [];
|
|
195
|
+
}
|
|
196
|
+
determineNewFeatures(_actor, _level) {
|
|
197
|
+
// Would integrate with class feature system
|
|
198
|
+
return [];
|
|
199
|
+
}
|
|
200
|
+
determineNewSkills(_actor, _level) {
|
|
201
|
+
// Would integrate with skill system
|
|
202
|
+
return [];
|
|
203
|
+
}
|
|
204
|
+
generateItemId() {
|
|
205
|
+
return `item_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
//# sourceMappingURL=manager.js.map
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The checks `init` (and `init --check`) runs, each returning
|
|
3
|
+
* a verdict with a message the user can act on.
|
|
4
|
+
*
|
|
5
|
+
* They connect the way the connector does — axios and socket.io-client with
|
|
6
|
+
* Node's default TLS verification, the 4-step `/join` login of `auth.ts` —
|
|
7
|
+
* but never start the module bridge: no bridge port is taken, so they run
|
|
8
|
+
* next to a running shared process. No message carries a password.
|
|
9
|
+
*/
|
|
10
|
+
import axios from 'axios';
|
|
11
|
+
import { io } from 'socket.io-client';
|
|
12
|
+
import { authenticateFoundry, isNoWorldPage, NoActiveWorldError, sessionSocketOptions, } from '../foundry/auth.js';
|
|
13
|
+
import { describeBrowser } from '../foundry/browser-detect.js';
|
|
14
|
+
import { gamemasterAccountWarning, roleLabel } from '../foundry/client.js';
|
|
15
|
+
import { USER_ROLES } from '../foundry/types.js';
|
|
16
|
+
/** Id of the companion module in FoundryVTT. */
|
|
17
|
+
export const BRIDGE_MODULE_ID = 'foundryvtt-mcp-bridge';
|
|
18
|
+
/** Stable manifest URL: always the latest bridge release. */
|
|
19
|
+
export const BRIDGE_MANIFEST_URL = 'https://raw.githubusercontent.com/G33ks/foundryvtt-mcp/main/foundry-module/module.json';
|
|
20
|
+
const REQUEST_TIMEOUT_MS = 15000;
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
// URL
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
function isLoopback(host) {
|
|
25
|
+
const bare = host.replace(/^\[|\]$/g, '');
|
|
26
|
+
return bare === 'localhost' || bare === '::1' || /^127\./.test(bare);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The FoundryVTT base URL from what the user typed: a scheme added when
|
|
30
|
+
* missing (http for this machine, https otherwise), trailing slashes and a
|
|
31
|
+
* pasted `/join`, `/game` or `/setup` removed, a route prefix kept.
|
|
32
|
+
*/
|
|
33
|
+
export function normalizeUrl(input) {
|
|
34
|
+
let text = input.trim();
|
|
35
|
+
if (text === '') {
|
|
36
|
+
return { ok: false, message: 'Type the address of your FoundryVTT server.' };
|
|
37
|
+
}
|
|
38
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) {
|
|
39
|
+
const host = text.split(/[/:]/)[0] ?? '';
|
|
40
|
+
text = `${isLoopback(host) ? 'http' : 'https'}://${text}`;
|
|
41
|
+
}
|
|
42
|
+
let url;
|
|
43
|
+
try {
|
|
44
|
+
url = new URL(text);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return { ok: false, message: `"${input.trim()}" is not a valid address.` };
|
|
48
|
+
}
|
|
49
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
50
|
+
return { ok: false, message: 'The address must start with http:// or https://.' };
|
|
51
|
+
}
|
|
52
|
+
const pathname = url.pathname
|
|
53
|
+
.replace(/\/+$/, '')
|
|
54
|
+
.replace(/\/(join|game|setup|auth|license)$/, '');
|
|
55
|
+
const value = `${url.protocol}//${url.host}${pathname}`;
|
|
56
|
+
const warning = url.protocol === 'http:' && !isLoopback(url.hostname)
|
|
57
|
+
? 'This address uses plain http: the password would cross the network unencrypted. Use https for a remote server.'
|
|
58
|
+
: undefined;
|
|
59
|
+
return { ok: true, value, message: value, ...(warning ? { warning } : {}) };
|
|
60
|
+
}
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
// Network errors
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
const TLS_CODES = {
|
|
65
|
+
CERT_HAS_EXPIRED: 'its certificate has expired',
|
|
66
|
+
CERT_NOT_YET_VALID: 'its certificate is not valid yet (check this computer’s clock)',
|
|
67
|
+
DEPTH_ZERO_SELF_SIGNED_CERT: 'its certificate is self-signed',
|
|
68
|
+
SELF_SIGNED_CERT_IN_CHAIN: 'its certificate chain ends in a self-signed certificate',
|
|
69
|
+
UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'its certificate cannot be verified (incomplete chain)',
|
|
70
|
+
UNABLE_TO_GET_ISSUER_CERT_LOCALLY: 'its certificate issuer is not trusted by Node.js',
|
|
71
|
+
ERR_TLS_CERT_ALTNAME_INVALID: 'its certificate is for another name or address',
|
|
72
|
+
};
|
|
73
|
+
function errorCode(error) {
|
|
74
|
+
if (typeof error !== 'object' || error === null) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
const { code, cause } = error;
|
|
78
|
+
if (typeof code === 'string' && code !== 'ERR_BAD_RESPONSE' && code !== 'ERR_BAD_REQUEST') {
|
|
79
|
+
return code;
|
|
80
|
+
}
|
|
81
|
+
return cause !== undefined ? errorCode(cause) : undefined;
|
|
82
|
+
}
|
|
83
|
+
/** What went wrong reaching `url`, in words. */
|
|
84
|
+
export function describeNetworkError(url, error) {
|
|
85
|
+
const code = errorCode(error);
|
|
86
|
+
const host = (() => {
|
|
87
|
+
try {
|
|
88
|
+
return new URL(url).host;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return url;
|
|
92
|
+
}
|
|
93
|
+
})();
|
|
94
|
+
if (code && TLS_CODES[code]) {
|
|
95
|
+
return (`The secure connection to ${host} was refused: ${TLS_CODES[code]} (${code}). ` +
|
|
96
|
+
'The connector checks certificates like a browser: fix the certificate on the server ' +
|
|
97
|
+
'(in FoundryVTT: Setup → Configuration → SSL), or give Node.js your own authority ' +
|
|
98
|
+
'with NODE_EXTRA_CA_CERTS.');
|
|
99
|
+
}
|
|
100
|
+
switch (code) {
|
|
101
|
+
case 'ENOTFOUND':
|
|
102
|
+
case 'EAI_AGAIN':
|
|
103
|
+
return `${host} could not be found (${code}): check the spelling of the address.`;
|
|
104
|
+
case 'ECONNREFUSED':
|
|
105
|
+
return `${host} refused the connection (${code}): is FoundryVTT running, on this port?`;
|
|
106
|
+
case 'ETIMEDOUT':
|
|
107
|
+
case 'ECONNABORTED':
|
|
108
|
+
case 'ENETUNREACH':
|
|
109
|
+
case 'EHOSTUNREACH':
|
|
110
|
+
return `${host} did not answer (${code}): check the address, the port and any firewall.`;
|
|
111
|
+
case 'ECONNRESET':
|
|
112
|
+
case 'EPROTO':
|
|
113
|
+
return `${host} closed the connection (${code}): check http versus https in the address.`;
|
|
114
|
+
}
|
|
115
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
116
|
+
return `Could not reach ${host}: ${detail}`;
|
|
117
|
+
}
|
|
118
|
+
const NO_WORLD_MESSAGE = 'FoundryVTT answers, but no world is running ("No Active Game"). Launch your world ' +
|
|
119
|
+
'from the Setup screen, then press Enter to try again.';
|
|
120
|
+
const defaultGet = (url) => axios.get(url, {
|
|
121
|
+
maxRedirects: 0,
|
|
122
|
+
timeout: REQUEST_TIMEOUT_MS,
|
|
123
|
+
validateStatus: () => true,
|
|
124
|
+
responseType: 'text',
|
|
125
|
+
});
|
|
126
|
+
/** Reaches `<url>/join` and says whether a world is running there. */
|
|
127
|
+
export async function probeJoin(url, get = defaultGet) {
|
|
128
|
+
let response;
|
|
129
|
+
try {
|
|
130
|
+
response = await get(`${url}/join`);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
return { ok: false, message: describeNetworkError(url, error) };
|
|
134
|
+
}
|
|
135
|
+
const location = String(response.headers?.location ?? '');
|
|
136
|
+
if (response.status >= 300 &&
|
|
137
|
+
response.status < 400 &&
|
|
138
|
+
/\/(setup|auth|license)\b/.test(location)) {
|
|
139
|
+
return { ok: false, message: NO_WORLD_MESSAGE };
|
|
140
|
+
}
|
|
141
|
+
if (response.status === 200 && isNoWorldPage(response.data)) {
|
|
142
|
+
return { ok: false, message: NO_WORLD_MESSAGE };
|
|
143
|
+
}
|
|
144
|
+
const cookies = response.headers?.['set-cookie'];
|
|
145
|
+
const hasSession = (Array.isArray(cookies) ? cookies.join(' ') : String(cookies ?? '')).includes('session=');
|
|
146
|
+
if ((response.status === 200 || response.status === 302) && hasSession) {
|
|
147
|
+
return {
|
|
148
|
+
ok: true,
|
|
149
|
+
value: undefined,
|
|
150
|
+
message: `FoundryVTT answers at ${url}, with a world running.`,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
ok: false,
|
|
155
|
+
message: `${url}/join answered HTTP ${response.status} without a FoundryVTT session: ` +
|
|
156
|
+
'is this the address of FoundryVTT (and its route prefix, if any)?',
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/** Why the login failed, worded for the user; `retry` names what to change. */
|
|
160
|
+
export function describeLoginError(url, username, error) {
|
|
161
|
+
if (error instanceof NoActiveWorldError) {
|
|
162
|
+
return { message: NO_WORLD_MESSAGE, retry: 'world' };
|
|
163
|
+
}
|
|
164
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
165
|
+
if (/^User ".*" not found$/.test(text)) {
|
|
166
|
+
return {
|
|
167
|
+
message: `There is no user named "${username}" in this world. Create it in FoundryVTT ` +
|
|
168
|
+
'(Game Settings → Configure Players / User Management), or check the spelling.',
|
|
169
|
+
retry: 'account',
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
const auth = /authentication failed \(HTTP (\d+)\): (.*)$/s.exec(text);
|
|
173
|
+
if (auth) {
|
|
174
|
+
const reason = auth[2] ?? '';
|
|
175
|
+
if (/password/i.test(reason)) {
|
|
176
|
+
return { message: `Wrong password for "${username}".`, retry: 'account' };
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
message: `FoundryVTT refused the login of "${username}" (HTTP ${auth[1]}): ${reason}`,
|
|
180
|
+
retry: 'account',
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
return { message: describeNetworkError(url, error), retry: 'url' };
|
|
184
|
+
}
|
|
185
|
+
/** Logs in like the connector, then reads the account's role and the installed modules. */
|
|
186
|
+
export async function loginAndReadWorld(url, username, password) {
|
|
187
|
+
const { session, userId } = await authenticateFoundry(url, username, password);
|
|
188
|
+
return await new Promise((resolve, reject) => {
|
|
189
|
+
const socket = io(url, { ...sessionSocketOptions(session), reconnection: false });
|
|
190
|
+
const finish = (outcome) => {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
socket.off('session', onSession);
|
|
193
|
+
socket.off('connect_error', onError);
|
|
194
|
+
socket.disconnect();
|
|
195
|
+
outcome();
|
|
196
|
+
};
|
|
197
|
+
const timer = setTimeout(() => finish(() => reject(new Error('FoundryVTT did not send the world data in time'))), REQUEST_TIMEOUT_MS);
|
|
198
|
+
const onSession = () => {
|
|
199
|
+
socket.emit('world', (data) => {
|
|
200
|
+
const users = Array.isArray(data?.users)
|
|
201
|
+
? data.users
|
|
202
|
+
: [];
|
|
203
|
+
const me = users.find((u) => u._id === userId);
|
|
204
|
+
finish(() => resolve({
|
|
205
|
+
role: typeof me?.role === 'number' ? me.role : null,
|
|
206
|
+
modules: Array.isArray(data?.modules) ? data.modules : [],
|
|
207
|
+
}));
|
|
208
|
+
});
|
|
209
|
+
};
|
|
210
|
+
const onError = (error) => finish(() => reject(error));
|
|
211
|
+
socket.on('session', onSession);
|
|
212
|
+
socket.on('connect_error', onError);
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
/** Whether `role` can run the connector: the module and the headless page need `isGM`. */
|
|
216
|
+
export function evaluateRole(username, role) {
|
|
217
|
+
if (role === null) {
|
|
218
|
+
return {
|
|
219
|
+
ok: true,
|
|
220
|
+
value: undefined,
|
|
221
|
+
message: `Logged in as "${username}".`,
|
|
222
|
+
warning: 'FoundryVTT did not report the role of this account: make sure it is an Assistant GM.',
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const label = roleLabel(role);
|
|
226
|
+
if (role < USER_ROLES.assistant) {
|
|
227
|
+
return {
|
|
228
|
+
ok: false,
|
|
229
|
+
message: `"${username}" is a ${label}: the companion module and the headless GM session need a GM ` +
|
|
230
|
+
'role. Make this account an Assistant GM (Game Settings → User Management), then press ' +
|
|
231
|
+
'Enter to try again.',
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
const warning = gamemasterAccountWarning(true, { name: username, role }) ?? undefined;
|
|
235
|
+
return {
|
|
236
|
+
ok: true,
|
|
237
|
+
value: undefined,
|
|
238
|
+
message: `Logged in as "${username}" (${label}).`,
|
|
239
|
+
...(warning ? { warning } : {}),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/** Whether the companion module is installed and enabled in the world. */
|
|
243
|
+
export function evaluateModule(modules) {
|
|
244
|
+
const bridge = modules.find((m) => m.id === BRIDGE_MODULE_ID);
|
|
245
|
+
if (!bridge) {
|
|
246
|
+
return {
|
|
247
|
+
ok: false,
|
|
248
|
+
message: [
|
|
249
|
+
`The companion module ${BRIDGE_MODULE_ID} is not installed on this FoundryVTT server. To install it:`,
|
|
250
|
+
' 1. In FoundryVTT, Return to Setup, then Add-on Modules → Install Module.',
|
|
251
|
+
` 2. Paste this manifest URL and press Install: ${BRIDGE_MANIFEST_URL}`,
|
|
252
|
+
' 3. Launch the world, open Game Settings → Manage Modules, tick "FoundryVTT MCP Bridge"',
|
|
253
|
+
' and Save Module Settings.',
|
|
254
|
+
'Then press Enter here to check again.',
|
|
255
|
+
].join('\n'),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
const version = typeof bridge.version === 'string' ? bridge.version : null;
|
|
259
|
+
const named = `${BRIDGE_MODULE_ID}${version ? ` v${version}` : ''}`;
|
|
260
|
+
if (bridge.active !== true) {
|
|
261
|
+
return {
|
|
262
|
+
ok: false,
|
|
263
|
+
message: [
|
|
264
|
+
`The companion module ${named} is installed but not enabled in this world. To enable it:`,
|
|
265
|
+
' Game Settings → Manage Modules, tick "FoundryVTT MCP Bridge", then Save Module Settings',
|
|
266
|
+
' (the world reloads).',
|
|
267
|
+
'Then press Enter here to check again.',
|
|
268
|
+
].join('\n'),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
return { ok: true, value: version, message: `Companion module ${named} installed and enabled.` };
|
|
272
|
+
}
|
|
273
|
+
// ---------------------------------------------------------------------------
|
|
274
|
+
// Browser
|
|
275
|
+
// ---------------------------------------------------------------------------
|
|
276
|
+
/**
|
|
277
|
+
* Launches the headless GM browser as the session would (headless, with a
|
|
278
|
+
* throwaway profile), opens `about:blank` and closes it.
|
|
279
|
+
*/
|
|
280
|
+
export async function checkBrowser(executablePath) {
|
|
281
|
+
const { launchHeadlessBrowser } = await import('../foundry/headless-gm-session.js');
|
|
282
|
+
let launched;
|
|
283
|
+
try {
|
|
284
|
+
launched = await launchHeadlessBrowser(executablePath ? { executablePath } : {});
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
return { ok: false, message: error instanceof Error ? error.message : String(error) };
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
const page = await launched.browser.newPage();
|
|
291
|
+
await page.goto('about:blank');
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
await launched.browser.close().catch(() => undefined);
|
|
295
|
+
return {
|
|
296
|
+
ok: false,
|
|
297
|
+
message: `${describeBrowser(launched.choice)} started but could not open a page: ${error instanceof Error ? error.message : String(error)}`,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
await launched.browser.close();
|
|
301
|
+
return {
|
|
302
|
+
ok: true,
|
|
303
|
+
value: launched.choice,
|
|
304
|
+
message: `Browser for the headless GM session: ${describeBrowser(launched.choice)} — started and closed.`,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
//# sourceMappingURL=checks.js.map
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Writes the configuration file for `init`.
|
|
3
|
+
*
|
|
4
|
+
* Each value is written so that `dotenv.parse` reads it back unchanged:
|
|
5
|
+
* between '…', else between `…` (it contains an apostrophe), else between
|
|
6
|
+
* "…" — never with a `\n` or `\r` sequence inside, which dotenv expands in
|
|
7
|
+
* double quotes. A value no quoting can carry is refused.
|
|
8
|
+
*
|
|
9
|
+
* An existing file keeps its comments and every key `init` does not manage:
|
|
10
|
+
* managed keys are rewritten in place (new ones go at the end), after a
|
|
11
|
+
* timestamped copy of the file.
|
|
12
|
+
*/
|
|
13
|
+
import { chmodSync, copyFileSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { readConfigFile } from '../config/sources.js';
|
|
16
|
+
/** Thrown for a value that cannot be written; never carries the value itself. */
|
|
17
|
+
export class UnwritableValueError extends Error {
|
|
18
|
+
name = 'UnwritableValueError';
|
|
19
|
+
}
|
|
20
|
+
/** The value quoted for a dotenv file. */
|
|
21
|
+
export function quoteValue(name, value) {
|
|
22
|
+
if (/[\r\n]/.test(value)) {
|
|
23
|
+
throw new UnwritableValueError(`${name} contains a line break, which cannot be written.`);
|
|
24
|
+
}
|
|
25
|
+
if (!value.includes("'")) {
|
|
26
|
+
return `'${value}'`;
|
|
27
|
+
}
|
|
28
|
+
if (!value.includes('`')) {
|
|
29
|
+
return `\`${value}\``;
|
|
30
|
+
}
|
|
31
|
+
if (!value.includes('"') && !/\\[nr]/.test(value)) {
|
|
32
|
+
return `"${value}"`;
|
|
33
|
+
}
|
|
34
|
+
throw new UnwritableValueError(`${name} contains ', \` and " (or a \\n sequence), which no quoting can carry: choose another value.`);
|
|
35
|
+
}
|
|
36
|
+
/** `KEY=…` line for `name`, possibly after `export`. */
|
|
37
|
+
function keyPattern(name) {
|
|
38
|
+
return new RegExp(`^\\s*(?:export\\s+)?${name.replace(/[.]/g, '\\.')}\\s*=`);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* `text` with each of `updates` set: existing lines rewritten in place,
|
|
42
|
+
* new keys appended. Comments, blank lines and other keys are kept.
|
|
43
|
+
*/
|
|
44
|
+
export function mergeConfig(text, updates) {
|
|
45
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
46
|
+
const lines = text.length > 0 ? text.split(/\r?\n/) : [];
|
|
47
|
+
// A trailing newline leaves one empty last element: appended keys go before it.
|
|
48
|
+
const trailing = lines.length > 0 && lines[lines.length - 1] === '' ? lines.pop() : undefined;
|
|
49
|
+
for (const [name, value] of updates) {
|
|
50
|
+
const line = `${name}=${quoteValue(name, value)}`;
|
|
51
|
+
const pattern = keyPattern(name);
|
|
52
|
+
let found = false;
|
|
53
|
+
for (let i = 0; i < lines.length; i++) {
|
|
54
|
+
if (pattern.test(lines[i] ?? '')) {
|
|
55
|
+
lines[i] = line;
|
|
56
|
+
found = true;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (!found) {
|
|
60
|
+
lines.push(line);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (trailing !== undefined || lines.length > 0) {
|
|
64
|
+
lines.push('');
|
|
65
|
+
}
|
|
66
|
+
return lines.join(eol);
|
|
67
|
+
}
|
|
68
|
+
/** Header of a file `init` creates. */
|
|
69
|
+
export const NEW_FILE_HEADER = [
|
|
70
|
+
'# FoundryVTT MCP — shared by every MCP client (written by the `init` command).',
|
|
71
|
+
'# One KEY=value per line; see SETUP_GUIDE.md (Configuration) for every setting.',
|
|
72
|
+
'',
|
|
73
|
+
].join('\n');
|
|
74
|
+
/** e.g. `20261102-183512`, local time. */
|
|
75
|
+
export function backupStamp(now) {
|
|
76
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
77
|
+
return (`${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-` +
|
|
78
|
+
`${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Writes `updates` to the configuration file at `file`, then reads it back
|
|
82
|
+
* with the resolver's own parser to check every value.
|
|
83
|
+
*
|
|
84
|
+
* @throws UnwritableValueError before touching anything, for a value no quoting can carry
|
|
85
|
+
* @throws Error when the file read back differs
|
|
86
|
+
*/
|
|
87
|
+
export function writeConfig(file, updates, options = {}) {
|
|
88
|
+
const platform = options.platform ?? process.platform;
|
|
89
|
+
let previous = null;
|
|
90
|
+
try {
|
|
91
|
+
previous = readFileSync(file, 'utf8');
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (error.code !== 'ENOENT') {
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
// Quoting errors surface here, before any copy or write.
|
|
99
|
+
const content = mergeConfig(previous ?? NEW_FILE_HEADER, updates);
|
|
100
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
101
|
+
let backup = null;
|
|
102
|
+
if (previous !== null) {
|
|
103
|
+
backup = `${file}.bak-${backupStamp(options.now ?? new Date())}`;
|
|
104
|
+
copyFileSync(file, backup);
|
|
105
|
+
}
|
|
106
|
+
const temp = `${file}.tmp-${process.pid}`;
|
|
107
|
+
writeFileSync(temp, content, { encoding: 'utf8', mode: 0o600 });
|
|
108
|
+
if (platform !== 'win32') {
|
|
109
|
+
chmodSync(temp, 0o600);
|
|
110
|
+
}
|
|
111
|
+
renameSync(temp, file);
|
|
112
|
+
const { state, values } = readConfigFile(file, platform);
|
|
113
|
+
const wrong = updates.filter(([name, value]) => values[name] !== value).map(([name]) => name);
|
|
114
|
+
if (state.error || wrong.length > 0) {
|
|
115
|
+
throw new Error(`${file} was written but does not read back as expected (${state.error ?? wrong.join(', ')})` +
|
|
116
|
+
(backup ? `; the previous file is in ${backup}` : ''));
|
|
117
|
+
}
|
|
118
|
+
return { backup, created: previous === null };
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=config-file.js.map
|