@g33ks/foundryvtt-mcp 0.0.0-stage → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +457 -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 +414 -0
- package/dist/cli/prompt.js +117 -0
- package/dist/cli/snippets.js +64 -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 +481 -0
- package/dist/diagnostics/client.js +291 -0
- package/dist/diagnostics/types.js +94 -0
- package/dist/foundry/auth.js +224 -0
- package/dist/foundry/browser-detect.js +170 -0
- package/dist/foundry/client.js +5874 -0
- package/dist/foundry/dice-formula.js +154 -0
- package/dist/foundry/event-log.js +298 -0
- package/dist/foundry/headless-gm-session.js +857 -0
- package/dist/foundry/journal-conflicts.js +141 -0
- package/dist/foundry/journal-history.js +90 -0
- package/dist/foundry/journal-integrity.js +322 -0
- package/dist/foundry/message-author.js +19 -0
- package/dist/foundry/module-bridge.js +441 -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 +65 -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 +291 -0
- package/dist/shared/daemon-link.js +135 -0
- package/dist/shared/daemon.js +311 -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 +38 -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 +450 -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 +48 -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/tool-dependencies.js +194 -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/mcp-errors.js +47 -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,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview The list of detected journal overwrites, kept on disk so that
|
|
3
|
+
* `get_health_status` still lists them after the shared process restarts.
|
|
4
|
+
*
|
|
5
|
+
* `<state dir>/journal-conflicts.json`:
|
|
6
|
+
* `{ "version": 1, "conflicts": [{ at, journalId, pageId, journalName,
|
|
7
|
+
* pageName, reason, savedBy, historyPath }] }`, `at` as an ISO date. Ids,
|
|
8
|
+
* names, who saved and the path of the local copy: never page content (that
|
|
9
|
+
* stays in the copies under `journal-history/`). Written whole on every
|
|
10
|
+
* change, to a `.tmp` file renamed over the list, so a crash leaves the old
|
|
11
|
+
* list or the new one, never half of one.
|
|
12
|
+
*/
|
|
13
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { z } from 'zod';
|
|
16
|
+
import { logger } from '../utils/logger.js';
|
|
17
|
+
const FILE_VERSION = 1;
|
|
18
|
+
const StoredConflictSchema = z.object({
|
|
19
|
+
at: z.string().refine((value) => !Number.isNaN(Date.parse(value))),
|
|
20
|
+
journalId: z.string(),
|
|
21
|
+
pageId: z.string(),
|
|
22
|
+
journalName: z.string(),
|
|
23
|
+
pageName: z.string(),
|
|
24
|
+
reason: z.string(),
|
|
25
|
+
savedBy: z.string().nullable(),
|
|
26
|
+
historyPath: z.string().nullable(),
|
|
27
|
+
});
|
|
28
|
+
const FileSchema = z.object({ version: z.literal(FILE_VERSION), conflicts: z.array(z.unknown()) });
|
|
29
|
+
const NODE_OPS = { writeFileSync, renameSync };
|
|
30
|
+
/** Windows: an antivirus or indexer briefly holding the file. */
|
|
31
|
+
const TRANSIENT_CODES = new Set(['EPERM', 'EBUSY']);
|
|
32
|
+
function errorCode(error) {
|
|
33
|
+
return typeof error === 'object' && error !== null && 'code' in error
|
|
34
|
+
? String(error.code)
|
|
35
|
+
: undefined;
|
|
36
|
+
}
|
|
37
|
+
function errorText(error) {
|
|
38
|
+
return error instanceof Error ? error.message : String(error);
|
|
39
|
+
}
|
|
40
|
+
export class JournalConflictFile {
|
|
41
|
+
file;
|
|
42
|
+
ops;
|
|
43
|
+
constructor(file, ops = NODE_OPS) {
|
|
44
|
+
this.file = file;
|
|
45
|
+
this.ops = ops;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The conflicts kept in the file. A missing file is an empty list; an
|
|
49
|
+
* unreadable or invalid one is an empty list and one warning; an invalid
|
|
50
|
+
* entry is skipped. Pruning is the caller's.
|
|
51
|
+
*/
|
|
52
|
+
load() {
|
|
53
|
+
let raw;
|
|
54
|
+
try {
|
|
55
|
+
raw = readFileSync(this.file, 'utf8');
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (errorCode(error) !== 'ENOENT') {
|
|
59
|
+
logger.warn('Could not read the list of journal overwrites; starting with an empty one', {
|
|
60
|
+
file: this.file,
|
|
61
|
+
error: errorText(error),
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
let parsed;
|
|
67
|
+
try {
|
|
68
|
+
parsed = FileSchema.parse(JSON.parse(raw));
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
logger.warn('The list of journal overwrites is not valid; starting with an empty one', {
|
|
72
|
+
file: this.file,
|
|
73
|
+
});
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
const conflicts = [];
|
|
77
|
+
let skipped = 0;
|
|
78
|
+
for (const entry of parsed.conflicts) {
|
|
79
|
+
const stored = StoredConflictSchema.safeParse(entry);
|
|
80
|
+
if (!stored.success) {
|
|
81
|
+
skipped++;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
conflicts.push({ ...stored.data, at: Date.parse(stored.data.at) });
|
|
85
|
+
}
|
|
86
|
+
if (skipped > 0) {
|
|
87
|
+
logger.warn(`Skipped ${skipped} invalid entr${skipped === 1 ? 'y' : 'ies'} of the list of journal overwrites`, {
|
|
88
|
+
file: this.file,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return conflicts;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Writes the whole list: a `.tmp` file, then a rename over the list, tried
|
|
95
|
+
* twice when Windows reports the file busy. A failure is one warning; the
|
|
96
|
+
* list in memory is unaffected.
|
|
97
|
+
*
|
|
98
|
+
* @returns whether the list was written
|
|
99
|
+
*/
|
|
100
|
+
save(conflicts) {
|
|
101
|
+
const content = `${JSON.stringify({
|
|
102
|
+
version: FILE_VERSION,
|
|
103
|
+
conflicts: conflicts.map((conflict) => ({
|
|
104
|
+
at: new Date(conflict.at).toISOString(),
|
|
105
|
+
journalId: conflict.journalId,
|
|
106
|
+
pageId: conflict.pageId,
|
|
107
|
+
journalName: conflict.journalName,
|
|
108
|
+
pageName: conflict.pageName,
|
|
109
|
+
reason: conflict.reason,
|
|
110
|
+
savedBy: conflict.savedBy,
|
|
111
|
+
historyPath: conflict.historyPath,
|
|
112
|
+
})),
|
|
113
|
+
}, null, 2)}\n`;
|
|
114
|
+
const tmp = `${this.file}.tmp`;
|
|
115
|
+
for (let attempt = 1;; attempt++) {
|
|
116
|
+
try {
|
|
117
|
+
mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
|
118
|
+
this.ops.writeFileSync(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
|
119
|
+
this.ops.renameSync(tmp, this.file);
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (attempt === 1 && TRANSIENT_CODES.has(errorCode(error) ?? '')) {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
rmSync(tmp, { force: true });
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
// Left behind; the next save overwrites it.
|
|
131
|
+
}
|
|
132
|
+
logger.warn('Could not save the list of journal overwrites; it is kept in memory', {
|
|
133
|
+
file: this.file,
|
|
134
|
+
error: errorText(error),
|
|
135
|
+
});
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=journal-conflicts.js.map
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Local copies of journal page bodies, kept in the state
|
|
3
|
+
* directory before every page write and when an overwrite is detected.
|
|
4
|
+
*
|
|
5
|
+
* Layout: `<root>/<journalId>/<pageId>/<timestamp>-<reason>.html` with a
|
|
6
|
+
* `.json` sidecar (entry and page names, reason, version token, who overwrote
|
|
7
|
+
* the version or is about to, the connector account, date).
|
|
8
|
+
* Each new copy prunes its page's folder to {@link MAX_COPIES_PER_PAGE}
|
|
9
|
+
* copies, dropping any older than {@link MAX_COPY_AGE_MS}.
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { journalVersion } from './journal-integrity.js';
|
|
14
|
+
export const MAX_COPIES_PER_PAGE = 20;
|
|
15
|
+
export const MAX_COPY_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
16
|
+
/** FoundryVTT document ids: the only path segments a copy may be filed under. */
|
|
17
|
+
const DOCUMENT_ID = /^[a-zA-Z0-9]{16}$/;
|
|
18
|
+
/** Makes a reason safe as part of a file name (user names may hold anything). */
|
|
19
|
+
function fileSafe(reason) {
|
|
20
|
+
return reason.replace(/[^A-Za-z0-9_-]+/g, '_').slice(0, 80) || 'unknown';
|
|
21
|
+
}
|
|
22
|
+
export class JournalHistory {
|
|
23
|
+
root;
|
|
24
|
+
now;
|
|
25
|
+
constructor(root, now = Date.now) {
|
|
26
|
+
this.root = root;
|
|
27
|
+
this.now = now;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Writes one copy and prunes the page's folder.
|
|
31
|
+
*
|
|
32
|
+
* @returns the path of the `.html` copy
|
|
33
|
+
* @throws when the copy cannot be written — callers must not go ahead with
|
|
34
|
+
* a page write they could not back up
|
|
35
|
+
*/
|
|
36
|
+
save(copy) {
|
|
37
|
+
if (!DOCUMENT_ID.test(copy.journalId) || !DOCUMENT_ID.test(copy.pageId)) {
|
|
38
|
+
throw new Error(`Invalid journal or page id for a local copy: ${copy.journalId}/${copy.pageId}`);
|
|
39
|
+
}
|
|
40
|
+
const dir = path.join(this.root, copy.journalId, copy.pageId);
|
|
41
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
42
|
+
const savedAt = new Date(this.now());
|
|
43
|
+
const stem = `${savedAt.toISOString().replace(/[:.]/g, '-')}-${fileSafe(copy.reason)}`;
|
|
44
|
+
let base = path.join(dir, stem);
|
|
45
|
+
for (let n = 2; existsSync(`${base}.html`); n++) {
|
|
46
|
+
base = path.join(dir, `${stem}-${n}`);
|
|
47
|
+
}
|
|
48
|
+
const htmlPath = `${base}.html`;
|
|
49
|
+
writeFileSync(htmlPath, copy.content, { encoding: 'utf8', mode: 0o600 });
|
|
50
|
+
writeFileSync(`${base}.json`, `${JSON.stringify({
|
|
51
|
+
journalId: copy.journalId,
|
|
52
|
+
pageId: copy.pageId,
|
|
53
|
+
journalName: copy.journalName,
|
|
54
|
+
pageName: copy.pageName,
|
|
55
|
+
reason: copy.reason,
|
|
56
|
+
version: journalVersion(copy.content),
|
|
57
|
+
overwrittenBy: copy.overwrittenBy,
|
|
58
|
+
...(copy.versionBy !== undefined ? { versionBy: copy.versionBy } : {}),
|
|
59
|
+
connectorAccount: copy.connectorAccount,
|
|
60
|
+
savedAt: savedAt.toISOString(),
|
|
61
|
+
}, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
62
|
+
this.prune(dir);
|
|
63
|
+
return htmlPath;
|
|
64
|
+
}
|
|
65
|
+
prune(dir) {
|
|
66
|
+
const cutoff = this.now() - MAX_COPY_AGE_MS;
|
|
67
|
+
const copies = readdirSync(dir)
|
|
68
|
+
.filter((name) => name.endsWith('.html'))
|
|
69
|
+
.map((name) => ({ name, savedAt: savedAtOf(name) ?? statSync(path.join(dir, name)).mtimeMs }))
|
|
70
|
+
.sort((a, b) => b.savedAt - a.savedAt || b.name.localeCompare(a.name));
|
|
71
|
+
copies.forEach((copy, index) => {
|
|
72
|
+
if (index >= MAX_COPIES_PER_PAGE || copy.savedAt < cutoff) {
|
|
73
|
+
const stem = copy.name.slice(0, -'.html'.length);
|
|
74
|
+
rmSync(path.join(dir, `${stem}.html`), { force: true });
|
|
75
|
+
rmSync(path.join(dir, `${stem}.json`), { force: true });
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** The save time encoded at the start of a copy's file name. */
|
|
81
|
+
function savedAtOf(name) {
|
|
82
|
+
const match = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/.exec(name);
|
|
83
|
+
if (!match) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
const [, day, h, m, s, ms] = match;
|
|
87
|
+
const time = Date.parse(`${day}T${h}:${m}:${s}.${ms}Z`);
|
|
88
|
+
return Number.isNaN(time) ? null : time;
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=journal-history.js.map
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Journal page integrity: version tokens, text normalization and
|
|
3
|
+
* the in-memory watch that detects a connector write being overwritten.
|
|
4
|
+
*
|
|
5
|
+
* Two ways a page write can be lost after the fact, both verified against the
|
|
6
|
+
* FoundryVTT v14 source:
|
|
7
|
+
*
|
|
8
|
+
* - **A stale save** — someone saves an older copy of the page over ours. It
|
|
9
|
+
* arrives as an ordinary `modifyDocument` update broadcast carrying the
|
|
10
|
+
* author's `userId`.
|
|
11
|
+
* - **A collaborative-editor autosave** — while a text page is open in an
|
|
12
|
+
* editor, the server holds its own in-memory copy of the page and writes it
|
|
13
|
+
* back every `core.editorAutosaveSecs` (60 s by default). A
|
|
14
|
+
* `modifyDocument` write never reaches that copy. An editor with typed text
|
|
15
|
+
* keeps its sheet from re-rendering, so the autosave reverts the write; an
|
|
16
|
+
* untouched editor re-renders on the update and, in a browser, picked the
|
|
17
|
+
* write up (verified in acceptance — the copy is only reloaded when the
|
|
18
|
+
* session restarts, so that case is watched too). The server saves the
|
|
19
|
+
* document directly (no `modifyDocument` broadcast) and only emits
|
|
20
|
+
* `pm.autosave(uuid, html)` — to every user, without saying who is editing.
|
|
21
|
+
*
|
|
22
|
+
* This module holds only pure logic and in-memory state; `FoundryClient`
|
|
23
|
+
* feeds it socket events and performs the side effects (local copies,
|
|
24
|
+
* logging, the GM whisper).
|
|
25
|
+
*/
|
|
26
|
+
import { createHash } from 'node:crypto';
|
|
27
|
+
/** How long a written page stays watched for an overwrite. */
|
|
28
|
+
export const WATCH_TTL_MS = 6 * 60 * 60 * 1000;
|
|
29
|
+
/** How recent a `pm.autosave` must be to warn that the page is open in an editor. */
|
|
30
|
+
export const RECENT_AUTOSAVE_MS = 10 * 60 * 1000;
|
|
31
|
+
/** How long detected conflicts stay listed by `get_health_status`. */
|
|
32
|
+
export const CONFLICT_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
/** Length of a page version token, in hex characters. */
|
|
34
|
+
const VERSION_LENGTH = 12;
|
|
35
|
+
/**
|
|
36
|
+
* Version token of a page body: the first 12 hex characters of the SHA-256 of
|
|
37
|
+
* `text.content` as stored by the server. It depends on the content only — not
|
|
38
|
+
* on the page name, sort or ownership.
|
|
39
|
+
*/
|
|
40
|
+
export function journalVersion(content) {
|
|
41
|
+
return createHash('sha256').update(content, 'utf8').digest('hex').slice(0, VERSION_LENGTH);
|
|
42
|
+
}
|
|
43
|
+
/** Named entities worth decoding; anything else is left as-is. */
|
|
44
|
+
const NAMED_ENTITIES = {
|
|
45
|
+
amp: '&',
|
|
46
|
+
lt: '<',
|
|
47
|
+
gt: '>',
|
|
48
|
+
quot: '"',
|
|
49
|
+
apos: "'",
|
|
50
|
+
nbsp: ' ',
|
|
51
|
+
laquo: '«',
|
|
52
|
+
raquo: '»',
|
|
53
|
+
hellip: '…',
|
|
54
|
+
lsquo: '‘',
|
|
55
|
+
rsquo: '’',
|
|
56
|
+
ldquo: '“',
|
|
57
|
+
rdquo: '”',
|
|
58
|
+
ndash: '–',
|
|
59
|
+
mdash: '—',
|
|
60
|
+
agrave: 'à',
|
|
61
|
+
acirc: 'â',
|
|
62
|
+
auml: 'ä',
|
|
63
|
+
ccedil: 'ç',
|
|
64
|
+
eacute: 'é',
|
|
65
|
+
egrave: 'è',
|
|
66
|
+
ecirc: 'ê',
|
|
67
|
+
euml: 'ë',
|
|
68
|
+
icirc: 'î',
|
|
69
|
+
iuml: 'ï',
|
|
70
|
+
ocirc: 'ô',
|
|
71
|
+
ouml: 'ö',
|
|
72
|
+
ugrave: 'ù',
|
|
73
|
+
ucirc: 'û',
|
|
74
|
+
uuml: 'ü',
|
|
75
|
+
oelig: 'œ',
|
|
76
|
+
Agrave: 'À',
|
|
77
|
+
Acirc: 'Â',
|
|
78
|
+
Ccedil: 'Ç',
|
|
79
|
+
Eacute: 'É',
|
|
80
|
+
Egrave: 'È',
|
|
81
|
+
Ecirc: 'Ê',
|
|
82
|
+
Icirc: 'Î',
|
|
83
|
+
Ocirc: 'Ô',
|
|
84
|
+
Ugrave: 'Ù',
|
|
85
|
+
OElig: 'Œ',
|
|
86
|
+
};
|
|
87
|
+
function decodeEntities(text) {
|
|
88
|
+
return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[A-Za-z]+);/g, (match, body) => {
|
|
89
|
+
if (body.startsWith('#')) {
|
|
90
|
+
const code = body[1] === 'x' || body[1] === 'X'
|
|
91
|
+
? Number.parseInt(body.slice(2), 16)
|
|
92
|
+
: Number.parseInt(body.slice(1), 10);
|
|
93
|
+
return Number.isFinite(code) && code > 0 && code <= 0x10ffff
|
|
94
|
+
? String.fromCodePoint(code)
|
|
95
|
+
: match;
|
|
96
|
+
}
|
|
97
|
+
return NAMED_ENTITIES[body] ?? match;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/** Tags whose start or end separates two blocks of text. */
|
|
101
|
+
const BLOCK_BOUNDARY = /<\/?(?:p|h[1-6]|li|div|br|ul|ol|blockquote|pre|table|tr|td|th|section|article|header|footer|hr)\b[^>]*>/gi;
|
|
102
|
+
/**
|
|
103
|
+
* Splits page HTML into normalized blocks of text: tags removed, entities
|
|
104
|
+
* decoded, whitespace collapsed, one entry per paragraph, heading, list item,
|
|
105
|
+
* div or line break.
|
|
106
|
+
*
|
|
107
|
+
* Absorbs the rewrites the v14 server applies on save (`cleanHTML`: attribute
|
|
108
|
+
* quoting, `<br/>` → `<br>`, named entities → characters, stripped tags and
|
|
109
|
+
* attributes) and the different block markup a ProseMirror autosave produces.
|
|
110
|
+
*/
|
|
111
|
+
export function normalizeJournalHtml(html) {
|
|
112
|
+
if (!html) {
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
// Raw newlines are plain whitespace in HTML; only block tags separate blocks.
|
|
116
|
+
const separated = html
|
|
117
|
+
.replace(/\0/g, '')
|
|
118
|
+
.replace(/<!--[\s\S]*?-->/g, '')
|
|
119
|
+
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, '')
|
|
120
|
+
.replace(BLOCK_BOUNDARY, '\0');
|
|
121
|
+
return separated
|
|
122
|
+
.split('\0')
|
|
123
|
+
.map((block) => decodeEntities(block.replace(/<[^>]*>/g, ''))
|
|
124
|
+
.replace(/\s+/g, ' ')
|
|
125
|
+
.trim())
|
|
126
|
+
.filter((block) => block.length > 0);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* What a connector write added to a page: the normalized blocks it put there.
|
|
130
|
+
*
|
|
131
|
+
* - Append: the blocks of the appended fragment that the stored page actually
|
|
132
|
+
* contains (the server may strip part of the fragment — a block it dropped
|
|
133
|
+
* was never ours to lose).
|
|
134
|
+
* - Replace: the blocks present after the write but not before it.
|
|
135
|
+
*/
|
|
136
|
+
export function journalContribution(params) {
|
|
137
|
+
const afterBlocks = normalizeJournalHtml(params.after);
|
|
138
|
+
if (params.fragment !== undefined) {
|
|
139
|
+
const stored = new Set(afterBlocks);
|
|
140
|
+
return unique(normalizeJournalHtml(params.fragment).filter((block) => stored.has(block)));
|
|
141
|
+
}
|
|
142
|
+
const beforeBlocks = new Set(normalizeJournalHtml(params.before));
|
|
143
|
+
return unique(afterBlocks.filter((block) => !beforeBlocks.has(block)));
|
|
144
|
+
}
|
|
145
|
+
/** The contribution blocks missing from `content`. */
|
|
146
|
+
export function lostContribution(contribution, content) {
|
|
147
|
+
const present = new Set(normalizeJournalHtml(content));
|
|
148
|
+
return contribution.filter((block) => !present.has(block));
|
|
149
|
+
}
|
|
150
|
+
function unique(blocks) {
|
|
151
|
+
return [...new Set(blocks)];
|
|
152
|
+
}
|
|
153
|
+
/** Reason recorded when a connector write overwrote someone else's change. */
|
|
154
|
+
export const OVERWRITTEN_BY_CONNECTOR = 'overwritten-by-connector';
|
|
155
|
+
/** English label of whoever saved, for logs and tool responses. */
|
|
156
|
+
export function conflictAuthor(conflict) {
|
|
157
|
+
return conflict.savedBy ?? 'an open editor (autosave)';
|
|
158
|
+
}
|
|
159
|
+
function escapeHtml(text) {
|
|
160
|
+
return text
|
|
161
|
+
.replace(/&/g, '&')
|
|
162
|
+
.replace(/</g, '<')
|
|
163
|
+
.replace(/>/g, '>')
|
|
164
|
+
.replace(/"/g, '"');
|
|
165
|
+
}
|
|
166
|
+
/** Speaker alias of the conflict whisper, so the chat names an author. */
|
|
167
|
+
export const JOURNAL_CONFLICT_SPEAKER = 'MCP connector';
|
|
168
|
+
/**
|
|
169
|
+
* The chat message whispered to the GMs about a conflict: entry, page, who
|
|
170
|
+
* saved, and where the local copy is. French or English.
|
|
171
|
+
*/
|
|
172
|
+
export function journalConflictMessage(conflict, french) {
|
|
173
|
+
const entry = escapeHtml(conflict.journalName);
|
|
174
|
+
const page = escapeHtml(conflict.pageName);
|
|
175
|
+
const who = escapeHtml(conflict.savedBy ??
|
|
176
|
+
(french ? 'un éditeur ouvert (sauvegarde automatique)' : 'an open editor (autosave)'));
|
|
177
|
+
const copy = conflict.historyPath
|
|
178
|
+
? // Not a <code> block: a long path must wrap inside the chat card.
|
|
179
|
+
`<span style="font-family: monospace; word-break: break-all">${escapeHtml(conflict.historyPath)}</span>`
|
|
180
|
+
: french
|
|
181
|
+
? 'aucune copie n’a pu être écrite'
|
|
182
|
+
: 'no copy could be written';
|
|
183
|
+
const byConnector = conflict.reason === OVERWRITTEN_BY_CONNECTOR;
|
|
184
|
+
if (french) {
|
|
185
|
+
const what = byConnector
|
|
186
|
+
? `Une modification de ${who} sur la page « ${page} » de l’entrée « ${entry} » est arrivée pendant une écriture du connecteur et a été écrasée.`
|
|
187
|
+
: `La page « ${page} » de l’entrée « ${entry} » a été sauvegardée par ${who}, et du texte écrit par le connecteur a disparu.`;
|
|
188
|
+
return `<p><strong>Connecteur MCP — écrasement de journal détecté</strong></p><p>${what}</p><p>Version écrasée : ${copy}</p>`;
|
|
189
|
+
}
|
|
190
|
+
const what = byConnector
|
|
191
|
+
? `A change by ${who} to page “${page}” of entry “${entry}” reached the server while the connector was writing it, and was overwritten.`
|
|
192
|
+
: `Page “${page}” of entry “${entry}” was saved by ${who}, and text written by the connector is gone.`;
|
|
193
|
+
return `<p><strong>MCP connector — journal overwrite detected</strong></p><p>${what}</p><p>Overwritten version: ${copy}</p>`;
|
|
194
|
+
}
|
|
195
|
+
function pageKey(journalId, pageId) {
|
|
196
|
+
return `${journalId}.${pageId}`;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Integrity state for journal pages: writes in flight, watched writes, recent
|
|
200
|
+
* editor autosaves and pending warnings, in memory; the recent conflicts also
|
|
201
|
+
* in a file when one is given ({@link JournalConflictFile}), so they survive
|
|
202
|
+
* a restart.
|
|
203
|
+
*/
|
|
204
|
+
export class JournalWatch {
|
|
205
|
+
now;
|
|
206
|
+
conflictFile;
|
|
207
|
+
watches = new Map();
|
|
208
|
+
inflight = new Map();
|
|
209
|
+
autosaves = new Map();
|
|
210
|
+
warnings = [];
|
|
211
|
+
conflicts = [];
|
|
212
|
+
constructor(now = Date.now, conflictFile = null) {
|
|
213
|
+
this.now = now;
|
|
214
|
+
this.conflictFile = conflictFile;
|
|
215
|
+
if (conflictFile) {
|
|
216
|
+
this.conflicts = conflictFile.load();
|
|
217
|
+
if (this.pruneConflicts()) {
|
|
218
|
+
conflictFile.save(this.conflicts);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** Starts collecting foreign changes to a page while a connector write is in flight. */
|
|
223
|
+
beginWrite(journalId, pageId) {
|
|
224
|
+
this.inflight.set(pageKey(journalId, pageId), []);
|
|
225
|
+
}
|
|
226
|
+
/** Stops collecting, returning the foreign body changes seen during the write. */
|
|
227
|
+
endWrite(journalId, pageId) {
|
|
228
|
+
const key = pageKey(journalId, pageId);
|
|
229
|
+
const seen = this.inflight.get(key) ?? [];
|
|
230
|
+
this.inflight.delete(key);
|
|
231
|
+
return seen;
|
|
232
|
+
}
|
|
233
|
+
/** Watches a written page for {@link WATCH_TTL_MS}, replacing any earlier watch. */
|
|
234
|
+
watch(write) {
|
|
235
|
+
if (write.contribution.length === 0) {
|
|
236
|
+
this.watches.delete(pageKey(write.journalId, write.pageId));
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
this.watches.set(pageKey(write.journalId, write.pageId), {
|
|
240
|
+
...write,
|
|
241
|
+
expiresAt: this.now() + WATCH_TTL_MS,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
isWatched(journalId, pageId) {
|
|
245
|
+
this.pruneWatches();
|
|
246
|
+
return this.watches.has(pageKey(journalId, pageId));
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Feeds a change made by someone other than the connector.
|
|
250
|
+
*
|
|
251
|
+
* During a write it is held for {@link endWrite}. Otherwise the first body
|
|
252
|
+
* change to a watched page ends the watch: either someone saved a version
|
|
253
|
+
* that still holds the connector's contribution, or part of it is gone.
|
|
254
|
+
*/
|
|
255
|
+
observe(change) {
|
|
256
|
+
const key = pageKey(change.journalId, change.pageId);
|
|
257
|
+
if (change.source.kind === 'autosave') {
|
|
258
|
+
this.autosaves.set(key, this.now());
|
|
259
|
+
}
|
|
260
|
+
if (change.content === undefined) {
|
|
261
|
+
return { kind: 'ignored' };
|
|
262
|
+
}
|
|
263
|
+
const window = this.inflight.get(key);
|
|
264
|
+
if (window) {
|
|
265
|
+
window.push(change);
|
|
266
|
+
return { kind: 'race' };
|
|
267
|
+
}
|
|
268
|
+
this.pruneWatches();
|
|
269
|
+
const watched = this.watches.get(key);
|
|
270
|
+
if (!watched) {
|
|
271
|
+
return { kind: 'ignored' };
|
|
272
|
+
}
|
|
273
|
+
this.watches.delete(key);
|
|
274
|
+
const lost = lostContribution(watched.contribution, change.content);
|
|
275
|
+
if (lost.length === 0) {
|
|
276
|
+
return { kind: 'kept' };
|
|
277
|
+
}
|
|
278
|
+
const { expiresAt: _expiresAt, ...write } = watched;
|
|
279
|
+
return { kind: 'lost', watched: write, lost };
|
|
280
|
+
}
|
|
281
|
+
/** True when an editor autosaved the page within {@link RECENT_AUTOSAVE_MS}. */
|
|
282
|
+
hasRecentAutosave(journalId, pageId) {
|
|
283
|
+
const at = this.autosaves.get(pageKey(journalId, pageId));
|
|
284
|
+
return at !== undefined && this.now() - at <= RECENT_AUTOSAVE_MS;
|
|
285
|
+
}
|
|
286
|
+
/** Queues a warning for the next journal tool response. */
|
|
287
|
+
addWarning(text) {
|
|
288
|
+
this.warnings.push(text);
|
|
289
|
+
}
|
|
290
|
+
/** Returns and clears the pending warnings. */
|
|
291
|
+
drainWarnings() {
|
|
292
|
+
return this.warnings.splice(0, this.warnings.length);
|
|
293
|
+
}
|
|
294
|
+
recordConflict(conflict) {
|
|
295
|
+
this.conflicts.push(conflict);
|
|
296
|
+
this.pruneConflicts();
|
|
297
|
+
this.conflictFile?.save(this.conflicts);
|
|
298
|
+
}
|
|
299
|
+
/** Conflicts detected within {@link CONFLICT_RETENTION_MS}, oldest first. */
|
|
300
|
+
recentConflicts() {
|
|
301
|
+
if (this.pruneConflicts()) {
|
|
302
|
+
this.conflictFile?.save(this.conflicts);
|
|
303
|
+
}
|
|
304
|
+
return [...this.conflicts];
|
|
305
|
+
}
|
|
306
|
+
pruneWatches() {
|
|
307
|
+
const now = this.now();
|
|
308
|
+
for (const [key, watched] of this.watches) {
|
|
309
|
+
if (watched.expiresAt <= now) {
|
|
310
|
+
this.watches.delete(key);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/** @returns whether any conflict was dropped */
|
|
315
|
+
pruneConflicts() {
|
|
316
|
+
const cutoff = this.now() - CONFLICT_RETENTION_MS;
|
|
317
|
+
const before = this.conflicts.length;
|
|
318
|
+
this.conflicts = this.conflicts.filter((conflict) => conflict.at > cutoff);
|
|
319
|
+
return this.conflicts.length !== before;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
//# sourceMappingURL=journal-integrity.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Who wrote a chat message.
|
|
3
|
+
*
|
|
4
|
+
* FoundryVTT stores the author of a chat message in `author` since v12
|
|
5
|
+
* (v14: common/documents/chat-message.mjs,
|
|
6
|
+
* `author: new fields.DocumentAuthorField(documents.BaseUser)`); `user` is
|
|
7
|
+
* its earlier name, kept for messages from older data (G33ks/foundryvtt-mcp#13).
|
|
8
|
+
*/
|
|
9
|
+
/** The id of the user who wrote `message`: `author`, else `user`; `undefined` when neither is a string. */
|
|
10
|
+
export function messageAuthorId(message) {
|
|
11
|
+
if (typeof message.author === 'string' && message.author !== '') {
|
|
12
|
+
return message.author;
|
|
13
|
+
}
|
|
14
|
+
if (typeof message.user === 'string' && message.user !== '') {
|
|
15
|
+
return message.user;
|
|
16
|
+
}
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=message-author.js.map
|