rpg-engine 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +3 -1
  2. package/dist/campaign/index.d.ts +1 -1
  3. package/dist/campaign/index.js +1 -1
  4. package/dist/campaign/settings.d.ts +5 -1
  5. package/dist/campaign/settings.js +18 -3
  6. package/dist/command-line.js +26 -8
  7. package/dist/commands/advance.js +26 -7
  8. package/dist/commands/ask.d.ts +6 -0
  9. package/dist/commands/ask.js +3 -3
  10. package/dist/commands/config.js +40 -10
  11. package/dist/commands/game-advance.d.ts +6 -0
  12. package/dist/commands/game-advance.js +9 -2
  13. package/dist/commands/game-extension-list.d.ts +27 -0
  14. package/dist/commands/game-extension-list.js +92 -0
  15. package/dist/commands/game-extensions.d.ts +27 -0
  16. package/dist/commands/game-extensions.js +177 -0
  17. package/dist/commands/game-mode.js +2 -1
  18. package/dist/commands/game-time.d.ts +15 -3
  19. package/dist/commands/game-time.js +76 -6
  20. package/dist/commands/game-world.js +6 -3
  21. package/dist/commands/index.js +2 -0
  22. package/dist/commands/package.d.ts +42 -0
  23. package/dist/commands/package.js +220 -0
  24. package/dist/commands/page-counters.js +4 -1
  25. package/dist/commands/problems.js +3 -1
  26. package/dist/commands/scene.d.ts +3 -3
  27. package/dist/commands/sheet.js +7 -1
  28. package/dist/commands/status.d.ts +1 -0
  29. package/dist/commands/status.js +10 -5
  30. package/dist/commands/travel.js +4 -2
  31. package/dist/commands/validate.js +4 -2
  32. package/dist/commands/view.d.ts +5 -0
  33. package/dist/commands/view.js +3 -1
  34. package/dist/core/context.d.ts +34 -0
  35. package/dist/core/context.js +11 -0
  36. package/dist/core/instruction-parts.d.ts +10 -0
  37. package/dist/core/instruction-parts.js +32 -0
  38. package/dist/core/store.d.ts +2 -0
  39. package/dist/core/store.js +8 -0
  40. package/dist/dashboard/app.js +2 -1
  41. package/dist/dashboard/game-words.js +21 -0
  42. package/dist/dashboard/i18n/ar.json +7 -0
  43. package/dist/dashboard/i18n/cs.json +7 -0
  44. package/dist/dashboard/i18n/da.json +7 -0
  45. package/dist/dashboard/i18n/de.json +7 -0
  46. package/dist/dashboard/i18n/el.json +7 -0
  47. package/dist/dashboard/i18n/es.json +7 -0
  48. package/dist/dashboard/i18n/fi.json +7 -0
  49. package/dist/dashboard/i18n/fr.json +7 -0
  50. package/dist/dashboard/i18n/he.json +7 -0
  51. package/dist/dashboard/i18n/hi.json +7 -0
  52. package/dist/dashboard/i18n/hu.json +7 -0
  53. package/dist/dashboard/i18n/is.json +7 -0
  54. package/dist/dashboard/i18n/it.json +7 -0
  55. package/dist/dashboard/i18n/ja.json +7 -0
  56. package/dist/dashboard/i18n/ko.json +7 -0
  57. package/dist/dashboard/i18n/nb.json +7 -0
  58. package/dist/dashboard/i18n/nl.json +7 -0
  59. package/dist/dashboard/i18n/pl.json +7 -0
  60. package/dist/dashboard/i18n/pt.json +7 -0
  61. package/dist/dashboard/i18n/ro.json +7 -0
  62. package/dist/dashboard/i18n/ru.json +7 -0
  63. package/dist/dashboard/i18n/sv.json +7 -0
  64. package/dist/dashboard/i18n/tr.json +7 -0
  65. package/dist/dashboard/i18n/uk.json +7 -0
  66. package/dist/dashboard/i18n/zh.json +7 -0
  67. package/dist/dashboard/icons.js +1 -0
  68. package/dist/dashboard/layout.js +2 -1
  69. package/dist/dashboard/top.js +5 -5
  70. package/dist/extensions/api.d.ts +73 -0
  71. package/dist/extensions/api.js +1 -0
  72. package/dist/extensions/extension.d.ts +43 -0
  73. package/dist/extensions/extension.js +113 -0
  74. package/dist/extensions/index.d.ts +3 -0
  75. package/dist/extensions/index.js +2 -0
  76. package/dist/extensions/packages.d.ts +11 -0
  77. package/dist/extensions/packages.js +141 -0
  78. package/dist/index.d.ts +1 -0
  79. package/dist/mcp-server.js +50 -4
  80. package/dist/systems/game-system.d.ts +1 -5
  81. package/dist/systems/game-system.js +6 -31
  82. package/dist/systems/index.d.ts +1 -1
  83. package/dist/time/calendar.d.ts +36 -0
  84. package/dist/time/calendar.js +84 -0
  85. package/dist/time/index.d.ts +1 -0
  86. package/dist/time/index.js +2 -1
  87. package/package.json +2 -3
  88. package/systems/5e/instructions/play.md +1 -0
  89. package/systems/5e/system.yaml +13 -2
  90. package/systems/5e/words/ar.yaml +8 -0
  91. package/systems/5e/words/cs.yaml +8 -0
  92. package/systems/5e/words/da.yaml +8 -0
  93. package/systems/5e/words/de.yaml +8 -0
  94. package/systems/5e/words/el.yaml +8 -0
  95. package/systems/5e/words/es.yaml +8 -0
  96. package/systems/5e/words/fi.yaml +8 -0
  97. package/systems/5e/words/fr.yaml +8 -0
  98. package/systems/5e/words/he.yaml +8 -0
  99. package/systems/5e/words/hi.yaml +8 -0
  100. package/systems/5e/words/hu.yaml +8 -0
  101. package/systems/5e/words/is.yaml +8 -0
  102. package/systems/5e/words/it.yaml +9 -0
  103. package/systems/5e/words/ja.yaml +8 -0
  104. package/systems/5e/words/ko.yaml +8 -0
  105. package/systems/5e/words/nb.yaml +8 -0
  106. package/systems/5e/words/nl.yaml +8 -0
  107. package/systems/5e/words/pl.yaml +8 -0
  108. package/systems/5e/words/pt.yaml +8 -0
  109. package/systems/5e/words/ro.yaml +8 -0
  110. package/systems/5e/words/ru.yaml +8 -0
  111. package/systems/5e/words/sv.yaml +8 -0
  112. package/systems/5e/words/tr.yaml +8 -0
  113. package/systems/5e/words/uk.yaml +8 -0
  114. package/systems/5e/words/zh.yaml +8 -0
