rpg-engine 0.1.2 → 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 (87) 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/problems.js +3 -1
  25. package/dist/commands/scene.d.ts +3 -3
  26. package/dist/commands/sheet.js +7 -1
  27. package/dist/commands/status.d.ts +1 -0
  28. package/dist/commands/status.js +10 -5
  29. package/dist/commands/travel.js +4 -2
  30. package/dist/commands/validate.js +4 -2
  31. package/dist/commands/view.d.ts +5 -0
  32. package/dist/commands/view.js +3 -1
  33. package/dist/core/context.d.ts +34 -0
  34. package/dist/core/context.js +11 -0
  35. package/dist/core/instruction-parts.d.ts +10 -0
  36. package/dist/core/instruction-parts.js +32 -0
  37. package/dist/core/store.d.ts +2 -0
  38. package/dist/core/store.js +8 -0
  39. package/dist/dashboard/app.js +2 -1
  40. package/dist/dashboard/game-words.js +21 -0
  41. package/dist/dashboard/i18n/ar.json +7 -0
  42. package/dist/dashboard/i18n/cs.json +7 -0
  43. package/dist/dashboard/i18n/da.json +7 -0
  44. package/dist/dashboard/i18n/de.json +7 -0
  45. package/dist/dashboard/i18n/el.json +7 -0
  46. package/dist/dashboard/i18n/es.json +7 -0
  47. package/dist/dashboard/i18n/fi.json +7 -0
  48. package/dist/dashboard/i18n/fr.json +7 -0
  49. package/dist/dashboard/i18n/he.json +7 -0
  50. package/dist/dashboard/i18n/hi.json +7 -0
  51. package/dist/dashboard/i18n/hu.json +7 -0
  52. package/dist/dashboard/i18n/is.json +7 -0
  53. package/dist/dashboard/i18n/it.json +7 -0
  54. package/dist/dashboard/i18n/ja.json +7 -0
  55. package/dist/dashboard/i18n/ko.json +7 -0
  56. package/dist/dashboard/i18n/nb.json +7 -0
  57. package/dist/dashboard/i18n/nl.json +7 -0
  58. package/dist/dashboard/i18n/pl.json +7 -0
  59. package/dist/dashboard/i18n/pt.json +7 -0
  60. package/dist/dashboard/i18n/ro.json +7 -0
  61. package/dist/dashboard/i18n/ru.json +7 -0
  62. package/dist/dashboard/i18n/sv.json +7 -0
  63. package/dist/dashboard/i18n/tr.json +7 -0
  64. package/dist/dashboard/i18n/uk.json +7 -0
  65. package/dist/dashboard/i18n/zh.json +7 -0
  66. package/dist/dashboard/icons.js +1 -0
  67. package/dist/dashboard/top.js +5 -5
  68. package/dist/extensions/api.d.ts +73 -0
  69. package/dist/extensions/api.js +1 -0
  70. package/dist/extensions/extension.d.ts +43 -0
  71. package/dist/extensions/extension.js +113 -0
  72. package/dist/extensions/index.d.ts +3 -0
  73. package/dist/extensions/index.js +2 -0
  74. package/dist/extensions/packages.d.ts +11 -0
  75. package/dist/extensions/packages.js +141 -0
  76. package/dist/index.d.ts +1 -0
  77. package/dist/mcp-server.js +50 -4
  78. package/dist/systems/game-system.d.ts +1 -5
  79. package/dist/systems/game-system.js +6 -31
  80. package/dist/systems/index.d.ts +1 -1
  81. package/dist/time/calendar.d.ts +36 -0
  82. package/dist/time/calendar.js +84 -0
  83. package/dist/time/index.d.ts +1 -0
  84. package/dist/time/index.js +2 -1
  85. package/package.json +2 -3
  86. package/systems/5e/instructions/play.md +1 -0
  87. package/systems/5e/system.yaml +2 -0
package/README.md CHANGED
@@ -77,7 +77,7 @@ A campaign is a folder of markdown pages with `[[links]]`, the format of Obsidia
77
77
 
