@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,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview A relay's link to the shared process: connects (starting the
|
|
3
|
+
* process when nobody listens), waits while it boots or while an outdated
|
|
4
|
+
* one drains, and turns IPC failures into MCP errors.
|
|
5
|
+
*/
|
|
6
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
7
|
+
import { ConnectionLostError, EndpointUnavailableError, HandshakeRejectedError, IpcConnection, RemoteError, } from './ipc-client.js';
|
|
8
|
+
import { IpcErrorCode } from './protocol.js';
|
|
9
|
+
/** Calls rejected by a draining process never started, so they may be resent. */
|
|
10
|
+
const MAX_DRAINING_RETRIES = 3;
|
|
11
|
+
export class DaemonLink {
|
|
12
|
+
options;
|
|
13
|
+
connection = null;
|
|
14
|
+
connecting = null;
|
|
15
|
+
readyTimeoutMs;
|
|
16
|
+
drainTimeoutMs;
|
|
17
|
+
respawnIntervalMs;
|
|
18
|
+
connect;
|
|
19
|
+
sleep;
|
|
20
|
+
now;
|
|
21
|
+
constructor(options) {
|
|
22
|
+
this.options = options;
|
|
23
|
+
this.readyTimeoutMs = options.readyTimeoutMs ?? 30_000;
|
|
24
|
+
// The shared process waits up to 120 s for in-flight calls, then 5 s for teardown.
|
|
25
|
+
this.drainTimeoutMs = options.drainTimeoutMs ?? 150_000;
|
|
26
|
+
this.respawnIntervalMs = options.respawnIntervalMs ?? 5000;
|
|
27
|
+
this.connect = options.connect ?? ((endpoint, hello) => IpcConnection.connect(endpoint, hello));
|
|
28
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
29
|
+
this.now = options.now ?? Date.now;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Forwards one operation and returns its result.
|
|
33
|
+
*
|
|
34
|
+
* @throws {McpError} the remote error, or a link failure explained for the user
|
|
35
|
+
*/
|
|
36
|
+
async call(op, name, args) {
|
|
37
|
+
for (let attempt = 0;; attempt++) {
|
|
38
|
+
const connection = await this.ensureConnected();
|
|
39
|
+
try {
|
|
40
|
+
return await connection.request(op, name, args);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error instanceof RemoteError) {
|
|
44
|
+
if (error.code === IpcErrorCode.Draining && attempt < MAX_DRAINING_RETRIES) {
|
|
45
|
+
this.drop(connection);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
throw new McpError(error.code, error.message, error.data);
|
|
49
|
+
}
|
|
50
|
+
if (error instanceof ConnectionLostError) {
|
|
51
|
+
// Never resend: the call may have been half-way through a write.
|
|
52
|
+
this.drop(connection);
|
|
53
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process exited during this call; its outcome is unknown. It will be restarted on the next call. Log: ${this.options.logFile}`);
|
|
54
|
+
}
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Returns a live connection, establishing one (single-flight) if needed. */
|
|
60
|
+
ensureConnected() {
|
|
61
|
+
if (this.connection && !this.connection.isClosed) {
|
|
62
|
+
return Promise.resolve(this.connection);
|
|
63
|
+
}
|
|
64
|
+
if (!this.connecting) {
|
|
65
|
+
this.connecting = this.establish().finally(() => {
|
|
66
|
+
this.connecting = null;
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return this.connecting;
|
|
70
|
+
}
|
|
71
|
+
close() {
|
|
72
|
+
this.connection?.close();
|
|
73
|
+
this.connection = null;
|
|
74
|
+
}
|
|
75
|
+
drop(connection) {
|
|
76
|
+
connection.close();
|
|
77
|
+
if (this.connection === connection) {
|
|
78
|
+
this.connection = null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async establish() {
|
|
82
|
+
const started = this.now();
|
|
83
|
+
let deadline = started + this.readyTimeoutMs;
|
|
84
|
+
let drainWaitGranted = false;
|
|
85
|
+
let lastSpawn = Number.NEGATIVE_INFINITY;
|
|
86
|
+
let delay = 50;
|
|
87
|
+
for (;;) {
|
|
88
|
+
try {
|
|
89
|
+
const connection = await this.connect(this.options.endpoint, this.options.hello());
|
|
90
|
+
connection.onClose(() => {
|
|
91
|
+
if (this.connection === connection) {
|
|
92
|
+
this.connection = null;
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
this.connection = connection;
|
|
96
|
+
this.options.onConnected?.(connection);
|
|
97
|
+
return connection;
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error instanceof EndpointUnavailableError) {
|
|
101
|
+
if (this.now() - lastSpawn >= this.respawnIntervalMs) {
|
|
102
|
+
this.options.log?.('No shared process is listening; starting one');
|
|
103
|
+
this.options.spawnDaemon();
|
|
104
|
+
lastSpawn = this.now();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else if (error instanceof HandshakeRejectedError) {
|
|
108
|
+
if (error.reason === 'protocol') {
|
|
109
|
+
// The shared process says which side is outdated and what to do.
|
|
110
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process refused this relay: ${error.message} Log: ${this.options.logFile}`);
|
|
111
|
+
}
|
|
112
|
+
if (error.reason === 'unauthorized') {
|
|
113
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process refused this relay (${error.reason}: ${error.message}). Stop it (foundryvtt-mcp stop, or end the process listed in its state file) and retry. Log: ${this.options.logFile}`);
|
|
114
|
+
}
|
|
115
|
+
// Outdated or shutting down: wait for it to exit, then start a fresh one.
|
|
116
|
+
if (!drainWaitGranted) {
|
|
117
|
+
this.options.log?.(`Shared process is restarting (${error.reason}); waiting`);
|
|
118
|
+
deadline = Math.max(deadline, this.now() + this.drainTimeoutMs);
|
|
119
|
+
drainWaitGranted = true;
|
|
120
|
+
}
|
|
121
|
+
lastSpawn = Number.NEGATIVE_INFINITY;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
this.options.log?.(`Connecting to the shared process failed: ${error instanceof Error ? error.message : error}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (this.now() >= deadline) {
|
|
128
|
+
throw new McpError(ErrorCode.InternalError, `The shared FoundryVTT MCP process did not become available within ${Math.round((this.now() - started) / 1000)} s. Log: ${this.options.logFile}`);
|
|
129
|
+
}
|
|
130
|
+
await this.sleep(delay);
|
|
131
|
+
delay = Math.min(delay * 2, 500);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
//# sourceMappingURL=daemon-link.js.map
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview `foundryvtt-mcp daemon`: the shared process.
|
|
3
|
+
*
|
|
4
|
+
* Owns the single FoundryVTT connection, module bridge and headless GM
|
|
5
|
+
* session ({@link FoundryCore}) and serves tool calls forwarded by relays.
|
|
6
|
+
* It outlives the relays MCP clients start and stop, and exits on `stop`,
|
|
7
|
+
* after a relay from a newer build knocks, after one whose settings match a
|
|
8
|
+
* changed configuration file knocks (see {@link mismatchDecision}), or once
|
|
9
|
+
* no relay has been connected for the idle timeout. When the
|
|
10
|
+
* FoundryVTT connection cannot be established (FoundryVTT not started yet,
|
|
11
|
+
* wrong URL…) it stays up and retries on the next call.
|
|
12
|
+
*/
|
|
13
|
+
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
14
|
+
import { configFromSettings, getConfig } from '../config/index.js';
|
|
15
|
+
import { displayValue, KNOWN_SETTINGS, resolveSettings } from '../config/sources.js';
|
|
16
|
+
import { logger } from '../utils/logger.js';
|
|
17
|
+
import { isRefusal } from '../utils/refusal.js';
|
|
18
|
+
import { compareBuilds } from './build-order.js';
|
|
19
|
+
import { configDigests, configFingerprint } from './config-hash.js';
|
|
20
|
+
import { IpcServer } from './ipc-server.js';
|
|
21
|
+
import { resolveSharedPaths } from './paths.js';
|
|
22
|
+
import { RotatingLog } from './rotating-log.js';
|
|
23
|
+
import { removeStateFile, writeStateFile } from './state-file.js';
|
|
24
|
+
import { loadOrCreateToken } from './token.js';
|
|
25
|
+
import { buildVersion } from './version.js';
|
|
26
|
+
/** McpError prefixes its message with "MCP error <code>: "; send the bare text. */
|
|
27
|
+
function bareMessage(error) {
|
|
28
|
+
return error.message.replace(/^MCP error -?\d+: /, '');
|
|
29
|
+
}
|
|
30
|
+
export function toIpcError(error) {
|
|
31
|
+
if (error instanceof McpError) {
|
|
32
|
+
return {
|
|
33
|
+
code: error.code,
|
|
34
|
+
message: bareMessage(error),
|
|
35
|
+
...(error.data !== undefined ? { data: error.data } : {}),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
code: ErrorCode.InternalError,
|
|
40
|
+
message: error instanceof Error ? error.message : String(error),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Whether a relay running another build or configuration restarts this
|
|
45
|
+
* process ("the file is authoritative"):
|
|
46
|
+
*
|
|
47
|
+
* - a strictly newer build restarts it (see build-order.ts); an older or
|
|
48
|
+
* unorderable one is served as it is;
|
|
49
|
+
* - another configuration restarts it only when the relay's settings are
|
|
50
|
+
* those of the configuration file as it is on disk now: the file changed,
|
|
51
|
+
* or this process was started by a client whose `env` block overrides it;
|
|
52
|
+
* - any other difference (a client's `env` block) is served with this
|
|
53
|
+
* process's settings, and the relay is told which of its own are ignored;
|
|
54
|
+
* - with the file unreadable or invalid, nothing restarts.
|
|
55
|
+
*
|
|
56
|
+
* @param fileHash - fingerprint of the file alone, `null` when unreadable or invalid
|
|
57
|
+
*/
|
|
58
|
+
export function mismatchDecision(reason, relayVersion, ownVersion, config = {}) {
|
|
59
|
+
if (reason === 'version') {
|
|
60
|
+
return compareBuilds(relayVersion, ownVersion) === 'newer' ? 'restart' : 'accept';
|
|
61
|
+
}
|
|
62
|
+
const { relayHash, ownHash, fileHash } = config;
|
|
63
|
+
if (!fileHash || relayHash === undefined) {
|
|
64
|
+
return 'accept';
|
|
65
|
+
}
|
|
66
|
+
return relayHash === fileHash && fileHash !== ownHash ? 'restart' : 'accept';
|
|
67
|
+
}
|
|
68
|
+
function sleep(ms) {
|
|
69
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
70
|
+
}
|
|
71
|
+
function errorText(error) {
|
|
72
|
+
return error instanceof Error ? error.message : String(error);
|
|
73
|
+
}
|
|
74
|
+
export class SharedProcess {
|
|
75
|
+
options;
|
|
76
|
+
ipc;
|
|
77
|
+
startedAt = new Date();
|
|
78
|
+
core = null;
|
|
79
|
+
startup = null;
|
|
80
|
+
startupError = null;
|
|
81
|
+
shuttingDown = null;
|
|
82
|
+
idleTimer = null;
|
|
83
|
+
constructor(options) {
|
|
84
|
+
this.options = options;
|
|
85
|
+
this.ipc = new IpcServer({
|
|
86
|
+
endpoint: options.paths.endpoint,
|
|
87
|
+
token: options.token,
|
|
88
|
+
version: options.version,
|
|
89
|
+
configHash: options.configHash,
|
|
90
|
+
...(options.configDigests ? { configDigests: options.configDigests } : {}),
|
|
91
|
+
...(options.configStatus ? { configFile: options.configStatus.file.path } : {}),
|
|
92
|
+
toIpcError,
|
|
93
|
+
log: (level, message) => logger[level](message),
|
|
94
|
+
onRelayCountChange: (count) => this.updateIdleTimer(count),
|
|
95
|
+
onMismatch: (reason, relayVersion, relayHash) => {
|
|
96
|
+
const decision = mismatchDecision(reason, relayVersion, options.version, {
|
|
97
|
+
relayHash,
|
|
98
|
+
ownHash: options.configHash,
|
|
99
|
+
// Re-read now: the file may have changed since this process started.
|
|
100
|
+
fileHash: reason === 'config' ? (options.fileConfigHash?.() ?? null) : null,
|
|
101
|
+
});
|
|
102
|
+
if (decision === 'restart') {
|
|
103
|
+
void this.drainAndExit(reason === 'version'
|
|
104
|
+
? `a relay from a newer build (v${relayVersion}) connected`
|
|
105
|
+
: "a relay with the configuration file's settings connected (the file changed, or this process was started with a client's own settings)");
|
|
106
|
+
}
|
|
107
|
+
return decision;
|
|
108
|
+
},
|
|
109
|
+
handler: async (op, name, args) => {
|
|
110
|
+
switch (op) {
|
|
111
|
+
case 'tool':
|
|
112
|
+
return (await this.ready()).callTool(name ?? '', args);
|
|
113
|
+
case 'resource':
|
|
114
|
+
return (await this.ready()).readResource(name ?? '');
|
|
115
|
+
case 'status':
|
|
116
|
+
return this.status();
|
|
117
|
+
case 'stop':
|
|
118
|
+
setImmediate(() => void this.drainAndExit('stop requested'));
|
|
119
|
+
return { stopping: true, pid: process.pid };
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Takes the single-instance lock, then builds and starts the core. A
|
|
126
|
+
* process that loses the race returns `in-use` without touching FoundryVTT.
|
|
127
|
+
*/
|
|
128
|
+
async start() {
|
|
129
|
+
const { paths, version } = this.options;
|
|
130
|
+
if ((await this.ipc.listen()) === 'in-use') {
|
|
131
|
+
return 'in-use';
|
|
132
|
+
}
|
|
133
|
+
writeStateFile(paths.stateFile, {
|
|
134
|
+
pid: process.pid,
|
|
135
|
+
version,
|
|
136
|
+
startedAt: this.startedAt.toISOString(),
|
|
137
|
+
endpoint: paths.endpoint,
|
|
138
|
+
logFile: paths.daemonLog,
|
|
139
|
+
});
|
|
140
|
+
logger.info(`Shared process ${process.pid} (v${version}) listening on ${paths.endpoint}`);
|
|
141
|
+
this.startup = this.bootCore();
|
|
142
|
+
this.updateIdleTimer(0);
|
|
143
|
+
return 'listening';
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Arms the idle timer while no relay is connected, disarms it otherwise.
|
|
147
|
+
* Hours without a call do not count as idle as long as a relay is there.
|
|
148
|
+
*/
|
|
149
|
+
updateIdleTimer(relays) {
|
|
150
|
+
const idleTimeoutMs = this.options.idleTimeoutMs ?? 0;
|
|
151
|
+
if (this.idleTimer) {
|
|
152
|
+
clearTimeout(this.idleTimer);
|
|
153
|
+
this.idleTimer = null;
|
|
154
|
+
}
|
|
155
|
+
if (relays === 0 && idleTimeoutMs > 0 && !this.shuttingDown) {
|
|
156
|
+
this.idleTimer = setTimeout(() => void this.drainAndExit(`no relay connected for ${Number((idleTimeoutMs / 60_000).toFixed(2))} min`), idleTimeoutMs);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** Builds and starts a core, replacing one whose start failed. */
|
|
160
|
+
bootCore() {
|
|
161
|
+
return (async () => {
|
|
162
|
+
if (this.core) {
|
|
163
|
+
await this.core.shutdown();
|
|
164
|
+
}
|
|
165
|
+
this.core = await this.options.createCore();
|
|
166
|
+
await this.core.start();
|
|
167
|
+
})().catch((error) => {
|
|
168
|
+
this.startupError = error;
|
|
169
|
+
if (isRefusal(error)) {
|
|
170
|
+
// Expected (no world launched yet): the core already logged one line.
|
|
171
|
+
logger.info('Shared process waits for FoundryVTT; the next call retries');
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
logger.error('Shared process could not connect to FoundryVTT; the next call retries', error);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Stops accepting work, lets started calls finish (a write is never cut
|
|
180
|
+
* in half), tears the core down, releases the endpoint and exits.
|
|
181
|
+
*/
|
|
182
|
+
drainAndExit(reason, code = 0) {
|
|
183
|
+
this.shuttingDown ??= (async () => {
|
|
184
|
+
const { drainMaxMs = 120_000, shutdownGraceMs = 5000, paths, exit } = this.options;
|
|
185
|
+
logger.info(`Shared process shutting down: ${reason}`);
|
|
186
|
+
if (this.idleTimer) {
|
|
187
|
+
clearTimeout(this.idleTimer);
|
|
188
|
+
}
|
|
189
|
+
this.ipc.setDraining();
|
|
190
|
+
await Promise.race([this.ipc.waitForIdle(), sleep(drainMaxMs)]);
|
|
191
|
+
const force = setTimeout(() => exit(1), shutdownGraceMs);
|
|
192
|
+
force.unref();
|
|
193
|
+
await this.core?.shutdown();
|
|
194
|
+
await this.ipc.close();
|
|
195
|
+
clearTimeout(force);
|
|
196
|
+
removeStateFile(paths.stateFile, process.pid);
|
|
197
|
+
exit(code);
|
|
198
|
+
})();
|
|
199
|
+
return this.shuttingDown;
|
|
200
|
+
}
|
|
201
|
+
/** Connected relays, and the builds of those older than this process. */
|
|
202
|
+
relays() {
|
|
203
|
+
return { connected: this.ipc.relayCount, outdated: this.ipc.outdatedRelayVersions };
|
|
204
|
+
}
|
|
205
|
+
status() {
|
|
206
|
+
const coreStatus = this.core?.status() ?? {};
|
|
207
|
+
return {
|
|
208
|
+
pid: process.pid,
|
|
209
|
+
version: this.options.version,
|
|
210
|
+
startedAt: this.startedAt.toISOString(),
|
|
211
|
+
uptimeSeconds: Math.round((Date.now() - this.startedAt.getTime()) / 1000),
|
|
212
|
+
endpoint: this.options.paths.endpoint,
|
|
213
|
+
logFile: this.options.paths.daemonLog,
|
|
214
|
+
relays: this.ipc.relayCount,
|
|
215
|
+
outdatedRelays: this.ipc.outdatedRelayVersions,
|
|
216
|
+
// Excludes this status request itself.
|
|
217
|
+
inFlight: this.ipc.inFlightCount - 1,
|
|
218
|
+
...(this.options.configStatus ? { config: this.options.configStatus } : {}),
|
|
219
|
+
relayConfigs: this.ipc.relayConfigList,
|
|
220
|
+
startupError: this.startupError ? errorText(this.startupError) : null,
|
|
221
|
+
...coreStatus,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/** Waits (bounded) for the FoundryVTT connection attempt, then hands out the core. */
|
|
225
|
+
async ready() {
|
|
226
|
+
if (this.startupError !== null && !this.shuttingDown) {
|
|
227
|
+
// The last attempt failed: this call retries (concurrent calls share the attempt).
|
|
228
|
+
this.startupError = null;
|
|
229
|
+
this.startup = this.bootCore();
|
|
230
|
+
}
|
|
231
|
+
if (this.startup) {
|
|
232
|
+
await Promise.race([this.startup, sleep(this.options.startupWaitMs ?? 30_000)]);
|
|
233
|
+
}
|
|
234
|
+
if (this.startupError) {
|
|
235
|
+
throw new McpError(ErrorCode.InternalError, `The shared process could not connect to FoundryVTT: ${errorText(this.startupError).replace(/\.$/, '')}. The next call retries. Log: ${this.options.paths.daemonLog}`);
|
|
236
|
+
}
|
|
237
|
+
if (!this.core) {
|
|
238
|
+
throw new McpError(ErrorCode.InternalError, `The shared process is still starting. Log: ${this.options.paths.daemonLog}`);
|
|
239
|
+
}
|
|
240
|
+
return this.core;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** Entry point of `foundryvtt-mcp daemon`. */
|
|
244
|
+
export async function runDaemon(paths = resolveSharedPaths()) {
|
|
245
|
+
// Started detached with stdio ignored: the log file is the only output.
|
|
246
|
+
const log = new RotatingLog(paths.daemonLog);
|
|
247
|
+
logger.addSink((line) => log.write(line));
|
|
248
|
+
logger.info(`Shared process ${process.pid} starting (node ${process.version}, cwd ${process.cwd()})`);
|
|
249
|
+
const token = loadOrCreateToken(paths.tokenFile);
|
|
250
|
+
let config;
|
|
251
|
+
try {
|
|
252
|
+
config = getConfig();
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
// A relay only starts this process with a usable configuration; the
|
|
256
|
+
// environment or the file changed in between. Nothing to serve.
|
|
257
|
+
logger.error(`Shared process cannot start: ${error instanceof Error ? error.message : error}`);
|
|
258
|
+
process.exit(1);
|
|
259
|
+
}
|
|
260
|
+
const settings = resolveSettings();
|
|
261
|
+
if (settings.file.warning) {
|
|
262
|
+
logger.warn(settings.file.warning);
|
|
263
|
+
}
|
|
264
|
+
const shared = new SharedProcess({
|
|
265
|
+
paths,
|
|
266
|
+
version: buildVersion(),
|
|
267
|
+
token,
|
|
268
|
+
configHash: configFingerprint(config, token),
|
|
269
|
+
configDigests: configDigests(config, token),
|
|
270
|
+
fileConfigHash: () => {
|
|
271
|
+
const fileOnly = resolveSettings({ fileOnly: true });
|
|
272
|
+
if (!fileOnly.file.found || fileOnly.file.error) {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
return configFingerprint(configFromSettings(fileOnly), token);
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
configStatus: {
|
|
283
|
+
file: settings.file,
|
|
284
|
+
settings: KNOWN_SETTINGS.filter((name) => settings.values[name] !== undefined).map((name) => ({
|
|
285
|
+
name,
|
|
286
|
+
value: displayValue(name, settings.values[name]),
|
|
287
|
+
source: settings.sources[name],
|
|
288
|
+
})),
|
|
289
|
+
},
|
|
290
|
+
idleTimeoutMs: config.shared.idleTimeoutMinutes * 60_000,
|
|
291
|
+
// Loaded lazily: Socket.IO, Playwright & co. are not needed to lose the race.
|
|
292
|
+
createCore: async () => new (await import('../core.js')).FoundryCore({ relays: () => shared.relays() }),
|
|
293
|
+
exit: (code) => process.exit(code),
|
|
294
|
+
});
|
|
295
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGBREAK', 'SIGHUP']) {
|
|
296
|
+
process.on(signal, () => void shared.drainAndExit(`received ${signal}`));
|
|
297
|
+
}
|
|
298
|
+
process.on('uncaughtException', (error) => {
|
|
299
|
+
logger.error('Uncaught exception in the shared process:', error);
|
|
300
|
+
removeStateFile(paths.stateFile, process.pid);
|
|
301
|
+
process.exit(1);
|
|
302
|
+
});
|
|
303
|
+
process.on('unhandledRejection', (reason) => {
|
|
304
|
+
logger.error('Unhandled rejection in the shared process:', { reason: String(reason) });
|
|
305
|
+
removeStateFile(paths.stateFile, process.pid);
|
|
306
|
+
process.exit(1);
|
|
307
|
+
});
|
|
308
|
+
if ((await shared.start()) === 'in-use') {
|
|
309
|
+
logger.info('Another shared process already listens on the endpoint; exiting');
|
|
310
|
+
process.exit(0);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
//# sourceMappingURL=daemon.js.map
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Client side of the relay ↔ shared-process channel.
|
|
3
|
+
*/
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import { encodeLine, HelloReplySchema, LineDecoder, ResponseSchema, } from './protocol.js';
|
|
6
|
+
/** Nothing listens on the endpoint (no shared process, or it just exited). */
|
|
7
|
+
export class EndpointUnavailableError extends Error {
|
|
8
|
+
endpoint;
|
|
9
|
+
constructor(endpoint, cause) {
|
|
10
|
+
super(`No shared process listening on ${endpoint}`, { cause });
|
|
11
|
+
this.endpoint = endpoint;
|
|
12
|
+
this.name = 'EndpointUnavailableError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** The shared process answered the handshake with a refusal. */
|
|
16
|
+
export class HandshakeRejectedError extends Error {
|
|
17
|
+
reason;
|
|
18
|
+
constructor(reason, message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.reason = reason;
|
|
21
|
+
this.name = 'HandshakeRejectedError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** The connection closed while a request was pending. */
|
|
25
|
+
export class ConnectionLostError extends Error {
|
|
26
|
+
constructor() {
|
|
27
|
+
super('Connection to the shared process was lost');
|
|
28
|
+
this.name = 'ConnectionLostError';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** The shared process answered a request with an error. */
|
|
32
|
+
export class RemoteError extends Error {
|
|
33
|
+
code;
|
|
34
|
+
data;
|
|
35
|
+
constructor(error) {
|
|
36
|
+
super(error.message);
|
|
37
|
+
this.name = 'RemoteError';
|
|
38
|
+
this.code = error.code;
|
|
39
|
+
this.data = error.data;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** How long the shared process may take to answer the handshake. */
|
|
43
|
+
const HELLO_TIMEOUT_MS = 5000;
|
|
44
|
+
export class IpcConnection {
|
|
45
|
+
socket;
|
|
46
|
+
pending = new Map();
|
|
47
|
+
nextId = 1;
|
|
48
|
+
closed = false;
|
|
49
|
+
closeListeners = [];
|
|
50
|
+
/** pid reported by the shared process at the handshake. */
|
|
51
|
+
serverPid;
|
|
52
|
+
/** Build the shared process reported at the handshake. */
|
|
53
|
+
serverVersion;
|
|
54
|
+
/**
|
|
55
|
+
* This relay's settings the shared process does not apply (it serves its
|
|
56
|
+
* own), with the file it reads; `null` when none are ignored.
|
|
57
|
+
*/
|
|
58
|
+
ignoredConfig;
|
|
59
|
+
constructor(socket, reply) {
|
|
60
|
+
this.socket = socket;
|
|
61
|
+
this.serverPid = reply.pid;
|
|
62
|
+
this.serverVersion = reply.version;
|
|
63
|
+
this.ignoredConfig = reply.ignoredConfig
|
|
64
|
+
? { settings: reply.ignoredConfig, configFile: reply.configFile ?? null }
|
|
65
|
+
: null;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Connects and performs the handshake.
|
|
69
|
+
*
|
|
70
|
+
* @throws {EndpointUnavailableError} nothing listens on `endpoint`
|
|
71
|
+
* @throws {HandshakeRejectedError} the shared process refused the hello
|
|
72
|
+
*/
|
|
73
|
+
static connect(endpoint, hello) {
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
const socket = net.connect(endpoint);
|
|
76
|
+
const decoder = new LineDecoder();
|
|
77
|
+
let connection = null;
|
|
78
|
+
let settled = false;
|
|
79
|
+
const fail = (error) => {
|
|
80
|
+
if (!settled) {
|
|
81
|
+
settled = true;
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
socket.destroy();
|
|
84
|
+
reject(error);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const timer = setTimeout(() => fail(new Error(`Shared process did not answer the handshake on ${endpoint}`)), HELLO_TIMEOUT_MS);
|
|
88
|
+
socket.once('connect', () => socket.write(encodeLine(hello)));
|
|
89
|
+
socket.on('error', (error) => {
|
|
90
|
+
if (!settled) {
|
|
91
|
+
fail(new EndpointUnavailableError(endpoint, error));
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
socket.on('close', () => {
|
|
95
|
+
if (connection) {
|
|
96
|
+
connection.handleClose();
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
fail(new ConnectionLostError());
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
socket.on('data', (chunk) => {
|
|
103
|
+
let messages;
|
|
104
|
+
try {
|
|
105
|
+
messages = decoder.push(chunk);
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
109
|
+
connection?.socket.destroy();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
for (const message of messages) {
|
|
113
|
+
if (connection) {
|
|
114
|
+
connection.handleMessage(message);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const reply = HelloReplySchema.safeParse(message);
|
|
118
|
+
if (!reply.success) {
|
|
119
|
+
fail(new Error('Invalid handshake reply from the shared process'));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (!reply.data.ok) {
|
|
123
|
+
fail(new HandshakeRejectedError(reply.data.reason, reply.data.message));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
settled = true;
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
connection = new IpcConnection(socket, reply.data);
|
|
129
|
+
resolve(connection);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
get isClosed() {
|
|
135
|
+
return this.closed;
|
|
136
|
+
}
|
|
137
|
+
/** Registers a callback for when the connection closes. */
|
|
138
|
+
onClose(listener) {
|
|
139
|
+
this.closeListeners.push(listener);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Sends one request. No client-side timeout: the shared process bounds
|
|
143
|
+
* every operation itself, and a relay must never give up earlier than it.
|
|
144
|
+
*
|
|
145
|
+
* @throws {RemoteError} the shared process answered with an error
|
|
146
|
+
* @throws {ConnectionLostError} the connection closed first
|
|
147
|
+
*/
|
|
148
|
+
request(op, name, args) {
|
|
149
|
+
if (this.closed) {
|
|
150
|
+
return Promise.reject(new ConnectionLostError());
|
|
151
|
+
}
|
|
152
|
+
const id = this.nextId++;
|
|
153
|
+
return new Promise((resolve, reject) => {
|
|
154
|
+
this.pending.set(id, { resolve, reject });
|
|
155
|
+
this.socket.write(encodeLine({
|
|
156
|
+
type: 'request',
|
|
157
|
+
id,
|
|
158
|
+
op,
|
|
159
|
+
...(name !== undefined ? { name } : {}),
|
|
160
|
+
...(args !== undefined ? { args } : {}),
|
|
161
|
+
}));
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
close() {
|
|
165
|
+
this.socket.end();
|
|
166
|
+
this.socket.destroy();
|
|
167
|
+
}
|
|
168
|
+
handleMessage(message) {
|
|
169
|
+
const parsed = ResponseSchema.safeParse(message);
|
|
170
|
+
if (!parsed.success) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const response = parsed.data;
|
|
174
|
+
const pending = this.pending.get(response.id);
|
|
175
|
+
if (!pending) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
this.pending.delete(response.id);
|
|
179
|
+
if ('error' in response) {
|
|
180
|
+
pending.reject(new RemoteError(response.error));
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
pending.resolve(response.result);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
handleClose() {
|
|
187
|
+
if (this.closed) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
this.closed = true;
|
|
191
|
+
for (const [, pending] of this.pending) {
|
|
192
|
+
pending.reject(new ConnectionLostError());
|
|
193
|
+
}
|
|
194
|
+
this.pending.clear();
|
|
195
|
+
for (const listener of this.closeListeners) {
|
|
196
|
+
listener();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
//# sourceMappingURL=ipc-client.js.map
|