@@ -0,0 +1,113 @@
1
+ import { existsSync, lstatSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ import { readParts } from "../core/instruction-parts.js";
5
+ import { files } from "../core/store.js";
6
+ import { comparableText } from "../core/text.js";
7
+ import { readYamlValues } from "../core/yaml-file.js";
8
+ /** The file that makes a folder an extension of rpg-engine (D-427). */
9
+ export const extensionFileName = "extension.yaml";
10
+ // The longest about and part of the instructions an extension may give, in words (D-441).
11
+ const aboutWords = 40;
12
+ const partWords = 400;
13
+ /** The version of the API an extension's code is given (api.ts), which its package.json names: a package made for another is refused. */
14
+ export const extensionApi = 1;
15
+ const extensionSchema = z.object({
16
+ title: z.string().trim().min(1),
17
+ about: z.string().trim().min(1),
18
+ language: z.string().regex(/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/, "use a language code such as en"),
19
+ attribution: z.string().trim().min(1).optional(),
20
+ needs: z.object({ system: z.string().trim().min(1).optional() }).strict().optional(),
21
+ calendar: z.unknown().optional(),
22
+ }).strict();
23
+ const packageSchema = z.object({
24
+ name: z.string().regex(/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/, "an npm package name, such as @rpgengine/weather"),
25
+ version: z.string().min(1),
26
+ main: z.string().min(1).optional(),
27
+ // What says it is a package for rpg-engine, of which kind, and for which version of the API (D-439).
28
+ "rpg-engine": z.object({ kind: z.string(), api: z.number().optional() }).optional(),
29
+ });
30
+ /** The extensions installed in these folders, each a package folder, or a scope's folder of them as npm keeps them (@rpgengine/weather); the first by a name wins. */
31
+ export function installedExtensions(folders) {
32
+ const found = [];
33
+ for (const folder of packageFolders(folders)) {
34
+ const name = packageName(folder);
35
+ if (name !== undefined && !found.some((other) => other.package === name)) {
36
+ found.push({ package: name, folder });
37
+ }
38
+ }
39
+ return found;
40
+ }
41
+ /** The installed extension of this package, as npm or campaign.yaml names it, or by its name alone (weather); undefined when none is. It throws when it does not read. */
42
+ export function findExtension(folders, wanted) {
43
+ const named = (candidate) => candidate === wanted.trim() || comparableText(shortName(candidate)) === comparableText(wanted.trim());
44
+ const found = installedExtensions(folders).find((candidate) => named(candidate.package));
45
+ return found === undefined ? undefined : readExtension(found.folder);
46
+ }
47
+ /** An extension from its folder: its package.json and its extension.yaml, refused with what is wrong (D-427). */
48
+ export function readExtension(folder) {
49
+ const where = (file) => join(folder, file);
50
+ const manifest = packageSchema.safeParse(readJson(where("package.json")));
51
+ if (!manifest.success) {
52
+ throw new Error(`The extension in ${folder} cannot be read, because its package.json is not valid: ${z.prettifyError(manifest.error).replace(/\s+/g, " ")}`);
53
+ }
54
+ const owner = `The extension ${manifest.data.name}`;
55
+ const marker = manifest.data["rpg-engine"];
56
+ if (marker?.kind !== "extension" || marker.api !== extensionApi) {
57
+ const made = marker?.kind !== "extension" ? 'its package.json does not say "rpg-engine": {"kind": "extension"}' : `it is made for the extension API ${marker.api ?? "none"}`;
58
+ throw new Error(`${owner} cannot be used, because ${made}; this rpg-engine reads the API ${extensionApi}: install a version of it made for this one.`);
59
+ }
60
+ const declared = extensionSchema.safeParse(readYamlValues(where(extensionFileName), "what the extension is, such as title: ..."));
61
+ if (!declared.success) {
62
+ throw new Error(`${owner} cannot be read, because its ${extensionFileName} is not valid: ${z.prettifyError(declared.error).replace(/\s+/g, " ")}`);
63
+ }
64
+ const { title, about, language, attribution, needs, calendar } = declared.data;
65
+ const parts = readParts(folder, owner);
66
+ // What the master reads of it in every chat, kept short (D-441).
67
+ const long = [["about", about, aboutWords], ...Object.entries(parts).map(([name, part]) => [`instructions/${name}.md`, part.text, partWords])]
68
+ .find(([, text, most]) => words(text) > most);
69
+ if (long !== undefined) {
70
+ throw new Error(`${owner} cannot be used, because its ${long[0]} has ${words(long[1])} words, and ${long[2]} at most are read.`);
71
+ }
72
+ return {
73
+ package: manifest.data.name,
74
+ name: shortName(manifest.data.name),
75
+ version: manifest.data.version,
76
+ folder,
77
+ title,
78
+ about,
79
+ language,
80
+ ...(attribution === undefined ? {} : { attribution }),
81
+ needs: needs ?? {},
82
+ ...(calendar === undefined ? {} : { calendar }),
83
+ parts,
84
+ ...(manifest.data.main === undefined ? {} : { code: where(manifest.data.main) }),
85
+ linked: lstatSync(folder).isSymbolicLink(),
86
+ };
87
+ }
88
+ /** The name a package's commands start with: its name without the scope, weather for @rpgengine/weather. */
89
+ export function shortName(packageName) {
90
+ return packageName.replace(/^@[^/]+\//, "");
91
+ }
92
+ /** The folders of packages with an extension.yaml in these folders, and in their scopes' folders; npm links a package installed from a folder. */
93
+ function packageFolders(folders) {
94
+ const children = (folder) => readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).map((entry) => join(folder, entry.name)).sort();
95
+ const candidates = folders.filter((folder) => existsSync(folder)).flatMap((folder) => children(folder).flatMap((child) => (child.split(/[\\/]/).at(-1)?.startsWith("@") === true ? children(child) : [child])));
96
+ return candidates.filter((candidate) => existsSync(join(candidate, extensionFileName)));
97
+ }
98
+ /** The name in a package's package.json; undefined when it has none that reads. */
99
+ function packageName(folder) {
100
+ const parsed = packageSchema.safeParse(readJson(join(folder, "package.json")));
101
+ return parsed.success ? parsed.data.name : undefined;
102
+ }
103
+ function readJson(path) {
104
+ try {
105
+ return JSON.parse(files().text(path) ?? "null");
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ }
111
+ function words(text) {
112
+ return text.split(/\s+/).filter((word) => word !== "").length;
113
+ }
@@ -0,0 +1,3 @@
1
+ export type { CalendarDay, ExtensionCode, ExtensionCommand, ExtensionEntry, ExtensionKit, Game, GameMoment, TimePassage } from "./api.ts";
2
+ export { type Extension, extensionApi, extensionFileName, findExtension, installedExtensions, readExtension, shortName } from "./extension.ts";
3
+ export { isFolderSpec, isVerified, npmPackages, packageKeyword, verifiedScope } from "./packages.ts";
@@ -0,0 +1,2 @@
1
+ export { extensionApi, extensionFileName, findExtension, installedExtensions, readExtension, shortName } from "./extension.js";
2
+ export { isFolderSpec, isVerified, npmPackages, packageKeyword, verifiedScope } from "./packages.js";
@@ -0,0 +1,11 @@
1
+ import type { PackageManager } from "../core/context.ts";
2
+ /** The keyword of the packages for rpg-engine on npm, by which they are found (D-439). */
3
+ export declare const packageKeyword = "rpg-engine-package";
4
+ /** The npm scope of the packages we publish, the verified ones (D-428, D-441). */
5
+ export declare const verifiedScope = "@rpgengine/";
6
+ /** npm on this computer, installing in this folder (D-436): never globally, never running a package's scripts. Its registry is read directly. */
7
+ export declare function npmPackages(folder: string): PackageManager;
8
+ /** Whether a package is given by its folder on this computer rather than by its name on npm. */
9
+ export declare function isFolderSpec(spec: string): boolean;
10
+ /** Whether an installed package is ours, verified: in our scope and installed from npm, never from a folder, which anyone can name so (D-428, D-441). */
11
+ export declare function isVerified(name: string, linked: boolean): boolean;
@@ -0,0 +1,141 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { isAbsolute, join, resolve } from "node:path";
5
+ /** The keyword of the packages for rpg-engine on npm, by which they are found (D-439). */
6
+ export const packageKeyword = "rpg-engine-package";
7
+ /** The npm scope of the packages we publish, the verified ones (D-428, D-441). */
8
+ export const verifiedScope = "@rpgengine/";
9
+ const registry = "https://registry.npmjs.org";
10
+ // An npm name with a version or a tag, or nothing a shell would read otherwise: the master writes it, and npm runs in a shell.
11
+ const npmSpec = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(@[0-9A-Za-z.+-]+)?$/;
12
+ const installWait = 5 * 60 * 1000;
13
+ /** npm on this computer, installing in this folder (D-436): never globally, never running a package's scripts. Its registry is read directly. */
14
+ export function npmPackages(folder) {
15
+ return {
16
+ describe: async (spec) => (isFolderSpec(spec) ? folderPackage(spec) : await registryPackage(spec)),
17
+ install: async (spec) => {
18
+ const what = isFolderSpec(spec) ? quotedFolder(spec) : checkedSpec(spec);
19
+ const ran = await npm(`install --prefix ${quotedFolder(folder)} ${what} --ignore-scripts --save-exact --no-audit --no-fund --json --loglevel=error`);
20
+ return ran.code === 0 ? undefined : `npm said: ${npmError(ran)}`;
21
+ },
22
+ search: async () => {
23
+ try {
24
+ const found = await json(`${registry}/-/v1/search?text=keywords:${packageKeyword}&size=250`);
25
+ // The keyword is only a hint: each package's latest package.json must say what it is for rpg-engine.
26
+ const described = await Promise.all((found?.objects ?? []).map(async (object) => await registryPackage(object.package.name)));
27
+ return described.filter((one) => !("failed" in one) && one.kind !== undefined);
28
+ }
29
+ catch (error) {
30
+ return { failed: `npm's registry could not be reached: ${error instanceof Error ? error.message : String(error)}` };
31
+ }
32
+ },
33
+ };
34
+ }
35
+ /** Whether a package is given by its folder on this computer rather than by its name on npm. */
36
+ export function isFolderSpec(spec) {
37
+ return spec.startsWith(".") || isAbsolute(spec);
38
+ }
39
+ /** Whether an installed package is ours, verified: in our scope and installed from npm, never from a folder, which anyone can name so (D-428, D-441). */
40
+ export function isVerified(name, linked) {
41
+ return name.startsWith(verifiedScope) && !linked;
42
+ }
43
+ /** What npm's registry says of a package, at a version or its latest, with what its package.json says for rpg-engine. */
44
+ async function registryPackage(spec) {
45
+ const checked = checkedSpec(spec);
46
+ const at = checked.lastIndexOf("@");
47
+ const [name, version] = at > 0 ? [checked.slice(0, at), checked.slice(at + 1)] : [checked, "latest"];
48
+ try {
49
+ const read = await json(`${registry}/${name.replace("/", "%2f")}/${version}`);
50
+ return read === undefined ? { failed: `npm has no package ${spec}`, missing: true } : infoOf(read);
51
+ }
52
+ catch (error) {
53
+ return { failed: `npm's registry could not be reached: ${error instanceof Error ? error.message : String(error)}` };
54
+ }
55
+ }
56
+ /** What a package's folder says of it, by its package.json. */
57
+ function folderPackage(spec) {
58
+ try {
59
+ const read = JSON.parse(readFileSync(join(resolve(spec), "package.json"), "utf8"));
60
+ return read.name === undefined || read.version === undefined ? { failed: `${spec} has a package.json without its name and version` } : infoOf(read);
61
+ }
62
+ catch {
63
+ return { failed: `${spec} is not the folder of a package: it has no package.json that reads` };
64
+ }
65
+ }
66
+ function infoOf(read) {
67
+ const marker = read["rpg-engine"];
68
+ return {
69
+ name: read.name ?? "",
70
+ version: read.version ?? "",
71
+ ...(typeof marker?.kind === "string" ? { kind: marker.kind } : {}),
72
+ ...(typeof marker?.api === "number" ? { api: marker.api } : {}),
73
+ ...(read.description === undefined ? {} : { description: read.description }),
74
+ };
75
+ }
76
+ /** A JSON answer of the registry; undefined when it has none, 404. */
77
+ async function json(url) {
78
+ const answer = await fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(20_000) });
79
+ if (answer.status === 404) {
80
+ return undefined;
81
+ }
82
+ if (!answer.ok) {
83
+ throw new Error(`${answer.status} ${answer.statusText}`);
84
+ }
85
+ return await answer.json();
86
+ }
87
+ function checkedSpec(spec) {
88
+ if (!npmSpec.test(spec)) {
89
+ throw new Error(`"${spec}" is not the name of an npm package, with its version if wanted, such as @rpgengine/weather or @rpgengine/weather@0.1.0.`);
90
+ }
91
+ return spec;
92
+ }
93
+ /** A folder in quotes for the shell; one with characters a shell would read is refused. */
94
+ function quotedFolder(folder) {
95
+ const path = resolve(folder);
96
+ if (/["%$`!&]/.test(path)) {
97
+ throw new Error(`The folder ${path} has characters npm cannot be given safely ("%$\`!&): move it to another path.`);
98
+ }
99
+ return `"${path}"`;
100
+ }
101
+ /** What npm said went wrong: its JSON error, with --json, else the last line it wrote that is not the pointer to its log. */
102
+ function npmError(ran) {
103
+ try {
104
+ const read = JSON.parse(ran.out);
105
+ if (read.error?.summary !== undefined) {
106
+ return `${read.error.code === undefined ? "" : `${read.error.code}, `}${read.error.summary}`;
107
+ }
108
+ }
109
+ catch {
110
+ // Not JSON: the lines it wrote say it.
111
+ }
112
+ const lines = ran.errors.split("\n").map((line) => line.trim()).filter((line) => line !== "" && !/complete log of this run/i.test(line));
113
+ return lines.at(-1) ?? "nothing";
114
+ }
115
+ /** Runs npm with these arguments, in a folder of no campaign, stopped with all it started after a while. */
116
+ function npm(args) {
117
+ return new Promise((done) => {
118
+ const child = spawn(`npm ${args}`, { shell: true, windowsHide: true, cwd: tmpdir(), env: { ...process.env, NoDefaultCurrentDirectoryInExePath: "1" }, stdio: ["ignore", "pipe", "pipe"] });
119
+ let [out, errors] = ["", ""];
120
+ const timer = setTimeout(() => stopTree(child.pid), installWait);
121
+ child.stdout.setEncoding("utf8").on("data", (chunk) => (out += chunk));
122
+ child.stderr.setEncoding("utf8").on("data", (chunk) => (errors += chunk));
123
+ child.on("error", (error) => (errors += error.message));
124
+ child.on("close", (code) => {
125
+ clearTimeout(timer);
126
+ done({ code, out, errors });
127
+ });
128
+ });
129
+ }
130
+ /** Stops a process with the ones it started: on Windows the shell's child, npm, outlives a kill of the shell alone. */
131
+ function stopTree(pid) {
132
+ if (pid === undefined) {
133
+ return;
134
+ }
135
+ if (process.platform === "win32") {
136
+ spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true });
137
+ }
138
+ else {
139
+ process.kill(pid, "SIGKILL");
140
+ }
141
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export { getVersion } from "./core/version.ts";
2
+ export type { CalendarDay, ExtensionCode, ExtensionCommand, ExtensionEntry, ExtensionKit, Game, GameMoment, TimePassage } from "./extensions/index.ts";
@@ -1,15 +1,17 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { findCampaign, refreshHostFiles } from "./campaign/index.js";
4
+ import { extensionCommands } from "./commands/game-extensions.js";
4
5
  import { outsideNews, whileClosedNews } from "./commands/game-outside.js";
