@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,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Server side of the relay ↔ shared-process channel.
|
|
3
|
+
*
|
|
4
|
+
* Listening on the endpoint doubles as the single-instance lock: a second
|
|
5
|
+
* shared process gets `in-use` from {@link IpcServer.listen} and exits.
|
|
6
|
+
*
|
|
7
|
+
* Deliberately free of config/logger imports; the owner passes a `log`
|
|
8
|
+
* callback and decides what each event means.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, rmSync } from 'node:fs';
|
|
11
|
+
import net from 'node:net';
|
|
12
|
+
import { compareBuilds } from './build-order.js';
|
|
13
|
+
import { differingSettings } from './config-hash.js';
|
|
14
|
+
import { encodeLine, HelloSchema, IpcErrorCode, LineDecoder, PROTOCOL_VERSION, RequestSchema, } from './protocol.js';
|
|
15
|
+
import { tokensMatch } from './token.js';
|
|
16
|
+
/** How long a peer may stay connected without completing the handshake. */
|
|
17
|
+
const HELLO_TIMEOUT_MS = 5000;
|
|
18
|
+
export class IpcServer {
|
|
19
|
+
options;
|
|
20
|
+
server = null;
|
|
21
|
+
sockets = new Set();
|
|
22
|
+
relays = 0;
|
|
23
|
+
/** Build of each accepted relay running another build than this process. */
|
|
24
|
+
outdatedRelays = new Map();
|
|
25
|
+
/** What each accepted relay declared about its settings, for `status`. */
|
|
26
|
+
relayConfigs = new Map();
|
|
27
|
+
inFlight = 0;
|
|
28
|
+
draining = false;
|
|
29
|
+
idleWaiters = [];
|
|
30
|
+
constructor(options) {
|
|
31
|
+
this.options = options;
|
|
32
|
+
}
|
|
33
|
+
/** Accepted relay connections (control connections excluded). */
|
|
34
|
+
get relayCount() {
|
|
35
|
+
return this.relays;
|
|
36
|
+
}
|
|
37
|
+
/** Builds of the connected relays that run another build than this process. */
|
|
38
|
+
get outdatedRelayVersions() {
|
|
39
|
+
return [...this.outdatedRelays.values()];
|
|
40
|
+
}
|
|
41
|
+
/** Each connected relay's declared provenance and the settings of it that are ignored. */
|
|
42
|
+
get relayConfigList() {
|
|
43
|
+
return [...this.relayConfigs.values()];
|
|
44
|
+
}
|
|
45
|
+
/** Requests currently being handled. */
|
|
46
|
+
get inFlightCount() {
|
|
47
|
+
return this.inFlight;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Binds the endpoint. `in-use` means another process holds it: the caller
|
|
51
|
+
* lost the single-instance race. A Unix socket file left by a crashed
|
|
52
|
+
* process is detected (nobody accepts on it) and replaced.
|
|
53
|
+
*/
|
|
54
|
+
async listen() {
|
|
55
|
+
const first = await this.tryListen();
|
|
56
|
+
if (first !== 'in-use' || process.platform === 'win32') {
|
|
57
|
+
return first;
|
|
58
|
+
}
|
|
59
|
+
if (await isEndpointAlive(this.options.endpoint)) {
|
|
60
|
+
return 'in-use';
|
|
61
|
+
}
|
|
62
|
+
rmSync(this.options.endpoint, { force: true });
|
|
63
|
+
return this.tryListen();
|
|
64
|
+
}
|
|
65
|
+
tryListen() {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
const server = net.createServer((socket) => this.accept(socket));
|
|
68
|
+
const onError = (error) => {
|
|
69
|
+
server.close();
|
|
70
|
+
if (error.code === 'EADDRINUSE') {
|
|
71
|
+
resolve('in-use');
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
reject(error);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
server.once('error', onError);
|
|
78
|
+
server.listen(this.options.endpoint, () => {
|
|
79
|
+
server.off('error', onError);
|
|
80
|
+
server.on('error', (error) => this.log('warn', `IPC server error: ${error.message}`));
|
|
81
|
+
this.server = server;
|
|
82
|
+
resolve('listening');
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Stops starting new work: new relays are told the process is draining and
|
|
88
|
+
* new requests on open connections fail with a retryable error. Requests
|
|
89
|
+
* already started run to completion.
|
|
90
|
+
*/
|
|
91
|
+
setDraining() {
|
|
92
|
+
this.draining = true;
|
|
93
|
+
}
|
|
94
|
+
/** Resolves once no request is in flight. */
|
|
95
|
+
waitForIdle() {
|
|
96
|
+
if (this.inFlight === 0) {
|
|
97
|
+
return Promise.resolve();
|
|
98
|
+
}
|
|
99
|
+
return new Promise((resolve) => this.idleWaiters.push(resolve));
|
|
100
|
+
}
|
|
101
|
+
/** Closes every connection and releases the endpoint. */
|
|
102
|
+
async close() {
|
|
103
|
+
for (const socket of this.sockets) {
|
|
104
|
+
socket.destroy();
|
|
105
|
+
}
|
|
106
|
+
this.sockets.clear();
|
|
107
|
+
const server = this.server;
|
|
108
|
+
this.server = null;
|
|
109
|
+
if (server) {
|
|
110
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
111
|
+
}
|
|
112
|
+
if (process.platform !== 'win32' && existsSync(this.options.endpoint)) {
|
|
113
|
+
rmSync(this.options.endpoint, { force: true });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
log(level, message) {
|
|
117
|
+
this.options.log?.(level, message);
|
|
118
|
+
}
|
|
119
|
+
accept(socket) {
|
|
120
|
+
this.sockets.add(socket);
|
|
121
|
+
const decoder = new LineDecoder();
|
|
122
|
+
let role = null;
|
|
123
|
+
const helloTimer = setTimeout(() => {
|
|
124
|
+
this.log('warn', 'IPC peer did not complete the handshake in time; closing it');
|
|
125
|
+
socket.destroy();
|
|
126
|
+
}, HELLO_TIMEOUT_MS);
|
|
127
|
+
socket.on('data', (chunk) => {
|
|
128
|
+
let messages;
|
|
129
|
+
try {
|
|
130
|
+
messages = decoder.push(chunk);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
this.log('warn', `Dropping IPC peer: ${error instanceof Error ? error.message : error}`);
|
|
134
|
+
socket.destroy();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
for (const message of messages) {
|
|
138
|
+
if (role === null) {
|
|
139
|
+
clearTimeout(helloTimer);
|
|
140
|
+
role = this.handleHello(socket, message);
|
|
141
|
+
if (role === null) {
|
|
142
|
+
socket.end();
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (role === 'relay') {
|
|
146
|
+
this.relays++;
|
|
147
|
+
this.options.onRelayCountChange?.(this.relays);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
this.handleRequest(socket, message);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
socket.on('error', () => {
|
|
156
|
+
// A relay killed mid-write surfaces as EPIPE/ECONNRESET; 'close' follows.
|
|
157
|
+
});
|
|
158
|
+
socket.on('close', () => {
|
|
159
|
+
clearTimeout(helloTimer);
|
|
160
|
+
this.sockets.delete(socket);
|
|
161
|
+
this.outdatedRelays.delete(socket);
|
|
162
|
+
this.relayConfigs.delete(socket);
|
|
163
|
+
if (role === 'relay') {
|
|
164
|
+
this.relays--;
|
|
165
|
+
this.options.onRelayCountChange?.(this.relays);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** Returns the accepted role, or `null` after sending a rejection. */
|
|
170
|
+
handleHello(socket, message) {
|
|
171
|
+
const reject = (reason, text) => {
|
|
172
|
+
write(socket, { type: 'hello', ok: false, reason, message: text });
|
|
173
|
+
return null;
|
|
174
|
+
};
|
|
175
|
+
const parsed = HelloSchema.safeParse(message);
|
|
176
|
+
if (!parsed.success) {
|
|
177
|
+
return reject('protocol', 'Expected a hello message');
|
|
178
|
+
}
|
|
179
|
+
const hello = parsed.data;
|
|
180
|
+
if (!tokensMatch(this.options.token, hello.token)) {
|
|
181
|
+
this.log('warn', 'Rejected an IPC peer with an invalid token');
|
|
182
|
+
return reject('unauthorized', 'Invalid token');
|
|
183
|
+
}
|
|
184
|
+
if (hello.protocol !== PROTOCOL_VERSION) {
|
|
185
|
+
// Never a restart: the two builds cannot talk, and restarting would
|
|
186
|
+
// not help an old client (it would only loop) — tell the user instead.
|
|
187
|
+
const text = `Protocol ${hello.protocol} not supported (expected ${PROTOCOL_VERSION})`;
|
|
188
|
+
if (hello.role !== 'relay') {
|
|
189
|
+
return reject('protocol', text);
|
|
190
|
+
}
|
|
191
|
+
this.log('warn', `Refused relay v${hello.version}: protocol ${hello.protocol}, this process speaks ${PROTOCOL_VERSION}`);
|
|
192
|
+
return reject('protocol', compareBuilds(hello.version, this.options.version) === 'newer'
|
|
193
|
+
? `${text}: the shared process (v${this.options.version}) is older than this client. ` +
|
|
194
|
+
'Run `foundryvtt-mcp stop` (or `node dist/index.js stop`); the next call starts the current build.'
|
|
195
|
+
: `${text}: this MCP client runs an older connector build (v${hello.version}) than the ` +
|
|
196
|
+
`shared process (v${this.options.version}). Restart the client (fully quit Claude desktop, or restart Claude Code).`);
|
|
197
|
+
}
|
|
198
|
+
let outdated = false;
|
|
199
|
+
let ignored = [];
|
|
200
|
+
if (hello.role === 'relay') {
|
|
201
|
+
if (this.draining) {
|
|
202
|
+
return reject('draining', 'The shared process is shutting down');
|
|
203
|
+
}
|
|
204
|
+
if (hello.version !== this.options.version) {
|
|
205
|
+
if (this.options.onMismatch?.('version', hello.version, hello.configHash) === 'accept') {
|
|
206
|
+
this.log('warn', `Serving relay v${hello.version} although this process runs v${this.options.version}: restart that client to load the current tool list`);
|
|
207
|
+
outdated = true;
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
this.log('info', `Relay version ${hello.version} differs from ${this.options.version}; restarting`);
|
|
211
|
+
return reject('version', `Shared process runs version ${this.options.version}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (hello.configHash !== this.options.configHash) {
|
|
215
|
+
if (this.options.onMismatch?.('config', hello.version, hello.configHash) !== 'accept') {
|
|
216
|
+
this.log('info', 'Relay configuration differs from this process; restarting');
|
|
217
|
+
return reject('config', 'Shared process runs with a different configuration');
|
|
218
|
+
}
|
|
219
|
+
ignored = this.ignoredSettings(hello);
|
|
220
|
+
this.log('warn', `Serving relay${hello.pid ? ` ${hello.pid}` : ''} with this process's configuration; its own is ignored (${ignored === null
|
|
221
|
+
? 'a relay too old to say which settings differ'
|
|
222
|
+
: ignored.map((s) => `${s.name} from ${s.source}`).join(', ')})`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (outdated) {
|
|
226
|
+
this.outdatedRelays.set(socket, hello.version);
|
|
227
|
+
}
|
|
228
|
+
if (hello.role === 'relay') {
|
|
229
|
+
this.relayConfigs.set(socket, {
|
|
230
|
+
pid: hello.pid ?? null,
|
|
231
|
+
version: hello.version,
|
|
232
|
+
sources: hello.configSources ?? null,
|
|
233
|
+
ignored,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
write(socket, {
|
|
237
|
+
type: 'hello',
|
|
238
|
+
ok: true,
|
|
239
|
+
pid: process.pid,
|
|
240
|
+
version: this.options.version,
|
|
241
|
+
...(ignored === null || ignored.length > 0
|
|
242
|
+
? {
|
|
243
|
+
ignoredConfig: ignored ?? [],
|
|
244
|
+
...(this.options.configFile ? { configFile: this.options.configFile } : {}),
|
|
245
|
+
}
|
|
246
|
+
: {}),
|
|
247
|
+
});
|
|
248
|
+
return hello.role;
|
|
249
|
+
}
|
|
250
|
+
/** The relay's identity settings that differ from this process's; `null` when it cannot say. */
|
|
251
|
+
ignoredSettings(hello) {
|
|
252
|
+
if (!hello.configDigests || !this.options.configDigests) {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
return differingSettings(this.options.configDigests, hello.configDigests).map((name) => ({
|
|
256
|
+
name,
|
|
257
|
+
source: hello.configSources?.[name] ?? 'default',
|
|
258
|
+
}));
|
|
259
|
+
}
|
|
260
|
+
handleRequest(socket, message) {
|
|
261
|
+
const parsed = RequestSchema.safeParse(message);
|
|
262
|
+
if (!parsed.success) {
|
|
263
|
+
const id = typeof message === 'object' && message !== null && 'id' in message ? message.id : null;
|
|
264
|
+
if (typeof id === 'number') {
|
|
265
|
+
write(socket, {
|
|
266
|
+
type: 'response',
|
|
267
|
+
id,
|
|
268
|
+
error: { code: IpcErrorCode.InvalidRequest, message: 'Malformed request' },
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
const { id, op, name, args } = parsed.data;
|
|
274
|
+
if (this.draining && op !== 'status') {
|
|
275
|
+
write(socket, {
|
|
276
|
+
type: 'response',
|
|
277
|
+
id,
|
|
278
|
+
error: { code: IpcErrorCode.Draining, message: 'The shared process is shutting down' },
|
|
279
|
+
});
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
this.inFlight++;
|
|
283
|
+
// The handler runs to completion even if the relay goes away; the
|
|
284
|
+
// result is then simply dropped (a write is never cut in half).
|
|
285
|
+
this.options
|
|
286
|
+
.handler(op, name, args ?? {})
|
|
287
|
+
.then((result) => write(socket, { type: 'response', id, result: result ?? null }), (error) => write(socket, { type: 'response', id, error: this.options.toIpcError(error) }))
|
|
288
|
+
.finally(() => {
|
|
289
|
+
this.inFlight--;
|
|
290
|
+
if (this.inFlight === 0) {
|
|
291
|
+
const waiters = this.idleWaiters;
|
|
292
|
+
this.idleWaiters = [];
|
|
293
|
+
for (const resolve of waiters) {
|
|
294
|
+
resolve();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function write(socket, message) {
|
|
301
|
+
if (!socket.destroyed && socket.writable) {
|
|
302
|
+
socket.write(encodeLine(message));
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/** True when something accepts connections on `endpoint`. */
|
|
306
|
+
export function isEndpointAlive(endpoint) {
|
|
307
|
+
return new Promise((resolve) => {
|
|
308
|
+
const probe = net.connect(endpoint);
|
|
309
|
+
probe.once('connect', () => {
|
|
310
|
+
probe.destroy();
|
|
311
|
+
resolve(true);
|
|
312
|
+
});
|
|
313
|
+
probe.once('error', () => resolve(false));
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
//# sourceMappingURL=ipc-server.js.map
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Per-user locations used by the shared process: the state
|
|
3
|
+
* directory (token, state file, logs) and the IPC endpoint relays dial.
|
|
4
|
+
*
|
|
5
|
+
* Kept free of config/logger imports: `status` and `stop` resolve these
|
|
6
|
+
* paths without a valid FoundryVTT configuration.
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { mkdirSync } from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { processSettings } from '../config/env-layers.js';
|
|
13
|
+
/** Longest Unix socket path we bind to; `sun_path` is 104 bytes on macOS, 108 on Linux. */
|
|
14
|
+
const MAX_UNIX_SOCKET_PATH = 100;
|
|
15
|
+
/** Sanitised OS user name, safe inside a pipe name or file name. */
|
|
16
|
+
function userTag() {
|
|
17
|
+
let name;
|
|
18
|
+
try {
|
|
19
|
+
name = os.userInfo().username;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
name = process.env.USERNAME ?? process.env.USER ?? 'user';
|
|
23
|
+
}
|
|
24
|
+
return name.replace(/[^A-Za-z0-9_.-]/g, '_') || 'user';
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* `%LOCALAPPDATA%\foundryvtt-mcp` on Windows, `$XDG_STATE_HOME/foundryvtt-mcp`
|
|
28
|
+
* or `~/.local/state/foundryvtt-mcp` elsewhere. `FOUNDRY_MCP_STATE_DIR`
|
|
29
|
+
* overrides it, which also gives that directory its own endpoint (an
|
|
30
|
+
* isolated shared process, e.g. for tests) — from the environment or a
|
|
31
|
+
* development `.env`, never from the configuration file it locates.
|
|
32
|
+
*/
|
|
33
|
+
export function defaultStateDir(platform = process.platform, env = processSettings()) {
|
|
34
|
+
if (env.FOUNDRY_MCP_STATE_DIR) {
|
|
35
|
+
return path.resolve(env.FOUNDRY_MCP_STATE_DIR);
|
|
36
|
+
}
|
|
37
|
+
if (platform === 'win32') {
|
|
38
|
+
const base = env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
39
|
+
return path.join(base, 'foundryvtt-mcp');
|
|
40
|
+
}
|
|
41
|
+
const base = env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state');
|
|
42
|
+
return path.join(base, 'foundryvtt-mcp');
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The IPC endpoint. A Unix socket path longer than `sun_path` allows cannot
|
|
46
|
+
* be bound, so a deep state directory falls back to a private directory
|
|
47
|
+
* under the system temp dir.
|
|
48
|
+
*/
|
|
49
|
+
export function endpointFor(stateDir, platform = process.platform, user = userTag(), isDefaultStateDir = true) {
|
|
50
|
+
if (platform === 'win32') {
|
|
51
|
+
// Pipes live in one flat namespace: a non-default state dir gets its own.
|
|
52
|
+
const suffix = isDefaultStateDir
|
|
53
|
+
? ''
|
|
54
|
+
: `-${createHash('sha256').update(stateDir.toLowerCase()).digest('hex').slice(0, 8)}`;
|
|
55
|
+
return `\\\\.\\pipe\\foundryvtt-mcp-${user}${suffix}`;
|
|
56
|
+
}
|
|
57
|
+
const preferred = path.join(stateDir, 'daemon.sock');
|
|
58
|
+
if (Buffer.byteLength(preferred) <= MAX_UNIX_SOCKET_PATH) {
|
|
59
|
+
return preferred;
|
|
60
|
+
}
|
|
61
|
+
return path.join(os.tmpdir(), `foundryvtt-mcp-${user}`, 'daemon.sock');
|
|
62
|
+
}
|
|
63
|
+
/** Resolves every shared-process path and creates the directories they live in. */
|
|
64
|
+
export function resolveSharedPaths(stateDir = defaultStateDir()) {
|
|
65
|
+
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
66
|
+
const endpoint = endpointFor(stateDir, process.platform, userTag(), !processSettings().FOUNDRY_MCP_STATE_DIR);
|
|
67
|
+
if (process.platform !== 'win32') {
|
|
68
|
+
mkdirSync(path.dirname(endpoint), { recursive: true, mode: 0o700 });
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
stateDir,
|
|
72
|
+
endpoint,
|
|
73
|
+
tokenFile: path.join(stateDir, 'token'),
|
|
74
|
+
stateFile: path.join(stateDir, 'daemon.json'),
|
|
75
|
+
daemonLog: path.join(stateDir, 'daemon.log'),
|
|
76
|
+
relayLog: path.join(stateDir, 'relay.log'),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=paths.js.map
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Wire protocol between relays and the shared process.
|
|
3
|
+
*
|
|
4
|
+
* Newline-delimited JSON over a named pipe / Unix socket. The client opens
|
|
5
|
+
* with a `hello`; once the server accepts it, the client sends `request`s and
|
|
6
|
+
* the server answers each with a `response` carrying the same `id`. Several
|
|
7
|
+
* requests may be in flight on one connection; responses arrive in
|
|
8
|
+
* completion order.
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
/** Bumped on any incompatible change to the messages below. */
|
|
12
|
+
export const PROTOCOL_VERSION = 1;
|
|
13
|
+
/**
|
|
14
|
+
* Guard against a peer streaming an unterminated line forever. Tool results
|
|
15
|
+
* can be large (`capture_scene` returns a base64 image), so this is generous.
|
|
16
|
+
*/
|
|
17
|
+
export const MAX_LINE_BYTES = 256 * 1024 * 1024;
|
|
18
|
+
/** JSON-RPC style error codes for conditions the protocol itself raises. */
|
|
19
|
+
export const IpcErrorCode = {
|
|
20
|
+
/** The shared process is shutting down and did not start this request. Safe to retry. */
|
|
21
|
+
Draining: -32001,
|
|
22
|
+
/** Malformed request. */
|
|
23
|
+
InvalidRequest: -32600,
|
|
24
|
+
};
|
|
25
|
+
/** Where a setting comes from (see config/sources.ts). */
|
|
26
|
+
export const SettingSourceSchema = z.enum(['env', '.env', 'file', 'default']);
|
|
27
|
+
/** A relay setting the shared process does not apply, and where the relay got it. */
|
|
28
|
+
export const IgnoredSettingSchema = z.object({ name: z.string(), source: SettingSourceSchema });
|
|
29
|
+
/*
|
|
30
|
+
* Fields marked "optional" below were added without bumping PROTOCOL_VERSION:
|
|
31
|
+
* zod objects drop unknown keys, so an older peer ignores them, and a newer
|
|
32
|
+
* one copes with their absence.
|
|
33
|
+
*/
|
|
34
|
+
export const HelloSchema = z.object({
|
|
35
|
+
type: z.literal('hello'),
|
|
36
|
+
protocol: z.number().int(),
|
|
37
|
+
/** `relay` connections are checked for version/config and keep the process alive;
|
|
38
|
+
* `control` connections (`status`, `stop`) are not. */
|
|
39
|
+
role: z.enum(['relay', 'control']),
|
|
40
|
+
version: z.string(),
|
|
41
|
+
configHash: z.string(),
|
|
42
|
+
token: z.string(),
|
|
43
|
+
/** Optional: the relay's pid, for `status`. */
|
|
44
|
+
pid: z.number().int().optional(),
|
|
45
|
+
/** Optional: where each of the relay's settings comes from (no values). */
|
|
46
|
+
configSources: z.record(z.string(), SettingSourceSchema).optional(),
|
|
47
|
+
/** Optional: one HMAC per identity setting (config-hash.ts). Never logged nor shown. */
|
|
48
|
+
configDigests: z.record(z.string(), z.string()).optional(),
|
|
49
|
+
});
|
|
50
|
+
export const HelloRejectReasonSchema = z.enum([
|
|
51
|
+
'unauthorized',
|
|
52
|
+
'protocol',
|
|
53
|
+
'version',
|
|
54
|
+
'config',
|
|
55
|
+
'draining',
|
|
56
|
+
]);
|
|
57
|
+
export const HelloReplySchema = z.discriminatedUnion('ok', [
|
|
58
|
+
z.object({
|
|
59
|
+
type: z.literal('hello'),
|
|
60
|
+
ok: z.literal(true),
|
|
61
|
+
pid: z.number(),
|
|
62
|
+
version: z.string(),
|
|
63
|
+
/** Optional: the relay's identity settings that differ and are not applied. */
|
|
64
|
+
ignoredConfig: z.array(IgnoredSettingSchema).optional(),
|
|
65
|
+
/** Optional: the configuration file the shared process reads. */
|
|
66
|
+
configFile: z.string().optional(),
|
|
67
|
+
}),
|
|
68
|
+
z.object({
|
|
69
|
+
type: z.literal('hello'),
|
|
70
|
+
ok: z.literal(false),
|
|
71
|
+
reason: HelloRejectReasonSchema,
|
|
72
|
+
message: z.string(),
|
|
73
|
+
}),
|
|
74
|
+
]);
|
|
75
|
+
export const OpSchema = z.enum(['tool', 'resource', 'status', 'stop']);
|
|
76
|
+
export const RequestSchema = z.object({
|
|
77
|
+
type: z.literal('request'),
|
|
78
|
+
id: z.number().int(),
|
|
79
|
+
op: OpSchema,
|
|
80
|
+
name: z.string().optional(),
|
|
81
|
+
args: z.record(z.string(), z.unknown()).optional(),
|
|
82
|
+
});
|
|
83
|
+
export const IpcErrorSchema = z.object({
|
|
84
|
+
code: z.number(),
|
|
85
|
+
message: z.string(),
|
|
86
|
+
data: z.unknown().optional(),
|
|
87
|
+
});
|
|
88
|
+
export const ResponseSchema = z.union([
|
|
89
|
+
z.object({ type: z.literal('response'), id: z.number(), result: z.unknown() }),
|
|
90
|
+
z.object({ type: z.literal('response'), id: z.number(), error: IpcErrorSchema }),
|
|
91
|
+
]);
|
|
92
|
+
/** Result of the `status` op. FoundryVTT fields are absent until the core is built. */
|
|
93
|
+
export const DaemonStatusSchema = z.object({
|
|
94
|
+
pid: z.number(),
|
|
95
|
+
version: z.string(),
|
|
96
|
+
startedAt: z.string(),
|
|
97
|
+
uptimeSeconds: z.number(),
|
|
98
|
+
endpoint: z.string(),
|
|
99
|
+
logFile: z.string(),
|
|
100
|
+
relays: z.number(),
|
|
101
|
+
/** Builds of the connected relays running an older build than this process
|
|
102
|
+
* (served, but their client should be restarted). Absent from older processes. */
|
|
103
|
+
outdatedRelays: z.array(z.string()).optional(),
|
|
104
|
+
inFlight: z.number(),
|
|
105
|
+
/** Optional: the shared process's own settings, secrets masked. */
|
|
106
|
+
config: z
|
|
107
|
+
.object({
|
|
108
|
+
file: z.object({
|
|
109
|
+
path: z.string(),
|
|
110
|
+
found: z.boolean(),
|
|
111
|
+
error: z.string().nullable(),
|
|
112
|
+
warning: z.string().nullable(),
|
|
113
|
+
}),
|
|
114
|
+
settings: z.array(z.object({ name: z.string(), value: z.string(), source: SettingSourceSchema })),
|
|
115
|
+
})
|
|
116
|
+
.optional(),
|
|
117
|
+
/** Optional: each connected relay's declared provenance and its ignored settings. */
|
|
118
|
+
relayConfigs: z
|
|
119
|
+
.array(z.object({
|
|
120
|
+
pid: z.number().nullable(),
|
|
121
|
+
version: z.string(),
|
|
122
|
+
/** `null`: a relay too old to declare it. */
|
|
123
|
+
sources: z.record(z.string(), SettingSourceSchema).nullable(),
|
|
124
|
+
/** `null`: differs, but a relay too old to say which settings. */
|
|
125
|
+
ignored: z.array(IgnoredSettingSchema).nullable(),
|
|
126
|
+
}))
|
|
127
|
+
.optional(),
|
|
128
|
+
writeQueue: z.number().optional(),
|
|
129
|
+
startupError: z.string().nullable(),
|
|
130
|
+
foundryConnected: z.boolean().optional(),
|
|
131
|
+
// Absent from shared processes older than single-account mode.
|
|
132
|
+
foundryConnection: z
|
|
133
|
+
.object({
|
|
134
|
+
state: z.enum([
|
|
135
|
+
'connected',
|
|
136
|
+
'disconnected',
|
|
137
|
+
'reauthenticating',
|
|
138
|
+
'waiting-for-world',
|
|
139
|
+
'retrying',
|
|
140
|
+
]),
|
|
141
|
+
error: z.string().nullable(),
|
|
142
|
+
})
|
|
143
|
+
.optional(),
|
|
144
|
+
account: z
|
|
145
|
+
.object({ name: z.string(), role: z.string().nullable(), warning: z.string().nullable() })
|
|
146
|
+
.nullable()
|
|
147
|
+
.optional(),
|
|
148
|
+
bridge: z
|
|
149
|
+
.object({
|
|
150
|
+
enabled: z.boolean(),
|
|
151
|
+
port: z.number(),
|
|
152
|
+
/** An authenticated module is connected. */
|
|
153
|
+
moduleConnected: z.boolean(),
|
|
154
|
+
// Absent from shared processes older than bridge authentication.
|
|
155
|
+
protocol: z.number().optional(),
|
|
156
|
+
origin: z.string().optional(),
|
|
157
|
+
moduleConnectedSince: z.string().nullable().optional(),
|
|
158
|
+
// Absent from shared processes older than these fields (then `enabled`
|
|
159
|
+
// alone decides, and a bridge that never started read as listening).
|
|
160
|
+
state: z.enum(['listening', 'not-started', 'failed', 'disabled']).optional(),
|
|
161
|
+
error: z.string().nullable().optional(),
|
|
162
|
+
})
|
|
163
|
+
.optional(),
|
|
164
|
+
headlessGm: z
|
|
165
|
+
.object({
|
|
166
|
+
enabled: z.boolean(),
|
|
167
|
+
active: z.boolean(),
|
|
168
|
+
status: z.string().nullable(),
|
|
169
|
+
// Absent from shared processes older than these fields.
|
|
170
|
+
launchError: z.string().nullable().optional(),
|
|
171
|
+
state: z.enum(['running', 'not-started', 'launch-failed', 'disabled']).optional(),
|
|
172
|
+
mode: z.enum(['shared', 'separate']).nullable().optional(),
|
|
173
|
+
modeText: z.string().nullable().optional(),
|
|
174
|
+
sessionState: z
|
|
175
|
+
.enum([
|
|
176
|
+
'waiting-for-session',
|
|
177
|
+
'logging-in',
|
|
178
|
+
'logged-in',
|
|
179
|
+
'reauthenticating',
|
|
180
|
+
'reconnecting',
|
|
181
|
+
])
|
|
182
|
+
.nullable()
|
|
183
|
+
.optional(),
|
|
184
|
+
// Absent from shared processes older than browser detection.
|
|
185
|
+
browser: z
|
|
186
|
+
.object({
|
|
187
|
+
name: z.string(),
|
|
188
|
+
path: z.string(),
|
|
189
|
+
origin: z.enum(['configured', 'detected']),
|
|
190
|
+
})
|
|
191
|
+
.nullable()
|
|
192
|
+
.optional(),
|
|
193
|
+
})
|
|
194
|
+
.optional(),
|
|
195
|
+
});
|
|
196
|
+
/** Result of the `stop` op. */
|
|
197
|
+
export const StopReplySchema = z.object({ stopping: z.literal(true), pid: z.number() });
|
|
198
|
+
/** Serialises one message as a protocol line. */
|
|
199
|
+
export function encodeLine(message) {
|
|
200
|
+
return `${JSON.stringify(message)}\n`;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Splits a byte stream into JSON values, one per line. Throws from `push`
|
|
204
|
+
* on invalid JSON or an over-long line; the caller drops the connection.
|
|
205
|
+
*/
|
|
206
|
+
export class LineDecoder {
|
|
207
|
+
maxLineBytes;
|
|
208
|
+
buffer = '';
|
|
209
|
+
constructor(maxLineBytes = MAX_LINE_BYTES) {
|
|
210
|
+
this.maxLineBytes = maxLineBytes;
|
|
211
|
+
}
|
|
212
|
+
push(chunk) {
|
|
213
|
+
this.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
|
|
214
|
+
const messages = [];
|
|
215
|
+
let newline = this.buffer.indexOf('\n');
|
|
216
|
+
while (newline !== -1) {
|
|
217
|
+
const line = this.buffer.slice(0, newline).trim();
|
|
218
|
+
this.buffer = this.buffer.slice(newline + 1);
|
|
219
|
+
if (line) {
|
|
220
|
+
messages.push(JSON.parse(line));
|
|
221
|
+
}
|
|
222
|
+
newline = this.buffer.indexOf('\n');
|
|
223
|
+
}
|
|
224
|
+
if (this.buffer.length > this.maxLineBytes) {
|
|
225
|
+
throw new Error(`IPC line exceeds ${this.maxLineBytes} bytes`);
|
|
226
|
+
}
|
|
227
|
+
return messages;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
//# sourceMappingURL=protocol.js.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview A relay's view of its configuration.
|
|
3
|
+
*
|
|
4
|
+
* Re-read before each handshake, and before each call while it is unusable:
|
|
5
|
+
* writing the configuration file is enough to make a waiting relay work,
|
|
6
|
+
* and editing it then `stop` is enough to apply a change — no client restart.
|
|
7
|
+
*/
|
|
8
|
+
import { configSettings, resetConfig, tryGetConfig } from '../config/index.js';
|
|
9
|
+
import { configDigests, configFingerprint } from './config-hash.js';
|
|
10
|
+
export class RelayConfig {
|
|
11
|
+
warn;
|
|
12
|
+
lastUsable = null;
|
|
13
|
+
lastProblem = null;
|
|
14
|
+
/**
|
|
15
|
+
* @param warn - told each new problem once (and the file permission warning)
|
|
16
|
+
*/
|
|
17
|
+
constructor(warn = () => undefined) {
|
|
18
|
+
this.warn = warn;
|
|
19
|
+
}
|
|
20
|
+
/** Resolves the configuration again from the environment, `.env` and the file. */
|
|
21
|
+
reload() {
|
|
22
|
+
resetConfig();
|
|
23
|
+
const loaded = tryGetConfig();
|
|
24
|
+
if ('config' in loaded) {
|
|
25
|
+
this.lastUsable = loaded.config;
|
|
26
|
+
this.lastProblem = null;
|
|
27
|
+
const { file } = configSettings();
|
|
28
|
+
if (file.warning) {
|
|
29
|
+
this.warn(file.warning);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
else if (loaded.error.message !== this.lastProblem) {
|
|
33
|
+
this.lastProblem = loaded.error.message;
|
|
34
|
+
this.warn(loaded.error.message);
|
|
35
|
+
}
|
|
36
|
+
return loaded;
|
|
37
|
+
}
|
|
38
|
+
/** The configuration once usable (re-read on every call until then), or why there is none. */
|
|
39
|
+
usable() {
|
|
40
|
+
if (this.lastUsable) {
|
|
41
|
+
return this.lastUsable;
|
|
42
|
+
}
|
|
43
|
+
const loaded = this.reload();
|
|
44
|
+
return 'config' in loaded ? loaded.config : loaded.error;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The configuration part of a handshake, re-read now. Unusable since the
|
|
48
|
+
* last call: the settings that last worked.
|
|
49
|
+
*
|
|
50
|
+
* @throws when there never was a usable configuration (calls check first)
|
|
51
|
+
*/
|
|
52
|
+
helloFields(token) {
|
|
53
|
+
const loaded = this.reload();
|
|
54
|
+
const config = 'config' in loaded ? loaded.config : this.lastUsable;
|
|
55
|
+
if (!config) {
|
|
56
|
+
throw new Error('no usable configuration');
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
configHash: configFingerprint(config, token),
|
|
60
|
+
configSources: configSettings().sources,
|
|
61
|
+
configDigests: configDigests(config, token),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=relay-config.js.map
|