78
78
  RPG Engine stays in that folder: it reads and writes the game only there, and never touches your other files. Outside it, it keeps only a data folder of its own (the dashboard's translations, and Codex or Claude Code if you let it install them) and temporary folders while a picture is drawn. The master plays through RPG Engine's tools; anything else your agent wants to do on your computer, it asks you first.
79
79
 
80
- For developers: [the architecture](https://github.com/stefanocaronia/rpg-engine/blob/main/docs/architecture.md), [the commands](https://github.com/stefanocaronia/rpg-engine/blob/main/docs/commands.md), [game systems](https://github.com/stefanocaronia/rpg-engine/blob/main/docs/game-systems.md) and [the guide for development agents](https://github.com/stefanocaronia/rpg-engine/blob/main/AGENTS.md).
80
+ For developers: [the architecture](https://github.com/stefanocaronia/rpg-engine/blob/main/docs/architecture.md), [the commands](https://github.com/stefanocaronia/rpg-engine/blob/main/docs/commands.md), [game systems](https://github.com/stefanocaronia/rpg-engine/blob/main/docs/game-systems.md), [extensions](https://github.com/stefanocaronia/rpg-engine/blob/main/docs/extensions.md) and [the guide for development agents](https://github.com/stefanocaronia/rpg-engine/blob/main/AGENTS.md).
81
81
 
82
82
  ## License
83
83
 
@@ -85,6 +85,8 @@ The code is under the [MIT](https://github.com/stefanocaronia/rpg-engine/blob/ma
85
85
 
86
86
  The 5e system, in `systems/5e/`, is under the Creative Commons Attribution 4.0 International License ([its license](https://github.com/stefanocaronia/rpg-engine/blob/main/systems/5e/LICENSE.md)): This work includes material taken from the System Reference Document 5.1 ("SRD 5.1") by Wizards of the Coast LLC and available at https://dnd.wizards.com/resources/systems-reference-document. The SRD 5.1 is licensed under the Creative Commons Attribution 4.0 International License available at https://creativecommons.org/licenses/by/4.0/legalcode. Its creatures' icons are from game-icons.net, under the Creative Commons Attribution 3.0 Unported License, by the authors its license names. rpg-engine is compatible with fifth edition.
87
87
 
88
+ The weather extension, in `extensions/weather/` and published apart as `@rpgengine/weather`, is Weather by the climate score, by Stefano Caronia, CC BY 4.0, with its code under MIT ([its license](https://github.com/stefanocaronia/rpg-engine/blob/main/extensions/weather/LICENSE.md)).
89
+
88
90
  rpg-engine ships only original or open-licensed content: for fifth edition, the SRD 5.1 under CC BY 4.0. Anything else that appears in your game is written by your AI or by you, as pages of your campaign on your computer: it is not part of rpg-engine, and we do not distribute it.
89
91
 
90
92
  The tests use a system based on Ironsworn, with the names of its mechanics and a foe of our own: This work is based on Ironsworn (https://www.ironswornrpg.com), created by Shawn Tomkin, and licensed for our use under the Creative Commons Attribution 4.0 International License (https://creativecommons.org/licenses/by/4.0/).
@@ -1,5 +1,5 @@
1
1
  export { createCampaign } from "./create-campaign.ts";
2
2
  export { campaignFileName, findCampaign, houseRulesFolderName, requireCampaign } from "./find-campaign.ts";
3
3
  export { hostFileNames, refreshHostFiles } from "./host-files.ts";
4
- export { type CampaignSettings, changeListSetting, changeListSettingToNone, changeMapSetting, changeOtherSetting, changeSetting, checkSettingName, checkSettings, clearSetting, companionWays, diceWays, difficulties, lethalities, listSettingNames, mapSettingNames, mentorWays, missingSettings, pictureWays, preparations, proseWays, readCampaignData, readCoinsSetting, readListSetting, readOneSetting, readSettings, readTextSetting, rigors, saveModes, settingMeaning, type SettingName, settingNames, setupSettingNames, storyWays, styleTextLengths, unansweredSettings, unitSystems, } from "./settings.ts";
4
+ export { type CampaignSettings, changeExtensions, changeListSetting, changeListSettingToNone, changeMapSetting, changeOtherSetting, changeSetting, checkSettingName, checkSettings, clearSetting, companionWays, diceWays, difficulties, lethalities, listSettingNames, mapSettingNames, mentorWays, missingSettings, pictureWays, preparations, proseWays, readCampaignData, readCoinsSetting, readListSetting, readOneSetting, readSettings, readTextSetting, rigors, saveModes, settingMeaning, type SettingName, settingNames, setupSettingNames, storyWays, styleTextLengths, unansweredSettings, unitSystems, } from "./settings.ts";
5
5
  export { type CampaignState, changeState, changeStateAt, readState, readStateValues } from "./state.ts";
@@ -2,5 +2,5 @@
2
2
  export { createCampaign } from "./create-campaign.js";
3
3
  export { campaignFileName, findCampaign, houseRulesFolderName, requireCampaign } from "./find-campaign.js";
4
4
  export { hostFileNames, refreshHostFiles } from "./host-files.js";
5
- export { changeListSetting, changeListSettingToNone, changeMapSetting, changeOtherSetting, changeSetting, checkSettingName, checkSettings, clearSetting, companionWays, diceWays, difficulties, lethalities, listSettingNames, mapSettingNames, mentorWays, missingSettings, pictureWays, preparations, proseWays, readCampaignData, readCoinsSetting, readListSetting, readOneSetting, readSettings, readTextSetting, rigors, saveModes, settingMeaning, settingNames, setupSettingNames, storyWays, styleTextLengths, unansweredSettings, unitSystems, } from "./settings.js";
5
+ export { changeExtensions, changeListSetting, changeListSettingToNone, changeMapSetting, changeOtherSetting, changeSetting, checkSettingName, checkSettings, clearSetting, companionWays, diceWays, difficulties, lethalities, listSettingNames, mapSettingNames, mentorWays, missingSettings, pictureWays, preparations, proseWays, readCampaignData, readCoinsSetting, readListSetting, readOneSetting, readSettings, readTextSetting, rigors, saveModes, settingMeaning, settingNames, setupSettingNames, storyWays, styleTextLengths, unansweredSettings, unitSystems, } from "./settings.js";
6
6
  export { changeState, changeStateAt, readState, readStateValues } from "./state.js";
@@ -102,6 +102,7 @@ export declare const settingsSchema: z.ZodObject<{
102
102
  "made by the master": "made by the master";
103
103
  "met in play": "met in play";
104
104
  }>>;
105
+ "calendar-start": z.ZodOptional<z.ZodString>;
105
106
  pictures: z.ZodOptional<z.ZodPreprocess<z.ZodEnum<{
106
107
  none: "none";
107
108
  "on request": "on request";
@@ -113,6 +114,7 @@ export declare const settingsSchema: z.ZodObject<{
113
114
  precedents: z.ZodOptional<z.ZodNullable<z.ZodPreprocess<z.ZodArray<z.ZodPreprocess<z.ZodString, unknown>>, unknown>>>;
114
115
  learned: z.ZodOptional<z.ZodNullable<z.ZodPreprocess<z.ZodArray<z.ZodPreprocess<z.ZodString, unknown>>, unknown>>>;
115
116
  coins: z.ZodOptional<z.ZodUnknown>;
117
+ calendar: z.ZodOptional<z.ZodUnknown>;
116
118
  fields: z.ZodOptional<z.ZodUnknown>;
117
119
  tables: z.ZodOptional<z.ZodUnknown>;
118
120
  computed: z.ZodOptional<z.ZodUnknown>;
@@ -129,7 +131,7 @@ export declare const settingNames: SettingName[];
129
131
  export declare const listSettingNames: SettingName[];
130
132
  /** The settings that hold entries by name, what the campaign adds to its game system (CAM-1): given or removed one entry at a time. */
131
133
  export declare const mapSettingNames: SettingName[];
132
- /** What only the setup asks (D-241, MOD-3, D-347): how much the master teaches the game, how the companions come, and the lines and veils, which "none" answers too. */
134
+ /** What only the setup asks (D-241, MOD-3, D-347): how much the master teaches the game, how the companions come, when the story starts, and the lines and veils, which "none" answers too. */
133
135
  export declare const setupSettingNames: SettingName[];
134
136
  /** What the setup asks only of a campaign without a written world (D-79, D-80, MOD-3). */
135
137
  export declare const premiseSettingNames: SettingName[];
@@ -163,6 +165,8 @@ export declare function changeListSetting(root: string, name: string, change: {
163
165
  }): boolean;
164
166
  /** Answers a list setting with none (MOD-3): an empty list, refused while it holds items, which are removed one by one. Returns whether it changed. */
165
167
  export declare function changeListSettingToNone(root: string, name: string): boolean;
168
+ /** Writes the extensions the campaign uses, by package with the version each was added with (D-27), keeping the rest of campaign.yaml; none takes the key away. */
169
+ export declare function changeExtensions(root: string, extensions: Record<string, string>): void;
166
170
  /** What campaign.yaml adds to the game system, as it writes it, read even when another setting breaks the file (CAM-1); empty when it cannot be read. */
167
171
  export declare function readCampaignData(root: string): Record<string, unknown>;
168
172
  /**
@@ -104,6 +104,8 @@ export const settingsSchema = z.object({
104
104
  dice: z.enum(diceWays).optional().describe("the player character's dice: digital (rpg rolls them) or physical (the player rolls their own and tells the values)"),
105
105
  units: z.enum(unitSystems).optional().describe("the units of measure of the story: metric or imperial"),
106
106
  companions: z.enum(companionWays).optional().describe("how the companions come: none, made with the player or made by the master in session zero, or met in play"),
107
+ // Checked by the time module against the calendar (TIM-8).
108
+ "calendar-start": z.string().min(1).optional().describe("when the story starts: day 1 to count only the days, or the day of the world's calendar that is day 1, such as 14 April 1491"),
107
109
  // new places and new places and quests, as campaigns wrote it before quests and then those met had pictures, are read as the value that took their place (D-388, D-420).
108
110
  pictures: z.preprocess((value) => (value === "new places" || value === "new places and quests" ? "new elements" : value), z.enum(pictureWays)).optional().describe("the pictures of places, quests and those met the engine has made on this computer, which spend the player's plan, Codex's or Claude's: none, on request (those the player asks for) "
109
111
  + "or new elements (one for each new place and quest, and for each character and kind of creature the character meets)"),
@@ -114,6 +116,8 @@ export const settingsSchema = z.object({
114
116
  learned: listSetting.describe("the game's mechanics the master has explained, by their names in the system's language: explained again only when the player gets one wrong"),
115
117
  // Checked by the money module (MON-1): coins written wrongly by hand must not stop the other settings from being read.
116
118
  coins: z.unknown().optional().describe("the coins, for a game with money: each with its value in the smallest coin, such as gp 100, sp 10, cp 1"),
119
+ // Checked by the time module (TIM-8): a mistake there never stops the game, whose date stays day N.
120
+ calendar: z.unknown().optional().describe("the months of the campaign's own calendar, in place of the real ones and an extension's: months: [{name: January, days: 31, season: winter}, ...]"),
117
121
  // What the campaign adds to its game system (CAM-1): checked by the systems module when it reads the system with them, so that a mistake there never hides the
118
122
  // other settings.
119
123
  fields: z.unknown().optional().describe("fields the campaign adds to its game system, by name with their kind, such as portent: rolls"),
@@ -130,15 +134,15 @@ export const settingNames = Object.keys(settingsSchema.shape);
130
134
  export const listSettingNames = ["lines", "veils", "table", "precedents", "learned", "status-line"];
131
135
  /** The settings that hold entries by name, what the campaign adds to its game system (CAM-1): given or removed one entry at a time. */
132
136
  export const mapSettingNames = ["fields", "tables", "computed", "counters", "recipes", "travel"];
133
- /** What only the setup asks (D-241, MOD-3, D-347): how much the master teaches the game, how the companions come, and the lines and veils, which "none" answers too. */
134
- export const setupSettingNames = ["mentor", "companions", "lines", "veils"];
137
+ /** What only the setup asks (D-241, MOD-3, D-347): how much the master teaches the game, how the companions come, when the story starts, and the lines and veils, which "none" answers too. */
138
+ export const setupSettingNames = ["mentor", "companions", "calendar-start", "lines", "veils"];
135
139
  /** What the setup asks only of a campaign without a written world (D-79, D-80, MOD-3). */
136
140
  export const premiseSettingNames = ["premise", "preparation"];
137
141
  // Settings that only some games have, or that only the setup asks: never asked for in play when missing.
138
142
  // The pictures: status asks for them once, only where they can be made (D-308).
139
143
  // How the master writes: the core's own until the player chooses (D-395).
140
144
  const styleSettingNames = ["prose", "story", "author", "style"];
141
- const optionalSettingNames = ["coins", "pictures", ...mapSettingNames, ...setupSettingNames, ...premiseSettingNames, ...styleSettingNames];
145
+ const optionalSettingNames = ["coins", "pictures", "calendar", "calendar-start", ...mapSettingNames, ...setupSettingNames, ...premiseSettingNames, ...styleSettingNames];
142
146
  export function readSettings(root) {
143
147
  return validateSettings(readYamlValues(join(root, campaignFileName), settingsHold));
144
148
  }
@@ -270,6 +274,17 @@ export function changeListSettingToNone(root, name) {
270
274
  saveSettings(root, document);
271
275
  return true;
272
276
  }
277
+ /** Writes the extensions the campaign uses, by package with the version each was added with (D-27), keeping the rest of campaign.yaml; none takes the key away. */
278
+ export function changeExtensions(root, extensions) {
279
+ const document = readSettingsDocument(root);
280
+ if (Object.keys(extensions).length === 0) {
281
+ document.delete("extensions");
282
+ }
283
+ else {
284
+ document.set("extensions", document.createNode(extensions, { flow: false }));
285
+ }
286
+ saveSettings(root, document);
287
+ }
273
288
  /** What campaign.yaml adds to the game system, as it writes it, read even when another setting breaks the file (CAM-1); empty when it cannot be read. */
274
289
  export function readCampaignData(root) {
275
290
  try {
@@ -1,18 +1,22 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { z } from "zod";
3
+ import { findCampaign } from "./campaign/index.js";
4
+ import { extensionCommands } from "./commands/game-extensions.js";
3
5
  import { commands } from "./commands/index.js";
4
- import { defaultContext } from "./core/context.js";
6
+ import { defaultContext, packagesFolder } from "./core/context.js";
5
7
  import { baseType, isBoolean, isList } from "./core/registry.js";
8
+ import { FileStore, withFiles } from "./core/store.js";
6
9
  import { firstSentence } from "./core/text.js";
7
10
  import { getVersion } from "./core/version.js";
11
+ import { npmPackages } from "./extensions/index.js";
8
12
  import { hostPictures } from "./pictures/index.js";
9
13
  // The one command that exists only on the command line: cli.ts starts the server when it comes alone.
10
14
  const mcpDescription = "Start the MCP server for an AI host. Through it the host uses these commands as tools; the host starts it, with no options.";
11
15
  /** The `rpg` command line: finds the command, validates its input, runs it and renders the result. */
12
- export async function runCommandLine(argv, context = { ...defaultContext(), pictures: hostPictures(() => undefined) }) {
16
+ export async function runCommandLine(argv, context = { ...defaultContext(), pictures: hostPictures(() => undefined), packages: npmPackages(packagesFolder()), terminal: true }) {
13
17
  const [commandName, ...args] = argv;
14
18
  if (commandName === undefined || commandName === "--help" || commandName === "-h") {
15
- return success(generalHelp());
19
+ return success(generalHelp(await campaignCommands(context)));
16
20
  }
17
21
  if (commandName === "--version" || commandName === "-v") {
18
22
  return success(getVersion());
@@ -20,9 +24,10 @@ export async function runCommandLine(argv, context = { ...defaultContext(), pict
20
24
  if (commandName === "mcp") {
21
25
  return success(`rpg mcp\n\n${mcpDescription}`);
22
26
  }
23
- const command = commands.find((candidate) => candidate.name === commandName);
27
+ const own = commands.some((candidate) => candidate.name === commandName) ? [] : await campaignCommands(context);
28
+ const command = [...commands, ...own].find((candidate) => candidate.name === commandName);
24
29
  if (!command) {
25
- return failure(`Unknown command "${commandName}".\n\n${generalHelp()}`);
30
+ return failure(`Unknown command "${commandName}".\n\n${generalHelp(own)}`);
26
31
  }
27
32
  if (command.needsPlayer) {
28
33
  return failure(`${command.name} works only in an AI app that shows the player a form; here, ask the player in words.`);
@@ -103,9 +108,21 @@ function checkRepeatedOptions(tokens, options) {
103
108
  function inputFields(command) {
104
109
  return Object.entries(command.input.shape);
105
110
  }
106
- /** The commands in two groups, each with the first sentence of its description. */
107
- function generalHelp() {
108
- const width = Math.max(...commands.map((command) => command.name.length));
111
+ /** The commands of the extensions of the campaign in the folder, if there is one (D-63): none where they do not load, which status says. */
112
+ async function campaignCommands(context) {
113
+ try {
114
+ return await withFiles(context.files ?? new FileStore(context.systemFolders), async () => {
115
+ const root = findCampaign(context.folder);
116
+ return root === undefined ? [] : (await extensionCommands(root, context, commands.map((command) => command.name))).commands;
117
+ });
118
+ }
119
+ catch {
120
+ return [];
121
+ }
122
+ }
123
+ /** The commands in two groups, each with the first sentence of its description, and those of the campaign's extensions. */
124
+ function generalHelp(own) {
125
+ const width = Math.max(...[...commands, ...own].map((command) => command.name.length));
109
126
  const line = (name, description) => ` ${name.padEnd(width)} ${firstSentence(description)}`;
110
127
  const groupLines = (group) => commands.filter((command) => command.group === group && !command.needsPlayer).map((command) => line(command.name, command.description));
111
128
  return [
@@ -118,6 +135,7 @@ function generalHelp() {
118
135
  "Game:",
119
136
  ...groupLines("game"),
120
137
  "",
138
+ ...(own.length === 0 ? [] : ["The campaign's extensions:", ...own.map((command) => line(command.name, command.description)), ""]),
121
139
  "Run `rpg <command> --help` for its options.",
122
140
  ].join("\n");
123
141
  }
@@ -3,8 +3,9 @@ import { changeState, requireCampaign } from "../campaign/index.js";
3
3
  import { appendLogEntry } from "../core/log.js";
4
4
  import { defineCommand } from "../core/registry.js";
5
5
  import { addDuration, formatDuration, formatGameDate, lastGameDay, minutesBetween, readDuration, readGameDate } from "../time/index.js";
6
- import { nextAfter, passedLines, passTime, unreadNotes } from "./game-advance.js";
6
+ import { calendarText, nextAfter, passedLines, passTime, unreadNotes } from "./game-advance.js";
7
7
  import { dueEvents, dueText, isDated, plannedEvents } from "./game-events.js";
8
+ import { timePassedLines } from "./game-extensions.js";
8
9
  import { newDatedLogEntry, presentDate } from "./game-time.js";
9
10
  import { campaignWorld } from "./game-world.js";
10
11
  export const advance = defineCommand({
@@ -19,7 +20,7 @@ export const advance = defineCommand({
19
20
  to: z.string().optional().describe("the game date to reach, such as day 3, 06:00 (day 3 alone is its midnight); the first one sets when play starts, such as day 1, 18:00"),
20
21
  why: z.string().optional().describe("what the time is spent on"),
21
22
  }),
22
- run(input, context) {
23
+ async run(input, context) {
23
24
  const root = requireCampaign(context.folder);
24
25
  const request = readRequest(input);
25
26
  const now = presentDate(root);
@@ -33,7 +34,23 @@ export const advance = defineCommand({
33
34
  changeState(root, { date: start });
34
35
  appendLogEntry(root, newDatedLogEntry(root, context, "time-advanced", "public", { to: start, why }));
35
36
  const next = nextAfter(plannedEvents(world).filter(isDated), request.to);
36
- return { to: start, passed: 0, wanted: 0, due: [], stillDue: dueEvents(world, request.to).map(dueText), next, ended: [], newDays: 0, clocks: [], newDayPart: "", ...unreadNotes(world) };
37
+ const calendar = calendarText(root, context, request.to);
38
+ const extensionLines = await timePassedLines(root, context, request.to, request.to);
39
+ return {
40
+ to: start,
41
+ passed: 0,
42
+ wanted: 0,
43
+ due: [],
44
+ stillDue: dueEvents(world, request.to).map(dueText),
45
+ next,
46
+ ended: [],
47
+ newDays: 0,
48
+ clocks: [],
49
+ newDayPart: "",
50
+ calendar,
51
+ extensionLines,
52
+ ...unreadNotes(world),
53
+ };
37
54
  }
38
55
  const end = "by" in request ? addDuration(now, request.by) : request.to;
39
56
  if (end.day > lastGameDay) {
@@ -43,7 +60,8 @@ export const advance = defineCommand({
43
60
  if (wanted < 0) {
44
61
  throw new Error(`${formatGameDate(end)} is before now, ${formatGameDate(now)}: time never goes back.`);
45
62
  }
46
- return passTime(root, context, world, now, wanted, why, input.by ?? input.to ?? "");
63
+ const passed = passTime(root, context, world, now, wanted, why, input.by ?? input.to ?? "");
64
+ return passed.passed === 0 ? passed : { ...passed, extensionLines: await timePassedLines(root, context, now, addDuration(now, passed.passed)) };
47
65
  },
48
66
  format(result) {
49
67
  const rest = result.wanted - result.passed;
@@ -70,11 +88,12 @@ function readRequest(input) {
70
88
  }
71
89
  /** The first line: where time went, and where it stopped short of what was asked. */
72
90
  function movedLine(result, rest) {
91
+ const to = result.calendar === undefined ? result.to : `${result.to} (${result.calendar})`;
73
92
  if (result.from === undefined) {
74
- return `The game starts on ${result.to}.`;
93
+ return `The game starts on ${to}.`;
75
94
  }
76
95
  if (result.passed === 0) {
77
- return `Nothing changed: it is already ${result.to}.`;
96
+ return `Nothing changed: it is already ${to}.`;
78
97
  }
79
- return `${result.from} → ${result.to}${rest > 0 ? `: stopped after ${formatDuration(result.passed)} of ${formatDuration(result.wanted)}` : ""}.`;
98
+ return `${result.from} → ${to}${rest > 0 ? `: stopped after ${formatDuration(result.passed)} of ${formatDuration(result.wanted)}` : ""}.`;
80
99
  }
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import type { Context, Rows, Said } from "../core/context.ts";
2
3
  type InWords = {
3
4
  kind: "unanswered" | "unavailable" | "absent" | "physical";
4
5
  asked: string;
@@ -30,4 +31,9 @@ export declare const ask: import("../core/registry.ts").Command<z.ZodObject<{
30
31
  who: z.ZodOptional<z.ZodString>;
31
32
  square: z.ZodOptional<z.ZodBoolean>;
32
33
  }, z.core.$strip>, AskResult>;
34
+ /**
35
+ * The player's answer: on the dashboard's page while one is open, else in the host's form, if it shows one (ASK-1, D-279). A form that does not show, while
36
+ * the dashboard runs, is only absent this time: a page may open.
37
+ */
38
+ export declare function chooseAnswer(context: Context, question: string, title: string, labels: string[], rows?: Rows): Promise<number | Said | undefined | "unavailable" | "absent">;
33
39
  export {};
@@ -100,7 +100,7 @@ export const ask = defineCommand({
100
100
  /** The buttons of a roll: the checks and a change of mind (ASK-3, ASK-4). The chosen check is rolled with the engine's dice and logged as the player's roll. */
101
101
  async function rollChosen(root, context, question, checks, who, words) {
102
102
  const labels = [...checks.map((check) => `${words.roll}: ${check.label} (${check.notation})`), words.change];
103
- const chosen = await choose(context, question, words.roll, labels, { who, fields: [...checks.map((check) => check.field ?? null), null] });
103
+ const chosen = await chooseAnswer(context, question, words.roll, labels, { who, fields: [...checks.map((check) => check.field ?? null), null] });
104
104
  const asked = askedText(question, "checks", checks);
105
105
  // A call the user stopped logs nothing (ASK-9).
106
106
  if (chosen === "absent" || context.signal?.aborted === true) {
@@ -172,7 +172,7 @@ function standingOn(world, who) {
172
172
  /** The buttons of a forced choice: the answers as given (ASK-5). */
173
173
  async function answer(root, context, question, options, words) {
174
174
  const labels = options.map((option) => option.label);
175
- const chosen = await choose(context, question, words.choice, labels);
175
+ const chosen = await chooseAnswer(context, question, words.choice, labels);
176
176
  const asked = askedText(question, "answers", options);
177
177
  if (chosen === "absent" || context.signal?.aborted === true) {
178
178
  return { kind: chosen === "absent" ? "absent" : "unanswered", asked };
@@ -203,7 +203,7 @@ function askedText(question, what, options) {
203
203
  * The player's answer: on the dashboard's page while one is open, else in the host's form, if it shows one (ASK-1, D-279). A form that does not show, while
204
204
  * the dashboard runs, is only absent this time: a page may open.
205
205
  */
206
- async function choose(context, question, title, labels, rows) {
206
+ export async function chooseAnswer(context, question, title, labels, rows) {
207
207
  const onPage = context.page === undefined ? "absent" : await context.page.choose(question, title, labels, context.signal, rows);
208
208
  if (onPage !== "absent" || context.player === undefined) {
209
209
  return onPage;
@@ -11,10 +11,11 @@ import { coinList, readAmount, readCoins } from "../money/index.js";
11
11
  import { declaredKind } from "../pages/index.js";
12
12
  import { claudeSays, codexSays } from "../pictures/index.js";
13
13
  import { campaignDataNames, findCampaignSystem, findSystem, installedSystems, systemFileName } from "../systems/index.js";
14
+ import { readCalendar, readCalendarStart } from "../time/index.js";
14
15
  import { campaignNote } from "./game-mode.js";
15
16
  import { campaignCoins, coinsShown } from "./game-money.js";
16
17
  import { readOpenScene } from "./game-scene.js";
17
- import { newDatedLogEntry } from "./game-time.js";
18
+ import { campaignCalendar, newDatedLogEntry } from "./game-time.js";
18
19
  import { campaignSystem, campaignWorld, installedSystemName, systemSetting, systemSettingValue, valuesText } from "./game-world.js";
19
20
  import { mentorPart, stylePart } from "./parts.js";
20
21
  // A use whose maximum reads what gives it, in quotes for its commas (CAM-1).
@@ -100,10 +101,14 @@ export const config = defineCommand({
100
101
  else if (input.setting !== undefined && input.value !== undefined && changeSetting(root, input.setting, settingValue(root, input.setting, input.value, context))) {
101
102
  appendLogEntry(root, newDatedLogEntry(root, context, "config-changed", "public", { setting: input.setting, value: input.value }));
102
103
  }
104
+ // New months may leave the day the story starts on without its month (TIM-8): said at once, not at the next date.
105
+ if (input.setting?.trim() === "calendar" && input.value !== undefined) {
106
+ replaced = [...replaced, ...campaignCalendar(root, context).problems.map((problem) => `${problem.message.replace(/\.$/, "")}: ${problem.fix ?? "fix it"}.`)];
107
+ }
103
108
  const settings = readSettings(root);
104
109
  // Listed all together, what the campaign adds to its system only when it adds something.
105
110
  const added = (name) => campaignDataNames.includes(name);
106
- const listed = input.setting === undefined ? shown.filter((name) => !added(name) || settings[name] !== undefined) : shown;
111
+ const listed = input.setting === undefined ? shown.filter((name) => !(added(name) || name === "calendar") || settings[name] !== undefined) : shown;
107
112
  const system = input.setting === undefined ? (campaignSystem(root, context)?.settings ?? []) : [];
108
113
  // The master's own change of the mentor brings its part, once in the chat; the player's comes with the news of the dashboard (D-347).
109
114
  const changed = input.value !== undefined && context.actor !== "player" ? input.setting?.trim() : undefined;
@@ -127,7 +132,7 @@ export const config = defineCommand({
127
132
  },
128
133
  });
129
134
  // The settings of free words the player may leave unset again, with the value none, and all those of how the master writes (D-395).
130
- const freeSettingNames = ["author", "style"];
135
+ const freeSettingNames = ["author", "style", "calendar"];
131
136
  const styleSettingNames = ["prose", "story", "author", "style"];
132
137
  /** The settings the player changes on the dashboard (D-341): how the game plays for them; the master's own, as house rules, coins and precedents, stay in the chat. */
133
138
  export const playerSettingNames = ["difficulty", "lethality", "saves", "rigor", "mentor", "learned", "prose", "story", "author", "style", "dice", "units", "pictures", "lines", "veils", "language"];
@@ -418,8 +423,30 @@ function shownValue(root, context, settings, name) {
418
423
  }
419
424
  /** A setting's value as config writes it: an installed system by the name it is installed under (D-167), the coins read and checked (MON-1), anything else as given. */
420
425
  function settingValue(root, setting, value, context) {
426
+ if (setting === "calendar") {
427
+ const read = yamlValue(value, "the calendar", "months: [{name: January, days: 31, season: winter}, ...]");
428
+ try {
429
+ return readCalendar(read);
430
+ }
431
+ catch (error) {
432
+ throw new Error(`${error instanceof Error ? error.message : String(error)} Nothing changed.`);
433
+ }
434
+ }
435
+ if (setting === "calendar-start") {
436
+ return calendarStartValue(root, context, value);
437
+ }
421
438
  return setting === "coins" ? newCoins(root, value, context) : setting === "system" ? installedSystemName(value, context, "config") : value;
422
439
  }
440
+ /** When the story starts, day 1 or a day of the campaign's calendar (TIM-8), checked and written as given. */
441
+ function calendarStartValue(root, context, value) {
442
+ try {
443
+ readCalendarStart(value, campaignCalendar(root, context).calendar);
444
+ }
445
+ catch (error) {
446
+ throw new Error(`${error instanceof Error ? error.message : String(error)} Nothing changed.`);
447
+ }
448
+ return value.trim().replace(/\s+/g, " ");
449
+ }
423
450
  /** The system as config shows it: what it is and which version brings it (D-173); missing or not installed, with those that are (D-167). */
424
451
  function systemShown(system, context) {
425
452
  const installed = `installed: ${installedSystems(context.systemFolders).map((installedSystem) => installedSystem.name).join(", ") || "none"}`;
@@ -462,18 +489,21 @@ function formatValue(value) {
462
489
  }
463
490
  /** The entries given to a setting that holds them, read as YAML, such as "superiority-dice: {max: 4, refill: short rest}" (CAM-1). */
464
491
  function entriesOf(setting, text) {
465
- let value;
466
- try {
467
- value = parse(text);
468
- }
469
- catch (error) {
470
- throw new Error(`"${text}" does not read: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}. Write the entries as in system.yaml, such as name: value. Nothing changed.`);
471
- }
492
+ const value = yamlValue(text, "the entries", "name: value");
472
493
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
473
494
  throw new Error(`${setting} takes entries by name, written as in system.yaml, such as ${setting === "counters" ? `'${counterExample}'` : '"name: value"'}. Nothing changed.`);
474
495
  }
475
496
  return value;
476
497
  }
498
+ /** A value given as YAML text, read; what does not read says how to write it. */
499
+ function yamlValue(text, what, example) {
500
+ try {
501
+ return parse(text);
502
+ }
503
+ catch (error) {
504
+ throw new Error(`"${text}" does not read: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}. Write ${what} as in system.yaml, such as ${example}. Nothing changed.`);
505
+ }
506
+ }
477
507
  /**
478
508
  * "counters channel-divinity takes the place of the system 5e's {max: …, refill: short rest}": what an entry given in place of one of the system's leaves out,
479
509
  * said so that nothing is lost unseen (CAM-2). A recipe adds to the system's and replaces nothing.
@@ -28,6 +28,10 @@ export interface TimePassed {
28
28
  newDays: number;
29
29
  clocks: string[];
30
30
  newDayPart: string;
31
+ /** The day of the calendar reached, when the campaign has one (TIM-8): 15 April, spring. */
32
+ calendar?: string;
33
+ /** What the campaign's extensions said of the time passed, such as the weather of a new morning (D-436). */
34
+ extensionLines?: string[];
31
35
  }
32
36
  /**
33
37
  * Lets `wanted` minutes pass from `now` (TIM-5), stopping at the first planned event whose date comes (TIM-6): writes the new date and a public line with `why`,
@@ -44,6 +48,8 @@ export declare function unreadNotes(world: World): {
44
48
  unreadable: string[];
45
49
  skipped: string[];
46
50
  };
51
+ /** The day of the calendar a date falls on, as outputs write it after the date: 15 April, spring; undefined without a calendar (TIM-8). */
52
+ export declare function calendarText(root: string, context: Context, date: GameDate): string | undefined;
47
53
  /** The first events after `date`: all those at the same moment. */
48
54
  export declare function nextAfter(events: DatedEvent[], date: GameDate): string | undefined;
49
55
  /** "Ettore: light: dark (Cripta)": what holds around the player character, for rules that count the hours spent there (ENV-5); undefined when nothing does. */
@@ -2,12 +2,12 @@
2
2
  import { changeState } from "../campaign/index.js";
3
3
  import { appendLogEntry } from "../core/log.js";
4
4
  import { isEmptyField } from "../pages/index.js";
5
- import { addDuration, formatGameDate, minutesBetween } from "../time/index.js";
5
+ import { addDuration, formatCalendarDay, formatGameDate, minutesBetween } from "../time/index.js";
6
6
  import { endedByDate, endEffects } from "./game-effects.js";
7
7
  import { surroundings, surroundingsText } from "./game-environment.js";
8
8
  import { clocksToMove, dueAdvice, dueEvents, dueText, isDated, plannedEvents, plannedText } from "./game-events.js";
9
9
  import { readOpenScene } from "./game-scene.js";
10
- import { newDatedLogEntry } from "./game-time.js";
10
+ import { calendarDayOf, newDatedLogEntry } from "./game-time.js";
11
11
  import { campaignSystem, campaignWorld } from "./game-world.js";
12
12
  import { shortList, skippedPagesNote } from "./notes.js";
13
13
  import { situationPart } from "./parts.js";
@@ -34,6 +34,7 @@ export function passTime(root, context, world, now, wanted, why, requested) {
34
34
  openScene: passed >= sceneReminderMinutes ? openSceneText(root) : undefined,
35
35
  newDays: reached.day - now.day,
36
36
  clocks: reached.day > now.day ? clocksToMove(world, reached) : [],
37
+ calendar: calendarText(root, context, reached),
37
38
  ...unreadNotes(world),
38
39
  };
39
40
  if (passed > 0) {
@@ -61,6 +62,7 @@ export function passedLines(result, then) {
61
62
  result.around === undefined ? "" : `Around ${result.around}.`,
62
63
  clocksLine(result.newDays, result.to, result.clocks),
63
64
  result.newDayPart,
65
+ ...(result.extensionLines ?? []),
64
66
  result.unreadable.length === 0 ? "" : `Time does not stop at these planned events, whose date is not a game date: ${result.unreadable.join(" · ")}. Give each one a game date with write.`,
65
67
  skippedPagesNote(result.skipped),
66
68
  ].filter((line) => line !== "");
@@ -70,6 +72,11 @@ export function unreadNotes(world) {
70
72
  const events = plannedEvents(world);
71
73
  return { unreadable: events.filter((event) => !isDated(event) && !isEmptyField(event.page.fields.date)).map((event) => event.page.name), skipped: world.problems };
72
74
  }
75
+ /** The day of the calendar a date falls on, as outputs write it after the date: 15 April, spring; undefined without a calendar (TIM-8). */
76
+ export function calendarText(root, context, date) {
77
+ const day = calendarDayOf(root, context, date.day);
78
+ return day === undefined ? undefined : formatCalendarDay(day);
79
+ }
73
80
  /** The first events after `date`: all those at the same moment. */
74
81
  export function nextAfter(events, date) {
75
82
  const next = events.find((event) => minutesBetween(date, event.date) > 0);
@@ -0,0 +1,27 @@
1
+ import type { Context } from "../core/context.ts";
2
+ import type { InstructionPart } from "../core/instruction-parts.ts";
3
+ import type { Problem } from "../core/problem.ts";
4
+ import { type Extension } from "../extensions/index.ts";
5
+ /** The extensions the campaign uses, and what keeps one from being used, with how to fix it. */
6
+ export interface CampaignExtensions {
7
+ extensions: Extension[];
8
+ problems: Problem[];
9
+ }
10
+ /**
11
+ * The extensions campaign.yaml lists (D-27), each as installed on this computer, in the order written: the nearest layer last. One not installed, that does not
12
+ * read, that needs another game system or has the name of another is left out, with its problem: the campaign plays without it.
13
+ */
14
+ export declare function campaignExtensions(root: string, context: Context): CampaignExtensions;
15
+ /** What the campaign's extensions are read from: campaign.yaml and the folders of the installed packages, which `package` refreshes after npm (D-436). */
16
+ export declare function extensionSources(root: string, context: Context): (path: string) => boolean;
17
+ /** The packages campaign.yaml lists as extensions, with the version each was added with: none when it lists none or the list does not read. */
18
+ export declare function listedExtensions(root: string): Record<string, string>;
19
+ /** Whether an extension's code may run (D-441): ours, verified, or one the player installed from a folder of their own; never a stranger's from npm, for now. */
20
+ export declare function runsCode(extension: Extension): boolean;
21
+ /**
22
+ * The parts of the instructions of the system and of the extensions above it, each part layered as D-121 says, under a title of the extension's own (D-441): an
23
+ * extension adds to a part, or takes its place when it is verified.
24
+ */
25
+ export declare function layeredParts(parts: Record<string, InstructionPart>, extensions: Extension[]): Record<string, InstructionPart>;
26
+ /** The extensions for status (D-28): each with its line, for the master to know what it brings. */
27
+ export declare function extensionsLine(root: string, context: Context): string;
@@ -0,0 +1,92 @@
1
+ // The extensions a campaign uses (D-27, D-28, D-427): those campaign.yaml lists, as installed, and their parts of the instructions over the system's (D-121).
2
+ import { join, resolve } from "node:path";
3
+ import { z } from "zod";
4
+ import { campaignFileName, readOneSetting, readTextSetting } from "../campaign/index.js";
5
+ import { files, isInside } from "../core/store.js";
6
+ import { comparableText } from "../core/text.js";
7
+ import { findExtension, isVerified } from "../extensions/index.js";
8
+ /**
9
+ * The extensions campaign.yaml lists (D-27), each as installed on this computer, in the order written: the nearest layer last. One not installed, that does not
10
+ * read, that needs another game system or has the name of another is left out, with its problem: the campaign plays without it.
11
+ */
12
+ export function campaignExtensions(root, context) {
13
+ return files().remember(`extensions ${resolve(root)}`, extensionSources(root, context), () => readCampaignExtensions(root, context));
14
+ }
15
+ /** What the campaign's extensions are read from: campaign.yaml and the folders of the installed packages, which `package` refreshes after npm (D-436). */
16
+ export function extensionSources(root, context) {
17
+ const settings = resolve(join(root, campaignFileName));
18
+ const folders = (context.extensionFolders ?? []).map((folder) => resolve(folder));
19
+ return (path) => path === settings || folders.some((folder) => path === folder || isInside(folder, path) || isInside(path, folder));
20
+ }
21
+ /** The packages campaign.yaml lists as extensions, with the version each was added with: none when it lists none or the list does not read. */
22
+ export function listedExtensions(root) {
23
+ try {
24
+ const listed = readOneSetting(root, "extensions");
25
+ return z.record(z.string(), z.string()).safeParse(listed).data ?? {};
26
+ }
27
+ catch {
28
+ return {};
29
+ }
30
+ }
31
+ /** Whether an extension's code may run (D-441): ours, verified, or one the player installed from a folder of their own; never a stranger's from npm, for now. */
32
+ export function runsCode(extension) {
33
+ return isVerified(extension.package, extension.linked) || extension.linked;
34
+ }
35
+ /**
36
+ * The parts of the instructions of the system and of the extensions above it, each part layered as D-121 says, under a title of the extension's own (D-441): an
37
+ * extension adds to a part, or takes its place when it is verified.
38
+ */
39
+ export function layeredParts(parts, extensions) {
40
+ const layered = { ...parts };
41
+ for (const extension of extensions) {
42
+ const title = `### ${extension.name.charAt(0).toUpperCase()}${extension.name.slice(1)} (extension)`;
43
+ for (const [name, part] of Object.entries(extension.parts)) {
44
+ const below = layered[name];
45
+ const text = `${title}\n\n${part.text}`;
46
+ const replaces = part.replace && isVerified(extension.package, extension.linked);
47
+ layered[name] = replaces || below === undefined ? { text, replace: replaces } : { text: `${below.text}\n\n${text}`, replace: below.replace };
48
+ }
49
+ }
50
+ return layered;
51
+ }
52
+ /** The extensions for status (D-28): each with its line, for the master to know what it brings. */
53
+ export function extensionsLine(root, context) {
54
+ const { extensions } = campaignExtensions(root, context);
55
+ return extensions.length === 0 ? "" : `Extensions: ${extensions.map((extension) => `${extension.name} (${extension.about})`).join("; ")}.`;
56
+ }
57
+ function readCampaignExtensions(root, context) {
58
+ const extensions = [];
59
+ const problems = [];
60
+ const system = readTextSetting(root, "system");
61
+ for (const name of Object.keys(listedExtensions(root))) {
62
+ let extension;
63
+ try {
64
+ extension = findExtension(context.extensionFolders ?? [], name);
65
+ }
66
+ catch (error) {
67
+ problems.push({ path: campaignFileName, message: error instanceof Error ? error.message : String(error), fix: `install it again with package install ${name}` });
68
+ continue;
69
+ }
70
+ if (extension === undefined) {
71
+ problems.push({ path: campaignFileName, message: `The extension ${name} is not installed on this computer: the campaign plays without it.`, fix: `install it with package install ${name}` });
72
+ }
73
+ else if (extension.needs.system !== undefined && comparableText(extension.needs.system) !== comparableText(system ?? "")) {
74
+ problems.push({
75
+ path: campaignFileName,
76
+ message: `The extension ${name} needs the game system ${extension.needs.system}, and the campaign plays ${system ?? "none"}: it is left out.`,
77
+ fix: `take it away with package remove ${extension.name}`,
78
+ });
79
+ }
80
+ else if (extensions.some((other) => other.name === extension.name)) {
81
+ problems.push({
82
+ path: campaignFileName,
83
+ message: `The extensions ${extensions.find((other) => other.name === extension.name)?.package ?? ""} and ${extension.package} have the same name, ${extension.name}: the second is left out.`,
84
+ fix: `take one away with package remove ${extension.package}`,
85
+ });
86
+ }
87
+ else {
88
+ extensions.push(extension);
89
+ }
90
+ }
91
+ return { extensions, problems };
92
+ }