5
6
  import { newChatText, wentBackTo } from "./commands/game-saves.js";
6
7
  import { campaignWorld } from "./commands/game-world.js";
7
8
  import { commands } from "./commands/index.js";
8
- import { defaultContext } from "./core/context.js";
9
+ import { defaultContext, packagesFolder } from "./core/context.js";
9
10
  import { SessionStore } from "./core/session-store.js";
10
- import { withFiles } from "./core/store.js";
11
+ import { FileStore, withFiles } from "./core/store.js";
11
12
  import { getVersion } from "./core/version.js";
12
13
  import { startDashboard } from "./dashboard-server.js";
14
+ import { npmPackages } from "./extensions/index.js";
13
15
  import { startInstructions } from "./instructions/index.js";
14
16
  import { computerHelpers, hostPictures, hostWriter } from "./pictures/index.js";
15
17
  // How long the player may take to click: as long as a host waits for a tool call that keeps reporting progress.
@@ -43,8 +45,11 @@ export function createMcpServer(context = defaultContext(), environment = proces
43
45
  askingTools.filter((tool) => !tool.enabled).forEach((tool) => tool.enable());
44
46
  }
45
47
  };
48
+ // The tools of the campaign's extensions, kept in step after every call, as one that installs an extension or makes the campaign (D-63).
49
+ const extensions = extensionTools(server, context, (command) => (input, extra) => runTool(command, input, context, extra, prepare, outside).finally(extensions));
50
+ firstExtensions.set(server, extensions());
46
51
  for (const command of commands) {
47
- const tool = server.registerTool(command.name, toolConfig(command), (input, extra) => runTool(command, input, context, extra, prepare, outside));
52
+ const tool = server.registerTool(command.name, toolConfig(command), (input, extra) => runTool(command, input, context, extra, prepare, outside).finally(extensions));
48
53
  if (command.needsPlayer && context.player === undefined) {
49
54
  tool.disable();
50
55
  askingTools.push(tool);
@@ -79,10 +84,12 @@ export async function startMcpServer() {
79
84
  // The pictures, by the chat in use, which names itself as the session starts (D-308, D-390).
80
85
  let server;
81
86
  const host = () => server?.server.getClientVersion()?.name;
82
- const context = { ...defaultContext(), pictures: hostPictures(host), writer: hostWriter(host), helpers: computerHelpers() };
87
+ const context = { ...defaultContext(), pictures: hostPictures(host), writer: hostWriter(host), helpers: computerHelpers(), packages: npmPackages(packagesFolder()), host };
83
88
  const session = new SessionStore({ systemFolders: context.systemFolders });
84
89
  const served = { ...context, files: session };
85
90
  server = createMcpServer(served, process.env, dashboardOpener(served, session).open);
91
+ // The extensions' tools are there in the first list the host asks for.
92
+ await firstExtensions.get(server);
86
93
  await server.connect(new StdioServerTransport());
87
94
  }
88
95
  /**
@@ -124,6 +131,45 @@ async function preload(context, session) {
124
131
  // The call that needs the campaign reads it again, and says what is wrong.
125
132
  }
126
133
  }
134
+ // The first loading of each server's extension tools, which the server started for a host waits for.
135
+ const firstExtensions = new WeakMap();
136
+ /**
137
+ * Keeps the tools of the campaign's extensions in step with campaign.yaml (D-63, D-428): a tool is registered once its code is loaded, and enabled only while
138
+ * the campaign uses its extension; hosts hear the list changed. What does not load stays out: status and validate say why.
139
+ */
140
+ function extensionTools(server, context, handler) {
141
+ // Each tool with the package and version that give it: another one in its place is registered anew.
142
+ const registered = new Map();
143
+ const taken = commands.map((command) => command.name);
144
+ let running = Promise.resolve();
145
+ const sync = async () => {
146
+ const store = context.files ?? new FileStore(context.systemFolders);
147
+ const own = await withFiles(store, async () => {
148
+ const root = findCampaign(context.folder);
149
+ return root === undefined ? { commands: [], sources: {} } : await extensionCommands(root, context, taken);
150
+ });
151
+ for (const command of own.commands) {
152
+ const kept = registered.get(command.name);
153
+ const source = own.sources[command.name] ?? "";
154
+ if (kept !== undefined && kept.source !== source) {
155
+ kept.tool.remove();
156
+ }
157
+ if (kept === undefined || kept.source !== source) {
158
+ registered.set(command.name, { tool: server.registerTool(command.name, toolConfig(command), handler(command)), source });
159
+ }
160
+ else if (!kept.tool.enabled) {
161
+ kept.tool.enable();
162
+ }
163
+ }
164
+ for (const [name, kept] of registered) {
165
+ if (kept.tool.enabled && !own.commands.some((command) => command.name === name)) {
166
+ kept.tool.disable();
167
+ }
168
+ }
169
+ };
170
+ // One at a time, and never failing the call it follows.
171
+ return () => (running = running.then(sync).catch(() => undefined));
172
+ }
127
173
  function toolConfig(command) {
128
174
  const annotations = command.readOnly ? { readOnlyHint: true } : undefined;
129
175
  const meta = command.alwaysLoad ? { "anthropic/alwaysLoad": true } : undefined;
@@ -1,5 +1,6 @@
1
1
  import { type FieldKind } from "../core/field-kind.ts";
2
2
  import { type Formula, type SystemFormulas } from "../core/formula.ts";
3
+ import { type InstructionPart } from "../core/instruction-parts.ts";
3
4
  import { type ImperialUnits } from "../core/length.ts";
4
5
  import type { ProgressionRule } from "../core/progression-rule.ts";
5
6
  /** The file that makes a folder a game system and says what it is. */
@@ -200,11 +201,6 @@ export interface GameSystem {
200
201
  */
201
202
  parts: Record<string, InstructionPart>;
202
203
  }
203
- /** A part of the master's instructions as a layer gives it: its text, and whether it takes the place of the layers below instead of adding to them (D-121). */
204
- export interface InstructionPart {
205
- text: string;
206
- replace: boolean;
207
- }
208
204
  /**
209
205
  * The system as a campaign plays it, with the values its settings have (DAT-10): the fields a value leaves out are gone from the sheet, the line, the experience
210
206
  * and the rewards. A setting without a value, or with one the system lacks, leaves out nothing.
@@ -1,12 +1,11 @@
1
1
  import { existsSync, readdirSync } from "node:fs";
2
- import { basename, join } from "node:path";
3
- import { parse } from "yaml";
2
+ import { join } from "node:path";
4
3
  import { z } from "zod";
5
4
  import { fieldKinds } from "../core/field-kind.js";
6
5
  import { formulaOf, readFormulas } from "../core/formula.js";
7
6
  import { frozen } from "../core/frozen.js";
7
+ import { readParts } from "../core/instruction-parts.js";
8
8
  import { lengthHelp, readLength, readSpeed, speedHelp } from "../core/length.js";
9
- import { files } from "../core/store.js";
10
9
  import { comparableText, sameName } from "../core/text.js";
11
10
  import { readYamlValues } from "../core/yaml-file.js";
12
11
  /** The file that makes a folder a game system and says what it is. */
@@ -232,9 +231,10 @@ function readSystem(folder, name, additions) {
232
231
  const sheet = sheetOf(data, name, path);
233
232
  const values = data.values ?? {};
234
233
  const kindOf = (field) => Object.entries(data.fields ?? {}).find(([declared]) => comparableText(declared) === comparableText(field))?.[1];
235
- const notList = Object.keys(values).find((field) => kindOf(field) !== "list");
234
+ // Closed names for a list, as the skills, or for a text, as an alignment.
235
+ const notList = Object.keys(values).find((field) => kindOf(field) !== "list" && kindOf(field) !== "text");
236
236
  if (notList !== undefined) {
237
- throw new Error(`The game system ${name} cannot be read, because ${path} is not valid: values.${notList}: declare ${notList} as a list in fields, or give no values to it.`);
237
+ throw new Error(`The game system ${name} cannot be read, because ${path} is not valid: values.${notList}: declare ${notList} as a list or a text in fields, or give no values to it.`);
238
238
  }
239
239
  // What breaks what someone keeps, and what a counter shields, read counters (EFF-14, DAT-14).
240
240
  const counted = [
@@ -355,7 +355,7 @@ function readSystem(folder, name, additions) {
355
355
  const [counter, value] = reward.overcome.split(" ");
356
356
  return { field, from: reward.from, counter, value: Number(value) };
357
357
  }),
358
- parts: readParts(folder, name),
358
+ parts: readParts(folder, `The game system ${name}`),
359
359
  });
360
360
  }
361
361
  /**
@@ -399,31 +399,6 @@ function progressionRule(data) {
399
399
  const { skip, ...rule } = data;
400
400
  return { ...rule, skip: skip ?? [] };
401
401
  }
402
- /** The system's parts of the master's instructions, from the files of its instructions folder: a part is named after its file (D-121). */
403
- function readParts(folder, name) {
404
- const parts = {};
405
- for (const path of files().files(join(folder, "instructions"), (file) => file.endsWith(".md"))) {
406
- parts[basename(path, ".md")] = partOf(files().text(path) ?? "", name, path);
407
- }
408
- return parts;
409
- }
410
- /** A part from its file: the text after its frontmatter, which says only whether it takes the place of the core's part, replace: true (D-121). */
411
- function partOf(file, system, path) {
412
- const text = file.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
413
- const frontmatter = text.match(/^---\n([\s\S]*?)\n---(?:\n|$)/);
414
- let settings;
415
- try {
416
- settings = frontmatter === null ? {} : (parse(frontmatter[1]) ?? {});
417
- }
418
- catch {
419
- settings = undefined;
420
- }
421
- const parsed = z.object({ replace: z.boolean().optional() }).strict().safeParse(settings);
422
- if (!parsed.success) {
423
- throw new Error(`The game system ${system} cannot be read, because ${path} is not valid: a part's frontmatter says only replace: true, for a part that takes the place of the core's.`);
424
- }
425
- return { text: (frontmatter === null ? text : text.slice(frontmatter[0].length)).trim(), replace: parsed.data.replace === true };
426
- }
427
402
  /** The progression without its experience, when a setting leaves its field out (DAT-10). */
428
403
  function withoutExperience(progression, kept) {
429
404
  if (progression.experience === undefined || kept(progression.experience.field)) {
@@ -1,2 +1,2 @@
1
- export { type CampaignData, campaignDataNames, findCampaignSystem, findSystem, type GameSystem, type GridRules, installedSystems, type InstructionPart, type Recipe, type Reward, rollName, type SheetEntry, type SheetGroup, systemFileName, type SystemSetting, type Threshold, type Travel, type TravelKind, withSettings, } from "./game-system.ts";
1
+ export { type CampaignData, campaignDataNames, findCampaignSystem, findSystem, type GameSystem, type GridRules, installedSystems, type Recipe, type Reward, rollName, type SheetEntry, type SheetGroup, systemFileName, type SystemSetting, type Threshold, type Travel, type TravelKind, withSettings, } from "./game-system.ts";
2
2
  export { type SystemWords, systemWords } from "./words.ts";
@@ -0,0 +1,36 @@
1
+ /** A month of a calendar: its name, how many days it has, and the season it falls in, when the calendar says (TIM-8). */
2
+ export interface CalendarMonth {
3
+ name: string;
4
+ days: number;
5
+ season?: string;
6
+ }
7
+ /** The months of a game's calendar, in order (TIM-8): what shows a game date as a day of a month. */
8
+ export interface Calendar {
9
+ months: CalendarMonth[];
10
+ }
11
+ /** The day 1 of the story in a calendar: the day of a month, the month by its place in the calendar, and the year when one is given (TIM-8). */
12
+ export interface CalendarStart {
13
+ day: number;
14
+ month: number;
15
+ year?: number;
16
+ }
17
+ /** A day of a calendar: the day of its month, the month, its season, and the year when the start gave one. */
18
+ export interface CalendarDay {
19
+ day: number;
20
+ month: string;
21
+ season?: string;
22
+ year?: number;
23
+ }
24
+ /** The core's calendar (D-437): the twelve real months, with the seasons of the northern hemisphere. */
25
+ export declare const realCalendar: Calendar;
26
+ /** The calendar as a system, an extension or campaign.yaml writes it; it throws what is wrong, with how to write it. */
27
+ export declare function readCalendar(value: unknown): Calendar;
28
+ /**
29
+ * When the story starts: day 1, undefined, when only the days are counted; else the day of the calendar that is day 1, written as 14 April or 14 April 1491, with
30
+ * a month of the calendar in any case. It throws what is wrong, with what it takes.
31
+ */
32
+ export declare function readCalendarStart(text: string, calendar: Calendar): CalendarStart | undefined;
33
+ /** The day of the calendar that a game day falls on, counting from the start as day 1; after the last month the first comes again, a year later. */
34
+ export declare function calendarDay(calendar: Calendar, start: CalendarStart, gameDay: number): CalendarDay;
35
+ /** A day of the calendar as it is written: 15 April, spring; 15 April 1491, spring; 15 April when the month has no season. */
36
+ export declare function formatCalendarDay(date: CalendarDay): string;
@@ -0,0 +1,84 @@
1
+ import { z } from "zod";
2
+ import { comparableText } from "../core/text.js";
3
+ /** The core's calendar (D-437): the twelve real months, with the seasons of the northern hemisphere. */
4
+ export const realCalendar = {
5
+ months: [
6
+ ["January", 31, "winter"],
7
+ ["February", 28, "winter"],
8
+ ["March", 31, "spring"],
9
+ ["April", 30, "spring"],
10
+ ["May", 31, "spring"],
11
+ ["June", 30, "summer"],
12
+ ["July", 31, "summer"],
13
+ ["August", 31, "summer"],
14
+ ["September", 30, "autumn"],
15
+ ["October", 31, "autumn"],
16
+ ["November", 30, "autumn"],
17
+ ["December", 31, "winter"],
18
+ ].map(([name, days, season]) => ({ name, days, season })),
19
+ };
20
+ const calendarExample = "months: [{name: January, days: 31, season: winter}, {name: February, days: 28, season: winter}, ...]";
21
+ const calendarSchema = z.object({
22
+ months: z.array(z.object({ name: z.string().trim().min(1), days: z.int().min(1).max(10_000), season: z.string().trim().min(1).optional() }).strict()).min(1),
23
+ }).strict();
24
+ // "14 April" or "14 April 1491": the day, the month's name, which may hold spaces, and the year.
25
+ const startPattern = /^(\d{1,5})\s+(.*?)(?:\s+(-?\d{1,6}))?$/;
26
+ /** The calendar as a system, an extension or campaign.yaml writes it; it throws what is wrong, with how to write it. */
27
+ export function readCalendar(value) {
28
+ const parsed = calendarSchema.safeParse(value);
29
+ if (!parsed.success) {
30
+ throw new Error(`The calendar does not read: ${z.prettifyError(parsed.error).replace(/\s+/g, " ")}. Write it as ${calendarExample}.`);
31
+ }
32
+ const names = parsed.data.months.map((month) => comparableText(month.name));
33
+ const twice = parsed.data.months.find((_, index) => names.indexOf(names[index]) !== index);
34
+ if (twice !== undefined) {
35
+ throw new Error(`The calendar names the month ${twice.name} twice: give each month a name of its own.`);
36
+ }
37
+ return parsed.data;
38
+ }
39
+ /**
40
+ * When the story starts: day 1, undefined, when only the days are counted; else the day of the calendar that is day 1, written as 14 April or 14 April 1491, with
41
+ * a month of the calendar in any case. It throws what is wrong, with what it takes.
42
+ */
43
+ export function readCalendarStart(text, calendar) {
44
+ if (/^day\s+1$/i.test(text.trim())) {
45
+ return undefined;
46
+ }
47
+ const match = startPattern.exec(text.trim().replace(/\s+/g, " "));
48
+ const month = match === null ? -1 : calendar.months.findIndex((candidate) => comparableText(candidate.name) === comparableText(match[2]));
49
+ const names = calendar.months.map((candidate) => candidate.name).join(", ");
50
+ if (match === null || match[2] === "") {
51
+ const first = calendar.months[0].name;
52
+ throw new Error(`"${text}" is not when the story starts: write day 1 to count the days, or a day of the calendar, the year if wanted, such as 14 ${first} or 14 ${first} 1491.`);
53
+ }
54
+ if (month === -1) {
55
+ throw new Error(`The calendar has no month "${match[2]}": its months are ${names}.`);
56
+ }
57
+ const day = Number(match[1]);
58
+ const { name, days } = calendar.months[month];
59
+ if (day < 1 || day > days) {
60
+ throw new Error(`${name} has days 1 to ${days}, not ${day}: give a day it has.`);
61
+ }
62
+ return match[3] === undefined ? { day, month } : { day, month, year: Number(match[3]) };
63
+ }
64
+ /** The day of the calendar that a game day falls on, counting from the start as day 1; after the last month the first comes again, a year later. */
65
+ export function calendarDay(calendar, start, gameDay) {
66
+ const { months } = calendar;
67
+ const yearDays = months.reduce((total, month) => total + month.days, 0);
68
+ const beforeStart = months.slice(0, start.month).reduce((total, month) => total + month.days, 0) + start.day - 1;
69
+ const sinceYearStart = beforeStart + gameDay - 1;
70
+ let left = sinceYearStart % yearDays;
71
+ let index = 0;
72
+ while (left >= months[index].days) {
73
+ left -= months[index].days;
74
+ index += 1;
75
+ }
76
+ const month = months[index];
77
+ const year = start.year === undefined ? {} : { year: start.year + Math.floor(sinceYearStart / yearDays) };
78
+ return { day: left + 1, month: month.name, ...(month.season === undefined ? {} : { season: month.season }), ...year };
79
+ }
80
+ /** A day of the calendar as it is written: 15 April, spring; 15 April 1491, spring; 15 April when the month has no season. */
81
+ export function formatCalendarDay(date) {
82
+ const day = `${date.day} ${date.month}${date.year === undefined ? "" : ` ${date.year}`}`;
83
+ return date.season === undefined ? day : `${day}, ${date.season}`;
84
+ }
@@ -1 +1,2 @@
1
+ export { type Calendar, type CalendarDay, calendarDay, type CalendarMonth, type CalendarStart, formatCalendarDay, readCalendar, readCalendarStart, realCalendar } from "./calendar.ts";
1
2
  export { addDuration, formatDuration, formatGameDate, type GameDate, lastGameDay, minutesBetween, readDuration, readGameDate } from "./game-date.ts";
@@ -1,2 +1,3 @@
1
- // Game time for any game: the date of the story, counted in days from the start of the adventure, and durations. Depends on nothing else in rpg-engine.
1
+ // Game time for any game: the date of the story, counted in days from the start of the adventure, durations, and the calendar that shows a date as a day of a month.
2
+ export { calendarDay, formatCalendarDay, readCalendar, readCalendarStart, realCalendar } from "./calendar.js";
2
3
  export { addDuration, formatDuration, formatGameDate, lastGameDay, minutesBetween, readDuration, readGameDate } from "./game-date.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rpg-engine",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Play a tabletop role-playing game with an AI as your game master: the AI tells the story; RPG Engine remembers the world, rolls the dice and keeps the accounts.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,11 +19,10 @@
19
19
  "systems",
20
20
  "!systems/*/test",
21
21
  "!systems/*/build",
22
- "extensions",
23
22
  "instructions"
24
23
  ],
25
24
  "scripts": {
26
- "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc && tsc -p src/dashboard && node -e \"require('node:fs').cpSync('src/dashboard', 'dist/dashboard', { recursive: true, filter: (path) => !/[.](tsx?|py)$|tsconfig[.]json$/.test(path) })\"",
25
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc && tsc -p src/dashboard && node -e \"require('node:fs').cpSync('src/dashboard', 'dist/dashboard', { recursive: true, filter: (path) => !/[.](tsx?|py)$|tsconfig[.]json$/.test(path) })\" && tsc -p extensions/weather",
27
26
  "dev": "tsc --watch",
28
27
  "demo": "npm run build && node --experimental-strip-types --no-warnings test/demo/dashboard.ts --ask --port 5760",
29
28
  "betasim": "npm run build && node --experimental-strip-types --no-warnings test/betasim/run.ts",
@@ -3,3 +3,4 @@
3
3
  - At difficulty normal, fights run from moderate to high difficulty (XP budget per character); easier or harder as the difficulty says.
4
4
  - A condition or effect that changes a check is rolled in: disadvantage on Athletics is 2d20kl1+athletics, named Athletics alone: the dice say the rest, and why goes in the question.
5
5
  - A roll in brackets: [Persuasion 14 + 3 = 17].
6
+ - Alignment describes a character, it never limits what the player does. When their choices keep going another way, you may say so once in brackets and offer a new alignment; change it only with their yes. It matters in play only where a page says so, as a talisman that only a good creature can attune to.